Re_Backend/build/assets/index-CYOEuscl.js

61 lines
1.3 MiB
Raw Blame History

This file contains invisible Unicode characters

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

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

const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-C_Bd1V1u.js","assets/radix-vendor-CYvDqP9X.js","assets/charts-vendor-BVfwAPj-.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-BFJfF1vG.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-B_rK4TXr.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 Ui=(t,s,a)=>Ng(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Ru,R as Du,I as Pu,F as Iu,a as wg,T as Cg,P as Sg,C as Ag,b as Tg,O as Eu,c as Fu,d as kg,e as Rg,f as Dg,D as Pg,g as Ig,A as Eg,h as Fg,i as _g,k as Lg,l as Mg,m as $g,n as Og,V as Ug,o as Bg,p as Vg,q as zg,r as Hg,s as Wg,t as Gg,u as Yg,v as Kg,w as Xg,x as Zg,y as Jg,z as Qg,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 _u,U as Lu,W as cf,X as Mu,Y as $u,Z as df,_ as mf,$ as uf,a0 as xf,a1 as hf,a2 as pf,a3 as gf,a4 as ff,a5 as bf,a6 as yf,a7 as vf,a8 as jf,a9 as Nf,aa as wf,ab as Cf}from"./radix-vendor-CYvDqP9X.js";import{a as Sf,r as p,c as Ou,d as Pr,B as kl,C as ei,X as ti,Y as si,T as Ir,L as ai,e as fa,P as Uu,f as Bu,g as Vu,h as Af,i as Td,j as fi,k as bi,b as Tf}from"./charts-vendor-BVfwAPj-.js";import{a as no,f as zu,s as Vs,e as io,b as kd,c as kf,d as ja,g as hn,i as lo,h as Hu,j as _s,k as Us,l as Bi,m as ka,n as Rf,o as Rl,p as Df,q as He,r as Dl,t as Pf,u as If,v as Ef,w as Ff,x as Vi,y as Rd,z as _f,A as Wu,B as Gu,C as oo,D as co,E as Lf,F as Mf,G as Yu,H as wr,I as zi,J as $f,K as Of,L as Uf}from"./utils-vendor-BTBPSQfW.js";import{L as Bf,S as hs,C as ze,a as Ls,b as lt,X as ft,H as Vf,c as Ku,U as Vt,F as Re,d as De,e as wn,P as gs,f as zf,g as Hf,B as qs,h as Va,i as Hi,j as mo,k as uo,l as yr,m as Xu,n as yi,o as Zu,p as ot,q as Ya,R as $t,I as Ur,T as Ot,r as st,s as ha,t as Wf,A as ss,u as as,M as As,v as vi,w as kt,x as Pl,D as Ct,Z as xo,y as cs,z as Gf,E as Yf,G as Kf,J as Xf,K as Zf,N as Jf,O as Qf,Q as qf,V as e0,W as Ju,Y as t0,_ as s0,$ as Ra,a0 as ji,a1 as za,a2 as ri,a3 as Dd,a4 as _n,a5 as ni,a6 as Qu,a7 as wt,a8 as a0,a9 as K,aa as ta,ab as Ns,ac as qu,ad as Gt,ae as ex,af as ht,ag as r0,ah as n0,ai as tx,aj as Ni,ak as sx,al as i0,am as l0,an as ho,ao as zs,ap as Da,aq as wi,ar as Ci,as as Rs,at as o0,au as c0,av as ax,aw as d0,ax as Wn,ay as pn,az as po,aA as Si,aB as ii,aC as rx,aD as nx,aE as ix,aF as Ai,aG as Ti,aH as m0,aI as ln,aJ as lx,aK as Il,aL as u0,aM as x0,aN as h0,aO as go,aP as fo,aQ as bo,aR as p0,aS as Pd,aT as ox,aU as g0,aV as yo,aW as f0,aX as Ln,aY as b0,aZ as Id,a_ as y0,a$ as v0,b0 as j0}from"./ui-vendor-BFJfF1vG.js";import{l as N0}from"./socket-vendor-TjCxX7sJ.js";import{c as Br,a as w0}from"./redux-vendor-tbZCm13o.js";import{u as Ks,a as Ea,b as cx,B as C0,R as S0,c as Lt,O as A0}from"./router-vendor-B_rK4TXr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function a(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=a(n);fetch(n.href,i)}})();var El={},Ed=Sf;El.createRoot=Ed.createRoot,El.hydrateRoot=Ed.hydrateRoot;var dx={exports:{}},mx={};var Cn=p;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=Cn.useSyncExternalStore,D0=Cn.useRef,P0=Cn.useEffect,I0=Cn.useMemo,E0=Cn.useDebugValue;mx.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 c(u){if(!d){if(d=!0,m=u,u=r(u),n!==void 0&&l.hasValue){var g=l.value;if(n(g,u))return h=g}return h=u}if(g=h,k0(m,u))return g;var b=r(u);return n!==void 0&&n(g,b)?(m=u,g):(m=u,h=b)}var d=!1,m,h,x=a===void 0?null:a;return[function(){return c(s())},x===null?void 0:function(){return c(x())}]},[s,a,r,n]);var o=R0(t,i[0],i[1]);return P0(function(){l.hasValue=!0,l.value=o},[o]),E0(o),o};dx.exports=mx;var F0=dx.exports;function _0(t){t()}function L0(){let t=null,s=null;return{clear(){t=null,s=null},notify(){_0(()=>{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 Fd={notify(){},get:()=>[]};function M0(t,s){let a,r=Fd,n=0,i=!1;function l(b){m();const f=r.subscribe(b);let y=!1;return()=>{y||(y=!0,f(),h())}}function o(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=L0())}function h(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Fd)}function x(){i||(i=!0,m())}function u(){i&&(i=!1,h())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:x,tryUnsubscribe:u,getListeners:()=>r};return g}var $0=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",O0=$0(),U0=()=>typeof navigator<"u"&&navigator.product==="ReactNative",B0=U0(),V0=()=>O0||B0?p.useLayoutEffect:p.useEffect,z0=V0(),Wi=Symbol.for("react-redux-context"),Gi=typeof globalThis<"u"?globalThis:{};function H0(){if(!p.createContext)return{};const t=Gi[Wi]??(Gi[Wi]=new Map);let s=t.get(p.createContext);return s||(s=p.createContext(null),t.set(p.createContext,s)),s}var Ha=H0();function W0(t){const{children:s,context:a,serverState:r,store:n}=t,i=p.useMemo(()=>{const c=M0(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=p.useMemo(()=>n.getState(),[n]);z0(()=>{const{subscription:c}=i;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),l!==n.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[i,l]);const o=a||Ha;return p.createElement(o.Provider,{value:i},s)}var G0=W0;function vo(t=Ha){return function(){return p.useContext(t)}}var ux=vo();function xx(t=Ha){const s=t===Ha?ux:vo(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var Y0=xx();function K0(t=Ha){const s=t===Ha?Y0:xx(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var X0=K0(),Z0=(t,s)=>t===s;function J0(t=Ha){const s=t===Ha?ux:vo(t),a=(r,n={})=>{const{equalityFn:i=Z0}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;p.useRef(!0);const m=p.useCallback({[r.name](x){return r(x)}}[r.name],[r]),h=F0.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return p.useDebugValue(h),h};return Object.assign(a,{withTypes:()=>a}),a}var Q0=J0(),Fl=function(t,s){return Fl=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])},Fl(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");Fl(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var li=function(){return li=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},li.apply(this,arguments)};var cr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function jo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function No(t,s){return t(s={exports:{}},s.exports),s.exports}var ir=No(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()}});jo(ir);var eb=jo(No(function(t,s){var a=cr&&cr.__awaiter||function(m,h,x,u){return new(x||(x=Promise))(function(g,b){function f(w){try{v(u.next(w))}catch(C){b(C)}}function y(w){try{v(u.throw(w))}catch(C){b(C)}}function v(w){w.done?g(w.value):new x(function(C){C(w.value)}).then(f,y)}v((u=u.apply(m,h||[])).next())})},r=cr&&cr.__generator||function(m,h){var x,u,g,b,f={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return b={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(b[Symbol.iterator]=function(){return this}),b;function y(v){return function(w){return function(C){if(x)throw new TypeError("Generator is already executing.");for(;f;)try{if(x=1,u&&(g=2&C[0]?u.return:C[0]?u.throw||((g=u.return)&&g.call(u),0):u.next)&&!(g=g.call(u,C[1])).done)return g;switch(u=0,g&&(C=[2&C[0],g.value]),C[0]){case 0:case 1:g=C;break;case 4:return f.label++,{value:C[1],done:!1};case 5:f.label++,u=C[1],C=[0];continue;case 7:C=f.ops.pop(),f.trys.pop();continue;default:if(g=f.trys,!((g=g.length>0&&g[g.length-1])||C[0]!==6&&C[0]!==2)){f=0;continue}if(C[0]===3&&(!g||C[1]>g[0]&&C[1]<g[3])){f.label=C[1];break}if(C[0]===6&&f.label<g[1]){f.label=g[1],g=C;break}if(g&&f.label<g[2]){f.label=g[2],f.ops.push(C);break}g[2]&&f.ops.pop(),f.trys.pop();continue}C=h.call(m,f)}catch(k){C=[6,k],u=0}finally{x=g=0}if(5&C[0])throw C[1];return{value:C[0]?C[1]:void 0,done:!0}}([v,w])}}},n=cr;Object.defineProperty(s,"__esModule",{value:!0});var i="browser-tabs-lock-key",l={key:function(m){return a(n,void 0,void 0,function(){return r(this,function(h){throw new Error("Unsupported")})})},getItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(h){throw new Error("Unsupported")})})},clear:function(){return a(n,void 0,void 0,function(){return r(this,function(m){return[2,window.localStorage.clear()]})})},removeItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(h){throw new Error("Unsupported")})})},setItem:function(m,h){return a(n,void 0,void 0,function(){return r(this,function(x){throw new Error("Unsupported")})})},keySync:function(m){return window.localStorage.key(m)},getItemSync:function(m){return window.localStorage.getItem(m)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(m){return window.localStorage.removeItem(m)},setItemSync:function(m,h){return window.localStorage.setItem(m,h)}};function o(m){return new Promise(function(h){return setTimeout(h,m)})}function c(m){for(var h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",x="",u=0;u<m;u++)x+=h[Math.floor(Math.random()*h.length)];return x}var d=function(){function m(h){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+c(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=h,m.waiters===void 0&&(m.waiters=[])}return m.prototype.acquireLock=function(h,x){return x===void 0&&(x=5e3),a(this,void 0,void 0,function(){var u,g,b,f,y,v,w;return r(this,function(C){switch(C.label){case 0:u=Date.now()+c(4),g=Date.now()+x,b=i+"-"+h,f=this.storageHandler===void 0?l:this.storageHandler,C.label=1;case 1:return Date.now()<g?[4,o(30)]:[3,8];case 2:return C.sent(),f.getItemSync(b)!==null?[3,5]:(y=this.id+"-"+h+"-"+u,[4,o(Math.floor(25*Math.random()))]);case 3:return C.sent(),f.setItemSync(b,JSON.stringify({id:this.id,iat:u,timeoutKey:y,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,o(30)];case 4:return C.sent(),(v=f.getItemSync(b))!==null&&(w=JSON.parse(v)).id===this.id&&w.iat===u?(this.acquiredIatSet.add(u),this.refreshLockWhileAcquired(b,u),[2,!0]):[3,7];case 5:return m.lockCorrector(this.storageHandler===void 0?l:this.storageHandler),[4,this.waitForSomethingToChange(g)];case 6:C.sent(),C.label=7;case 7:return u=Date.now()+c(4),[3,1];case 8:return[2,!1]}})})},m.prototype.refreshLockWhileAcquired=function(h,x){return a(this,void 0,void 0,function(){var u=this;return r(this,function(g){return setTimeout(function(){return a(u,void 0,void 0,function(){var b,f,y;return r(this,function(v){switch(v.label){case 0:return[4,ir.default().lock(x)];case 1:return v.sent(),this.acquiredIatSet.has(x)?(b=this.storageHandler===void 0?l:this.storageHandler,(f=b.getItemSync(h))===null?(ir.default().unlock(x),[2]):((y=JSON.parse(f)).timeRefreshed=Date.now(),b.setItemSync(h,JSON.stringify(y)),ir.default().unlock(x),this.refreshLockWhileAcquired(h,x),[2])):(ir.default().unlock(x),[2])}})})},1e3),[2]})})},m.prototype.waitForSomethingToChange=function(h){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,new Promise(function(u){var g=!1,b=Date.now(),f=!1;function y(){if(f||(window.removeEventListener("storage",y),m.removeFromWaiting(y),clearTimeout(v),f=!0),!g){g=!0;var w=50-(Date.now()-b);w>0?setTimeout(u,w):u(null)}}window.addEventListener("storage",y),m.addToWaiting(y);var v=setTimeout(y,Math.max(0,h-Date.now()))})];case 1:return x.sent(),[2]}})})},m.addToWaiting=function(h){this.removeFromWaiting(h),m.waiters!==void 0&&m.waiters.push(h)},m.removeFromWaiting=function(h){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(x){return x!==h}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(h){return h()})},m.prototype.releaseLock=function(h){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,this.releaseLock__private__(h)];case 1:return[2,x.sent()]}})})},m.prototype.releaseLock__private__=function(h){return a(this,void 0,void 0,function(){var x,u,g,b;return r(this,function(f){switch(f.label){case 0:return x=this.storageHandler===void 0?l:this.storageHandler,u=i+"-"+h,(g=x.getItemSync(u))===null?[2]:(b=JSON.parse(g)).id!==this.id?[3,2]:[4,ir.default().lock(b.iat)];case 1:f.sent(),this.acquiredIatSet.delete(b.iat),x.removeItemSync(u),ir.default().unlock(b.iat),m.notifyWaiters(),f.label=2;case 2:return[2]}})})},m.lockCorrector=function(h){for(var x=Date.now()-5e3,u=h,g=[],b=0;;){var f=u.keySync(b);if(f===null)break;g.push(f),b++}for(var y=!1,v=0;v<g.length;v++){var w=g[v];if(w.includes(i)){var C=u.getItemSync(w);if(C!==null){var k=JSON.parse(C);(k.timeRefreshed===void 0&&k.timeAcquired<x||k.timeRefreshed!==void 0&&k.timeRefreshed<x)&&(u.removeItemSync(w),y=!0)}}}y&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var ur=No(function(t,s){var a=cr&&cr.__assign||function(){return a=Object.assign||function(c){for(var d,m=1,h=arguments.length;m<h;m++)for(var x in d=arguments[m])Object.prototype.hasOwnProperty.call(d,x)&&(c[x]=d[x]);return c},a.apply(this,arguments)};function r(c,d){if(!d)return"";var m="; "+c;return d===!0?m:m+"="+d}function n(c,d,m){return encodeURIComponent(c).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(d).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(h){if(typeof h.expires=="number"){var x=new Date;x.setMilliseconds(x.getMilliseconds()+864e5*h.expires),h.expires=x}return r("Expires",h.expires?h.expires.toUTCString():"")+r("Domain",h.domain)+r("Path",h.path)+r("Secure",h.secure)+r("SameSite",h.sameSite)}(m)}function i(c){for(var d={},m=c?c.split("; "):[],h=/(%[\dA-F]{2})+/gi,x=0;x<m.length;x++){var u=m[x].split("="),g=u.slice(1).join("=");g.charAt(0)==='"'&&(g=g.slice(1,-1));try{d[u[0].replace(h,decodeURIComponent)]=g.replace(h,decodeURIComponent)}catch{}}return d}function l(){return i(document.cookie)}function o(c,d,m){document.cookie=n(c,d,a({path:"/"},m))}s.__esModule=!0,s.encode=n,s.parse=i,s.getAll=l,s.get=function(c){return l()[c]},s.set=o,s.remove=function(c,d){o(c,"",a(a({},d),{expires:-1}))}});jo(ur),ur.encode,ur.parse,ur.getAll;ur.get;ur.set;ur.remove;var _d;(function(t){t.Code="code",t.ConnectCode="connect_code"})(_d||(_d={}));var Ld;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(Ld||(Ld={}));new eb;var tb={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Es=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},sb=li(li({},tb),{buildAuthorizeUrl:Es,buildLogoutUrl:Es,getAccessTokenSilently:Es,getAccessTokenWithPopup:Es,getIdTokenClaims:Es,loginWithRedirect:Es,loginWithPopup:Es,connectAccountWithRedirect:Es,logout:Es,handleRedirectCallback:Es,getDpopNonce:Es,setDpopNonce:Es,generateDpopProof:Es,createFetcher:Es}),ab=p.createContext(sb);(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 rb=function(t){return t===void 0&&(t=ab),p.useContext(t)};const Yi="idToken",Ki="userData",nb=()=>!0;class tt{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(Yi,s)}static getIdToken(){return sessionStorage.getItem(Yi)}static setUserData(s){localStorage.setItem(Ki,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(Ki);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(Ki),sessionStorage.removeItem(Yi)}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 nb()}}function Xi(t,s=5){if(!t)return!0;try{const a=t.split(".");if(a.length!==3||!a[1])return!0;const n=JSON.parse(atob(a[1])).exp*1e3,i=Date.now(),l=s*60*1e3;return n-i<l}catch{return!0}}const hx="https://reflow-uat.royalenfield.com/api/v1/",je=no.create({baseURL:hx,headers:{"Content-Type":"application/json"},withCredentials:!0});je.interceptors.request.use(t=>t,t=>Promise.reject(t));je.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=tt.getRefreshToken(),l=await no.post(`${hx}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(l.data.data||l.data).accessToken;return je(s)}catch(i){return tt.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function ib(t,s){var a,r;try{const n=await je.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&&tt.setUserData(l.user),l.idToken&&tt.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(tt.setAccessToken(l.accessToken),tt.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 lb(){var r;const t={},a=(await je.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 sn(){const s=(await je.get("/auth/me")).data;return s.data||s}async function ob(){var t,s;try{await je.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 _l="https://ssodev.rebridge.co.in/realms/RE",px="REFLOW",wo=`${window.location.origin}/login/callback`;function cb(){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=`${_l}/protocol/openid-connect/auth?client_id=${px}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(wo)}&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 db(t,s){var r,n,i;const a="https://reflow-uat.royalenfield.com/api/v1/";try{const l=await no.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:wo,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),o=((r=l.data)==null?void 0:r.data)||l.data;return o.accessToken&&tt.setAccessToken(o.accessToken),o.refreshToken&&tt.setRefreshToken(o.refreshToken),o.idToken&&tt.setIdToken(o.idToken),o.user&&tt.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 mb(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=wo,a=new URL(`${_l}/protocol/openid-connect/logout`);a.searchParams.set("client_id",px),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:`${_l}/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 gx=p.createContext(void 0);function ub({children:t}){const[s,a]=p.useState(!1),[r,n]=p.useState(!0),[i,l]=p.useState(null),[o,c]=p.useState(null),[d,m]=p.useState(!1);p.useEffect(()=>{const v=sessionStorage.getItem("__logout_in_progress__"),w=sessionStorage.getItem("__force_logout__");if(v==="true"||w==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),tt.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(k){console.error("Error clearing storage:",k)}a(!1),l(null),n(!1),c(null);return}const C=new URLSearchParams(window.location.search);if(C.has("logout")||C.has("okta_logged_out")||C.has("tanflow_logged_out")){console.log("🚪 Logout parameter detected in URL, clearing all tokens"),tt.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 k=new URLSearchParams;C.has("okta_logged_out")&&k.set("okta_logged_out","true"),C.has("tanflow_logged_out")&&k.set("tanflow_logged_out","true");const S=k.toString()?`/?${k.toString()}`:"/";window.history.replaceState({},document.title,S);return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(tt.getUserData(),d?n(!1):x())},[d]),p.useEffect(()=>{if(!s)return;const v=async()=>{try{await f()}catch(k){console.error("Silent refresh failed:",k)}},w=10*60*1e3,C=setInterval(v,w);return()=>clearInterval(C)},[s]);const h=p.useRef(!1);p.useEffect(()=>{if(h.current||window.location.pathname!=="/login/callback")return;(async()=>{const w=new URLSearchParams(window.location.search);if((w.has("logout")||w.has("tanflow_logged_out")||w.has("okta_logged_out"))&&!w.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const _=new URLSearchParams;w.has("tanflow_logged_out")&&_.set("tanflow_logged_out","true"),w.has("okta_logged_out")&&_.set("okta_logged_out","true"),w.has("logout")&&_.set("logout",w.get("logout")||Date.now().toString());const D=_.toString()?`/?${_.toString()}`:"/?logout="+Date.now();window.location.replace(D);return}h.current=!0;const C=w.get("code"),k=w.get("error");if(window.history.replaceState({},document.title,"/login/callback"),sessionStorage.getItem("auth_provider")==="tanflow"){h.current=!1;return}if(k){c(new Error(`Authentication error: ${k}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!C){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),c(null);const _=`${window.location.origin}/login/callback`,D=await ib(C,_);l(D.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(_){console.error("❌ Token exchange error in AuthContext:",_),c(_),a(!1),l(null),sessionStorage.removeItem("auth_provider"),h.current=!1}finally{n(!1)}})()},[]);const x=async()=>{var w;if(d){n(!1);return}const v=!0;try{if(n(!0),v){const S=tt.getUserData();try{const _=await sn();l(_),tt.setUserData(_),a(!0)}catch(_){if(((w=_==null?void 0:_.response)==null?void 0:w.status)===401)try{await f();const D=await sn();l(D),tt.setUserData(D),a(!0)}catch{tt.clearAll(),a(!1),l(null)}else _!=null&&_.isConnectionError?S?(l(S),a(!0)):(a(!1),l(null)):(tt.clearAll(),a(!1),l(null))}return}const C=tt.getAccessToken(),k=tt.getUserData();if(!C){a(!1),l(null),n(!1);return}if(Xi(C))try{await f();const S=tt.getAccessToken();if(S&&!Xi(S)){const _=tt.getUserData();if(_)l(_),a(!0);else try{const D=await sn();l(D),tt.setUserData(D),a(!0)}catch{tt.clearAll(),a(!1),l(null)}}else tt.clearAll(),a(!1),l(null)}catch{tt.clearAll(),a(!1),l(null)}else if(k)l(k),a(!0);else try{const S=await sn();l(S),tt.setUserData(S),a(!0)}catch{tt.clearAll(),a(!1),l(null)}}catch(C){console.error("Error checking auth status:",C),c(C),tt.clearAll(),a(!1),l(null)}finally{n(!1)}},u=async()=>{try{c(null);const v="https://dev-830839.oktapreview.com",w="0oa2jgzvrpdwx2iqd0h8",C=`${window.location.origin}/login/callback`,k="code",S="openid profile email",_=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const D=new URLSearchParams(window.location.search),A=D.has("logout")||D.has("okta_logged_out")||D.has("tanflow_logged_out");let N=`${v}/oauth2/default/v1/authorize?client_id=${w}&redirect_uri=${encodeURIComponent(C)}&response_type=${k}&scope=${encodeURIComponent(S)}&state=${_}`;A&&(N+="&prompt=login"),window.location.href=N}catch(v){throw c(v),v}},g=async()=>{try{const v=tt.getIdToken(),w=sessionStorage.getItem("auth_provider")||(v&&v.includes("tanflow")?"tanflow":null)||"okta";sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),l(null),c(null),n(!0);try{await ob(),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 C=sessionStorage.getItem("__logout_in_progress__"),k=sessionStorage.getItem("__force_logout__"),S=sessionStorage.getItem("auth_provider");if(tt.clearAll(),C&&sessionStorage.setItem("__logout_in_progress__",C),k&&sessionStorage.setItem("__force_logout__",k),v&&tt.setIdToken(v),S&&sessionStorage.setItem("auth_provider",S),await new Promise(D=>setTimeout(D,100)),w==="tanflow"&&v){console.log("🚪 Initiating Tanflow logout...");try{mb(v);return}catch(D){console.error("🚪 Tanflow logout error:",D)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),v&&tt.clearAll();const _=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(_)}catch(v){console.error("🚪 Logout error:",v);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const w=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(w)}catch{window.location.replace("/?logout="+Date.now())}}},b=async()=>{{if(s)return"cookie-based-auth";try{return await f(),s?"cookie-based-auth":null}catch{return null}}const v=tt.getAccessToken();if(v&&!Xi(v))return v;try{return await f(),tt.getAccessToken()}catch{return null}},f=async()=>{try{const w=await lb();return}catch(w){throw tt.clearAll(),a(!1),l(null),w}},y={isAuthenticated:s,isLoading:r,user:i,error:o,login:u,logout:g,getAccessTokenSilently:b,refreshTokenSilently:f};return e.jsx(gx.Provider,{value:y,children:t})}function xb({children:t}){return e.jsx(ub,{children:t})}function Kt(){const t=p.useContext(gx);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function lr(t){return(t==null?void 0:t.role)==="ADMIN"}function Jr(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function ki(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Md=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,$d=Ou,fx=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return $d(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,l=Object.keys(n).map(d=>{const m=a==null?void 0:a[d],h=i==null?void 0:i[d];if(m===null)return null;const x=Md(m)||Md(h);return n[d][x]}),o=a&&Object.entries(a).reduce((d,m)=>{let[h,x]=m;return x===void 0||(d[h]=x),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:h,className:x,...u}=m;return Object.entries(u).every(g=>{let[b,f]=g;return Array.isArray(f)?f.includes({...i,...o}[b]):{...i,...o}[b]===f})?[...d,h,x]:d},[]);return $d(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},Co="-",hb=t=>{const s=gb(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(Co);return o[0]===""&&o.length!==1&&o.shift(),bx(o,s)||pb(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},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(Co);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Od=/^\[(.+)\]$/,pb=t=>{if(Od.test(t)){const s=Od.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},gb=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return bb(Object.entries(t.classGroups),a).forEach(([i,l])=>{Ll(l,r,i,s)}),r},Ll=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:Ud(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(fb(n)){Ll(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{Ll(l,Ud(s,i),a,r)})})},Ud=(t,s)=>{let a=t;return s.split(Co).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},fb=t=>t.isThemeGetter,bb=(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,yb=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)}}},yx="!",vb=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,l=o=>{const c=[];let d=0,m=0,h;for(let f=0;f<o.length;f++){let y=o[f];if(d===0){if(y===n&&(r||o.slice(f,f+i)===s)){c.push(o.slice(m,f)),m=f+i;continue}if(y==="/"){h=f;continue}}y==="["?d++:y==="]"&&d--}const x=c.length===0?o:o.substring(m),u=x.startsWith(yx),g=u?x.substring(1):x,b=h&&h>m?h-m:void 0;return{modifiers:c,hasImportantModifier:u,baseClassName:g,maybePostfixModifierPosition:b}};return a?o=>a({className:o,parseClassName:l}):l},jb=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},Nb=t=>({cache:yb(t.cacheSize),parseClassName:vb(t),...hb(t)}),wb=/\s+/,Cb=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(wb);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:h,baseClassName:x,maybePostfixModifierPosition:u}=a(d);let g=!!u,b=r(g?x.substring(0,u):x);if(!b){if(!g){o=d+(o.length>0?" "+o:o);continue}if(b=r(x),!b){o=d+(o.length>0?" "+o:o);continue}g=!1}const f=jb(m).join(":"),y=h?f+yx:f,v=y+b;if(i.includes(v))continue;i.push(v);const w=n(b,g);for(let C=0;C<w.length;++C){const k=w[C];i.push(y+k)}o=d+(o.length>0?" "+o:o)}return o};function Sb(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=vx(s))&&(r&&(r+=" "),r+=a);return r}const vx=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=vx(t[r]))&&(a&&(a+=" "),a+=s);return a};function Ab(t,...s){let a,r,n,i=l;function l(c){const d=s.reduce((m,h)=>h(m),t());return a=Nb(d),r=a.cache.get,n=a.cache.set,i=o,o(c)}function o(c){const d=r(c);if(d)return d;const m=Cb(c,a);return n(c,m),m}return function(){return i(Sb.apply(null,arguments))}}const Et=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},jx=/^\[(?:([a-z-]+):)?(.+)\]$/i,Tb=/^\d+\/\d+$/,kb=new Set(["px","full","screen"]),Rb=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Db=/\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$/,Pb=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Ib=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Eb=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Sa=t=>Er(t)||kb.has(t)||Tb.test(t),$a=t=>Vr(t,"length",Bb),Er=t=>!!t&&!Number.isNaN(Number(t)),Zi=t=>Vr(t,"number",Er),Qr=t=>!!t&&Number.isInteger(Number(t)),Fb=t=>t.endsWith("%")&&Er(t.slice(0,-1)),it=t=>jx.test(t),Oa=t=>Rb.test(t),_b=new Set(["length","size","percentage"]),Lb=t=>Vr(t,_b,Nx),Mb=t=>Vr(t,"position",Nx),$b=new Set(["image","url"]),Ob=t=>Vr(t,$b,zb),Ub=t=>Vr(t,"",Vb),qr=()=>!0,Vr=(t,s,a)=>{const r=jx.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},Bb=t=>Db.test(t)&&!Pb.test(t),Nx=()=>!1,Vb=t=>Ib.test(t),zb=t=>Eb.test(t),Hb=()=>{const t=Et("colors"),s=Et("spacing"),a=Et("blur"),r=Et("brightness"),n=Et("borderColor"),i=Et("borderRadius"),l=Et("borderSpacing"),o=Et("borderWidth"),c=Et("contrast"),d=Et("grayscale"),m=Et("hueRotate"),h=Et("invert"),x=Et("gap"),u=Et("gradientColorStops"),g=Et("gradientColorStopPositions"),b=Et("inset"),f=Et("margin"),y=Et("opacity"),v=Et("padding"),w=Et("saturate"),C=Et("scale"),k=Et("sepia"),S=Et("skew"),_=Et("space"),D=Et("translate"),A=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto",it,s],R=()=>[it,s],O=()=>["",Sa,$a],F=()=>["auto",Er,it],$=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],V=()=>["solid","dashed","dotted","double","none"],T=()=>["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",it],I=()=>["auto","avoid","all","avoid-page","page","left","right","column"],M=()=>[Er,it];return{cacheSize:500,separator:":",theme:{colors:[qr],spacing:[Sa,$a],blur:["none","",Oa,it],brightness:M(),borderColor:[t],borderRadius:["none","","full",Oa,it],borderSpacing:R(),borderWidth:O(),contrast:M(),grayscale:U(),hueRotate:M(),invert:U(),gap:R(),gradientColorStops:[t],gradientColorStopPositions:[Fb,$a],inset:P(),margin:P(),opacity:M(),padding:R(),saturate:M(),scale:M(),sepia:U(),skew:M(),space:R(),translate:R()},classGroups:{aspect:[{aspect:["auto","square","video",it]}],container:["container"],columns:[{columns:[Oa]}],"break-after":[{"break-after":I()}],"break-before":[{"break-before":I()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...$(),it]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:A()}],"overscroll-x":[{"overscroll-x":A()}],"overscroll-y":[{"overscroll-y":A()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[b]}],"inset-x":[{"inset-x":[b]}],"inset-y":[{"inset-y":[b]}],start:[{start:[b]}],end:[{end:[b]}],top:[{top:[b]}],right:[{right:[b]}],bottom:[{bottom:[b]}],left:[{left:[b]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Qr,it]}],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",it]}],grow:[{grow:U()}],shrink:[{shrink:U()}],order:[{order:["first","last","none",Qr,it]}],"grid-cols":[{"grid-cols":[qr]}],"col-start-end":[{col:["auto",{span:["full",Qr,it]},it]}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":[qr]}],"row-start-end":[{row:["auto",{span:[Qr,it]},it]}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",it]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",it]}],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":[_]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[_]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",it,s]}],"min-w":[{"min-w":[it,s,"min","max","fit"]}],"max-w":[{"max-w":[it,s,"none","full","min","max","fit","prose",{screen:[Oa]},Oa]}],h:[{h:[it,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[it,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[it,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[it,s,"auto","min","max","fit"]}],"font-size":[{text:["base",Oa,$a]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Zi]}],"font-family":[{font:[qr]}],"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",it]}],"line-clamp":[{"line-clamp":["none",Er,Zi]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Sa,it]}],"list-image":[{"list-image":["none",it]}],"list-style-type":[{list:["none","disc","decimal",it]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Sa,$a]}],"underline-offset":[{"underline-offset":["auto",Sa,it]}],"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",it]}],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",it]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...$(),Mb]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Lb]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Ob]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[u]}],"gradient-via":[{via:[u]}],"gradient-to":[{to:[u]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[y]}],"border-style":[{border:[...V(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[y]}],"divide-style":[{divide:V()}],"border-color":[{border:[n]}],"border-color-x":[{"border-x":[n]}],"border-color-y":[{"border-y":[n]}],"border-color-s":[{"border-s":[n]}],"border-color-e":[{"border-e":[n]}],"border-color-t":[{"border-t":[n]}],"border-color-r":[{"border-r":[n]}],"border-color-b":[{"border-b":[n]}],"border-color-l":[{"border-l":[n]}],"divide-color":[{divide:[n]}],"outline-style":[{outline:["",...V()]}],"outline-offset":[{"outline-offset":[Sa,it]}],"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":[y]}],"ring-offset-w":[{"ring-offset":[Sa,$a]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Oa,Ub]}],"shadow-color":[{shadow:[qr]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...T(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":T()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Oa,it]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[h]}],saturate:[{saturate:[w]}],sepia:[{sepia:[k]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[k]}],"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",it]}],duration:[{duration:M()}],ease:[{ease:["linear","in","out","in-out",it]}],delay:[{delay:M()}],animate:[{animate:["none","spin","ping","pulse","bounce",it]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[C]}],"scale-x":[{"scale-x":[C]}],"scale-y":[{"scale-y":[C]}],rotate:[{rotate:[Qr,it]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[S]}],"skew-y":[{"skew-y":[S]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",it]}],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",it]}],"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",it]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Sa,$a,Zi]}],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"]}}},Wb=Ab(Hb);function ke(...t){return Wb(Ou(t))}const gn=fx("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"}}),E=p.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Ru:"button";return e.jsx(l,{"data-slot":"button",className:ke(gn({variant:s,size:a,className:t})),ref:i,...n})});E.displayName="Button";function ee({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:ke("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function ge({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:ke("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",t),...s})}function fe({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:ke("leading-none",t),...s})}function $e({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:ke("text-muted-foreground",t),...s})}function se({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:ke("px-6 [&:last-child]:pb-6",t),...s})}const Ri="/assets/Re_Logo-By51taPS.png",Bd="/assets/landing_page_image-ClTD-4qZ.jpg";function Gb(){const{login:t,isLoading:s,error:a}=Kt(),[r,n]=p.useState(!1),[i,l]=p.useState(!1);p.useEffect(()=>{const d=new Image;d.src=Bd,d.onload=()=>{l(!0)},d.complete&&l(!0)},[]);const o=async()=>{localStorage.clear(),sessionStorage.clear();try{await t()}catch(d){console.error("========================================"),console.error("OKTA LOGIN ERROR"),console.error("Error details:",d),console.error("Error message:",d==null?void 0:d.message),console.error("Error stack:",d==null?void 0:d.stack),console.error("========================================")}},c=()=>{localStorage.clear(),sessionStorage.clear(),n(!0);try{cb()}catch(d){console.error("========================================"),console.error("TANFLOW LOGIN ERROR"),console.error("Error details:",d),n(!1)}};return a&&console.error("Auth Error in Auth Component:",{message:a.message,error:a}),e.jsxs("div",{className:"min-h-screen flex items-center justify-center p-4 relative",style:{backgroundImage:i?`url(${Bd})`:"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(ee,{className:"w-full max-w-md shadow-xl relative z-10 bg-black backdrop-blur-sm border-gray-800",children:[e.jsx(ge,{className:"space-y-1 text-center pb-6",children:e.jsxs("div",{className:"flex flex-col items-center justify-center mb-4",children:[e.jsx("img",{src:Ri,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(se,{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(E,{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(E,{onClick:c,disabled:s||r,className:"w-full h-12 text-base font-semibold bg-indigo-600 hover:bg-indigo-700 text-white",size:"lg",children:r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Redirecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hs,{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 wx(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Kt(),[n,i]=p.useState("exchanging");p.useEffect(()=>{if(a){i("error");return}if(s){const c=new URLSearchParams(window.location.search).get("code");i(c&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&i("complete")},[t,s,a,r]);const l=()=>{switch(n){case"exchanging":return"Exchanging authorization code...";case"fetching":return"Fetching your profile...";case"complete":return"Authentication successful!";case"error":return"Authentication failed";default:return"Completing authentication..."}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"}),e.jsxs("div",{className:"relative z-10 text-center px-4 max-w-md w-full",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Ri,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(ze,{className:"w-16 h-16 text-red-500"})}),e.jsx(ze,{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(Ls,{className:"w-16 h-16 text-green-500"})}),e.jsx(Ls,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(lt,{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 Yb(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Kt(),[n,i]=p.useState("exchanging"),[l,o]=p.useState(""),c=p.useRef(!1);p.useEffect(()=>{if(a){i("error");return}if(s){const h=new URLSearchParams(window.location.search).get("code");i(h&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&(i("complete"),setTimeout(()=>{window.location.href="/"},1e3))},[t,s,a,r]),p.useEffect(()=>{if(c.current||window.location.pathname!=="/login/callback")return;const m=new URLSearchParams(window.location.search),h=m.get("code"),x=m.get("error");if(!h&&!x){console.log("🚪 Logout redirect detected: no code, no error - redirecting to home immediately"),c.current=!0;const b=new URLSearchParams;b.set("tanflow_logged_out","true"),b.set("logout",Date.now().toString());const f=`/?${b.toString()}`;console.log("🚪 Redirecting to:",f),window.location.replace(f);return}if(sessionStorage.getItem("auth_provider")!=="tanflow")return;(async()=>{c.current=!0;const b=new URLSearchParams(window.location.search),f=b.get("code"),y=b.get("state"),v=b.get("error");if(window.history.replaceState({},document.title,"/login/callback"),v){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}const w=sessionStorage.getItem("tanflow_auth_state");if(y&&y!==w){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 C=await db(f,y||"");sessionStorage.removeItem("tanflow_auth_state"),i("fetching");const k=C.user||await sn();if(k)tt.setUserData(k),i("complete"),setTimeout(()=>{window.history.replaceState({},document.title,"/"),window.location.href="/"},1e3);else throw new Error("User data not received")}catch(C){console.error("Tanflow callback error:",C),i("error"),o(C.message||"Authentication failed"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state")}})()},[]);const d=()=>{switch(n){case"exchanging":return"Exchanging authorization code...";case"fetching":return"Fetching your profile...";case"complete":return"Authentication successful!";case"error":return"Authentication failed";default:return"Completing authentication..."}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"}),e.jsxs("div",{className:"relative z-10 text-center px-4 max-w-md w-full",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Ri,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(ze,{className:"w-16 h-16 text-red-500"})}),e.jsx(ze,{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(Ls,{className:"w-16 h-16 text-green-500"})}),e.jsx(Ls,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(lt,{className:"w-16 h-16 animate-spin text-re-red"}),e.jsx("div",{className:"absolute inset-0 border-4 rounded-full border-re-red/20"}),e.jsx("div",{className:"absolute inset-0 border-4 border-transparent border-t-re-red rounded-full animate-spin"})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-white mb-2",children:n==="complete"?"Welcome Back!":n==="error"?"Authentication Error":"Authenticating"}),e.jsx("p",{className:"text-slate-300 text-sm",children:d()})]}),n!=="error"&&e.jsxs("div",{className:"space-y-3 mb-6",children:[e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="exchanging"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="exchanging"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Validating credentials"})]}),e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="fetching"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="fetching"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Loading your profile"})]}),n==="complete"&&e.jsxs("div",{className:"flex items-center gap-3 text-sm transition-all duration-500 text-white",children:[e.jsx("div",{className:"w-2 h-2 rounded-full transition-all duration-500 bg-green-500"}),e.jsx("span",{children:"Setting up your session"})]})]}),n==="error"&&l&&e.jsxs("div",{className:"mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx("p",{className:"text-red-400 text-sm",children:l}),e.jsx("button",{onClick:()=>{window.location.href="/"},className:"mt-4 text-sm text-red-400 hover:text-red-300 underline",children:"Return to login"})]}),n!=="error"&&n!=="complete"&&e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"h-1.5 bg-slate-700/50 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-re-red rounded-full animate-pulse",style:{animation:"progress 2s ease-in-out infinite"}})}),e.jsx("style",{children:`
@keyframes progress {
0%, 100% { width: 20%; }
50% { width: 80%; }
}
`})]})]}),e.jsx("p",{className:"mt-6 text-slate-500 text-xs",children:n==="complete"?"Loading dashboard...":"Please wait while we secure your session"})]}),e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute top-1/4 left-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-1/4 right-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse delay-1000"})]})]})}const Kb=fx("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?Ru:"span";return e.jsx(n,{"data-slot":"badge",className:ke(Kb({variant:s}),t),...r})}function Xb({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=rb();return p.useEffect(()=>{},[a,r,n,i]),t?e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4",children:e.jsxs(ee,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{children:"Authentication Debug Information"}),e.jsx(E,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(ft,{className:"h-4 w-4"})})]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold",children:"Status:"}),e.jsx(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 Zt=p.forwardRef(({className:t,...s},a)=>e.jsx(Du,{ref:a,"data-slot":"avatar",className:ke("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));Zt.displayName=Du.displayName;const Di=p.forwardRef(({className:t,...s},a)=>e.jsx(Pu,{ref:a,"data-slot":"avatar-image",className:ke("aspect-square size-full",t),...s}));Di.displayName=Pu.displayName;const Jt=p.forwardRef(({className:t,...s},a)=>e.jsx(Iu,{ref:a,"data-slot":"avatar-fallback",className:ke("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));Jt.displayName=Iu.displayName;function Vd({...t}){return e.jsx(wg,{"data-slot":"dropdown-menu",...t})}function zd({...t}){return e.jsx(Cg,{"data-slot":"dropdown-menu-trigger",...t})}function Hd({className:t,sideOffset:s=4,...a}){return e.jsx(Sg,{children:e.jsx(Ag,{"data-slot":"dropdown-menu-content",sideOffset:s,className:ke("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 Ji({className:t,inset:s,variant:a="default",...r}){return e.jsx(Tg,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:ke("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 Zb({...t}){return e.jsx(Rg,{"data-slot":"alert-dialog",...t})}function Jb({...t}){return e.jsx(kg,{"data-slot":"alert-dialog-portal",...t})}const Cx=p.forwardRef(({className:t,...s},a)=>e.jsx(Eu,{"data-slot":"alert-dialog-overlay",className:ke("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}));Cx.displayName=Eu.displayName;const Sx=p.forwardRef(({className:t,...s},a)=>e.jsxs(Jb,{children:[e.jsx(Cx,{}),e.jsx(Fu,{"data-slot":"alert-dialog-content",ref:a,className:ke("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=Fu.displayName;function Qb({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:ke("flex flex-col gap-2 text-center sm:text-left",t),...s})}function qb({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:ke("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function ey({className:t,...s}){return e.jsx(Dg,{"data-slot":"alert-dialog-title",className:ke("text-lg font-semibold",t),...s})}function ty({className:t,...s}){return e.jsx(Pg,{"data-slot":"alert-dialog-description",className:ke("text-muted-foreground text-sm",t),...s})}function sy({className:t,...s}){return e.jsx(Eg,{className:ke(gn(),t),...s})}function ay({className:t,...s}){return e.jsx(Ig,{className:ke(gn({variant:"outline"}),t),...s})}const Ba={async list(t){return(await je.get("/notifications",{params:t})).data},async getUnreadCount(){return(await je.get("/notifications/unread-count")).data},async markAsRead(t){return(await je.patch(`/notifications/${t}/read`)).data},async markAllAsRead(){return(await je.post("/notifications/mark-all-read")).data},async delete(t){return(await je.delete(`/notifications/${t}`)).data}},ry=async()=>(await je.get("/notifications/subscriptions")).data.data.subscriptions;let rr=null;function ny(){return"https://reflow-uat.royalenfield.com"}function Lr(t){const s=ny();return rr||(rr=N0(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),rr.on("connect",()=>{}),rr.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),rr.on("disconnect",a=>{}),rr)}function Ml(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function Ax(t,s){t.emit("leave:request",s)}function Tx(t,s){t.emit("join:user",{userId:s})}function ys({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,l]=p.useState(!1),[o,c]=p.useState(!1),[d,m]=p.useState([]),[h,x]=p.useState(0),[u,g]=p.useState(!1),{user:b}=Kt(),f=p.useMemo(()=>{try{const S=tt.getUserData();return(S==null?void 0:S.jobTitle)==="Dealer"}catch(S){return console.error("[PageLayout] Error checking dealer status:",S),!1}},[]),y=()=>{var S,_;try{if(b!=null&&b.displayName&&typeof b.displayName=="string"){const D=b.displayName.split(" ").filter(Boolean);return D.length>=2?`${((S=D[0])==null?void 0:S[0])||""}${((_=D[D.length-1])==null?void 0:_[0])||""}`.toUpperCase():b.displayName.substring(0,2).toUpperCase()}return b!=null&&b.email&&typeof b.email=="string"?b.email.substring(0,2).toUpperCase():"U"}catch(D){return console.error("[PageLayout] Error getting user initials:",D),"U"}},v=p.useMemo(()=>{const S=[{id:"dashboard",label:"Dashboard",icon:Vf},{id:"requests",label:"All Requests",icon:Ku,adminOnly:!1}];return f||S.push({id:"my-requests",label:"My Requests",icon:Vt}),S.push({id:"open-requests",label:"Open Requests",icon:Re},{id:"closed-requests",label:"Closed Requests",icon:De},{id:"shared-summaries",label:"Shared Summary",icon:wn}),S},[f]),w=()=>{l(!i)},C=async S=>{var _;try{if(S.isRead||(await Ba.markAsRead(S.notificationId),m(D=>D.map(A=>A.notificationId===S.notificationId?{...A,isRead:!0}:A)),x(D=>Math.max(0,D-1))),S.actionUrl&&a){const D=(_=S.metadata)==null?void 0:_.requestNumber;if(D){let A=`request/${D}`;(S.notificationType==="mention"||S.notificationType==="comment"||S.notificationType==="worknote")&&(A+="?tab=worknotes"),a(A)}}g(!1)}catch(D){console.error("[PageLayout] Error handling notification click:",D)}},k=async()=>{try{await Ba.markAllAsRead(),m(S=>S.map(_=>({..._,isRead:!0}))),x(0)}catch(S){console.error("[PageLayout] Error marking all as read:",S)}};return p.useEffect(()=>{const S=b==null?void 0:b.userId;if(!S)return;let _=!0;(async()=>{var N,P;try{const R=await Ba.list({page:1,limit:4,unreadOnly:!1});if(!_)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 A=Lr();if(A){Tx(A,S);const N=P=>{_&&(m(R=>[P.notification,...R].slice(0,4)),x(R=>R+1))};return A.on("notification:new",N),()=>{_=!1,A.off("notification:new",N)}}return()=>{_=!1}},[b]),p.useEffect(()=>{const S=()=>{window.innerWidth>=768?l(!0):l(!1)};return S(),window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[]),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:Ri,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain"}),e.jsx("p",{className:"text-xs text-gray-400 text-center mt-1 truncate",children:"RE Flow"})]})}),e.jsxs("div",{className:"p-3 flex-1 overflow-y-auto",children:[e.jsx("div",{className:"space-y-2",children:v.filter(S=>!S.adminOnly||(b==null?void 0:b.role)==="ADMIN").map(S=>e.jsxs("button",{onClick:()=>{S.id==="admin/templates"?a==null||a("admin/templates"):a==null||a(S.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===S.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(S.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:S.label})]},S.id))}),!f&&e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(E,{onClick:r,className:"w-full bg-re-green hover:bg-re-green/90 text-white text-sm font-medium",size:"sm",children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Raise New Request"]})})]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("header",{className:"h-16 border-b border-gray-200 bg-white flex items-center justify-between px-6 shrink-0",children:[e.jsx("div",{className:"flex items-center gap-4 min-w-0 flex-1",children:e.jsx(E,{variant:"ghost",size:"icon",onClick:w,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(E,{onClick:r,className:"bg-re-green hover:bg-re-green/90 text-white gap-2 hidden md:flex text-sm",size:"sm",children:[e.jsx(gs,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(Vd,{open:u,onOpenChange:g,children:[e.jsx(zd,{asChild:!0,children:e.jsxs(E,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(qs,{className:"w-5 h-5"}),h>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:h>9?"9+":h})]})}),e.jsxs(Hd,{align:"end",className:"w-96 max-h-[500px]",children:[e.jsxs("div",{className:"p-3 border-b flex items-center justify-between sticky top-0 bg-white z-10",children:[e.jsx("h4",{className:"font-semibold text-base",children:"Notifications"}),h>0&&e.jsx(E,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:S=>{S.stopPropagation(),k()},children:"Mark all as read"})]}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:d.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(qs,{className:"w-12 h-12 text-gray-300 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No notifications yet"})]}):e.jsx("div",{className:"divide-y",children:d.map(S=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${S.isRead?"":"bg-blue-50"}`,onClick:()=>C(S),children:e.jsxs("div",{className:"flex gap-2",children:[!S.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 ${S.isRead?"font-medium":"font-semibold"}`,children:S.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:S.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:zu(new Date(S.createdAt),{addSuffix:!0})})]})]})},S.notificationId))})}),d.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(E,{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(Vd,{children:[e.jsx(zd,{asChild:!0,children:e.jsxs(Zt,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Di,{src:(b==null?void 0:b.picture)||""}),e.jsx(Jt,{className:"bg-re-green text-white text-sm",children:y()})]})}),e.jsxs(Hd,{align:"end",children:[e.jsxs(Ji,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(Vt,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(Ji,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(Va,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(Ji,{onClick:()=>c(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(Hi,{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(Zb,{open:o,onOpenChange:c,children:e.jsxs(Sx,{children:[e.jsxs(Qb,{children:[e.jsxs(ey,{className:"flex items-center gap-2",children:[e.jsx(Hi,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(ty,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(qb,{children:[e.jsx(ay,{onClick:()=>c(!1),children:"Cancel"}),e.jsxs(sy,{onClick:async()=>{if(c(!1),n)try{await n()}catch(S){console.error("🔴 Error calling onLogout:",S)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(Hi,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const Sn=()=>X0(),zr=Q0,iy=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},ly={viewAsUser:iy()},kx=Br({name:"dashboard",initialState:ly,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:oy}=kx.actions;function cy(){const[t,s]=p.useState("all"),[a,r]=p.useState(void 0),[n,i]=p.useState(void 0),[l,o]=p.useState(!1),c=p.useCallback(h=>{const x=h;s(x),x!=="custom"?(r(void 0),i(void 0),o(!1)):o(!0)},[]),d=p.useCallback(h=>{if(a&&n){if(a>n){const x=a;r(n),i(x),h(n,x)}else h(a,n);o(!1)}},[a,n]),m=p.useCallback(()=>{r(void 0),i(void 0),o(!1),s("all")},[]);return{dateRange:t,customStartDate:a,customEndDate:n,showCustomDatePicker:l,setDateRange:s,setCustomStartDate:r,setCustomEndDate:i,setShowCustomDatePicker:o,handleDateRangeChange:c,handleApplyCustomDate:d,resetCustomDates:m}}function dy(){const[t,s]=p.useState({page:1,totalPages:1,totalRecords:0}),[a,r]=p.useState({page:1,totalPages:1,totalRecords:0}),[n,i]=p.useState({page:1,totalPages:1,totalRecords:0}),[l,o]=p.useState({page:1,totalPages:1,totalRecords:0}),c=p.useCallback((f,y,v)=>{s({page:f,totalPages:y,totalRecords:v})},[]),d=p.useCallback((f,y,v)=>{r({page:f,totalPages:y,totalRecords:v})},[]),m=p.useCallback((f,y,v)=>{i({page:f,totalPages:y,totalRecords:v})},[]),h=p.useCallback((f,y,v)=>{o({page:f,totalPages:y,totalRecords:v})},[]),x=p.useCallback((f,y)=>{f>=1&&f<=t.totalPages&&(s(v=>({...v,page:f})),y(f))},[t.totalPages]),u=p.useCallback((f,y)=>{f>=1&&f<=a.totalPages&&(r(v=>({...v,page:f})),y(f))},[a.totalPages]),g=p.useCallback((f,y)=>{f>=1&&f<=n.totalPages&&(i(v=>({...v,page:f})),y(f))},[n.totalPages]),b=p.useCallback((f,y)=>{f>=1&&f<=l.totalPages&&(o(v=>({...v,page:f})),y(f))},[l.totalPages]);return{activity:t,critical:a,deadlines:n,approver:l,updateActivityPagination:c,updateCriticalPagination:d,updateDeadlinesPagination:m,updateApproverPagination:h,handleActivityPageChange:x,handleCriticalPageChange:u,handleDeadlinesPageChange:g,handleApproverPageChange:b}}class my{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 je.get("/dashboard/kpis",{params:i})).data.data}catch(i){throw console.error("Failed to fetch KPIs:",i),i}}async getRequestStats(s,a,r,n,i,l,o,c,d,m,h,x,u){try{const g={dateRange:s};return s==="custom"&&a&&r&&(g.startDate=a,g.endDate=r),n&&n!=="all"&&(g.status=n),i&&i!=="all"&&(g.priority=i),l&&l!=="all"&&(g.templateType=l),o&&o!=="all"&&(g.department=o),c&&c!=="all"&&(g.initiator=c),d&&d!=="all"&&(g.approver=d),m&&(g.approverType=m),h&&(g.search=h),x&&x!=="all"&&(g.slaCompliance=x),u&&(g.viewAsUser="true"),(await je.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 je.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 je.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 je.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 je.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 je.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 je.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 je.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 je.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 je.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 je.get("/dashboard/stats/ai-remark-utilization",{params:n})).data.data}catch(n){throw console.error("Failed to fetch AI remark utilization:",n),n}}async getApproverPerformance(s,a=1,r=10,n,i,l,o){try{const c={dateRange:s,page:a,limit:r||10};s==="custom"&&n&&i&&(c.startDate=n.toISOString(),c.endDate=i.toISOString()),l&&l!=="all"&&(c.priority=l),o&&o!=="all"&&(c.slaCompliance=o),console.log("[Dashboard Service] Fetching approver performance with params:",c);const d=await je.get("/dashboard/stats/approver-performance",{params:c});return{performance:d.data.data,pagination:d.data.pagination}}catch(c){throw console.error("Failed to fetch approver performance:",c),c}}async getLifecycleReport(s=1,a=50,r,n,i){try{const l={page:s,limit:a};r&&(l.dateRange=r),r==="custom"&&n&&i&&(l.startDate=n.toISOString(),l.endDate=i.toISOString());const o=await je.get("/dashboard/reports/lifecycle",{params:l});return{lifecycleData:o.data.data,pagination:o.data.pagination}}catch(l){throw console.error("Failed to fetch lifecycle report:",l),l}}async getActivityLogReport(s=1,a=50,r,n,i,l,o,c,d){try{const m={page:s,limit:a,filterUserId:n,filterType:i,filterCategory:l,filterSeverity:o};r&&(m.dateRange=r),r==="custom"&&c&&d&&(m.startDate=c.toISOString(),m.endDate=d.toISOString());const h=await je.get("/dashboard/reports/activity-log",{params:m});return{activities:h.data.data,pagination:h.data.pagination}}catch(m){throw console.error("Failed to fetch activity log report:",m),m}}async getDepartments(){try{return(await je.get("/dashboard/metadata/departments")).data.data.departments||[]}catch(s){throw console.error("Failed to fetch departments:",s),s}}async getWorkflowAgingReport(s=7,a=1,r=50,n,i,l){try{const o={threshold:s,page:a,limit:r};n&&(o.dateRange=n),n==="custom"&&i&&l&&(o.startDate=i.toISOString(),o.endDate=l.toISOString());const c=await je.get("/dashboard/reports/workflow-aging",{params:o});return{agingData:c.data.data,pagination:c.data.pagination}}catch(o){throw console.error("Failed to fetch workflow aging report:",o),o}}async getSingleApproverStats(s,a,r,n,i,l){try{const o={approverId:s};return a&&(o.dateRange=a),a==="custom"&&r&&n&&(o.startDate=r.toISOString(),o.endDate=n.toISOString()),i&&i!=="all"&&(o.priority=i),l&&l!=="all"&&(o.slaCompliance=l),(await je.get("/dashboard/stats/single-approver",{params:o})).data.data}catch(o){throw console.error("Failed to fetch single approver stats:",o),o}}async getRequestsByApprover(s,a=1,r=50,n,i,l,o,c,d,m){try{const h={approverId:s,page:a,limit:r};n&&(h.dateRange=n),n==="custom"&&i&&l&&(h.startDate=i.toISOString(),h.endDate=l.toISOString()),o&&(h.status=o),c&&(h.priority=c),d&&(h.slaCompliance=d),m&&(h.search=m);const x=await je.get("/dashboard/requests/by-approver",{params:h});return{requests:x.data.data,pagination:x.data.pagination}}catch(h){throw console.error("Failed to fetch requests by approver:",h),h}}}const At=new my;function uy({isAdmin:t,viewAsUser:s=!1,userId:a,dateRange:r,customStartDate:n,customEndDate:i,onPaginationUpdate:l}){const[o,c]=p.useState(null),[d,m]=p.useState([]),[h,x]=p.useState([]),[u,g]=p.useState([]),[b,f]=p.useState([]),[y,v]=p.useState([]),[w,C]=p.useState(null),[k,S]=p.useState([]),[_,D]=p.useState(!0),[A,N]=p.useState(!1),P=p.useRef(l);P.current=l;const R=p.useCallback(async(T=!1)=>{try{T?N(!0):D(!0);const j=[At.getKPIs(r,n,i,s),At.getRecentActivity(1,10,s),At.getCriticalRequests(1,10,s),At.getUpcomingDeadlines(1,10,s)],U=!t&&a?At.getRequestStats(r,n==null?void 0:n.toISOString(),i==null?void 0:i.toISOString(),void 0,void 0,void 0,void 0,a,void 0,void 0,void 0,void 0,s):null,I=t?[At.getDepartmentStats(r,n,i),At.getPriorityDistribution(r,n,i),At.getAIRemarkUtilization(r,n,i),At.getApproverPerformance(r,1,10,n,i)]:[],[M,W,G]=await Promise.all([Promise.all(j),U,Promise.all(I)]),ce=M[0],te=M[1],L=M[2],z=M[3];if(!t&&W&&(ce.requestVolume=W),c(ce),m(te.activities),P.current.activity(te.pagination.currentPage,te.pagination.totalPages,te.pagination.totalRecords),x(L.criticalRequests),P.current.critical(L.pagination.currentPage,L.pagination.totalPages,L.pagination.totalRecords),v(z.deadlines),P.current.deadlines(z.pagination.currentPage,z.pagination.totalPages,z.pagination.totalRecords),t&&G.length>=4){const H=G[0],ye=G[1],ae=G[2],me=G[3];g(H),f(ye),C(ae),S(me.performance),P.current.approver(me.pagination.currentPage,me.pagination.totalPages,me.pagination.totalRecords)}else t||(g([]),f([]),C(null),S([]))}catch(j){console.error("Failed to fetch dashboard data:",j)}finally{D(!1),N(!1)}},[t,s,a,r,n,i]),O=p.useCallback(async(T=1)=>{try{const j=await At.getRecentActivity(T,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]),F=p.useCallback(async(T=1)=>{try{const j=await At.getCriticalRequests(T,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]),$=p.useCallback(async(T=1)=>{try{const j=await At.getUpcomingDeadlines(T,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]),V=p.useCallback(async(T=1)=>{try{const j=await At.getApproverPerformance(r,T,10,n,i);S(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:d,criticalRequests:h,departmentStats:u,priorityDistribution:b,upcomingDeadlines:y,aiRemarkUtilization:w,approverPerformance:k,loading:_,refreshing:A,fetchDashboardData:R,fetchRecentActivities:O,fetchCriticalRequests:F,fetchUpcomingDeadlines:$,fetchApproverPerformance:V}}const Aa={appName:"Royal Enfield Workflow Management",appVersion:"1.2.0",workingHours:{START_HOUR:9,END_HOUR:18,START_DAY:1,END_DAY:5,TIMEZONE:"Asia/Kolkata"},tat:{thresholds:{warning:50,critical:75,breach:100},testMode:!1},upload:{maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"],maxFilesPerRequest:10},workflow:{maxApprovalLevels:10,maxParticipants:50,maxSpectators:20},workNotes:{maxMessageLength:2e3,maxAttachmentsPerNote:5,enableReactions:!0,enableMentions:!0},features:{ENABLE_AI_CONCLUSION:!0,ENABLE_TEMPLATES:!1,ENABLE_ANALYTICS:!0,ENABLE_EXPORT:!0},ui:{DEFAULT_THEME:"light",DEFAULT_LANGUAGE:"en",DATE_FORMAT:"DD/MM/YYYY",TIME_FORMAT:"12h",CURRENCY:"INR",CURRENCY_SYMBOL:"₹"}};class xy{constructor(){Ui(this,"config",null);Ui(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 je.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...Aa,...r,workingHours:{...Aa.workingHours,...r.workingHours},tat:{...Aa.tat,...r.tat},upload:{...Aa.upload,...r.upload},workflow:{...Aa.workflow,...r.workflow},workNotes:{...Aa.workNotes,...r.workNotes},features:{...Aa.features,...r.features},ui:{...Aa.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),Aa}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const hy=new xy;let py=9,gy=18,fy=1,by=5,Wd=!1;async function yy(){if(!Wd)try{const t=await hy.getConfig();py=t.workingHours.START_HOUR,gy=t.workingHours.END_HOUR,fy=t.workingHours.START_DAY,by=t.workingHours.END_DAY,Wd=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}yy().catch(()=>{});function Ft(t){if(t==null||t<0||t===0)return"0 hours";const s=8;if(t<1){const o=Math.round(t*60);return o>0?`${o}m`:"0 hours"}const a=Math.floor(t/s),r=Math.floor(t%s),n=Math.round(t%1*60);if(a>0){const o=a===1?"day":"days",c=r===1?"hour":"hours",d=n===1?"min":"m";return n>0?`${a} ${o} ${r} ${c} ${n}${d}`:`${a} ${o} ${r} ${c}`}const i=r===1?"hour":"hours",l=n===1?"min":"m";return n>0?`${r} ${i} ${n}${l}`:`${r} ${i}`}async function vy(t,s,a){const r=[];let n=1,i=!0;const l=100;for(;i&&n<=l;){const x=await At.getApproverPerformance(t,n,100,s,a);x.performance&&x.performance.length>0?(r.push(...x.performance),n++,i=n<=x.pagination.totalPages):i=!1}const o=[["Approver Name","Total Approved","TAT Compliance (%)","Avg Response Time","Pending Count"].join(",")];r.forEach(x=>{const u=[`"${(x.approverName||"Unknown").replace(/"/g,'""')}"`,x.totalApproved||0,x.tatCompliancePercent||0,Ft(x.avgResponseHours),x.pendingCount||0];o.push(u.join(","))});const c=o.join(`
`),d=new Blob([c],{type:"text/csv;charset=utf-8;"}),m=document.createElement("a"),h=URL.createObjectURL(d);m.setAttribute("href",h),m.setAttribute("download",`approver-performance-report-${new Date().toISOString().split("T")[0]}.csv`),m.style.visibility="hidden",document.body.appendChild(m),m.click(),document.body.removeChild(m),URL.revokeObjectURL(h)}async function jy(t,s,a){const r=await At.getDepartmentStats(t,s,a),n=[["Department","Total Requests","Approved","Rejected","In Progress","Approval Rate (%)"].join(",")];r.forEach(d=>{const m=[`"${(d.department||"Unknown").replace(/"/g,'""')}"`,d.totalRequests||0,d.approved||0,d.rejected||0,d.inProgress||0,d.approvalRate||0];n.push(m.join(","))});const i=n.join(`
`),l=new Blob([i],{type:"text/csv;charset=utf-8;"}),o=document.createElement("a"),c=URL.createObjectURL(l);o.setAttribute("href",c),o.setAttribute("download",`department-workflow-summary-${new Date().toISOString().split("T")[0]}.csv`),o.style.visibility="hidden",document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(c)}function Ny(){const[t,s]=p.useState(!1),[a,r]=p.useState(!1),n=p.useCallback(async(l,o,c)=>{try{s(!0),await jy(l,o,c)}catch(d){console.error("Failed to export department stats:",d),alert("Failed to export department statistics. Please try again.")}finally{s(!1)}},[]),i=p.useCallback(async(l,o,c)=>{try{r(!0),await vy(l,o,c)}catch(d){console.error("Failed to export approver performance:",d),alert("Failed to export approver performance data. Please try again.")}finally{r(!1)}},[]);return{exportingDeptStats:t,exportingApproverPerformance:a,handleExportDepartmentStats:n,handleExportApproverPerformance:i}}function on({className:t,...s}){return e.jsx(Fg,{"data-slot":"switch",className:ke("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(_g,{"data-slot":"switch-thumb",className:ke("bg-card dark:data-[state=unchecked]:bg-card-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}function re({className:t,...s}){return e.jsx(Lg,{"data-slot":"label",className:ke("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 wy({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(ee,{className:"relative overflow-hidden shadow-xl border-0","data-testid":"dashboard-hero",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsxs(se,{className:"relative z-10 p-4 sm:p-6 lg:p-12",children:[t&&e.jsx("div",{className:"absolute top-4 right-4 sm:top-6 sm:right-6 z-20","data-testid":"view-toggle",children:e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 p-1.5 sm:p-2 bg-white/10 backdrop-blur-sm rounded-lg border border-white/20 shadow-lg",children:[e.jsxs("div",{className:`flex items-center gap-1 sm:gap-1.5 px-1.5 sm:px-2 py-0.5 sm:py-1 rounded transition-all cursor-pointer ${a?"opacity-60 hover:opacity-80":"bg-red-600/20 border border-red-600/50"}`,onClick:()=>r(!1),children:[e.jsx(mo,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(re,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-gray-300":"text-red-600"}`,children:"Org"})]}),e.jsx(on,{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(Vt,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(re,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-red-600":"text-gray-300"}`,children:"Personal"})]})]})}),e.jsx("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 sm:gap-6",children:e.jsxs("div",{className:`text-white w-full lg:w-auto ${t?"pt-12 sm:pt-0":""}`,children:[e.jsx("div",{className:"flex items-center gap-3 sm:gap-4 mb-4 sm:mb-6",children:e.jsxs("div",{className:"pr-2 sm:pr-0",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl lg:text-4xl font-bold mb-1 sm:mb-2 text-white","data-testid":"hero-title",children:["Welcome, ",o,"!"]}),e.jsx("p",{className:"text-sm sm:text-lg lg:text-xl text-gray-200","data-testid":"hero-subtitle",children:s?"Organization-wide analytics and insights":"Track your requests and approvals"})]})}),e.jsx("div",{className:"flex flex-wrap gap-2 sm:gap-4 mt-4 sm:mt-8","data-testid":"quick-actions",children:n.map((c,d)=>e.jsxs(E,{onClick:c.action,className:`${c.color} text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200`,size:window.innerWidth<640?"sm":"lg","data-testid":`quick-action-${c.label.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsx(c.icon,{className:"w-4 h-4 sm:w-5 sm:h-5 mr-1 sm:mr-2"}),c.label]},d))})]})})]})]})}function We({...t}){return e.jsx(Mg,{"data-slot":"select",...t})}function Ge({...t}){return e.jsx(Ug,{"data-slot":"select-value",...t})}function Ye({className:t,size:s="default",children:a,...r}){return e.jsxs($g,{"data-slot":"select-trigger","data-size":s,className:ke("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(Og,{asChild:!0,children:e.jsx(uo,{className:"size-4 opacity-50"})})]})}function Ke({className:t,children:s,position:a="popper",...r}){return e.jsx(Bg,{children:e.jsxs(Vg,{"data-slot":"select-content",className:ke("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(Cy,{}),e.jsx(zg,{className:ke("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(Sy,{})]})})}function Y({className:t,children:s,...a}){return e.jsxs(Hg,{"data-slot":"select-item",className:ke("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(yr,{className:"size-4"})})}),e.jsx(Gg,{children:s})]})}function Cy({className:t,...s}){return e.jsx(Yg,{"data-slot":"select-scroll-up-button",className:ke("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Xu,{className:"size-4"})})}function Sy({className:t,...s}){return e.jsx(Kg,{"data-slot":"select-scroll-down-button",className:ke("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(uo,{className:"size-4"})})}function Ts({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(Xg,{"data-slot":"separator-root",decorative:a,orientation:s,className:ke("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 Hs({...t}){return e.jsx(Zg,{"data-slot":"popover",...t})}function Ws({...t}){return e.jsx(Jg,{"data-slot":"popover-trigger",...t})}function Gs({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(Qg,{children:e.jsx(qg,{"data-slot":"popover-content",align:s,sideOffset:a,className:ke("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 Qe=function(){return Qe=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},Qe.apply(this,arguments)};function Ay(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 Rx(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 An(t){return t.mode==="multiple"}function Tn(t){return t.mode==="range"}function Pi(t){return t.mode==="single"}var Ty={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 ky(t,s){return He(t,"LLLL y",s)}function Ry(t,s){return He(t,"d",s)}function Dy(t,s){return He(t,"LLLL",s)}function Py(t){return"".concat(t)}function Iy(t,s){return He(t,"cccccc",s)}function Ey(t,s){return He(t,"yyyy",s)}var Fy=Object.freeze({__proto__:null,formatCaption:ky,formatDay:Ry,formatMonthCaption:Dy,formatWeekNumber:Py,formatWeekdayName:Iy,formatYearCaption:Ey}),_y=function(t,s,a){return He(t,"do MMMM (EEEE)",a)},Ly=function(){return"Month: "},My=function(){return"Go to next month"},$y=function(){return"Go to previous month"},Oy=function(t,s){return He(t,"cccc",s)},Uy=function(t){return"Week n. ".concat(t)},By=function(){return"Year: "},Vy=Object.freeze({__proto__:null,labelDay:_y,labelMonthDropdown:Ly,labelNext:My,labelPrevious:$y,labelWeekNumber:Uy,labelWeekday:Oy,labelYearDropdown:By});function zy(){var t="buttons",s=Ty,a=kf,r={},n={},i=1,l={},o=new Date;return{captionLayout:t,classNames:s,formatters:Fy,labels:Vy,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:l,today:o,mode:"default"}}function Hy(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,l=t.toDate;return r?i=Vs(r):s&&(i=new Date(s,0,1)),n?l=io(n):a&&(l=new Date(a,11,31)),{fromDate:i?kd(i):void 0,toDate:l?kd(l):void 0}}var Dx=p.createContext(void 0);function Wy(t){var s,a=t.initialProps,r=zy(),n=Hy(a),i=n.fromDate,l=n.toDate,o=(s=a.captionLayout)!==null&&s!==void 0?s:r.captionLayout;o!=="buttons"&&(!i||!l)&&(o="buttons");var c;(Pi(a)||An(a)||Tn(a))&&(c=a.onSelect);var d=Qe(Qe(Qe({},r),a),{captionLayout:o,classNames:Qe(Qe({},r.classNames),a.classNames),components:Qe({},a.components),formatters:Qe(Qe({},r.formatters),a.formatters),fromDate:i,labels:Qe(Qe({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:Qe(Qe({},r.modifiers),a.modifiers),modifiersClassNames:Qe(Qe({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:Qe(Qe({},r.styles),a.styles),toDate:l});return e.jsx(Dx.Provider,{value:d,children:t.children})}function Rt(){var t=p.useContext(Dx);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function Px(t){var s=Rt(),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 Gy(t){return e.jsx("svg",Qe({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 Ix(t){var s,a,r=t.onChange,n=t.value,i=t.children,l=t.caption,o=t.className,c=t.style,d=Rt(),m=(a=(s=d.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:Gy;return e.jsxs("div",{className:o,style:c,children:[e.jsx("span",{className:d.classNames.vhidden,children:t["aria-label"]}),e.jsx("select",{name:t.name,"aria-label":t["aria-label"],className:d.classNames.dropdown,style:d.styles.dropdown,value:n,onChange:r,children:i}),e.jsxs("div",{className:d.classNames.caption_label,style:d.styles.caption_label,"aria-hidden":"true",children:[l,e.jsx(m,{className:d.classNames.dropdown_icon,style:d.styles.dropdown_icon})]})]})}function Yy(t){var s,a=Rt(),r=a.fromDate,n=a.toDate,i=a.styles,l=a.locale,o=a.formatters.formatMonthCaption,c=a.classNames,d=a.components,m=a.labels.labelMonthDropdown;if(!r)return e.jsx(e.Fragment,{});if(!n)return e.jsx(e.Fragment,{});var h=[];if(Ff(r,n))for(var x=Vs(r),u=r.getMonth();u<=n.getMonth();u++)h.push(Vi(x,u));else for(var x=Vs(new Date),u=0;u<=11;u++)h.push(Vi(x,u));var g=function(f){var y=Number(f.target.value),v=Vi(Vs(t.displayMonth),y);t.onChange(v)},b=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Ix;return e.jsx(b,{name:"months","aria-label":m(),className:c.dropdown_month,style:i.dropdown_month,onChange:g,value:t.displayMonth.getMonth(),caption:o(t.displayMonth,{locale:l}),children:h.map(function(f){return e.jsx("option",{value:f.getMonth(),children:o(f,{locale:l})},f.getMonth())})})}function Ky(t){var s,a=t.displayMonth,r=Rt(),n=r.fromDate,i=r.toDate,l=r.locale,o=r.styles,c=r.classNames,d=r.components,m=r.formatters.formatYearCaption,h=r.labels.labelYearDropdown,x=[];if(!n)return e.jsx(e.Fragment,{});if(!i)return e.jsx(e.Fragment,{});for(var u=n.getFullYear(),g=i.getFullYear(),b=u;b<=g;b++)x.push(Rd(_f(new Date),b));var f=function(v){var w=Rd(Vs(a),Number(v.target.value));t.onChange(w)},y=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Ix;return e.jsx(y,{name:"years","aria-label":h(),className:c.dropdown_year,style:o.dropdown_year,onChange:f,value:a.getFullYear(),caption:m(a,{locale:l}),children:x.map(function(v){return e.jsx("option",{value:v.getFullYear(),children:m(v,{locale:l})},v.getFullYear())})})}function Xy(t,s){var a=p.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function Zy(t){var s=t.month,a=t.defaultMonth,r=t.today,n=s||a||r||new Date,i=t.toDate,l=t.fromDate,o=t.numberOfMonths,c=o===void 0?1:o;if(i&&hn(i,n)<0){var d=-1*(c-1);n=ja(i,d)}return l&&hn(n,l)<0&&(n=l),Vs(n)}function Jy(){var t=Rt(),s=Zy(t),a=Xy(s,t.month),r=a[0],n=a[1],i=function(l){var o;if(!t.disableNavigation){var c=Vs(l);n(c),(o=t.onMonthChange)===null||o===void 0||o.call(t,c)}};return[r,i]}function Qy(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=Vs(t),i=Vs(ja(n,r)),l=hn(i,n),o=[],c=0;c<l;c++){var d=ja(n,c);o.push(d)}return a&&(o=o.reverse()),o}function qy(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=Vs(t);if(!a)return ja(o,l);var c=hn(a,t);if(!(c<i))return ja(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=Vs(t);if(!a)return ja(o,-l);var c=hn(o,a);if(!(c<=0))return ja(o,-l)}}var Ex=p.createContext(void 0);function tv(t){var s=Rt(),a=Jy(),r=a[0],n=a[1],i=Qy(r,s),l=qy(r,s),o=ev(r,s),c=function(h){return i.some(function(x){return lo(h,x)})},d=function(h,x){c(h)||(x&&Hu(h,x)?n(ja(h,1+s.numberOfMonths*-1)):n(h))},m={currentMonth:r,displayMonths:i,goToMonth:n,goToDate:d,previousMonth:o,nextMonth:l,isDateDisplayed:c};return e.jsx(Ex.Provider,{value:m,children:t.children})}function kn(){var t=p.useContext(Ex);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function Gd(t){var s,a=Rt(),r=a.classNames,n=a.styles,i=a.components,l=kn().goToMonth,o=function(m){l(ja(m,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:Px,d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth});return e.jsxs("div",{className:r.caption_dropdowns,style:n.caption_dropdowns,children:[e.jsx("div",{className:r.vhidden,children:d}),e.jsx(Yy,{onChange:o,displayMonth:t.displayMonth}),e.jsx(Ky,{onChange:o,displayMonth:t.displayMonth})]})}function sv(t){return e.jsx("svg",Qe({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",Qe({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 oi=p.forwardRef(function(t,s){var a=Rt(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var l=i.join(" "),o=Qe(Qe({},n.button_reset),n.button);return t.style&&Object.assign(o,t.style),e.jsx("button",Qe({},t,{ref:s,type:"button",className:l,style:o}))});function rv(t){var s,a,r=Rt(),n=r.dir,i=r.locale,l=r.classNames,o=r.styles,c=r.labels,d=c.labelPrevious,m=c.labelNext,h=r.components;if(!t.nextMonth&&!t.previousMonth)return e.jsx(e.Fragment,{});var x=d(t.previousMonth,{locale:i}),u=[l.nav_button,l.nav_button_previous].join(" "),g=m(t.nextMonth,{locale:i}),b=[l.nav_button,l.nav_button_next].join(" "),f=(s=h==null?void 0:h.IconRight)!==null&&s!==void 0?s:av,y=(a=h==null?void 0:h.IconLeft)!==null&&a!==void 0?a:sv;return e.jsxs("div",{className:l.nav,style:o.nav,children:[!t.hidePrevious&&e.jsx(oi,{name:"previous-month","aria-label":x,className:u,style:o.nav_button_previous,disabled:!t.previousMonth,onClick:t.onPreviousClick,children:n==="rtl"?e.jsx(f,{className:l.nav_icon,style:o.nav_icon}):e.jsx(y,{className:l.nav_icon,style:o.nav_icon})}),!t.hideNext&&e.jsx(oi,{name:"next-month","aria-label":g,className:b,style:o.nav_button_next,disabled:!t.nextMonth,onClick:t.onNextClick,children:n==="rtl"?e.jsx(y,{className:l.nav_icon,style:o.nav_icon}):e.jsx(f,{className:l.nav_icon,style:o.nav_icon})})]})}function Yd(t){var s=Rt().numberOfMonths,a=kn(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,l=a.displayMonths,o=l.findIndex(function(g){return lo(t.displayMonth,g)}),c=o===0,d=o===l.length-1,m=s>1&&(c||!d),h=s>1&&(d||!c),x=function(){r&&i(r)},u=function(){n&&i(n)};return e.jsx(rv,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:h,nextMonth:n,previousMonth:r,onPreviousClick:x,onNextClick:u})}function nv(t){var s,a=Rt(),r=a.classNames,n=a.disableNavigation,i=a.styles,l=a.captionLayout,o=a.components,c=(s=o==null?void 0:o.CaptionLabel)!==null&&s!==void 0?s:Px,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):l==="dropdown"?d=e.jsx(Gd,{displayMonth:t.displayMonth,id:t.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Gd,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(Yd,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id})]}):d=e.jsxs(e.Fragment,{children:[e.jsx(c,{id:t.id,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(Yd,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function iv(t){var s=Rt(),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?oo(new Date):co(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var l=Us(r,i);n.push(l)}return n}function ov(){var t=Rt(),s=t.classNames,a=t.styles,r=t.showWeekNumber,n=t.locale,i=t.weekStartsOn,l=t.ISOWeek,o=t.formatters.formatWeekdayName,c=t.labels.labelWeekday,d=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}),d.map(function(m,h){return e.jsx("th",{scope:"col",className:s.head_cell,style:a.head_cell,"aria-label":c(m,{locale:n}),children:o(m,{locale:n})},h)})]})}function cv(){var t,s=Rt(),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=Rt(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var So=p.createContext(void 0);function mv(t){if(!An(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(So.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(d,m,h){var x,u;(x=s.onDayClick)===null||x===void 0||x.call(s,d,m,h);var g=!!(m.selected&&n&&(r==null?void 0:r.length)===n);if(!g){var b=!!(!m.selected&&i&&(r==null?void 0:r.length)===i);if(!b){var f=r?Rx([],r):[];if(m.selected){var y=f.findIndex(function(v){return _s(d,v)});f.splice(y,1)}else f.push(d);(u=s.onSelect)===null||u===void 0||u.call(s,f,d,m,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var m=i&&r.length>i-1,h=r.some(function(x){return _s(x,d)});return!!(m&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(So.Provider,{value:c,children:a})}function Ao(){var t=p.useContext(So);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?_s(n,t)&&_s(r,t)?void 0:_s(n,t)?{from:n,to:void 0}:_s(r,t)?void 0:Dl(r,t)?{from:t,to:n}:{from:r,to:t}:n?Dl(t,n)?{from:n,to:t}:{from:t,to:n}:r?Hu(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var To=p.createContext(void 0);function hv(t){if(!Tn(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(To.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,c=s.max,d=function(u,g,b){var f,y;(f=s.onDayClick)===null||f===void 0||f.call(s,u,g,b);var v=xv(u,r);(y=s.onSelect)===null||y===void 0||y.call(s,v,u,g,b)},m={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(m.range_start=[i],l?(m.range_end=[l],_s(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:Bi(i,o-1),before:Us(i,o-1)}),i&&l&&m.disabled.push({after:i,before:Us(i,o-1)}),!i&&l&&m.disabled.push({after:Bi(l,o-1),before:Us(l,o-1)})),c){if(i&&!l&&(m.disabled.push({before:Us(i,-c+1)}),m.disabled.push({after:Us(i,c-1)})),i&&l){var h=ka(l,i)+1,x=c-h;m.disabled.push({before:Bi(i,x)}),m.disabled.push({after:Us(l,x)})}!i&&l&&(m.disabled.push({before:Us(l,-c+1)}),m.disabled.push({after:Us(l,c-1)}))}return e.jsx(To.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function ko(){var t=p.useContext(To);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function Gn(t){return Array.isArray(t)?Rx([],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]=Gn(n)}),s}var ua;(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"})(ua||(ua={}));var fv=ua.Selected,Ta=ua.Disabled,bv=ua.Hidden,yv=ua.Today,Qi=ua.RangeEnd,qi=ua.RangeMiddle,el=ua.RangeStart,vv=ua.Outside;function jv(t,s,a){var r,n=(r={},r[fv]=Gn(t.selected),r[Ta]=Gn(t.disabled),r[bv]=Gn(t.hidden),r[yv]=[t.today],r[Qi]=[],r[qi]=[],r[el]=[],r[vv]=[],r);return t.fromDate&&n[Ta].push({before:t.fromDate}),t.toDate&&n[Ta].push({after:t.toDate}),An(t)?n[Ta]=n[Ta].concat(s.modifiers[Ta]):Tn(t)&&(n[Ta]=n[Ta].concat(a.modifiers[Ta]),n[el]=a.modifiers[el],n[qi]=a.modifiers[qi],n[Qi]=a.modifiers[Qi]),n}var Fx=p.createContext(void 0);function Nv(t){var s=Rt(),a=Ao(),r=ko(),n=jv(s,a,r),i=gv(s.modifiers),l=Qe(Qe({},n),i);return e.jsx(Fx.Provider,{value:l,children:t.children})}function _x(){var t=p.useContext(Fx);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 Sv(t){return!!(t&&typeof t=="object"&&"after"in t)}function Av(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=ka(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var l=ka(t,r)>=0&&ka(n,t)>=0;return l}return n?_s(n,t):r?_s(r,t):!1}function Rv(t){return Yu(t)}function Dv(t){return Array.isArray(t)&&t.every(Yu)}function Pv(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(Rv(a))return _s(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=ka(a.before,t),n=ka(a.after,t),i=r>0,l=n<0,o=Dl(a.before,a.after);return o?l&&i:i||l}return Sv(a)?ka(t,a.after)>0:Av(a)?ka(a.before,t)>0:typeof a=="function"?a(t):!1})}function Ro(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&&!lo(t,a)&&(n.outside=!0),n}function Iv(t,s){for(var a=Vs(t[0]),r=io(t[t.length-1]),n,i,l=a;l<=r;){var o=Ro(l,s),c=!o.disabled&&!o.hidden;if(!c){l=Us(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),n||(n=l),l=Us(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,c=n.weekStartsOn,d=n.fromDate,m=n.toDate,h=n.locale,x={day:Us,week:Rl,month:ja,year:Pf,startOfWeek:function(f){return n.ISOWeek?oo(f):co(f,{locale:h,weekStartsOn:c})},endOfWeek:function(f){return n.ISOWeek?Wu(f):Gu(f,{locale:h,weekStartsOn:c})}},u=x[a](t,r==="after"?1:-1);r==="before"&&d?u=If([d,u]):r==="after"&&m&&(u=Ef([m,u]));var g=!0;if(i){var b=Ro(u,i);g=!b.disabled&&!b.hidden}return g?u:o.count>Ev?o.lastFocused:Lx(u,{moveBy:a,direction:r,context:n,modifiers:i,retry:Qe(Qe({},o),{count:o.count+1})})}var Mx=p.createContext(void 0);function Fv(t){var s=kn(),a=_x(),r=p.useState(),n=r[0],i=r[1],l=p.useState(),o=l[0],c=l[1],d=Iv(s.displayMonths,a),m=n??(o&&s.isDateDisplayed(o))?o:d,h=function(){c(n),i(void 0)},x=function(f){i(f)},u=Rt(),g=function(f,y){if(n){var v=Lx(n,{moveBy:f,direction:y,context:u,modifiers:a});_s(n,v)||(s.goToDate(v,n),x(v))}},b={focusedDay:n,focusTarget:m,blur:h,focus:x,focusDayAfter:function(){return g("day","after")},focusDayBefore:function(){return g("day","before")},focusWeekAfter:function(){return g("week","after")},focusWeekBefore:function(){return g("week","before")},focusMonthBefore:function(){return g("month","before")},focusMonthAfter:function(){return g("month","after")},focusYearBefore:function(){return g("year","before")},focusYearAfter:function(){return g("year","after")},focusStartOfWeek:function(){return g("startOfWeek","before")},focusEndOfWeek:function(){return g("endOfWeek","after")}};return e.jsx(Mx.Provider,{value:b,children:t.children})}function Do(){var t=p.useContext(Mx);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function _v(t,s){var a=_x(),r=Ro(t,a,s);return r}var Po=p.createContext(void 0);function Lv(t){if(!Pi(t.initialProps)){var s={selected:void 0};return e.jsx(Po.Provider,{value:s,children:t.children})}return e.jsx(Mv,{initialProps:t.initialProps,children:t.children})}function Mv(t){var s=t.initialProps,a=t.children,r=function(i,l,o){var c,d,m;if((c=s.onDayClick)===null||c===void 0||c.call(s,i,l,o),l.selected&&!s.required){(d=s.onSelect)===null||d===void 0||d.call(s,void 0,i,l,o);return}(m=s.onSelect)===null||m===void 0||m.call(s,i,i,l,o)},n={selected:s.selected,onDayClick:r};return e.jsx(Po.Provider,{value:n,children:a})}function $x(){var t=p.useContext(Po);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function $v(t,s){var a=Rt(),r=$x(),n=Ao(),i=ko(),l=Do(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,m=l.focusWeekBefore,h=l.blur,x=l.focus,u=l.focusMonthBefore,g=l.focusMonthAfter,b=l.focusYearBefore,f=l.focusYearAfter,y=l.focusStartOfWeek,v=l.focusEndOfWeek,w=function(T){var j,U,I,M;Pi(a)?(j=r.onDayClick)===null||j===void 0||j.call(r,t,s,T):An(a)?(U=n.onDayClick)===null||U===void 0||U.call(n,t,s,T):Tn(a)?(I=i.onDayClick)===null||I===void 0||I.call(i,t,s,T):(M=a.onDayClick)===null||M===void 0||M.call(a,t,s,T)},C=function(T){var j;x(t),(j=a.onDayFocus)===null||j===void 0||j.call(a,t,s,T)},k=function(T){var j;h(),(j=a.onDayBlur)===null||j===void 0||j.call(a,t,s,T)},S=function(T){var j;(j=a.onDayMouseEnter)===null||j===void 0||j.call(a,t,s,T)},_=function(T){var j;(j=a.onDayMouseLeave)===null||j===void 0||j.call(a,t,s,T)},D=function(T){var j;(j=a.onDayPointerEnter)===null||j===void 0||j.call(a,t,s,T)},A=function(T){var j;(j=a.onDayPointerLeave)===null||j===void 0||j.call(a,t,s,T)},N=function(T){var j;(j=a.onDayTouchCancel)===null||j===void 0||j.call(a,t,s,T)},P=function(T){var j;(j=a.onDayTouchEnd)===null||j===void 0||j.call(a,t,s,T)},R=function(T){var j;(j=a.onDayTouchMove)===null||j===void 0||j.call(a,t,s,T)},O=function(T){var j;(j=a.onDayTouchStart)===null||j===void 0||j.call(a,t,s,T)},F=function(T){var j;(j=a.onDayKeyUp)===null||j===void 0||j.call(a,t,s,T)},$=function(T){var j;switch(T.key){case"ArrowLeft":T.preventDefault(),T.stopPropagation(),a.dir==="rtl"?o():c();break;case"ArrowRight":T.preventDefault(),T.stopPropagation(),a.dir==="rtl"?c():o();break;case"ArrowDown":T.preventDefault(),T.stopPropagation(),d();break;case"ArrowUp":T.preventDefault(),T.stopPropagation(),m();break;case"PageUp":T.preventDefault(),T.stopPropagation(),T.shiftKey?b():u();break;case"PageDown":T.preventDefault(),T.stopPropagation(),T.shiftKey?f():g();break;case"Home":T.preventDefault(),T.stopPropagation(),y();break;case"End":T.preventDefault(),T.stopPropagation(),v();break}(j=a.onDayKeyDown)===null||j===void 0||j.call(a,t,s,T)},V={onClick:w,onFocus:C,onBlur:k,onKeyDown:$,onKeyUp:F,onMouseEnter:S,onMouseLeave:_,onPointerEnter:D,onPointerLeave:A,onTouchCancel:N,onTouchEnd:P,onTouchMove:R,onTouchStart:O};return V}function Ov(){var t=Rt(),s=$x(),a=Ao(),r=ko(),n=Pi(t)?s.selected:An(t)?a.selected:Tn(t)?r.selected:void 0;return n}function Uv(t){return Object.values(ua).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=Qe({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=Qe(Qe({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function zv(t,s,a){var r,n,i,l=Rt(),o=Do(),c=_v(t,s),d=$v(t,c),m=Ov(),h=!!(l.onDayClick||l.mode!=="default");p.useEffect(function(){var S;c.outside||o.focusedDay&&h&&_s(o.focusedDay,t)&&((S=a.current)===null||S===void 0||S.focus())},[o.focusedDay,t,a,h,c.outside]);var x=Bv(l,c).join(" "),u=Vv(l,c),g=!!(c.outside&&!l.showOutsideDays||c.hidden),b=(i=(n=l.components)===null||n===void 0?void 0:n.DayContent)!==null&&i!==void 0?i:dv,f=e.jsx(b,{date:t,displayMonth:s,activeModifiers:c}),y={style:u,className:x,children:f,role:"gridcell"},v=o.focusTarget&&_s(o.focusTarget,t)&&!c.outside,w=o.focusedDay&&_s(o.focusedDay,t),C=Qe(Qe(Qe({},y),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=w||v?0:-1,r)),d),k={isButton:h,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:C,divProps:y};return k}function Hv(t){var s=p.useRef(null),a=zv(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(oi,Qe({name:"day",ref:s},a.buttonProps)):e.jsx("div",Qe({},a.divProps))}function Wv(t){var s=t.number,a=t.dates,r=Rt(),n=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,m=d(Number(s),{locale:o});if(!n)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:m});var h=c(Number(s),{locale:o}),x=function(u){n(s,a,u)};return e.jsx(oi,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:x,children:m})}function Gv(t){var s,a,r=Rt(),n=r.styles,i=r.classNames,l=r.showWeekNumber,o=r.components,c=(s=o==null?void 0:o.Day)!==null&&s!==void 0?s:Hv,d=(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(d,{number:t.weekNumber,dates:t.dates})})),e.jsxs("tr",{className:i.row,style:n.row,children:[m,t.dates.map(function(h){return e.jsx("td",{className:i.cell,style:n.cell,role:"presentation",children:e.jsx(c,{displayMonth:t.displayMonth,date:h})},Df(h))})]})}function Kd(t,s,a){for(var r=a!=null&&a.ISOWeek?Wu(s):Gu(s,a),n=a!=null&&a.ISOWeek?oo(t):co(t,a),i=ka(r,n),l=[],o=0;o<=i;o++)l.push(Us(n,o));var c=l.reduce(function(d,m){var h=a!=null&&a.ISOWeek?Lf(m):Mf(m,a),x=d.find(function(u){return u.weekNumber===h});return x?(x.dates.push(m),d):(d.push({weekNumber:h,dates:[m]}),d)},[]);return c}function Yv(t,s){var a=Kd(Vs(t),io(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=Rl(i,6-r),o=Kd(Rl(i,1),l,s);a.push.apply(a,o)}}return a}function Kv(t){var s,a,r,n=Rt(),i=n.locale,l=n.classNames,o=n.styles,c=n.hideHead,d=n.fixedWeeks,m=n.components,h=n.weekStartsOn,x=n.firstWeekContainsDate,u=n.ISOWeek,g=Yv(t.displayMonth,{useFixedWeeks:!!d,ISOWeek:u,locale:i,weekStartsOn:h,firstWeekContainsDate:x}),b=(s=m==null?void 0:m.Head)!==null&&s!==void 0?s:cv,f=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:Gv,y=(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:[!c&&e.jsx(b,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:g.map(function(v){return e.jsx(f,{displayMonth:t.displayMonth,dates:v.dates,weekNumber:v.weekNumber},v.weekNumber)})}),e.jsx(y,{displayMonth:t.displayMonth})]})}function Xv(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Zv=Xv()?p.useLayoutEffect:p.useEffect,tl=!1,Jv=0;function Xd(){return"react-day-picker-".concat(++Jv)}function Qv(t){var s,a=t??(tl?Xd():null),r=p.useState(a),n=r[0],i=r[1];return Zv(function(){n===null&&i(Xd())},[]),p.useEffect(function(){tl===!1&&(tl=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function qv(t){var s,a,r=Rt(),n=r.dir,i=r.classNames,l=r.styles,o=r.components,c=kn().displayMonths,d=Qv(r.id?"".concat(r.id,"-").concat(t.displayIndex):void 0),m=r.id?"".concat(r.id,"-grid-").concat(t.displayIndex):void 0,h=[i.month],x=l.month,u=t.displayIndex===0,g=t.displayIndex===c.length-1,b=!u&&!g;n==="rtl"&&(s=[u,g],g=s[0],u=s[1]),u&&(h.push(i.caption_start),x=Qe(Qe({},x),l.caption_start)),g&&(h.push(i.caption_end),x=Qe(Qe({},x),l.caption_end)),b&&(h.push(i.caption_between),x=Qe(Qe({},x),l.caption_between));var f=(a=o==null?void 0:o.Caption)!==null&&a!==void 0?a:nv;return e.jsxs("div",{className:h.join(" "),style:x,children:[e.jsx(f,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(Kv,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function ej(t){var s=Rt(),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=Rt(),i=Do(),l=kn(),o=p.useState(!1),c=o[0],d=o[1];p.useEffect(function(){n.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[n.initialFocus,c,i.focus,i.focusTarget,i]);var m=[n.classNames.root,n.className];n.numberOfMonths>1&&m.push(n.classNames.multiple_months),n.showWeekNumber&&m.push(n.classNames.with_weeknumber);var h=Qe(Qe({},n.styles.root),n.style),x=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,b){var f;return Qe(Qe({},g),(f={},f[b]=r[b],f))},{}),u=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:ej;return e.jsx("div",Qe({className:m.join(" "),style:h,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},x,{children:e.jsx(u,{children:l.displayMonths.map(function(g,b){return e.jsx(qv,{displayIndex:b,displayMonth:g},b)})})}))}function sj(t){var s=t.children,a=Ay(t,["children"]);return e.jsx(Wy,{initialProps:a,children:e.jsx(tv,{children:e.jsx(Lv,{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,Qe({},t,{children:e.jsx(tj,{initialProps:t})}))}function Yn({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(aj,{showOutsideDays:a,className:ke("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:ke(gn({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:ke("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:ke(gn({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(Zu,{className:ke("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(yi,{className:ke("size-4",n),...i})},...r})}function Ms({value:t,onChange:s,minDate:a,maxDate:r,placeholderText:n="dd/mm/yyyy",disabled:i=!1,className:l,wrapperClassName:o,error:c=!1,displayFormat:d="dd/MM/yyyy",id:m}){const[h,x]=p.useState(!1),u=p.useMemo(()=>{if(t){if(t instanceof Date)return wr(t)?t:void 0;if(typeof t=="string")try{const y=zi(t,"yyyy-MM-dd",new Date);return wr(y)?y:void 0}catch{return}}},[t]),g=p.useMemo(()=>{if(a){if(a instanceof Date)return wr(a)?a:void 0;if(typeof a=="string"){const y=zi(a,"yyyy-MM-dd",new Date);return wr(y)?y:void 0}}},[a]),b=p.useMemo(()=>{if(r){if(r instanceof Date)return wr(r)?r:void 0;if(typeof r=="string"){const y=zi(r,"yyyy-MM-dd",new Date);return wr(y)?y:void 0}}},[r]),f=y=>{if(x(!1),!!s){if(!y){s(null);return}s(He(y,"yyyy-MM-dd"))}};return e.jsx("div",{className:ke("relative",o),children:e.jsxs(Hs,{open:h,onOpenChange:x,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{id:m,disabled:i,variant:"outline",className:ke("w-full justify-start text-left font-normal",!u&&"text-muted-foreground",c&&"border-destructive ring-destructive/20",l),children:[e.jsx(ot,{className:"mr-2 h-4 w-4"}),u?He(u,d):e.jsx("span",{children:n})]})}),e.jsx(Gs,{className:"w-auto p-0",align:"start",children:e.jsx(Yn,{mode:"single",selected:u,onSelect:f,disabled:y=>!!(g&&y<g||b&&y>b),initialFocus:!0})})]})})}function rj({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,showCustomDatePicker:n,refreshing:i,onDateRangeChange:l,onCustomStartDateChange:o,onCustomEndDateChange:c,onShowCustomDatePickerChange:d,onApplyCustomDate:m,onResetCustomDates:h,onRefresh:x}){return e.jsx(ee,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:s,onValueChange:l,"data-testid":"date-range-select",children:[e.jsx(Ye,{className:"w-[140px]",children:e.jsx(Ge,{placeholder:"Select period"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(Hs,{open:n,onOpenChange:d,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(ot,{className:"w-4 h-4"}),a&&r?`${He(a,"MMM d, yyyy")} - ${He(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",sideOffset:8,"data-testid":"custom-date-picker",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Ms,{value:a||null,onChange:u=>{const g=u?new Date(u):void 0;g?(o(g),r&&g>r&&c(g)):o(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Ms,{value:r||null,onChange:u=>{const g=u?new Date(u):void 0;g?(c(g),a&&g<a&&o(g)):c(void 0)},minDate:a||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"end-date-input"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{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(E,{size:"sm",variant:"outline",onClick:h,"data-testid":"cancel-custom-date",children:"Cancel"})]})]})})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:s,onValueChange:u=>l(u),"data-testid":"date-range-select-user",children:[e.jsx(Ye,{className:"w-[140px]",children:e.jsx(Ge,{placeholder:"Select period"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(Hs,{open:n,onOpenChange:d,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(ot,{className:"w-4 h-4"}),a&&r?`${He(a,"MMM d, yyyy")} - ${He(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",sideOffset:8,"data-testid":"custom-date-picker",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date-user",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Ms,{value:a||null,onChange:u=>{const g=u?new Date(u):void 0;g?(o(g),r&&g>r&&c(g)):o(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"start-date-input-user"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date-user",className:"text-sm font-medium",children:"End Date"}),e.jsx(Ms,{value:r||null,onChange:u=>{const g=u?new Date(u):void 0;g?(c(g),a&&g<a&&o(g)):c(void 0)},minDate:a||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"end-date-input-user"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{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(E,{size:"sm",variant:"outline",onClick:h,"data-testid":"cancel-custom-date-user",children:"Cancel"})]})]})})]})]}),e.jsx(Ts,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(E,{variant:"outline",size:"sm",onClick:x,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx($t,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function xr({title:t,value:s,icon:a,iconBgColor:r,iconColor:n,subtitle:i,children:l,testId:o="kpi-card",onClick:c,onJustifyClick:d,showJustifyButton:m=!1}){const h=x=>{x.stopPropagation(),d==null||d()};return e.jsxs(ee,{className:"hover:shadow-lg transition-all duration-200 shadow-md cursor-pointer h-full flex flex-col",onClick:c,"data-testid":o,children:[e.jsxs(ge,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(fe,{className:"text-sm font-medium text-muted-foreground","data-testid":`${o}-title`,children:t}),e.jsxs("div",{className:"flex items-center gap-2",children:[m&&d&&e.jsx("button",{type:"button",onClick:h,className:"p-1.5 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-colors","data-testid":`${o}-justify-button`,title:"View detailed breakdown of numbers","aria-label":"View detailed breakdown",children:e.jsx(Ur,{className:"h-4 w-4"})}),e.jsx("div",{className:`p-1.5 sm:p-2 rounded-lg ${r}`,"data-testid":`${o}-icon-wrapper`,children:e.jsx(a,{className:`h-4 w-4 sm:h-4 sm:w-4 ${n}`,"data-testid":`${o}-icon`})})]})]}),e.jsxs(se,{className:"flex flex-col flex-1 py-3",children:[e.jsx("div",{className:"text-xl sm:text-2xl font-bold text-gray-900 mb-2","data-testid":`${o}-value`,children:s}),i&&e.jsx("div",{className:"text-xs text-muted-foreground mb-2","data-testid":`${o}-subtitle`,children:i}),l&&e.jsx("div",{className:"flex-1 flex flex-col","data-testid":`${o}-children`,children:l})]})]})}function os({label:t,value:s,bgColor:a,textColor:r,testId:n="stat-card",children:i,onClick:l}){return e.jsxs("div",{className:`${a} rounded-lg p-2 sm:p-3 ${l?"cursor-pointer hover:shadow-md transition-shadow":""}`,"data-testid":n,onClick:l,children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1 leading-tight","data-testid":`${n}-label`,children:t}),e.jsx("p",{className:`text-lg sm:text-xl font-bold ${r}`,"data-testid":`${n}-value`,children:s}),i]})}function na({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(ef,{"data-slot":"progress",className:ke("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(tf,{"data-slot":"progress-indicator",className:ke("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(xr,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Re,iconBgColor:"bg-blue-50",iconColor:"text-blue-600",testId:"kpi-total-requests",onClick:()=>i(l()),children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[e.jsx(os,{label:"Approved",value:(t==null?void 0:t.requestVolume.approvedRequests)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-approved",onClick:o=>{o.stopPropagation(),i({...l(),status:"approved"})}}),e.jsx(os,{label:"Rejected",value:(t==null?void 0:t.requestVolume.rejectedRequests)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-rejected",onClick:o=>{o.stopPropagation(),i({...l(),status:"rejected"})}})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[e.jsx(os,{label:"Pending",value:(t==null?void 0:t.requestVolume.openRequests)||0,bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-pending",onClick:o=>{o.stopPropagation(),i({...l(),status:"pending"})}}),e.jsx(os,{label:"Closed",value:(t==null?void 0:t.requestVolume.closedRequests)||0,bgColor:"bg-gray-50",textColor:"text-gray-600",testId:"stat-closed",onClick:o=>{o.stopPropagation(),i({...l(),status:"closed"})}})]}),(t==null?void 0:t.requestVolume.pausedRequests)!==void 0&&e.jsx("div",{className:"grid grid-cols-2 gap-2",children:e.jsx(os,{label:"Paused",value:t.requestVolume.pausedRequests||0,bgColor:"bg-orange-100",textColor:"text-orange-700",testId:"stat-paused",onClick:o=>{o.stopPropagation(),i({...l(),status:"paused"})}})})]}),e.jsx(xr,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:Ot,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(na,{value:(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0,className:"h-2 mb-2","data-testid":"sla-progress-bar"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(os,{label:"Compliant",value:(t==null?void 0:t.tatEfficiency.compliantWorkflows)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-compliant",onClick:o=>{o.stopPropagation(),i({...l(),slaCompliance:"compliant"})}}),e.jsx(os,{label:"Breached",value:(t==null?void 0:t.tatEfficiency.delayedWorkflows)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-breached",onClick:o=>{o.stopPropagation(),i({...l(),slaCompliance:"breached"})}})]})]})}),e.jsx(xr,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?Ft(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:st,iconBgColor:"bg-purple-50",iconColor:"text-purple-600",subtitle:`≈ ${(t==null?void 0:t.tatEfficiency.avgCycleTimeDays.toFixed(1))||0} working days`,testId:"kpi-avg-cycle-time",onClick:()=>i(l()),children:e.jsx("div",{className:"flex flex-col flex-1",children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(os,{label:"Express",value:(()=>{const o=s.find(d=>d.priority==="express"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Ft(c):"N/A"})(),bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-express-time",onClick:o=>{o.stopPropagation(),i({...l(),priority:"express"})}}),e.jsx(os,{label:"Standard",value:(()=>{const o=s.find(d=>d.priority==="standard"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Ft(c):"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:c}){const d=()=>({dateRange:a,startDate:r,endDate:n}),m=()=>{if(!o)return;const x=new URLSearchParams;x.set("approverId",o),x.set("approverName",c||"My Performance"),x.set("dateRange",a),a==="custom"&&r&&n&&(x.set("startDate",r.toISOString()),x.set("endDate",n.toISOString())),l==null||l(`/approver-performance?${x.toString()}`)},h=t&&t.requestVolume.totalRequests>0?t.requestVolume.approvedRequests/t.requestVolume.totalRequests*100:0;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 items-stretch","data-testid":"user-kpi-cards",children:[e.jsx(xr,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Re,iconBgColor:"bg-blue-50",iconColor:"text-blue-600",testId:"kpi-my-requests",onClick:()=>i(d()),children:e.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:gap-2",children:[e.jsx(os,{label:"Approved",value:(t==null?void 0:t.requestVolume.approvedRequests)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-user-approved",onClick:x=>{x.stopPropagation(),i({...d(),status:"approved"})}}),e.jsx(os,{label:"Pending",value:(t==null?void 0:t.requestVolume.openRequests)||0,bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-user-pending",onClick:x=>{x.stopPropagation(),i({...d(),status:"pending"})}}),e.jsx(os,{label:"Paused",value:(t==null?void 0:t.requestVolume.pausedRequests)||0,bgColor:"bg-amber-50",textColor:"text-amber-600",testId:"stat-user-paused",onClick:x=>{x.stopPropagation(),i({...d(),status:"paused"})}}),e.jsx(os,{label:"Rejected",value:(t==null?void 0:t.requestVolume.rejectedRequests)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-user-rejected",onClick:x=>{x.stopPropagation(),i({...d(),status:"rejected"})}}),e.jsx(os,{label:"Closed",value:(t==null?void 0:t.requestVolume.closedRequests)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-user-closed",onClick:x=>{x.stopPropagation(),i({...d(),status:"closed"})}})]})}),e.jsx(xr,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:st,iconBgColor:"bg-orange-50",iconColor:"text-orange-600",subtitle:"at current level",testId:"kpi-pending-actions",onClick:()=>i({...d(),targetPage:"open-requests",status:"pending"}),onJustifyClick:m,showJustifyButton:!!o,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(os,{label:"Approved Today",value:(t==null?void 0:t.approverLoad.completedToday)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-today",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}}),e.jsx(os,{label:"This Week",value:(t==null?void 0:t.approverLoad.completedThisWeek)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-week",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}})]})}),e.jsx(xr,{title:"Critical Alerts",value:s.length,icon:ha,iconBgColor:"bg-red-50",iconColor:"text-red-600",testId:"kpi-user-critical",onClick:()=>i({...d(),targetPage:"open-requests"}),onJustifyClick:m,showJustifyButton:!!o,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(os,{label:"Breached",value:s.filter(x=>x.breachCount>0).length,bgColor:"bg-orange-50",textColor:"text-red-600",testId:"stat-user-breached",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests"})}}),e.jsx(os,{label:"Warning",value:s.filter(x=>x.breachCount===0).length,bgColor:"bg-yellow-50",textColor:"text-orange-600",testId:"stat-user-warning",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests"})}})]})}),e.jsx(xr,{title:"Success Rate",value:`${h.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(na,{value:h,className:"h-4 bg-gray-200 [&>div]:bg-green-600","data-testid":"success-rate-progress"}),e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Rejected"}),e.jsx("span",{className:"font-semibold text-red-600",children:(t==null?void 0:t.requestVolume.rejectedRequests)||0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsxs("div",{className:"bg-green-50 rounded-lg p-2 text-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Approved"}),e.jsx("div",{className:"text-lg font-semibold text-green-600",children:(t==null?void 0:t.requestVolume.approvedRequests)||0})]}),e.jsxs("div",{className:"bg-red-50 rounded-lg p-2 text-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Rejected"}),e.jsx("div",{className:"text-lg font-semibold text-red-600",children:(t==null?void 0:t.requestVolume.rejectedRequests)||0})]})]})]})})]})}const 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(na,{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 Ox(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(ee,{className:"lg:col-span-2 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden h-full","data-testid":"critical-alerts-section",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-red-100 rounded-lg",children:e.jsx(ha,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx($e,{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(se,{className:`overflow-y-auto flex-1 p-4 ${a.totalPages>1?"max-h-[calc(100%-140px)]":"max-h-[calc(100%-80px)]"}`,children:e.jsx("div",{className:"space-y-3 sm:space-y-4",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-critical-alerts",children:[e.jsx(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(E,{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(ss,{className:"h-3 w-3 rotate-180"})}),Ox(a.page,a.totalPages,3).map(i=>e.jsx(E,{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(E,{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(ss,{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=$f(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=Of(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()},bj=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(as,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-red-600"}):s.includes("comment")?e.jsx(As,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(ha,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(Re,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(vi,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(kt,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function yj({activity:t,currentUserId:s,currentUserDisplayName:a,currentUserEmail:r,onNavigate:n,testId:i="activity-feed-item"}){const l=t.userId===s,o=l?"You":t.userName||"System",c=l?(a||r||"ME").split(" ").map(d=>d[0]).join("").toUpperCase().substring(0,2):t.userName?t.userName.split(" ").map(d=>d[0]).join("").toUpperCase().substring(0,2):"SY";return e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 p-3 sm:p-4 rounded-lg hover:bg-gray-50 transition-all duration-200 cursor-pointer border border-gray-100 hover:border-gray-300",onClick:()=>n==null?void 0:n(t.requestNumber),"data-testid":`${i}-${t.activityId}`,children:[e.jsxs("div",{className:"relative flex-shrink-0 mt-0.5",children:[e.jsxs(Zt,{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(Di,{src:""}),e.jsx(Jt,{className:`text-white font-semibold text-xs sm:text-sm ${l?"bg-blue-600":"bg-slate-700"}`,children:c})]}),e.jsx("div",{className:"absolute -bottom-0.5 -right-0.5 sm:-bottom-1 sm:-right-1 w-4 h-4 sm:w-5 sm:h-5 bg-white rounded-full flex items-center justify-center shadow-sm border border-gray-200",children:bj(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(ss,{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:c,currentUserEmail:d}){return e.jsxs(ee,{className:"lg:col-span-1 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden h-full","data-testid":"recent-activity-section",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-blue-100 rounded-lg",children:e.jsx(kt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(fe,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx($e,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(E,{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($t,{className:`w-3 h-3 sm:w-4 sm:h-4 ${r?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline ml-2 sm:w-[60px] sm:text-center",children:r?"Refreshing...":"Refresh"})]})]})}),e.jsx(se,{className:`overflow-y-auto flex-1 p-4 ${a.totalPages>1?"max-h-[calc(100%-140px)]":"max-h-[calc(100%-80px)]"}`,children:e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-recent-activity",children:[e.jsx(kt,{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(yj,{activity:m,currentUserId:o,currentUserDisplayName:c,currentUserEmail:d,onNavigate:h=>l==null?void 0:l(`request/${h}`),testId:"dashboard-activity"},m.activityId))})}),a.totalPages>1&&s.length>0&&e.jsx("div",{className:"border-t bg-gray-50 px-4 py-2 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Page ",a.page," of ",a.totalPages," (",a.totalRecords," total)"]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[e.jsx(E,{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(ss,{className:"h-3 w-3 rotate-180"})}),Ox(a.page,a.totalPages,3).map(m=>e.jsx(E,{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(E,{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(ss,{className:"h-3 w-3"})})]})]})})]})}function jj({kpis:t,upcomingDeadlines:s,criticalRequests:a,departmentStats:r,dateRange:n,customStartDate:i,customEndDate:l,exportingDeptStats:o,onKPIClick:c,onExportDepartmentStats:d}){if(!t)return null;const m=()=>({dateRange:n,startDate:i,endDate:l});return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6","data-testid":"admin-analytics-section",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:gap-6 lg:col-span-1",children:[e.jsxs(ee,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(kt,{className:"h-4 w-4 text-blue-600"})}),e.jsx(fe,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl sm:text-3xl font-bold text-blue-600",children:s.length}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"levels"})]}),e.jsx(Ts,{}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg Time/Level"}),e.jsxs("span",{className:"font-semibold",children:[s.length>0?(t.tatEfficiency.avgCycleTimeHours/s.length).toFixed(1):"0","h"]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"At Risk"}),e.jsx("span",{className:"font-semibold text-red-600",children:a.filter(h=>h.breachCount>0).length})]})]})]})})]}),e.jsxs(ee,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(As,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(fe,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center p-2 bg-indigo-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-indigo-600",children:t.engagement.workNotesAdded})]}),e.jsxs("div",{className:"text-center p-2 bg-purple-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Files"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-purple-600",children:t.engagement.attachmentsUploaded})]})]}),e.jsx(Ts,{}),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(ee,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-blue-50 p-2 sm:p-3 rounded-lg",children:e.jsx(Pl,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2 self-start sm:self-auto",onClick:()=>d(n,i,l),disabled:o,"data-testid":"export-dept-stats-button",children:[e.jsx(Ct,{className:`w-3 h-3 sm:w-4 sm:h-4 ${o?"animate-pulse":""}`}),e.jsx("span",{className:"text-xs sm:text-sm",children:o?"Exporting...":"Export"})]})]})}),e.jsx(se,{children:e.jsx(Pr,{width:"100%",height:400,children:e.jsxs(kl,{data:r,children:[e.jsx(ei,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ti,{dataKey:"department",stroke:"#999",tick:h=>{const{x,y:u,payload:g}=h;return e.jsx("g",{transform:`translate(${x},${u})`,children:e.jsx("text",{x:0,y:0,dy:16,textAnchor:"middle",fill:"#999",fontSize:11,className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{c({...m(),department:g.value})},children:g.value})})}}),e.jsx(si,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Ir,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(ai,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(fa,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(fa,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(fa,{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(ee,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(As,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(fe,{className:"text-sm",children:"My Activity"})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center p-3 bg-indigo-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Work Notes"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold text-indigo-600",children:t.engagement.workNotesAdded})]}),e.jsxs("div",{className:"text-center p-3 bg-purple-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Attachments"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold text-purple-600",children:t.engagement.attachmentsUploaded})]})]})})})]}),e.jsxs(ee,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(st,{className:"h-4 w-4 text-purple-600"})}),e.jsx(fe,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-baseline gap-2",children:e.jsx("span",{className:"text-2xl sm:text-3xl font-bold text-purple-600",children:Ft(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(Ts,{}),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(ee,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-green-50 p-2 sm:p-3 rounded-lg",children:e.jsx(Ot,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"grid grid-cols-2 gap-4 mb-6",children:t.map((a,r)=>{const n=Number(a.avgCycleTimeHours)||0,i=a.priority==="express",l=i?"bg-red-50":"bg-blue-50",o=i?"bg-red-500":"bg-blue-500";return e.jsxs("div",{className:`${l} p-4 rounded-lg`,"data-testid":`priority-card-${a.priority}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`w-3 h-3 ${o} rounded-full`}),e.jsx("span",{className:"text-sm text-gray-600 capitalize",children:a.priority})]}),e.jsx("div",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-1",children:a.totalCount}),e.jsxs("div",{className:"text-xs text-gray-500",children:["Avg: ",Ft(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Pr,{width:"100%",height:300,children:e.jsxs(Uu,{children:[e.jsx(Bu,{data:t.map(a=>({name:a.priority.charAt(0).toUpperCase()+a.priority.slice(1),value:a.totalCount,priority:a.priority,percentage:Math.round(a.totalCount/t.reduce((r,n)=>r+n.totalCount,0)*100)})),cx:"50%",cy:"50%",labelLine:!0,label:({cx:a,cy:r,midAngle:n,outerRadius:i,name:l,percentage:o})=>{const c=Math.PI/180,d=i+35,m=a+d*Math.cos(-n*c),h=r+d*Math.sin(-n*c);return e.jsx("text",{x:m,y:h,fill:"#1f2937",textAnchor:m>a?"start":"end",dominantBaseline:"central",className:"text-sm font-semibold pointer-events-none",children:`${l}: ${o}%`})},outerRadius:90,fill:"#8884d8",dataKey:"value",onClick:a=>{a&&a.priority&&s&&s(`requests?priority=${a.priority}`)},className:"cursor-pointer",children:t.map((a,r)=>e.jsx(Vu,{fill:a.priority==="express"?"#ef4444":"#3b82f6",className:"cursor-pointer"},`cell-${r}`))}),e.jsx(Ir,{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 vr({currentPage:t,totalPages:s,itemsPerPage:a,totalRecords:r,onPageChange:n,loading:i=!1,itemLabel:l="items",testIdPrefix:o="pagination"}){const c=()=>{const h=[];let u=Math.max(1,t-Math.floor(2.5)),g=Math.min(s,u+5-1);g-u<4&&(u=Math.max(1,g-5+1));for(let b=u;b<=g;b++)h.push(b);return h},d=r>0?(t-1)*a+1:0,m=Math.min(t*a,r);return s<=1?e.jsx(ee,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(se,{className:"p-4",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("div",{className:"text-sm sm:text-base font-medium text-gray-700","data-testid":`${o}-info`,children:i?`Loading ${l}...`:r===0?`No ${l} found`:r===1?`Showing 1 ${l.slice(0,-1)}`:d===m?`Showing ${d} of ${r} ${l}`:`Showing ${d} to ${m} of ${r} ${l}`})})})}):e.jsx(ee,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-sm sm:text-base font-medium text-gray-700","data-testid":`${o}-info`,children:["Showing ",d," to ",m," of ",r," ",l]}),e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${o}-controls`,children:[e.jsx(E,{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(ss,{className:"h-4 w-4 rotate-180"})}),t>3&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>n(1),className:"h-8 w-8 p-0","data-testid":`${o}-page-1`,children:"1"}),e.jsx("span",{className:"text-muted-foreground","data-testid":`${o}-ellipsis-start`,children:"..."})]}),c().map(h=>e.jsx(E,{variant:h===t?"default":"outline",size:"sm",onClick:()=>n(h),className:`h-8 w-8 p-0 ${h===t?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`${o}-page-${h}`,"aria-current":h===t?"page":void 0,children:h},h)),t<s-2&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground","data-testid":`${o}-ellipsis-end`,children:"..."}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${o}-page-${s}`,children:s})]}),e.jsx(E,{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(ss,{className:"h-4 w-4"})})]})]})})})}function Cj(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${He(s,"MMM d, yyyy")} - ${He(a,"MMM d, yyyy")}`:{all:"(All Time)",today:`${r} Today`,week:`${r} This Week`,month:`${r} This Month`,quarter:`${r} This Quarter`,year:`${r} This Year`,last30days:`${r} Last 30 Days`,custom:`${r} Custom Range`}[t]||`${r} Selected Period`}function Sj(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${He(s,"MMM d, yyyy")} to ${He(a,"MMM d, yyyy")}`:{all:"All historical data",today:"Today's data",week:"This week data",month:"This month data",quarter:"This quarter data",year:"This year data",last30days:"Last 30 days data",custom:"Custom date range"}[t]||"Filtered data"}function Aj({breachedRequests:t,pagination:s,dateRange:a,customStartDate:r,customEndDate:n,onPageChange:i,onKPIClick:l,onNavigate:o}){if(t.length===0)return null;const c=()=>({dateRange:a,startDate:r,endDate:n});return e.jsxs(ee,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-red-50 p-2 sm:p-3 rounded-lg",children:e.jsx(as,{className:"h-5 w-5 sm:h-6 sm:w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs($e,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",Sj(a,r,n)]})]})]}),e.jsxs(ne,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[s.totalRecords," ",s.totalRecords===1?"Breach":"Breaches"]})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"overflow-x-auto -mx-4 sm:mx-0",children:e.jsxs("table",{className:"w-full min-w-[1000px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 bg-gray-50",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Request ID"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[250px]",children:"Title"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Department"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Approver"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Level"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[140px]",children:"Breach Time"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[300px]",children:"Reason"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Priority"})]})}),e.jsx("tbody",{children:t.map((d,m)=>{const h=d.breachTime||0;return e.jsxs("tr",{className:"border-b border-gray-100 hover:bg-gray-50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-blue-600 cursor-pointer hover:underline",onClick:()=>o==null?void 0:o(`request/${d.requestNumber}`),"data-testid":`breach-request-${d.requestNumber}`,children:d.requestNumber}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-900 w-[250px]",children:e.jsx("p",{className:"break-words leading-relaxed",children:d.title})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{d.department&&d.department!=="Unknown"&&l({...c(),department:d.department})},children:d.department||"Unknown"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.approverId?e.jsx("span",{className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{if(o){const x=new URLSearchParams;x.set("approver",d.approverId),x.set("approverType","current"),x.set("slaCompliance","breached"),a&&x.set("dateRange",a),r&&x.set("startDate",r.toISOString()),n&&x.set("endDate",n.toISOString()),o(`requests?${x.toString()}`)}},title:"Click to view all requests for this approver",children:d.approver||"N/A"}):d.approver||"N/A"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.currentLevel&&d.totalLevels?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/",d.totalLevels]}):d.currentLevel?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/—"]}):e.jsx("span",{className:"text-gray-400",children:"—"})}),e.jsx("td",{className:"py-3 px-4 w-[140px]",children:e.jsx("span",{className:"bg-red-500 text-white px-2 py-1 rounded text-xs font-medium whitespace-nowrap",children:uj(h)})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 w-[300px]",children:e.jsx("div",{className:"max-h-32 overflow-y-auto",children:e.jsx("p",{className:"whitespace-pre-line break-words leading-relaxed",children:d.breachReason||"TAT Exceeded"})})}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(ne,{variant:"outline",className:`text-xs font-medium ${d.priority==="express"?"bg-orange-100 text-orange-800 border-orange-200":"bg-blue-100 text-blue-800 border-blue-200"}`,children:d.priority})})]},m)})})]})}),e.jsx("div",{className:"mt-4",children:e.jsx(vr,{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(ee,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(ge,{children:e.jsx("div",{className:"flex items-center justify-between gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx($e,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(se,{children:[e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.map((i,l)=>{const o=Number(i.tatPercentageUsed)||0,c=Number(i.elapsedHours)||0,d=Number(i.remainingHours)||0;return e.jsxs("div",{className:"p-3 sm:p-4 border rounded-lg hover:shadow-md transition-all cursor-pointer",onClick:()=>n==null?void 0:n(`request/${i.requestNumber}`),"data-testid":`deadline-item-${i.requestNumber}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-xs sm:text-sm",children:i.requestNumber}),e.jsx(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(na,{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:[Ft(c)," elapsed"]}),e.jsxs("span",{children:[Ft(d)," left"]})]})]})]},l)})}),e.jsx("div",{className:"mt-4",children:e.jsx(vr,{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(ee,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-purple-50 p-2 sm:p-3 rounded-lg",children:e.jsx(xo,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx($e,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(se,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4 mb-6",children:[e.jsxs("div",{className:"bg-purple-50 p-4 rounded-lg text-center","data-testid":"ai-total-usage",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Total Usage"}),e.jsx("div",{className:"text-2xl font-bold text-gray-900",children:t.totalUsage})]}),e.jsxs("div",{className:"bg-pink-50 p-4 rounded-lg text-center","data-testid":"ai-total-edits",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Total Edits"}),e.jsx("div",{className:"text-2xl font-bold text-gray-900",children:t.totalEdits})]}),e.jsxs("div",{className:"bg-purple-50 p-4 rounded-lg text-center","data-testid":"ai-edit-rate",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Edit Rate"}),e.jsxs("div",{className:"text-2xl font-bold text-gray-900",children:[t.editRate,"%"]})]})]}),t.monthlyTrends&&t.monthlyTrends.length>0&&e.jsx(Pr,{width:"100%",height:250,children:e.jsxs(Af,{data:t.monthlyTrends,children:[e.jsx(ei,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ti,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(si,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Ir,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(ai,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Td,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(Td,{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:c,onNavigate:d}){return t.length===0?null:e.jsxs(ee,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-yellow-50 p-2 sm:p-3 rounded-lg",children:e.jsx(cs,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(E,{onClick:()=>c(a,r,n),disabled:l||i,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-approver-performance-button",children:l?e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"space-y-3",children:t.map((m,h)=>{const x=m.tatCompliancePercent;return e.jsxs("div",{className:"border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{const u=new URLSearchParams;u.set("approverId",m.approverId),u.set("approverName",m.approverName),u.set("dateRange",a),a==="custom"&&r&&n&&(u.set("startDate",r.toISOString()),u.set("endDate",n.toISOString())),d==null||d(`/approver-performance?${u.toString()}`)},"data-testid":`approver-item-${m.approverId}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-orange-500 rounded-full flex items-center justify-center text-white font-semibold text-sm flex-shrink-0",children:h+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-gray-900 truncate",children:m.approverName}),e.jsxs("div",{className:"text-xs text-gray-500",children:[m.totalApproved," requests approved"]})]})]}),e.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium ${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:Ft(m.avgResponseHours)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"Pending"}),e.jsx("div",{className:"text-sm font-medium text-gray-900",children:e.jsx("span",{className:"bg-gray-500 text-white px-2 py-1 rounded text-xs",children:m.pendingCount})})]})]})]},h)})}),e.jsx("div",{className:"mt-4",children:e.jsx(vr,{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:Re,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"}),n.push({label:"View Pending",icon:st,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:Va,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:kt,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}=Kt(),r=Sn(),n=zr(nt=>nt.dashboard.viewAsUser),i=p.useMemo(()=>ki(a),[a]),l=i&&!n,o=p.useCallback(nt=>{r(oy(nt))},[r]),c=cy(),{dateRange:d,customStartDate:m,customEndDate:h,showCustomDatePicker:x,handleDateRangeChange:u,handleApplyCustomDate:g,resetCustomDates:b,setCustomStartDate:f,setCustomEndDate:y,setShowCustomDatePicker:v}=c,w=dy(),{activity:C,critical:k,deadlines:S,approver:_,updateActivityPagination:D,updateCriticalPagination:A,updateDeadlinesPagination:N,updateApproverPagination:P,handleActivityPageChange:R,handleCriticalPageChange:O,handleDeadlinesPageChange:F,handleApproverPageChange:$}=w,V=uy({isAdmin:l,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:h,onPaginationUpdate:{activity:D,critical:A,deadlines:N,approver:P}}),{kpis:T,recentActivity:j,criticalRequests:U,departmentStats:I,priorityDistribution:M,upcomingDeadlines:W,aiRemarkUtilization:G,approverPerformance:ce,loading:te,refreshing:L,fetchDashboardData:z,fetchRecentActivities:H,fetchCriticalRequests:ye,fetchUpcomingDeadlines:ae,fetchApproverPerformance:me}=V,Q=Ny(),{exportingDeptStats:oe,exportingApproverPerformance:Ce,handleExportDepartmentStats:Ee,handleExportApproverPerformance:be}=Q,q=p.useMemo(()=>dj(U),[U]),ue=p.useMemo(()=>mj(W),[W]),Ae=p.useCallback(()=>{z(!0)},[d,m,h,z]),Ue=p.useCallback(()=>{g(()=>{m&&h&&z(!1)})},[m,h,g,z]),Z=p.useCallback(nt=>{R(nt,H)},[R,H]),Te=p.useCallback(nt=>{O(nt,ye)},[O,ye]),Xe=p.useCallback(nt=>{F(nt,ae)},[F,ae]),pe=p.useCallback(nt=>{$(nt,()=>me(nt))},[$,me]);p.useEffect(()=>{d==="custom"?m&&h&&z(!1):z(!1)},[d,m,h,n]);const _e=p.useMemo(()=>{try{const nt=tt.getUserData();return(nt==null?void 0:nt.jobTitle)==="Dealer"}catch(nt){return console.error("[Dashboard] Error checking dealer status:",nt),!1}},[]),rt=p.useMemo(()=>Pj(i,s,t,_e),[i,s,t,_e]),ut=p.useCallback(nt=>{const Ps=Dj(nt);t==null||t(Ps)},[t]);return te?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx($t,{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(wy,{isAdmin:i,effectiveIsAdmin:l,viewAsUser:n,onToggleView:o,quickActions:rt,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(rj,{isAdmin:l,dateRange:d,customStartDate:m,customEndDate:h,showCustomDatePicker:x,refreshing:L,onDateRangeChange:u,onCustomStartDateChange:f,onCustomEndDateChange:y,onShowCustomDatePickerChange:v,onApplyCustomDate:Ue,onResetCustomDates:b,onRefresh:Ae}),l?e.jsx(nj,{kpis:T,priorityDistribution:M,dateRange:d,customStartDate:m,customEndDate:h,onKPIClick:ut}):e.jsx(ij,{kpis:T,criticalRequests:U,dateRange:d,customStartDate:m,customEndDate:h,onKPIClick:ut,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:q,pagination:k,onPageChange:Te,onNavigate:t}),e.jsx(vj,{isAdmin:l,recentActivity:j,pagination:C,refreshing:L,onPageChange:Z,onRefresh:Ae,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),l&&T&&e.jsx(jj,{kpis:T,upcomingDeadlines:W,criticalRequests:U,departmentStats:I,dateRange:d,customStartDate:m,customEndDate:h,exportingDeptStats:oe,onKPIClick:ut,onExportDepartmentStats:Ee}),!l&&T&&e.jsx(Nj,{kpis:T}),l&&M.length>0&&e.jsx(wj,{priorityDistribution:M,onNavigate:t}),l&&q.length>0&&e.jsx(Aj,{breachedRequests:q,pagination:k,dateRange:d,customStartDate:m,customEndDate:h,onPageChange:Te,onKPIClick:ut,onNavigate:t}),ue.length>0&&e.jsx(Tj,{isAdmin:l,upcomingDeadlines:ue,pagination:S,onPageChange:Xe,onNavigate:t}),l&&G&&e.jsx(kj,{aiRemarkUtilization:G}),l&&ce.length>0&&e.jsx(Rj,{approverPerformance:ce,pagination:_,dateRange:d,customStartDate:m,customEndDate:h,loading:te,exportingApproverPerformance:Ce,onPageChange:pe,onExport:be,onNavigate:t})]})}const Ej={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},Ux=Br({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:_j,setPriorityFilter:Lj,setTemplateTypeFilter:Mj,setSortBy:$j,setSortOrder:Oj,setCurrentPage:Uj,clearFilters:Bj}=Ux.actions;function Vj(){const t=Sn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,sortBy:i,sortOrder:l,currentPage:o}=zr(y=>y.openRequests),c=p.useCallback(y=>t(Fj(y)),[t]),d=p.useCallback(y=>t(_j(y)),[t]),m=p.useCallback(y=>t(Lj(y)),[t]),h=p.useCallback(y=>t(Mj(y)),[t]),x=p.useCallback(y=>t($j(y)),[t]),u=p.useCallback(y=>t(Oj(y)),[t]),g=p.useCallback(y=>t(Uj(y)),[t]),b=p.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:c,setStatusFilter:d,setPriorityFilter:m,setTemplateTypeFilter:h,setSortBy:x,setSortOrder:u,setCurrentPage:g,clearFilters:b,activeFiltersCount:f}}function sl(){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},(c,d)=>{const m=d,h=t.approvers[m]||{},x=m+1,u=h.tat??"";let g=0;typeof u=="number"&&(g=h.tatType==="days"?u*24:u);const b=h.email||"",f=h.name&&h.name.trim()||b.split("@")[0]||`Approver ${x}`;return{levelNumber:x,levelName:`Level ${x}`,approverId:sl(),approverEmail:b,approverName:f,tatHours:g>0?g:24,isFinalApprover:x===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:sl(),userEmail:c.email,userName:c.name||c.email.split("@")[0]||"Spectator",participantType:"SPECTATOR",canComment:!0,canViewDocuments:!0,canDownloadDocuments:!1,notificationEnabled:!0})),...(t.ccList||[]).map(c=>({userId:sl(),userEmail:c.email,userName:c.name||c.email.split("@")[0]||"CC",participantType:"CONSULTATION",canComment:!1,canViewDocuments:!0,canDownloadDocuments:!1,notificationEnabled:!0}))],n={templateType:t.templateType,title:t.title,description:t.description,priority:s,approvalLevels:a,participants:r.length?r:void 0,isDraft:t.isDraft},i=await je.post("/workflows",n),l=((o=i.data)==null?void 0:o.data)||i.data;return{id:l.id||l.workflowId||""}}async function Io(t,s,a="SUPPORTING"){var o;const r={templateType:t.templateType,title:t.title,description:t.description,priority:t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",isDraft:t.isDraft,approvers:Array.from({length:t.approverCount||1},(c,d)=>{const m=t.approvers[d]||{},h=typeof m.tat=="number"?m.tat:0;if(!m.email||!m.email.trim())throw new Error(`Email is required for approver at level ${d+1}.`);return{email:m.email,tat:h,tatType:m.tatType||"hours"}})};t.spectators&&t.spectators.length>0&&(r.spectators=t.spectators.filter(c=>c==null?void 0:c.email).map(c=>({email:c.email})));const n=new FormData;n.append("payload",JSON.stringify(r)),n.append("category",a),s.forEach(c=>n.append("files",c));const i=await je.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 b;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,slaCompliance:m,dateRange:h,startDate:x,endDate:u}=t,g=await je.get("/workflows",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,slaCompliance:m,dateRange:h,startDate:x,endDate:u}});return((b=g.data)==null?void 0:b.data)||g.data}async function Wj(t={}){var f,y,v,w,C;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,approverType:m,slaCompliance:h,dateRange:x,startDate:u,endDate:g}=t,b=await je.get("/workflows/participant-requests",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,approverType:m,slaCompliance:h,dateRange:x,startDate:u,endDate:g}});return{data:((y=(f=b.data)==null?void 0:f.data)==null?void 0:y.data)||((v=b.data)==null?void 0:v.data)||[],pagination:((C=(w=b.data)==null?void 0:w.data)==null?void 0:C.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Gj(t={}){var g,b,f,y,v;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:l,initiator:o,approver:c,slaCompliance:d,dateRange:m,startDate:h,endDate:x}=t,u=await je.get("/workflows/my",{params:{page:s,limit:a,search:r,status:n,priority:i,department:l,initiator:o,approver:c,slaCompliance:d,dateRange:m,startDate:h,endDate:x}});return{data:((b=(g=u.data)==null?void 0:g.data)==null?void 0:b.data)||((f=u.data)==null?void 0:f.data)||[],pagination:((v=(y=u.data)==null?void 0:y.data)==null?void 0:v.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Yj(t={}){var u,g,b,f,y;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:c,dateRange:d,startDate:m,endDate:h}=t,x=await je.get("/workflows/my-initiated",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:c,dateRange:d,startDate:m,endDate:h}});return{data:((g=(u=x.data)==null?void 0:u.data)==null?void 0:g.data)||((b=x.data)==null?void 0:b.data)||[],pagination:((y=(f=x.data)==null?void 0:f.data)==null?void 0:y.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Kj(t={}){var m,h,x,u,g;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}=t,d=await je.get("/workflows/open-for-me",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}});return{data:((h=(m=d.data)==null?void 0:m.data)==null?void 0:h.data)||((x=d.data)==null?void 0:x.data)||[],pagination:((g=(u=d.data)==null?void 0:u.data)==null?void 0:g.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Xj(t={}){var m,h,x,u,g;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}=t,d=await je.get("/workflows/closed-by-me",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}});return{data:((h=(m=d.data)==null?void 0:m.data)==null?void 0:h.data)||((x=d.data)==null?void 0:x.data)||[],pagination:((g=(u=d.data)==null?void 0:u.data)==null?void 0:g.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function vs(t,s){var r;const a=await je.get(`/workflows/${t}/details`);return((r=a.data)==null?void 0:r.data)||a.data}async function Fr(t){var a;const s=await je.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function Bx(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 je.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 Vx(t,s,a,r){var i;const n=await je.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 Zj(t,s,a){var n;const r=await je.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function zx(t,s){var r;const a=await je.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function Jj(t,s,a,r){var i;const n=await je.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function Qj(t,s){var r;const a=await je.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 je.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function Zd(t){var a;const s=await je.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function eN(t){return`https://reflow-uat.royalenfield.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function Hr(t){return`https://reflow-uat.royalenfield.com/api/v1/workflows/documents/${t}/preview`}function Hx(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 ps(t){const a=`https://reflow-uat.royalenfield.com/api/v1/workflows/documents/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const h=await i.text();throw new Error(`Download failed: ${i.status} - ${h}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=Hx(c),m=document.createElement("a");m.href=o,m.download=d,document.body.appendChild(m),m.click(),document.body.removeChild(m),window.URL.revokeObjectURL(o)}catch(n){throw console.error("[Download] Failed:",n),n}}async function Jd(t){const a=`https://reflow-uat.royalenfield.com/api/v1/workflows/work-notes/attachments/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const h=await i.text();throw new Error(`Download failed: ${i.status} - ${h}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=Hx(c),m=document.createElement("a");m.href=o,m.download=d,document.body.appendChild(m),m.click(),document.body.removeChild(m),window.URL.revokeObjectURL(o)}catch(n){throw console.error("[Download] Failed:",n),n}}const ks={createWorkflowFromForm:zj,createWorkflowMultipart:Io,listWorkflows:Hj,listParticipantRequests:Wj,listMyWorkflows:Gj,listMyInitiatedWorkflows:Yj,listOpenForMe:Kj,listClosedByMe:Xj,submitWorkflow:Wx,getWorkflowDetails:vs,getWorkNotes:Fr,createWorkNoteMultipart:Bx,handleInitiatorAction:Gx};async function Wx(t){var a;const s=await je.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 je.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(c=>i.append("files",c));const l=await je.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((o=l.data)==null?void 0:o.data)||l.data}async function an(t,s,a){var n;const r=await je.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function Sr(t,s,a,r){var i;const n=await je.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 je.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}async function Gx(t,s,a){var n;const r=await je.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 je.get(`/workflows/${t}/history`)).data)==null?void 0:a.data)||[]}function Qt(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 Yx(t){return Qt(t,{includeTime:!1,format:"short"})}function xa(t,s=!1){if(!t)return"N/A";try{const a=typeof t=="string"?new Date(t):t;if(isNaN(a.getTime()))return"Invalid Date";const r=String(a.getDate()).padStart(2,"0"),i=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][a.getMonth()],l=a.getFullYear();if(s){const o=a.getHours(),c=o%12||12,d=String(a.getMinutes()).padStart(2,"0"),m=String(a.getSeconds()).padStart(2,"0"),h=o>=12?"PM":"AM";return`${r} ${i} ${l}, ${c}:${d}:${m} ${h}`}return`${r} ${i} ${l}`}catch(a){return console.error("Error formatting date:",a),String(t)}}function nN(t){return t?t.jobTitle==="Dealer"||t.jobTitle==="DEALER":!1}function Eo(t){return nN(t)?"DEALER":"STANDARD"}function ba(t){if(!t)return"";let s=t.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"");return s=s.replace(/\s+on\w+\s*=\s*(?:'[^']*'|"[^"]*"|[^\s>]+)/gi,""),s=s.replace(/(href|src)\s*=\s*(?:'javascript:[^']*'|"javascript:[^"]*"|javascript:[^\s>]+)/gi,'$1="#"'),s=s.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),s=s.replace(/<(meta|link|iframe|object|embed|applet)[^>]*>/gi,""),s=s.replace(/<a[^>]*>([\s\S]*?)<\/a>/gi,"$1"),s}const Mn=[{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 Rn({value:t,onChange:s,placeholder:a="Enter text...",className:r,minHeight:n="120px",...i}){const l=p.useRef(null),[o,c]=p.useState(!1),[d,m]=p.useState(new Set),[h,x]=p.useState(!1),[u,g]=p.useState(null),[b,f]=p.useState("#FFEB3B"),[y,v]=p.useState(!1),[w,C]=p.useState(null),[k,S]=p.useState("#000000");p.useEffect(()=>{l.current&&l.current.innerHTML!==t&&l.current.innerHTML!==t&&(l.current.innerHTML=ba(t||""))},[t]);const _=p.useCallback(T=>(T=T.replace(/<!--[\s\S]*?-->/g,""),T=T.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),T=T.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),T=T.replace(/<meta[^>]*>/gi,""),T=T.replace(/\s*class="Mso[^"]*"/gi,""),T=T.replace(/\s*class="mso[^"]*"/gi,""),T=T.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),T=T.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),T=T.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),T=T.replace(/<\/?o:p[^>]*>/gi,""),T=T.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),T=T.replace(/<v:[^>]*\/>/gi,""),T=T.replace(/<p[^>]*>\s*<\/p>/gi,""),T=T.replace(/<div[^>]*>\s*<\/div>/gi,""),T=T.replace(/\s+/g," "),T=T.trim(),T),[]),D=p.useCallback(T=>{T.preventDefault();const j=T.clipboardData;let U=j.getData("text/html")||j.getData("text/plain");if((U.includes("<!--")||U.includes("<style")||U.includes("MsoNormal"))&&(U=_(U)),!l.current)return;const I=window.getSelection();if(!I||I.rangeCount===0)return;const M=I.getRangeAt(0);M.deleteContents();const W=document.createElement("div");W.innerHTML=U;const G=document.createDocumentFragment();Array.from(W.childNodes).forEach(ce=>{if(ce.nodeType===Node.ELEMENT_NODE){const te=ce;if(te.tagName==="UL"||te.tagName==="OL"){const L=te.cloneNode(!0);L.removeAttribute("style"),L.removeAttribute("class"),L.querySelectorAll("li").forEach(z=>{z.removeAttribute("style"),z.removeAttribute("class");const H=z.textContent||"";H.trim()&&(z.textContent=H.trim())}),G.appendChild(L)}else if(te.tagName==="TABLE"){const L=te.cloneNode(!0);L.removeAttribute("style"),L.removeAttribute("class"),L.querySelectorAll("td, th").forEach(H=>{H.removeAttribute("style"),H.removeAttribute("class")});const z=document.createElement("div");z.className="table-wrapper",z.appendChild(L),G.appendChild(z)}else if(te.tagName==="P"||te.tagName==="DIV"){const L=document.createElement("p"),H=te.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");L.innerHTML=H,L.removeAttribute("style"),L.removeAttribute("class"),G.appendChild(L)}else if(te.tagName==="BR")G.appendChild(te.cloneNode(!0));else{const L=te.textContent||"";if(L.trim()){const z=document.createElement("p");z.textContent=L.trim(),G.appendChild(z)}}}else if(ce.nodeType===Node.TEXT_NODE){const te=ce.textContent||"";if(te.trim()){const L=document.createElement("p");L.textContent=te.trim(),G.appendChild(L)}}}),G.childNodes.length===0&&j.getData("text/plain").split(`
`).forEach(L=>{if(L.trim()){const z=document.createElement("p");z.textContent=L.trim(),G.appendChild(z)}else G.appendChild(document.createElement("br"))}),M.insertNode(G),M.collapse(!1),I.removeAllRanges(),I.addRange(M),l.current&&s(ba(l.current.innerHTML))},[s,_]),A=p.useCallback(()=>{if(!l.current||!o)return;const T=new Set,j=window.getSelection();if(j&&j.rangeCount>0){const I=j.getRangeAt(0).commonAncestorContainer;let M=null;for(I.nodeType===Node.TEXT_NODE?M=I.parentElement:M=I;M&&M!==l.current;){const W=M.tagName.toLowerCase();(W==="strong"||W==="b")&&T.add("bold"),(W==="em"||W==="i")&&T.add("italic"),W==="u"&&T.add("underline"),W==="h1"&&T.add("h1"),W==="h2"&&T.add("h2"),W==="h3"&&T.add("h3"),W==="ul"&&T.add("ul"),W==="ol"&&T.add("ol");const G=window.getComputedStyle(M);G.textAlign==="center"&&T.add("center"),G.textAlign==="right"&&T.add("right"),G.textAlign==="left"&&T.add("left");const ce=H=>{if(H.startsWith("#"))return H.toUpperCase();const ye=H.match(/\d+/g);if(!ye||ye.length<3)return null;const ae=ye[0],me=ye[1],Q=ye[2];if(!ae||!me||!Q)return null;const oe=parseInt(ae).toString(16).padStart(2,"0"),Ce=parseInt(me).toString(16).padStart(2,"0"),Ee=parseInt(Q).toString(16).padStart(2,"0");return`#${oe}${Ce}${Ee}`.toUpperCase()},te=G.backgroundColor;if(te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"&&te!=="rgb(255, 255, 255)"&&te!=="#ffffff"&&te!=="#FFFFFF"){T.add("highlight");const H=ce(te);if(H){const ye=Mn.find(ae=>ae.value==="transparent"?!1:ae.value.toUpperCase()===H);g(ye?ye.value:H)}}else T.has("highlight")||g(null);const L=G.color,z=ce(L);if(L&&z&&L!=="rgba(0, 0, 0, 0)"&&z!=="#000000"){T.add("textColor");const H=Mn.find(ye=>ye.value==="transparent"?!1:ye.value.toUpperCase()===z);C(H?H.value:z)}else T.has("textColor")||C(z==="#000000"||!z?"#000000":null);M=M.parentElement}}m(T)},[o]),N=p.useCallback((T,j)=>{if(!l.current)return;o||l.current.focus();const U=window.getSelection();if(!U||U.rangeCount===0){l.current.focus();return}document.execCommand(T,!1,j),l.current&&s(ba(l.current.innerHTML)),setTimeout(A,10)},[o,s,A]),P=p.useCallback(T=>{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 W=j.getRangeAt(0).commonAncestorContainer;let G=null;for(W.nodeType===Node.TEXT_NODE?G=W.parentElement:G=W;G&&G!==l.current;){const te=window.getComputedStyle(G).backgroundColor;if(te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"&&te!=="rgb(255, 255, 255)"&&te!=="#ffffff"&&te!=="#FFFFFF"){const z=(H=>{if(H.startsWith("#"))return H.toUpperCase();const ye=H.match(/\d+/g);if(!ye||ye.length<3)return null;const ae=ye[0],me=ye[1],Q=ye[2];if(!ae||!me||!Q)return null;const oe=parseInt(ae).toString(16).padStart(2,"0"),Ce=parseInt(me).toString(16).padStart(2,"0"),Ee=parseInt(Q).toString(16).padStart(2,"0");return`#${oe}${Ce}${Ee}`.toUpperCase()})(te);if(z&&z===T.toUpperCase()){U=!0;break}}G=G.parentElement}}if(T==="transparent"||U){const M=j.getRangeAt(0);if(M.collapsed)document.execCommand("removeFormat",!1);else{const W=M.extractContents(),G=document.createDocumentFragment(),ce=te=>{if(te.nodeType===Node.TEXT_NODE)return te.cloneNode(!0);if(te.nodeType===Node.ELEMENT_NODE){const L=te,z=document.createElement(L.tagName.toLowerCase());return Array.from(L.attributes).forEach(H=>{H.name!=="style"&&H.name!=="class"&&z.setAttribute(H.name,H.value)}),Array.from(L.childNodes).forEach(H=>{const ye=ce(H);ye&&z.appendChild(ye)}),L.style.backgroundColor&&(z.style.backgroundColor=""),z}return null};Array.from(W.childNodes).forEach(te=>{const L=ce(te);L&&G.appendChild(L)}),M.insertNode(G),document.execCommand("removeFormat",!1)}g(null),f("#FFEB3B")}else if(j.rangeCount>0&&!j.getRangeAt(0).collapsed)document.execCommand("backColor",!1,T),g(T),T!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(T)&&f(T);else return;const I=window.getSelection();I&&I.removeAllRanges(),l.current&&s(ba(l.current.innerHTML)),x(!1),setTimeout(()=>{l.current&&l.current.focus(),A()},50)},[o,s,A]),R=p.useCallback(T=>{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 M=j.getRangeAt(0).commonAncestorContainer;let W=null;for(M.nodeType===Node.TEXT_NODE?W=M.parentElement:W=M;W&&W!==l.current;){const ce=window.getComputedStyle(W).color;if(ce){const L=(z=>{if(z.startsWith("#"))return z.toUpperCase();const H=z.match(/\d+/g);if(!H||H.length<3)return null;const ye=H[0],ae=H[1],me=H[2];if(!ye||!ae||!me)return null;const Q=parseInt(ye).toString(16).padStart(2,"0"),oe=parseInt(ae).toString(16).padStart(2,"0"),Ce=parseInt(me).toString(16).padStart(2,"0");return`#${Q}${oe}${Ce}`.toUpperCase()})(ce);if(T==="#000000"){if(L==="#000000"||!L){U=!0;break}}else if(L&&L===T.toUpperCase()){U=!0;break}}W=W.parentElement}}if(T==="transparent"||T==="default"||U){if(T==="#000000"&&U){v(!1);return}document.execCommand("removeFormat",!1),C(null),S("#000000")}else document.execCommand("foreColor",!1,T),C(T),T!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(T)&&S(T);l.current&&s(ba(l.current.innerHTML)),v(!1),setTimeout(A,10)},[o,s,A]),O=p.useCallback(()=>{l.current&&s(ba(l.current.innerHTML)),A()},[s,A]),F=p.useCallback(T=>{if(T.ctrlKey&&T.key==="b"){T.preventDefault(),N("bold");return}if(T.ctrlKey&&T.key==="i"){T.preventDefault(),N("italic");return}if(T.ctrlKey&&T.key==="u"){T.preventDefault(),N("underline");return}},[N]),$=p.useCallback(()=>{c(!0)},[]),V=p.useCallback(()=>{c(!1),l.current&&s(ba(l.current.innerHTML))},[s]);return p.useEffect(()=>{if(!o)return;const T=()=>{A()};return document.addEventListener("selectionchange",T),()=>{document.removeEventListener("selectionchange",T)}},[o,A]),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(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.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(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>N("italic"),title:"Italic (Ctrl+I)",children:e.jsx(Yf,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>N("underline"),title:"Underline (Ctrl+U)",children:e.jsx(Kf,{className:"h-4 w-4"})}),e.jsxs(Hs,{open:h,onOpenChange:x,children:[e.jsx(Ws,{asChild:!0,children:e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.has("highlight")&&"bg-blue-100 text-blue-700"),title:"Text Highlight",children:e.jsx(Xf,{className:"h-4 w-4"})})}),e.jsx(Gs,{className:"w-auto p-2",align:"start",onPointerDownOutside:T=>{T.target.closest("[data-popover-content]")&&T.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:T=>T.stopPropagation(),children:[e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:T=>{T.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:Mn.map(T=>{const j=u===T.value,U=T.value==="transparent";return e.jsxs("button",{type:"button",onClick:I=>{I.preventDefault(),I.stopPropagation(),P(j&&!U?"transparent":T.value)},className:ke("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",T.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?`${T.name} (Click to remove)`:T.name,style:U?{}:{backgroundColor:T.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"})})]},T.value)})}),u&&u!=="transparent"&&e.jsx("div",{className:"mb-2",children:e.jsx(E,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:T=>{T.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:u&&u!=="transparent"?u:b,onChange:T=>{const j=T.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:u&&u!=="transparent"?u:b,onChange:T=>{T.stopPropagation();const j=T.target.value;f(j)},onKeyDown:T=>{if(T.stopPropagation(),T.key==="Enter"){T.preventDefault();const j=T.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(j)&&P(j)}},onPaste:T=>{T.stopPropagation();const j=T.clipboardData.getData("text").trim();T.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 I=`#${U[1]}`;f(I);const M=window.getSelection();M&&M.rangeCount>0&&!M.getRangeAt(0).collapsed&&P(I)}}},0)},onClick:T=>{T.stopPropagation()},onFocus:T=>{T.stopPropagation(),T.target.select()},onBlur:T=>{const j=T.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===""?u||"#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(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{const T=b.trim();/^#[0-9A-Fa-f]{6}$/i.test(T)?P(T):f(u||"#FFEB3B")},title:"Apply custom color",children:"Apply"})]})]})]})})]}),e.jsxs(Hs,{open:y,onOpenChange:v,children:[e.jsx(Ws,{asChild:!0,children:e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.has("textColor")&&"bg-blue-100 text-blue-700"),title:"Text Color",children:e.jsx(Zf,{className:"h-4 w-4"})})}),e.jsx(Gs,{className:"w-auto p-2",align:"start",onPointerDownOutside:T=>{T.target.closest("[data-popover-content]")&&T.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:T=>T.stopPropagation(),children:[e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:T=>{T.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:T=>{T.preventDefault(),T.stopPropagation(),w==="#000000"||!w&&!d.has("textColor")||R("#000000")},className:ke("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center bg-black",(w==="#000000"||!w&&!d.has("textColor"))&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",w!=="#000000"&&(w||d.has("textColor"))&&"border-gray-300"),title:"Default (Black)",children:[e.jsx("span",{className:"text-[10px] text-white font-bold",children:"A"}),(w==="#000000"||!w&&!d.has("textColor"))&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]}),Mn.filter(T=>T.value!=="transparent").map(T=>{const j=w===T.value;return e.jsxs("button",{type:"button",onClick:U=>{U.preventDefault(),U.stopPropagation(),R(j?"#000000":T.value)},className:ke("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?`${T.name} (Click to reset to default)`:T.name,style:{color:T.value,borderColor:j?"#2563eb":T.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-${T.value}`)})]}),w&&w!=="#000000"&&e.jsx("div",{className:"mb-2",children:e.jsx(E,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:T=>{T.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:w||k,onChange:T=>{const j=T.target.value;S(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:w||k,onChange:T=>{const j=T.target.value;S(j)},onKeyDown:T=>{if(T.key==="Enter"){T.preventDefault();const j=T.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(j)&&R(j)}},onBlur:T=>{const j=T.target.value;/^#[0-9A-Fa-f]{6}$/.test(j)?R(j):j===""&&S(w||"#000000")},placeholder:"#000000",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply)"}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>R(k),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(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>N("formatBlock","<h1>"),title:"Heading 1",children:e.jsx(Jf,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>N("formatBlock","<h2>"),title:"Heading 2",children:e.jsx(Qf,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.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(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>N("insertUnorderedList"),title:"Bullet List",children:e.jsx(Ku,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.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(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>N("justifyLeft"),title:"Align Left",children:e.jsx(Ju,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.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(E,{type:"button",variant:"ghost",size:"sm",className:ke("h-7 w-7 p-0",d.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:$,onBlur:V,onKeyDown:F,onMouseUp:A,onKeyUp:A,"data-placeholder":a,className:ke("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 sa({content:t,className:s}){const a=p.useMemo(()=>{if(!t)return"";let r=t;const n=/<table[^>]*>[\s\S]*?<\/table>/gi;return r=r.replace(n,i=>i.includes("table-wrapper")?i:`<div class="table-wrapper">${i}</div>`),ba(r)},[t]);return t?e.jsx("div",{className:ke("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 Kx={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(fi,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",l="second",o="minute",c="hour",d="day",m="week",h="month",x="quarter",u="year",g="date",b="Invalid Date",f=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,y=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,v={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(F){var $=["th","st","nd","rd"],V=F%100;return"["+F+($[(V-20)%10]||$[V]||$[0])+"]"}},w=function(F,$,V){var T=String(F);return!T||T.length>=$?F:""+Array($+1-T.length).join(V)+F},C={s:w,z:function(F){var $=-F.utcOffset(),V=Math.abs($),T=Math.floor(V/60),j=V%60;return($<=0?"+":"-")+w(T,2,"0")+":"+w(j,2,"0")},m:function F($,V){if($.date()<V.date())return-F(V,$);var T=12*(V.year()-$.year())+(V.month()-$.month()),j=$.clone().add(T,h),U=V-j<0,I=$.clone().add(T+(U?-1:1),h);return+(-(T+(V-j)/(U?j-I:I-j))||0)},a:function(F){return F<0?Math.ceil(F)||0:Math.floor(F)},p:function(F){return{M:h,y:u,w:m,d,D:g,h:c,m:o,s:l,ms:i,Q:x}[F]||String(F||"").toLowerCase().replace(/s$/,"")},u:function(F){return F===void 0}},k="en",S={};S[k]=v;var _="$isDayjsObject",D=function(F){return F instanceof R||!(!F||!F[_])},A=function F($,V,T){var j;if(!$)return k;if(typeof $=="string"){var U=$.toLowerCase();S[U]&&(j=U),V&&(S[U]=V,j=U);var I=$.split("-");if(!j&&I.length>1)return F(I[0])}else{var M=$.name;S[M]=$,j=M}return!T&&j&&(k=j),j||!T&&k},N=function(F,$){if(D(F))return F.clone();var V=typeof $=="object"?$:{};return V.date=F,V.args=arguments,new R(V)},P=C;P.l=A,P.i=D,P.w=function(F,$){return N(F,{locale:$.$L,utc:$.$u,x:$.$x,$offset:$.$offset})};var R=function(){function F(V){this.$L=A(V.locale,null,!0),this.parse(V),this.$x=this.$x||V.x||{},this[_]=!0}var $=F.prototype;return $.parse=function(V){this.$d=function(T){var j=T.date,U=T.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 I=j.match(f);if(I){var M=I[2]-1||0,W=(I[7]||"0").substring(0,3);return U?new Date(Date.UTC(I[1],M,I[3]||1,I[4]||0,I[5]||0,I[6]||0,W)):new Date(I[1],M,I[3]||1,I[4]||0,I[5]||0,I[6]||0,W)}}return new Date(j)}(V),this.init()},$.init=function(){var V=this.$d;this.$y=V.getFullYear(),this.$M=V.getMonth(),this.$D=V.getDate(),this.$W=V.getDay(),this.$H=V.getHours(),this.$m=V.getMinutes(),this.$s=V.getSeconds(),this.$ms=V.getMilliseconds()},$.$utils=function(){return P},$.isValid=function(){return this.$d.toString()!==b},$.isSame=function(V,T){var j=N(V);return this.startOf(T)<=j&&j<=this.endOf(T)},$.isAfter=function(V,T){return N(V)<this.startOf(T)},$.isBefore=function(V,T){return this.endOf(T)<N(V)},$.$g=function(V,T,j){return P.u(V)?this[T]:this.set(j,V)},$.unix=function(){return Math.floor(this.valueOf()/1e3)},$.valueOf=function(){return this.$d.getTime()},$.startOf=function(V,T){var j=this,U=!!P.u(T)||T,I=P.p(V),M=function(ye,ae){var me=P.w(j.$u?Date.UTC(j.$y,ae,ye):new Date(j.$y,ae,ye),j);return U?me:me.endOf(d)},W=function(ye,ae){return P.w(j.toDate()[ye].apply(j.toDate("s"),(U?[0,0,0,0]:[23,59,59,999]).slice(ae)),j)},G=this.$W,ce=this.$M,te=this.$D,L="set"+(this.$u?"UTC":"");switch(I){case u:return U?M(1,0):M(31,11);case h:return U?M(1,ce):M(0,ce+1);case m:var z=this.$locale().weekStart||0,H=(G<z?G+7:G)-z;return M(U?te-H:te+(6-H),ce);case d:case g:return W(L+"Hours",0);case c:return W(L+"Minutes",1);case o:return W(L+"Seconds",2);case l:return W(L+"Milliseconds",3);default:return this.clone()}},$.endOf=function(V){return this.startOf(V,!1)},$.$set=function(V,T){var j,U=P.p(V),I="set"+(this.$u?"UTC":""),M=(j={},j[d]=I+"Date",j[g]=I+"Date",j[h]=I+"Month",j[u]=I+"FullYear",j[c]=I+"Hours",j[o]=I+"Minutes",j[l]=I+"Seconds",j[i]=I+"Milliseconds",j)[U],W=U===d?this.$D+(T-this.$W):T;if(U===h||U===u){var G=this.clone().set(g,1);G.$d[M](W),G.init(),this.$d=G.set(g,Math.min(this.$D,G.daysInMonth())).$d}else M&&this.$d[M](W);return this.init(),this},$.set=function(V,T){return this.clone().$set(V,T)},$.get=function(V){return this[P.p(V)]()},$.add=function(V,T){var j,U=this;V=Number(V);var I=P.p(T),M=function(ce){var te=N(U);return P.w(te.date(te.date()+Math.round(ce*V)),U)};if(I===h)return this.set(h,this.$M+V);if(I===u)return this.set(u,this.$y+V);if(I===d)return M(1);if(I===m)return M(7);var W=(j={},j[o]=r,j[c]=n,j[l]=a,j)[I]||1,G=this.$d.getTime()+V*W;return P.w(G,this)},$.subtract=function(V,T){return this.add(-1*V,T)},$.format=function(V){var T=this,j=this.$locale();if(!this.isValid())return j.invalidDate||b;var U=V||"YYYY-MM-DDTHH:mm:ssZ",I=P.z(this),M=this.$H,W=this.$m,G=this.$M,ce=j.weekdays,te=j.months,L=j.meridiem,z=function(ae,me,Q,oe){return ae&&(ae[me]||ae(T,U))||Q[me].slice(0,oe)},H=function(ae){return P.s(M%12||12,ae,"0")},ye=L||function(ae,me,Q){var oe=ae<12?"AM":"PM";return Q?oe.toLowerCase():oe};return U.replace(y,function(ae,me){return me||function(Q){switch(Q){case"YY":return String(T.$y).slice(-2);case"YYYY":return P.s(T.$y,4,"0");case"M":return G+1;case"MM":return P.s(G+1,2,"0");case"MMM":return z(j.monthsShort,G,te,3);case"MMMM":return z(te,G);case"D":return T.$D;case"DD":return P.s(T.$D,2,"0");case"d":return String(T.$W);case"dd":return z(j.weekdaysMin,T.$W,ce,2);case"ddd":return z(j.weekdaysShort,T.$W,ce,3);case"dddd":return ce[T.$W];case"H":return String(M);case"HH":return P.s(M,2,"0");case"h":return H(1);case"hh":return H(2);case"a":return ye(M,W,!0);case"A":return ye(M,W,!1);case"m":return String(W);case"mm":return P.s(W,2,"0");case"s":return String(T.$s);case"ss":return P.s(T.$s,2,"0");case"SSS":return P.s(T.$ms,3,"0");case"Z":return I}return null}(ae)||I.replace(":","")})},$.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},$.diff=function(V,T,j){var U,I=this,M=P.p(T),W=N(V),G=(W.utcOffset()-this.utcOffset())*r,ce=this-W,te=function(){return P.m(I,W)};switch(M){case u:U=te()/12;break;case h:U=te();break;case x:U=te()/3;break;case m:U=(ce-G)/6048e5;break;case d:U=(ce-G)/864e5;break;case c: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)},$.daysInMonth=function(){return this.endOf(h).$D},$.$locale=function(){return S[this.$L]},$.locale=function(V,T){if(!V)return this.$L;var j=this.clone(),U=A(V,T,!0);return U&&(j.$L=U),j},$.clone=function(){return P.w(this.$d,this)},$.toDate=function(){return new Date(this.valueOf())},$.toJSON=function(){return this.isValid()?this.toISOString():null},$.toISOString=function(){return this.$d.toISOString()},$.toString=function(){return this.$d.toUTCString()},F}(),O=R.prototype;return N.prototype=O,[["$ms",i],["$s",l],["$m",o],["$H",c],["$W",d],["$M",h],["$y",u],["$D",g]].forEach(function(F){O[F[1]]=function($){return this.$g($,F[0],F[1])}}),N.extend=function(F,$){return F.$i||(F($,R,N),F.$i=!0),N},N.locale=A,N.isDayjs=D,N.unix=function(F){return N(1e3*F)},N.en=S[k],N.Ls=S,N.p={},N})})(Kx);var iN=Kx.exports;const Bt=bi(iN);var Xx={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(fi,function(){return function(a,r,n){a=a||{};var i=r.prototype,l={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function o(d,m,h,x){return i.fromToBase(d,m,h,x)}n.en.relativeTime=l,i.fromToBase=function(d,m,h,x,u){for(var g,b,f,y=h.$locale().relativeTime||l,v=a.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],w=v.length,C=0;C<w;C+=1){var k=v[C];k.d&&(g=x?n(d).diff(h,k.d,!0):h.diff(d,k.d,!0));var S=(a.rounding||Math.round)(Math.abs(g));if(f=g>0,S<=k.r||!k.r){S<=1&&C>0&&(k=v[C-1]);var _=y[k.l];u&&(S=u(""+S)),b=typeof _=="string"?_.replace("%d",S):_(S,m,k.l,f);break}}if(m)return b;var D=f?y.future:y.past;return typeof D=="function"?D(b):D.replace("%s",b)},i.to=function(d,m){return o(d,m,this,!0)},i.from=function(d,m){return o(d,m,this)};var c=function(d){return d.$u?n.utc():n()};i.toNow=function(d){return this.to(c(this),d)},i.fromNow=function(d){return this.from(c(this),d)}}})})(Xx);var lN=Xx.exports;const oN=bi(lN);Bt.extend(oN);function cN({request:t,isInitiator:s,needsClosure:a,conclusionRemark:r,setConclusionRemark:n,conclusionLoading:i,conclusionSubmitting:l,aiGenerated:o,handleGenerateConclusion:c,handleFinalizeConclusion:d,onPause:m,onResume:h,onRetrigger:x,currentUserIsApprover:u=!1,pausedByUserId:g,currentUserId:b,generationAttempts:f=0,generationFailed:y=!1,maxAttemptsReached:v=!1}){var N,P,R,O,F,$,V,T;const{user:w}=Kt(),C=t==null?void 0:t.pauseInfo,k=(C==null?void 0:C.isPaused)||!1,S=(N=C==null?void 0:C.pausedBy)==null?void 0:N.userId,_=(w==null?void 0:w.userId)||"",D=k&&h&&(u||s),A=k&&s&&S&&S!==_&&x;return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[e.jsxs(ee,{"data-testid":"initiator-card",children:[e.jsx(ge,{className:"pb-3 sm:pb-4",children:e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Vt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(se,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(Zt,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(Jt,{className:"bg-gray-700 text-white font-semibold text-sm",children:((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:((F=t.initiator)==null?void 0:F.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(Ra,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:(($=t.initiator)==null?void 0:$.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(ji,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((V=t.initiator)==null?void 0:V.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(ee,{"data-testid":"request-details-card",children:[e.jsx(ge,{className:"pb-3 sm:pb-4",children:e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(se,{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs sm:text-sm font-medium text-gray-700 block mb-2",children:"Description"}),e.jsx("div",{className:"bg-gray-50 rounded-lg p-3 sm:p-4 border border-gray-300",children:e.jsx(sa,{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:Qt(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:Qt(t.updatedAt)})]})]})]})]}),k&&C&&e.jsxs(ee,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(ge,{className:"pb-3 sm:pb-4",children:e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(za,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(se,{className:"space-y-3 sm:space-y-4",children:[e.jsx("div",{className:"bg-white rounded-lg p-3 sm:p-4 border border-orange-200",children:e.jsxs("div",{className:"space-y-2 sm:space-y-3",children:[C.pauseReason&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Reason"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:C.pauseReason})]}),C.pausedBy&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused By"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:C.pausedBy.name||C.pausedBy.email})]}),C.pauseResumeDate&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Auto-Resume Date"}),e.jsxs("p",{className:"text-sm text-gray-900 mt-1",children:[Qt(C.pauseResumeDate),Bt(C.pauseResumeDate).isAfter(Bt())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",Bt(C.pauseResumeDate).fromNow(),")"]})]})]}),C.pausedAt&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused At"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:Qt(C.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[D&&h&&e.jsxs(E,{onClick:h,className:"bg-green-600 hover:bg-green-700 text-white text-xs sm:text-sm h-8 sm:h-9",size:"sm",children:[e.jsx(ri,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),A&&x&&e.jsxs(E,{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(ze,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Request Resume"]})]})]})]}),t.claimDetails&&e.jsxs(ee,{children:[e.jsx(ge,{className:"pb-4",children:e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(Re,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityName||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Type"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityType||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Location"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.location||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Date"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityDate?Yx(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(sa,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(ee,{children:[e.jsxs(ge,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(De,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx($e,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(se,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(sa,{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 ",Qt(t.closureDate)]}),e.jsxs("span",{children:["By ",((T=t.initiator)==null?void 0:T.name)||"Initiator"]})]})]})]}),a&&e.jsxs(ee,{"data-testid":"conclusion-remark-card",children:[e.jsx(ge,{className:`bg-gradient-to-r border-b ${t.status==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(De,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx($e,{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(E,{variant:"outline",size:"sm",onClick:c,disabled:i||v,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx($t,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),o?"Regenerate":"Generate with AI"]}),o&&!v&&!y&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-f," attempts remaining"]})]})]})}),e.jsx(se,{className:"pt-4",children:i?e.jsx("div",{className:"flex items-center justify-center py-8","data-testid":"conclusion-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx(lt,{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(Rn,{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(E,{onClick:d,disabled:l||!r.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:l?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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 Kn({delayDuration:t=0,...s}){return e.jsx(sf,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function al({...t}){return e.jsx(Kn,{children:e.jsx(af,{"data-slot":"tooltip",...t})})}function rl({...t}){return e.jsx(rf,{"data-slot":"tooltip-trigger",...t})}function nl({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(nf,{children:e.jsxs(lf,{"data-slot":"tooltip-content",sideOffset:s,className:ke("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 pt({...t}){return e.jsx(mf,{"data-slot":"dialog",...t})}function dN({...t}){return e.jsx(df,{"data-slot":"dialog-portal",...t})}const Zx=p.forwardRef(({className:t,...s},a)=>e.jsx(_u,{ref:a,"data-slot":"dialog-overlay",className:ke("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}));Zx.displayName=_u.displayName;const dt=p.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(dN,{"data-slot":"dialog-portal",children:[e.jsx(Zx,{}),e.jsxs(Lu,{ref:r,"data-slot":"dialog-content",className:ke("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"})]})]})]}));dt.displayName=Lu.displayName;const gt=p.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:ke("flex flex-col gap-2 text-center sm:text-left",t),...s}));gt.displayName="DialogHeader";const Tt=p.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:ke("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));Tt.displayName="DialogFooter";const mt=p.forwardRef(({className:t,...s},a)=>e.jsx(Mu,{ref:a,"data-slot":"dialog-title",className:ke("text-lg leading-none font-semibold",t),...s}));mt.displayName=Mu.displayName;const Dt=p.forwardRef(({className:t,...s},a)=>e.jsx($u,{ref:a,"data-slot":"dialog-description",className:ke("text-muted-foreground text-sm",t),...s}));Dt.displayName=$u.displayName;function Ds({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:ke("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 Qd=t=>{if(t<8)return Ft(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${Ft(r)}`:`${a}d`},mN=(t,s)=>{if(s)return e.jsx(ze,{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(wt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"paused":return e.jsx(Qu,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(st,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(st,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(st,{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:c="approval-step"}){const{user:d}=Kt(),[m,h]=p.useState(!1),[x,u]=p.useState(""),[g,b]=p.useState(!1),f=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";p.useEffect(()=>{m||u("")},[m]);const y=t.status==="pending"||t.status==="in-review",v=t.status==="approved",w=t.status==="rejected",C=t.status==="waiting",k=t.status==="paused",S=Number(t.tatHours||0),_=t.actualHours??0,D=v&&_?Math.max(0,S-_):0,A=S>0?_/S*100:0,N=A>=100,P=(d==null?void 0:d.role)==="ADMIN",R=ki(d),O=t.approverId===(d==null?void 0:d.userId),F=P||R||O,$=async()=>{var V,T;if(!x.trim()){K.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}b(!0);try{await aN(t.levelId,x.trim()),h(!1),u(""),K.success("Breach Reason Updated",{description:"The breach reason has been saved and will appear in the TAT Breach Report.",duration:5e3}),o?await o():setTimeout(()=>{window.location.reload()},1e3)}catch(j){console.error("Error updating breach reason:",j);const U=((T=(V=j==null?void 0:j.response)==null?void 0:V.data)==null?void 0:T.error)||(j==null?void 0:j.message)||"Failed to update breach reason. Please try again.";K.error("Failed to Update Breach Reason",{description:U,duration:5e3})}finally{b(!1)}};return e.jsxs("div",{className:`relative p-3 sm:p-4 md:p-5 rounded-lg border-2 transition-all ${t.isSkipped?"border-orange-500 bg-orange-50":y?"border-blue-500 bg-blue-50 shadow-md":v?"border-green-500 bg-green-50":w?"border-red-500 bg-red-50":C?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${c}-${t.step}`,children:[e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 md:gap-4",children:[e.jsx("div",{className:`p-2 sm:p-2.5 md:p-3 rounded-xl flex-shrink-0 ${t.isSkipped?"bg-orange-100":k?"bg-yellow-100":y?"bg-blue-100":v?"bg-green-100":w?"bg-red-100":C?"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":`${c}-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":y?"bg-yellow-100 text-yellow-800 border-yellow-200":v?"bg-green-100 text-green-800 border-green-200":w?"bg-red-100 text-red-800 border-red-200":C?"bg-gray-200 text-gray-600 border-gray-300":"bg-gray-100 text-gray-800 border-gray-200"}`,"data-testid":`${c}-status-badge`,children:t.isSkipped?"skipped":t.status}),t.isSkipped&&t.skipReason&&e.jsx(Kn,{delayDuration:200,children:e.jsxs(al,{children:[e.jsx(rl,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:V=>V.stopPropagation(),children:e.jsx(ze,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(nl,{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(Dd,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),v&&_&&e.jsx(ne,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:Qd(_)})]}),e.jsx("p",{className:"text-sm font-semibold text-gray-900","data-testid":`${c}-approver-name`,children:r?e.jsx("span",{className:"text-blue-600",children:"You"}):t.approver}),e.jsx("p",{className:"text-xs text-gray-600","data-testid":`${c}-role`,children:t.role})]}),e.jsxs("div",{className:"text-left sm:text-right flex-shrink-0",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium",children:"Turnaround Time (TAT)"}),e.jsxs("p",{className:"text-lg font-bold text-gray-900","data-testid":`${c}-tat-hours`,children:[S," hours"]})]})]}),v&&_!==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?Qt(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:Qd(_)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const V=Math.min(100,A),T=()=>N?"bg-red-600":A>=75?"bg-orange-500":A>=50?"bg-amber-500":"bg-green-600",j=()=>N?"text-red-600":A>=75?"text-orange-600":A>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(na,{value:V,className:"h-2 bg-gray-200",indicatorClassName:T(),"data-testid":`${c}-progress-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-semibold ${j()}`,children:[Math.round(V),"% of TAT used"]}),N&&F&&e.jsx(Kn,{children:e.jsxs(al,{children:[e.jsx(rl,{asChild:!0,children:e.jsx(E,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{u(f),h(!0)},children:e.jsx(_n,{className:"w-3 h-3"})})}),e.jsx(nl,{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 ",Ft(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(As,{className:"w-3.5 h-3.5 text-blue-600"}),"Conclusion Remark:"]}),e.jsx("p",{className:"text-sm text-gray-700 italic leading-relaxed",children:t.comment})]})]}),i&&(y||k)&&(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?xa(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${k?"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(st,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",k&&"(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," / ",Ft(S)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const V=a.sla.percentageUsed||0,T=()=>k?"bg-gray-500":V>=100?"bg-red-600":V>=75?"bg-orange-500":V>=50?"bg-amber-500":"bg-green-600",j=()=>k?"text-gray-600":V>=100?"text-red-600":V>=75?"text-orange-600":V>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(na,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:T(),"data-testid":`${c}-sla-progress`}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`text-xs font-semibold ${j()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&F&&e.jsx(Kn,{children:e.jsxs(al,{children:[e.jsx(rl,{asChild:!0,children:e.jsx(E,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{u(f),h(!0)},children:e.jsx(_n,{className:"w-3 h-3"})})}),e.jsx(nl,{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(ni,{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(as,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),C&&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(Qu,{className:"w-3.5 h-3.5 text-gray-500"}),"Awaiting Previous Approval"]}),e.jsx("p",{className:"text-sm font-medium text-gray-700",children:"Will be assigned after previous step"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Allocated ",S," hours for approval"]})]})}),w&&t.comment&&e.jsxs("div",{className:"mt-3 p-3 sm:p-4 bg-red-50 border-l-4 border-red-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 mb-2 flex items-center gap-1.5",children:[e.jsx(wt,{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(Dd,{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 ",Qt(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((V,T)=>{var j,U,I,M,W,G;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${V.isBreached?"bg-red-50 border-red-200":(V.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${T}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(V.thresholdPercentage||0)===50&&e.jsx(a0,{className:"w-5 h-5 text-yellow-600"}),(V.thresholdPercentage||0)===75&&e.jsx(as,{className:"w-5 h-5 text-orange-600"}),(V.thresholdPercentage||0)===100&&e.jsx(ni,{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 ",T+1," - ",V.thresholdPercentage||0,"% TAT"]}),e.jsx(ne,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${V.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:V.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[V.thresholdPercentage||0,"% of SLA breach reminder have been sent"]}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-1.5 sm:gap-2 text-[10px] sm:text-xs",children:[e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Allocated:"}),e.jsx("span",{className:"ml-1 font-medium text-gray-900",children:Ft(Number(V.tatHoursAllocated||0))})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Elapsed:"}),e.jsxs("span",{className:"ml-1 font-medium text-gray-900",children:[Ft(Number(V.tatHoursElapsed||0)),((j=V.metadata)==null?void 0:j.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(V.tatHoursElapsed||0)*60).toFixed(0),"m)"]})]})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Remaining:"}),e.jsxs("span",{className:`ml-1 font-medium ${(V.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[Ft(Number(V.tatHoursRemaining||0)),((U=V.metadata)==null?void 0:U.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(V.tatHoursRemaining||0)*60).toFixed(0),"m)"]})]})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Due by:"}),e.jsx("span",{className:"ml-1 font-medium text-gray-900",children:V.expectedCompletionTime?xa(V.expectedCompletionTime,!0):"N/A"})]})]}),e.jsxs("div",{className:"mt-2 pt-2 border-t border-gray-200",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1",children:[e.jsx("p",{className:"text-[10px] sm:text-xs text-gray-500",children:"Reminder sent by system automatically"}),(((I=V.metadata)==null?void 0:I.testMode)||((M=V.metadata)==null?void 0:M.tatTestMode))&&e.jsx(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: ",V.alertSentAt?Qt(V.alertSentAt):"N/A"]}),(((W=V.metadata)==null?void 0:W.testMode)||((G=V.metadata)==null?void 0:G.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},T)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[v?"Approved":w?"Rejected":"Actioned"," on ",Qt(t.timestamp)]}),n&&!k&&(y||t.status==="pending")&&!v&&!w&&t.levelId&&l&&e.jsxs("div",{className:"mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-200",children:[e.jsxs(E,{variant:"outline",size:"sm",className:"w-full border-orange-300 text-orange-700 hover:bg-orange-50 h-9 sm:h-10 text-xs sm:text-sm",onClick:()=>l({levelId:t.levelId,approverName:t.approver,levelNumber:t.step}),"data-testid":`${c}-skip-button`,children:[e.jsx(ze,{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:k?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(pt,{open:m,onOpenChange:h,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsxs(gt,{children:[e.jsx(mt,{children:f?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(Dt,{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(Ds,{placeholder:"Enter the reason for the breach...",value:x,onChange:V=>u(V.target.value),className:"min-h-[100px]",maxLength:500}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[x.length,"/500 characters"]})]}),e.jsxs(Tt,{children:[e.jsx(E,{variant:"outline",onClick:()=>{h(!1),u("")},disabled:g,children:"Cancel"}),e.jsx(E,{onClick:$,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(ee,{children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(ta,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx($e,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var u;const i=t.totalSteps||1,l=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,o=((u=t.approvalFlow)==null?void 0:u.filter(g=>{const b=(g.status||"").toLowerCase();return b==="approved"||b==="rejected"}).length)||0,c=o>=i,d=(t.status||"").toLowerCase(),m=d==="approved"||d==="rejected"||d==="closed",h=l>i,x=Math.min(Math.max(1,l),i);return h?e.jsxs(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||c?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(se,{children:t.approvalFlow&&t.approvalFlow.length>0?e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.approvalFlow.map((i,l)=>{var u,g,b;const o=(u=t.approvals)==null?void 0:u.find(f=>f.levelId===i.levelId),c=(g=s==null?void 0:s.email)==null?void 0:g.toLowerCase(),d=(b=i.approverEmail)==null?void 0:b.toLowerCase(),m=c&&d&&c===d,h=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,x=i.step===h;return e.jsx(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 Fo=p.createContext({});function _o(t){const s=p.useRef(null);return s.current===null&&(s.current=t()),s.current}const Lo=typeof window<"u",Jx=Lo?p.useLayoutEffect:p.useEffect,Ii=p.createContext(null);function Mo(t,s){t.indexOf(s)===-1&&t.push(s)}function $o(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const Pa=(t,s,a)=>a>s?s:a<t?t:a;let Oo=()=>{};const Ia={},Qx=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function qx(t){return typeof t=="object"&&t!==null}const eh=t=>/^0[^.\s]+$/u.test(t);function Uo(t){let s;return()=>(s===void 0&&(s=t()),s)}const aa=t=>t,hN=(t,s)=>a=>s(t(a)),Dn=(...t)=>t.reduce(hN),fn=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class Bo{constructor(){this.subscriptions=[]}add(s){return Mo(this.subscriptions,s),()=>$o(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 ya=t=>t*1e3,ea=t=>t/1e3;function th(t,s){return s?t*(1e3/s):0}const sh=(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=sh(l,r,n)-t,i>0?a=l:s=l;while(Math.abs(i)>pN&&++o<gN);return l}function Pn(t,s,a,r){if(t===s&&a===r)return aa;const n=i=>fN(i,0,1,t,a);return i=>i===0||i===1?i:sh(n(i),s,r)}const ah=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,rh=t=>s=>1-t(1-s),nh=Pn(.33,1.53,.69,.99),Vo=rh(nh),ih=ah(Vo),lh=t=>(t*=2)<1?.5*Vo(t):.5*(2-Math.pow(2,-10*(t-1))),zo=t=>1-Math.sin(Math.acos(t)),oh=rh(zo),ch=ah(zo),bN=Pn(.42,0,1,1),yN=Pn(0,0,.58,1),dh=Pn(.42,0,.58,1),vN=t=>Array.isArray(t)&&typeof t[0]!="number",mh=t=>Array.isArray(t)&&typeof t[0]=="number",jN={linear:aa,easeIn:bN,easeInOut:dh,easeOut:yN,circIn:zo,circInOut:ch,circOut:oh,backIn:Vo,backInOut:ih,backOut:nh,anticipate:lh},NN=t=>typeof t=="string",qd=t=>{if(mh(t)){Oo(t.length===4);const[s,a,r,n]=t;return Pn(s,a,r,n)}else if(NN(t))return jN[t];return t},$n=["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 c(m){l.has(m)&&(d.schedule(m),t()),m(o)}const d={schedule:(m,h=!1,x=!1)=>{const g=x&&n?a:r;return h&&l.add(m),g.has(m)||g.add(m),m},cancel:m=>{r.delete(m),l.delete(m)},process:m=>{if(o=m,n){i=!0;return}n=!0,[a,r]=[r,a],a.forEach(c),a.clear(),n=!1,i&&(i=!1,d.process(m))}};return d}const CN=40;function uh(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,l=$n.reduce((w,C)=>(w[C]=wN(i),w),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:m,update:h,preRender:x,render:u,postRender:g}=l,b=()=>{const w=Ia.useManualTiming?n.timestamp:performance.now();a=!1,Ia.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(w-n.timestamp,CN),1)),n.timestamp=w,n.isProcessing=!0,o.process(n),c.process(n),d.process(n),m.process(n),h.process(n),x.process(n),u.process(n),g.process(n),n.isProcessing=!1,a&&s&&(r=!1,t(b))},f=()=>{a=!0,r=!0,n.isProcessing||t(b)};return{schedule:$n.reduce((w,C)=>{const k=l[C];return w[C]=(S,_=!1,D=!1)=>(a||f(),k.schedule(S,_,D)),w},{}),cancel:w=>{for(let C=0;C<$n.length;C++)l[$n[C]].cancel(w)},state:n,steps:l}}const{schedule:Mt,cancel:Wa,state:xs,steps:il}=uh(typeof requestAnimationFrame<"u"?requestAnimationFrame:aa,!0);let Xn;function SN(){Xn=void 0}const $s={now:()=>(Xn===void 0&&$s.set(xs.isProcessing||Ia.useManualTiming?xs.timestamp:performance.now()),Xn),set:t=>{Xn=t,queueMicrotask(SN)}},xh=t=>s=>typeof s=="string"&&s.startsWith(t),Ho=xh("--"),AN=xh("var(--"),Wo=t=>AN(t)?TN.test(t.split("/*")[0].trim()):!1,TN=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Wr={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},bn={...Wr,transform:t=>Pa(0,1,t)},On={...Wr,default:1},cn=t=>Math.round(t*1e5)/1e5,Go=/-?(?:\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,Yo=(t,s)=>a=>!!(typeof a=="string"&&RN.test(a)&&a.startsWith(t)||s&&!kN(a)&&Object.prototype.hasOwnProperty.call(a,s)),hh=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,l,o]=r.match(Go);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},DN=t=>Pa(0,255,t),ll={...Wr,transform:t=>Math.round(DN(t))},hr={test:Yo("rgb","red"),parse:hh("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+ll.transform(t)+", "+ll.transform(s)+", "+ll.transform(a)+", "+cn(bn.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 $l={test:Yo("#"),parse:PN,transform:hr.transform},In=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),Ua=In("deg"),va=In("%"),Je=In("px"),IN=In("vh"),EN=In("vw"),em={...va,parse:t=>va.parse(t)/100,transform:t=>va.transform(t*100)},Ar={test:Yo("hsl","hue"),parse:hh("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+va.transform(cn(s))+", "+va.transform(cn(a))+", "+cn(bn.transform(r))+")"},Xt={test:t=>hr.test(t)||$l.test(t)||Ar.test(t),parse:t=>hr.test(t)?hr.parse(t):Ar.test(t)?Ar.parse(t):$l.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?hr.transform(t):Ar.transform(t),getAnimatableNone:t=>{const s=Xt.parse(t);return s.alpha=0,Xt.transform(s)}},FN=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function _N(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(Go))==null?void 0:s.length)||0)+(((a=t.match(FN))==null?void 0:a.length)||0)>0}const ph="number",gh="color",LN="var",MN="var(",tm="${}",$N=/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 yn(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const o=s.replace($N,c=>(Xt.test(c)?(r.color.push(i),n.push(gh),a.push(Xt.parse(c))):c.startsWith(MN)?(r.var.push(i),n.push(LN),a.push(c)):(r.number.push(i),n.push(ph),a.push(parseFloat(c))),++i,tm)).split(tm);return{values:a,split:o,indexes:r,types:n}}function fh(t){return yn(t).values}function bh(t){const{split:s,types:a}=yn(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===ph?i+=cn(n[l]):o===gh?i+=Xt.transform(n[l]):i+=n[l]}return i}}const ON=t=>typeof t=="number"?0:Xt.test(t)?Xt.getAnimatableNone(t):t;function UN(t){const s=fh(t);return bh(t)(s.map(ON))}const Ga={test:_N,parse:fh,createTransformer:bh,getAnimatableNone:UN};function ol(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,c=2*a-o;n=ol(c,o,t+1/3),i=ol(c,o,t),l=ol(c,o,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function ci(t,s){return a=>a>0?s:t}const zt=(t,s,a)=>t+(s-t)*a,cl=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},VN=[$l,hr,Ar],zN=t=>VN.find(s=>s.test(t));function sm(t){const s=zN(t);if(!s)return!1;let a=s.parse(t);return s===Ar&&(a=BN(a)),a}const am=(t,s)=>{const a=sm(t),r=sm(s);if(!a||!r)return ci(t,s);const n={...a};return i=>(n.red=cl(a.red,r.red,i),n.green=cl(a.green,r.green,i),n.blue=cl(a.blue,r.blue,i),n.alpha=zt(a.alpha,r.alpha,i),hr.transform(n))},Ol=new Set(["none","hidden"]);function HN(t,s){return Ol.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function WN(t,s){return a=>zt(t,s,a)}function Ko(t){return typeof t=="number"?WN:typeof t=="string"?Wo(t)?ci:Xt.test(t)?am:KN:Array.isArray(t)?yh:typeof t=="object"?Xt.test(t)?am:GN:ci}function yh(t,s){const a=[...t],r=a.length,n=t.map((i,l)=>Ko(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]=Ko(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function YN(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 KN=(t,s)=>{const a=Ga.createTransformer(s),r=yn(t),n=yn(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?Ol.has(t)&&!n.values.length||Ol.has(s)&&!r.values.length?HN(t,s):Dn(yh(YN(r,n),n.values),a):ci(t,s)};function vh(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?zt(t,s,a):Ko(t)(t,s)}const XN=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>Mt.update(s,a),stop:()=>Wa(s),now:()=>xs.isProcessing?xs.timestamp:$s.now()}},jh=(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)})`},di=2e4;function Xo(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<di;)s+=a,r=t.next(s);return s>=di?1/0:s}function ZN(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(Xo(r),di);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:ea(n)}}const JN=5;function Nh(t,s,a){const r=Math.max(s-JN,0);return th(a-t(r),s-r)}const Wt={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},dl=.001;function QN({duration:t=Wt.duration,bounce:s=Wt.bounce,velocity:a=Wt.velocity,mass:r=Wt.mass}){let n,i,l=1-s;l=Pa(Wt.minDamping,Wt.maxDamping,l),t=Pa(Wt.minDuration,Wt.maxDuration,ea(t)),l<1?(n=d=>{const m=d*l,h=m*t,x=m-a,u=Ul(d,l),g=Math.exp(-h);return dl-x/u*g},i=d=>{const h=d*l*t,x=h*a+a,u=Math.pow(l,2)*Math.pow(d,2)*t,g=Math.exp(-h),b=Ul(Math.pow(d,2),l);return(-n(d)+dl>0?-1:1)*((x-u)*g)/b}):(n=d=>{const m=Math.exp(-d*t),h=(d-a)*t+1;return-dl+m*h},i=d=>{const m=Math.exp(-d*t),h=(a-d)*(t*t);return m*h});const o=5/t,c=ew(n,i,o);if(t=ya(t),isNaN(c))return{stiffness:Wt.stiffness,damping:Wt.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),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 Ul(t,s){return t*Math.sqrt(1-s*s)}const tw=["duration","bounce"],sw=["stiffness","damping","mass"];function rm(t,s){return s.some(a=>t[a]!==void 0)}function aw(t){let s={velocity:Wt.velocity,stiffness:Wt.stiffness,damping:Wt.damping,mass:Wt.mass,isResolvedFromDuration:!1,...t};if(!rm(t,sw)&&rm(t,tw))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*Pa(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:Wt.mass,stiffness:n,damping:i}}else{const a=QN(t);s={...s,...a,mass:Wt.mass},s.isResolvedFromDuration=!0}return s}function mi(t=Wt.visualDuration,s=Wt.bounce){const a=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:s}:t;let{restSpeed:r,restDelta:n}=a;const i=a.keyframes[0],l=a.keyframes[a.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:m,duration:h,velocity:x,isResolvedFromDuration:u}=aw({...a,velocity:-ea(a.velocity||0)}),g=x||0,b=d/(2*Math.sqrt(c*m)),f=l-i,y=ea(Math.sqrt(c/m)),v=Math.abs(f)<5;r||(r=v?Wt.restSpeed.granular:Wt.restSpeed.default),n||(n=v?Wt.restDelta.granular:Wt.restDelta.default);let w;if(b<1){const k=Ul(y,b);w=S=>{const _=Math.exp(-b*y*S);return l-_*((g+b*y*f)/k*Math.sin(k*S)+f*Math.cos(k*S))}}else if(b===1)w=k=>l-Math.exp(-y*k)*(f+(g+y*f)*k);else{const k=y*Math.sqrt(b*b-1);w=S=>{const _=Math.exp(-b*y*S),D=Math.min(k*S,300);return l-_*((g+b*y*f)*Math.sinh(D)+k*f*Math.cosh(D))/k}}const C={calculatedDuration:u&&h||null,next:k=>{const S=w(k);if(u)o.done=k>=h;else{let _=k===0?g:0;b<1&&(_=k===0?ya(g):Nh(w,k,S));const D=Math.abs(_)<=r,A=Math.abs(l-S)<=n;o.done=D&&A}return o.value=o.done?l:S,o},toString:()=>{const k=Math.min(Xo(C),di),S=jh(_=>C.next(k*_).value,k,30);return k+"ms "+S},toTransition:()=>{}};return C}mi.applyToOptions=t=>{const s=ZN(t,100,mi);return t.ease=s.ease,t.duration=ya(s.duration),t.type="keyframes",t};function Bl({keyframes:t,velocity:s=0,power:a=.8,timeConstant:r=325,bounceDamping:n=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:m}){const h=t[0],x={done:!1,value:h},u=D=>o!==void 0&&D<o||c!==void 0&&D>c,g=D=>o===void 0?c:c===void 0||Math.abs(o-D)<Math.abs(c-D)?o:c;let b=a*s;const f=h+b,y=l===void 0?f:l(f);y!==f&&(b=y-h);const v=D=>-b*Math.exp(-D/r),w=D=>y+v(D),C=D=>{const A=v(D),N=w(D);x.done=Math.abs(A)<=d,x.value=x.done?y:N};let k,S;const _=D=>{u(x.value)&&(k=D,S=mi({keyframes:[x.value,g(x.value)],velocity:Nh(w,D,x.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return _(0),{calculatedDuration:null,next:D=>{let A=!1;return!S&&k===void 0&&(A=!0,C(D),_(D)),k!==void 0&&D>=k?S.next(D-k):(!A&&C(D),x)}}}function rw(t,s,a){const r=[],n=a||Ia.mix||vh,i=t.length-1;for(let l=0;l<i;l++){let o=n(t[l],t[l+1]);if(s){const c=Array.isArray(s)?s[l]||aa:s;o=Dn(c,o)}r.push(o)}return r}function nw(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(Oo(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),c=o.length,d=m=>{if(l&&m<t[0])return s[0];let h=0;if(c>1)for(;h<t.length-2&&!(m<t[h+1]);h++);const x=fn(t[h],t[h+1],m);return o[h](x)};return a?m=>d(Pa(t[0],t[i-1],m)):d}function iw(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=fn(0,s,r);t.push(zt(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||dh).splice(0,t.length-1)}function dn({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=vN(r)?r.map(qd):qd(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:c=>(i.value=o(c),i.done=c>=t,i)}}const dw=t=>t!==null;function Zo(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:Bl,inertia:Bl,tween:dn,keyframes:dn,spring:mi};function wh(t){typeof t.type=="string"&&(t.type=mw[t.type])}class Jo{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 Qo extends Jo{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!==$s.now()&&this.tick($s.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;wh(s);const{type:a=dn,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:l=0}=s;let{keyframes:o}=s;const c=a||dn;c!==dn&&typeof o[0]!="number"&&(this.mixKeyframes=Dn(uw,vh(o[0],o[1])),o=[0,100]);const d=c({...s,keyframes:o});i==="mirror"&&(this.mirroredGenerator=c({...s,keyframes:[...o].reverse(),velocity:-l})),d.calculatedDuration===null&&(d.calculatedDuration=Xo(d));const{calculatedDuration:m}=d;this.calculatedDuration=m,this.resolvedDuration=m+n,this.totalDuration=this.resolvedDuration*(r+1)-n,this.generator=d}updateTime(s){const a=Math.round(s-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=a}tick(s,a=!1){const{generator:r,totalDuration:n,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:m,repeat:h,repeatType:x,repeatDelay:u,type:g,onUpdate:b,finalKeyframe:f}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,s):this.speed<0&&(this.startTime=Math.min(s-n/this.speed,this.startTime)),a?this.currentTime=s:this.updateTime(s);const y=this.currentTime-d*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?y<0:y>n;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let w=this.currentTime,C=r;if(h){const D=Math.min(this.currentTime,n)/o;let A=Math.floor(D),N=D%1;!N&&D>=1&&(N=1),N===1&&A--,A=Math.min(A,h+1),!!(A%2)&&(x==="reverse"?(N=1-N,u&&(N-=u/o)):x==="mirror"&&(C=l)),w=Pa(0,1,N)*o}const k=v?{done:!1,value:m[0]}:C.next(w);i&&(k.value=i(k.value));let{done:S}=k;!v&&c!==null&&(S=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const _=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&S);return _&&g!==Bl&&(k.value=Zo(m,this.options,f,this.speed)),b&&b(k.value),_&&this.finish(),k}then(s,a){return this.finished.then(s,a)}get duration(){return ea(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ea(s)}get time(){return ea(this.currentTime)}set time(s){var a;s=ya(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($s.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=ea(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=XN,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($s.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 pr=t=>t*180/Math.PI,Vl=t=>{const s=pr(Math.atan2(t[1],t[0]));return zl(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:Vl,rotateZ:Vl,skewX:t=>pr(Math.atan(t[1])),skewY:t=>pr(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},zl=t=>(t=t%360,t<0&&(t+=360),t),nm=Vl,im=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),lm=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:im,scaleY:lm,scale:t=>(im(t)+lm(t))/2,rotateX:t=>zl(pr(Math.atan2(t[6],t[5]))),rotateY:t=>zl(pr(Math.atan2(-t[2],t[0]))),rotateZ:nm,rotate:nm,skewX:t=>pr(Math.atan(t[4])),skewY:t=>pr(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Hl(t){return t.includes("scale")?1:0}function Wl(t,s){if(!t||t==="none")return Hl(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 Hl(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 Wl(a,s)};function fw(t){return parseFloat(t.trim())}const Gr=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Yr=new Set(Gr),om=t=>t===Wr||t===Je,bw=new Set(["x","y","z"]),yw=Gr.filter(t=>!bw.has(t));function vw(t){const s=[];return yw.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const gr={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})=>Wl(s,"x"),y:(t,{transform:s})=>Wl(s,"y")};gr.translateX=gr.x;gr.translateY=gr.y;const fr=new Set;let Gl=!1,Yl=!1,Kl=!1;function Ch(){if(Yl){const t=Array.from(fr).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)})}Yl=!1,Gl=!1,fr.forEach(t=>t.complete(Kl)),fr.clear()}function Sh(){fr.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Yl=!0)})}function jw(){Kl=!0,Sh(),Ch(),Kl=!1}class qo{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?(fr.add(this),Gl||(Gl=!0,Mt.read(Sh),Mt.resolveKeyframes(Ch))):(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),fr.delete(this)}cancel(){this.state==="scheduled"&&(fr.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=Uo(()=>window.ScrollTimeline!==void 0),Sw={};function Aw(t,s){const a=Uo(t);return()=>Sw[s]??a()}const Ah=Aw(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),rn=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,cm={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:rn([0,.65,.55,1]),circOut:rn([.55,0,1,.45]),backIn:rn([.31,.01,.66,-.59]),backOut:rn([.33,1.53,.69,.99])};function Th(t,s){if(t)return typeof t=="function"?Ah()?jh(t,s):"ease-out":mh(t)?rn(t):Array.isArray(t)?t.map(a=>Th(a,s)||cm.easeOut):cm[t]}function Tw(t,s,a,{delay:r=0,duration:n=300,repeat:i=0,repeatType:l="loop",ease:o="easeOut",times:c}={},d=void 0){const m={[s]:a};c&&(m.offset=c);const h=Th(o,n);Array.isArray(h)&&(m.easing=h);const x={delay:r,duration:n,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(x.pseudoElement=d),t.animate(m,x)}function kh(t){return typeof t=="function"&&"applyToOptions"in t}function kw({type:t,...s}){return kh(t)&&Ah()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class Rw extends Jo{constructor(s){if(super(),this.finishedTime=null,this.isStopped=!1,!s)return;const{element:a,name:r,keyframes:n,pseudoElement:i,allowFlatten:l=!1,finalKeyframe:o,onComplete:c}=s;this.isPseudoElement=!!i,this.allowFlatten=l,this.options=s,Oo(typeof s.type!="string");const d=kw(s);this.animation=Tw(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=Zo(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(m):ww(a,r,m),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var s,a;(a=(s=this.animation).finish)==null||a.call(s)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:s}=this;s==="idle"||s==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var s,a;this.isPseudoElement||(a=(s=this.animation).commitStyles)==null||a.call(s)}get duration(){var a,r;const s=((r=(a=this.animation.effect)==null?void 0:a.getComputedTiming)==null?void 0:r.call(a).duration)||0;return ea(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ea(s)}get time(){return ea(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=ya(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,aa):a(this)}}const Rh={anticipate:lh,backInOut:ih,circInOut:ch};function Dw(t){return t in Rh}function Pw(t){typeof t.ease=="string"&&Dw(t.ease)&&(t.ease=Rh[t.ease])}const dm=10;class Iw extends Rw{constructor(s){Pw(s),wh(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 Qo({...l,autoplay:!1}),c=ya(this.finishedTime??this.time);a.setWithVelocity(o.sample(c-dm).value,o.sample(c).value,dm),o.stop()}}const mm=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ga.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=mm(n,s),o=mm(i,s);return!l||!o?!1:Ew(t)||(a==="spring"||kh(a))&&r}function Xl(t){t.duration=0,t.type="keyframes"}const _w=new Set(["opacity","clipPath","filter","transform"]),Lw=Uo(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Mw(t){var m;const{motionValue:s,name:a,repeatDelay:r,repeatType:n,damping:i,type:l}=t;if(!(((m=s==null?void 0:s.owner)==null?void 0:m.current)instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:d}=s.owner.getProps();return Lw()&&a&&_w.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&l!=="inertia"}const $w=40;class Ow extends Jo{constructor({autoplay:s=!0,delay:a=0,type:r="keyframes",repeat:n=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:m,...h}){var g;super(),this.stop=()=>{var b,f;this._animation&&(this._animation.stop(),(b=this.stopTimeline)==null||b.call(this)),(f=this.keyframeResolver)==null||f.cancel()},this.createdAt=$s.now();const x={autoplay:s,delay:a,type:r,repeat:n,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:m,...h},u=(m==null?void 0:m.KeyframeResolver)||qo;this.keyframeResolver=new u(o,(b,f,y)=>this.onKeyframesResolved(b,f,x,!y),c,d,m),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(s,a,r,n){this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:m}=r;this.resolvedAt=$s.now(),Fw(s,i,l,o)||((Ia.instantAnimations||!c)&&(m==null||m(Zo(s,r,a))),s[0]=s[s.length-1],Xl(r),r.repeat=0);const x={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>$w?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},u=!d&&Mw(x)?new Iw({...x,element:x.motionValue.owner.current}):new Qo(x);u.finished.then(()=>this.notifyFinished()).catch(aa),this.pendingTimeline&&(this.stopTimeline=u.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=u}get finished(){return this._animation?this.animation.finished:this._finished}then(s,a){return this.finished.finally(s).then(()=>{})}get animation(){var s;return this._animation||((s=this.keyframeResolver)==null||s.resume(),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 Dh(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 Qx(l)?parseFloat(l):l}return Wo(n)?Dh(n,s,a+1):n}function ec(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const Ph=new Set(["width","height","top","left","right","bottom",...Gr]),Vw={test:t=>t==="auto",parse:t=>t},Ih=t=>s=>s.test(t),Eh=[Wr,Je,va,Ua,EN,IN,Vw],um=t=>Eh.find(Ih(t));function zw(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||eh(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(Go)||[];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,Zl={...Ga,getAnimatableNone:t=>{const s=t.match(Gw);return s?s.map(Ww).join(" "):t}},xm={...Wr,transform:Math.round},Yw={rotate:Ua,rotateX:Ua,rotateY:Ua,rotateZ:Ua,scale:On,scaleX:On,scaleY:On,scaleZ:On,skew:Ua,skewX:Ua,skewY:Ua,distance:Je,translateX:Je,translateY:Je,translateZ:Je,x:Je,y:Je,z:Je,perspective:Je,transformPerspective:Je,opacity:bn,originX:em,originY:em,originZ:Je},tc={borderWidth:Je,borderTopWidth:Je,borderRightWidth:Je,borderBottomWidth:Je,borderLeftWidth:Je,borderRadius:Je,radius:Je,borderTopLeftRadius:Je,borderTopRightRadius:Je,borderBottomRightRadius:Je,borderBottomLeftRadius:Je,width:Je,maxWidth:Je,height:Je,maxHeight:Je,top:Je,right:Je,bottom:Je,left:Je,padding:Je,paddingTop:Je,paddingRight:Je,paddingBottom:Je,paddingLeft:Je,margin:Je,marginTop:Je,marginRight:Je,marginBottom:Je,marginLeft:Je,backgroundPositionX:Je,backgroundPositionY:Je,...Yw,zIndex:xm,fillOpacity:bn,strokeOpacity:bn,numOctaves:xm},Kw={...tc,color:Xt,backgroundColor:Xt,outlineColor:Xt,fill:Xt,stroke:Xt,borderColor:Xt,borderTopColor:Xt,borderRightColor:Xt,borderBottomColor:Xt,borderLeftColor:Xt,filter:Zl,WebkitFilter:Zl},Fh=t=>Kw[t];function _h(t,s){let a=Fh(t);return a!==Zl&&(a=Ga),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const Xw=new Set(["auto","none","0"]);function Zw(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!Xw.has(i)&&yn(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=_h(a,n)}class Jw extends qo{constructor(s,a,r,n,i){super(s,a,r,n,i,!0)}readKeyframes(){const{unresolvedKeyframes:s,element:a,name:r}=this;if(!a||!a.current)return;super.readKeyframes();for(let c=0;c<s.length;c++){let d=s[c];if(typeof d=="string"&&(d=d.trim(),Wo(d))){const m=Dh(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!Ph.has(r)||s.length!==2)return;const[n,i]=s,l=um(n),o=um(i);if(l!==o)if(om(l)&&om(o))for(let c=0;c<s.length;c++){const d=s[c];typeof d=="string"&&(s[c]=parseFloat(d))}else gr[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&&Zw(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=gr[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]=gr[a](s.measureViewportBox(),window.getComputedStyle(s.current)),l!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=l),(o=this.removedTransforms)!=null&&o.length&&this.removedTransforms.forEach(([c,d])=>{s.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function Qw(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 Lh=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function Mh(t){return qx(t)&&"offsetHeight"in t}const hm=30,qw=t=>!isNaN(parseFloat(t));class e1{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=$s.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=$s.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 Bo);const r=this.events[s].add(a);return s==="change"?()=>{r(),Mt.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=$s.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>hm)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,hm);return th(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 Mr(t,s){return new e1(t,s)}const{schedule:sc}=uh(queueMicrotask,!1),ma={x:!1,y:!1};function $h(){return ma.x||ma.y}function t1(t){return t==="x"||t==="y"?ma[t]?null:(ma[t]=!0,()=>{ma[t]=!1}):ma.x||ma.y?null:(ma.x=ma.y=!0,()=>{ma.x=ma.y=!1})}function Oh(t,s){const a=Qw(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function pm(t){return!(t.pointerType==="touch"||$h())}function s1(t,s,a={}){const[r,n,i]=Oh(t,a),l=o=>{if(!pm(o))return;const{target:c}=o,d=s(c,o);if(typeof d!="function"||!c)return;const m=h=>{pm(h)&&(d(h),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(o=>{o.addEventListener("pointerenter",l,n)}),i}const Uh=(t,s)=>s?t===s?!0:Uh(t,s.parentElement):!1,ac=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 Zn=new WeakSet;function gm(t){return s=>{s.key==="Enter"&&t(s)}}function ml(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=gm(()=>{if(Zn.has(a))return;ml(a,"down");const n=gm(()=>{ml(a,"up")}),i=()=>ml(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 fm(t){return ac(t)&&!$h()}function i1(t,s,a={}){const[r,n,i]=Oh(t,a),l=o=>{const c=o.currentTarget;if(!fm(o))return;Zn.add(c);const d=s(c,o),m=(u,g)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",x),Zn.has(c)&&Zn.delete(c),fm(u)&&typeof d=="function"&&d(u,{success:g})},h=u=>{m(u,c===window||c===document||a.useGlobalTarget||Uh(c,u.target))},x=u=>{m(u,!1)};window.addEventListener("pointerup",h,n),window.addEventListener("pointercancel",x,n)};return r.forEach(o=>{(a.useGlobalTarget?window:o).addEventListener("pointerdown",l,n),Mh(o)&&(o.addEventListener("focus",d=>n1(d,n)),!r1(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function Bh(t){return qx(t)&&"ownerSVGElement"in t}function l1(t){return Bh(t)&&t.tagName==="svg"}const js=t=>!!(t&&t.getVelocity),o1=[...Eh,Xt,Ga],c1=t=>o1.find(Ih(t)),rc=p.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function bm(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=bm(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():bm(t[n],null)}}}}function m1(...t){return p.useCallback(d1(...t),t)}class u1 extends p.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=Mh(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=p.useId(),i=p.useRef(null),l=p.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:o}=p.useContext(rc),c=m1(i,t==null?void 0:t.ref);return p.useInsertionEffect(()=>{const{width:d,height:m,top:h,left:x,right:u}=l.current;if(s||!i.current||!d||!m)return;const g=a==="left"?`left: ${x}`:`right: ${u}`;i.current.dataset.motionPopId=n;const b=document.createElement("style");o&&(b.nonce=o);const f=r??document.head;return f.appendChild(b),b.sheet&&b.sheet.insertRule(`
[data-motion-pop-id="${n}"] {
position: absolute !important;
width: ${d}px !important;
height: ${m}px !important;
${g}px !important;
top: ${h}px !important;
}
`),()=>{f.contains(b)&&f.removeChild(b)}},[s]),e.jsx(u1,{isPresent:s,childRef:i,sizeRef:l,children:p.cloneElement(t,{ref:c})})}const h1=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=_o(p1),m=p.useId();let h=!0,x=p.useMemo(()=>(h=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:u=>{d.set(u,!0);for(const g of d.values())if(!g)return;r&&r()},register:u=>(d.set(u,!1),()=>d.delete(u))}),[a,d,r]);return i&&h&&(x={...x}),p.useMemo(()=>{d.forEach((u,g)=>d.set(g,!1))},[a]),p.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(x1,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(Ii.Provider,{value:x,children:t})};function p1(){return new Map}function Vh(t=!0){const s=p.useContext(Ii);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=p.useId();p.useEffect(()=>{if(t)return n(i)},[t]);const l=p.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const Un=t=>t.key||"";function ym(t){const s=[];return p.Children.forEach(t,a=>{p.isValidElement(a)&&s.push(a)}),s}const Ei=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",root:c})=>{const[d,m]=Vh(l),h=p.useMemo(()=>ym(t),[t]),x=l&&!d?[]:h.map(Un),u=p.useRef(!0),g=p.useRef(h),b=_o(()=>new Map),[f,y]=p.useState(h),[v,w]=p.useState(h);Jx(()=>{u.current=!1,g.current=h;for(let S=0;S<v.length;S++){const _=Un(v[S]);x.includes(_)?b.delete(_):b.get(_)!==!0&&b.set(_,!1)}},[v,x.length,x.join("-")]);const C=[];if(h!==f){let S=[...h];for(let _=0;_<v.length;_++){const D=v[_],A=Un(D);x.includes(A)||(S.splice(_,0,D),C.push(D))}return i==="wait"&&C.length&&(S=C),w(ym(S)),y(h),null}const{forceRender:k}=p.useContext(Fo);return e.jsx(e.Fragment,{children:v.map(S=>{const _=Un(S),D=l&&!d?!1:h===v||x.includes(_),A=()=>{if(b.has(_))b.set(_,!0);else return;let N=!0;b.forEach(P=>{P||(N=!1)}),N&&(k==null||k(),w(g.current),l&&(m==null||m()),r&&r())};return e.jsx(h1,{isPresent:D,initial:!u.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:D?void 0:A,anchorX:o,children:S},_)})})},zh=p.createContext({strict:!1}),vm={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 vm)$r[t]={isEnabled:s=>vm[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 ui(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 Hh=t=>!ui(t);function b1(t){typeof t=="function"&&(Hh=s=>s.startsWith("on")?!ui(s):t(s))}try{b1(require("@emotion/is-prop-valid").default)}catch{}function y1(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(Hh(n)||a===!0&&ui(n)||!s&&!ui(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Fi=p.createContext({});function _i(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function vn(t){return typeof t=="string"||Array.isArray(t)}const nc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ic=["initial",...nc];function Li(t){return _i(t.animate)||ic.some(s=>vn(t[s]))}function Wh(t){return!!(Li(t)||t.variants)}function v1(t,s){if(Li(t)){const{initial:a,animate:r}=t;return{initial:a===!1||vn(a)?a:void 0,animate:vn(r)?r:void 0}}return t.inherit!==!1?s:{}}function j1(t){const{initial:s,animate:a}=v1(t,p.useContext(Fi));return p.useMemo(()=>({initial:s,animate:a}),[jm(s),jm(a)])}function jm(t){return Array.isArray(t)?t.join(" "):t}const jn={};function N1(t){for(const s in t)jn[s]=t[s],Ho(s)&&(jn[s].isCSSVariable=!0)}function Gh(t,{layout:s,layoutId:a}){return Yr.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!jn[t]||t==="opacity")}const w1={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},C1=Gr.length;function S1(t,s,a){let r="",n=!0;for(let i=0;i<C1;i++){const l=Gr[i],o=t[l];if(o===void 0)continue;let c=!0;if(typeof o=="number"?c=o===(l.startsWith("scale")?1:0):c=parseFloat(o)===0,!c||a){const d=Lh(o,tc[l]);if(!c){n=!1;const m=w1[l]||l;r+=`${m}(${d}) `}a&&(s[l]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function lc(t,s,a){const{style:r,vars:n,transformOrigin:i}=t;let l=!1,o=!1;for(const c in s){const d=s[c];if(Yr.has(c)){l=!0;continue}else if(Ho(c)){n[c]=d;continue}else{const m=Lh(d,tc[c]);c.startsWith("origin")?(o=!0,i[c]=m):r[c]=m}}if(s.transform||(l||a?r.transform=S1(s,t.transform,a):r.transform&&(r.transform="none")),o){const{originX:c="50%",originY:d="50%",originZ:m=0}=i;r.transformOrigin=`${c} ${d} ${m}`}}const oc=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Yh(t,s,a){for(const r in s)!js(s[r])&&!Gh(r,a)&&(t[r]=s[r])}function A1({transformTemplate:t},s){return p.useMemo(()=>{const a=oc();return lc(a,s,t),Object.assign({},a.vars,a.style)},[s])}function T1(t,s){const a=t.style||{},r={};return Yh(r,a,t),Object.assign(r,A1(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]=Je.transform(-r);const l=Je.transform(s),o=Je.transform(a);t[i.array]=`${l} ${o}`}function Kh(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(lc(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:h,style:x}=t;h.transform&&(x.transform=h.transform,delete h.transform),(x.transform||h.transformOrigin)&&(x.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),x.transform&&(x.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete h.transformBox),s!==void 0&&(h.x=s),a!==void 0&&(h.y=a),r!==void 0&&(h.scale=r),n!==void 0&&P1(h,n,i,l,!1)}const Xh=()=>({...oc(),attrs:{}}),Zh=t=>typeof t=="string"&&t.toLowerCase()==="svg";function I1(t,s,a,r){const n=p.useMemo(()=>{const i=Xh();return Kh(i,s,Zh(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};Yh(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 cc(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=(cc(t)?I1:k1)(s,r,n,t),c=y1(s,typeof t=="string",i),d=t!==p.Fragment?{...c,...o,ref:a}:{},{children:m}=s,h=p.useMemo(()=>js(m)?m.get():m,[m]);return p.createElement(t,{...d,children:h})}function Nm(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function dc(t,s,a,r){if(typeof s=="function"){const[n,i]=Nm(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]=Nm(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Jn(t){return js(t)?t.get():t}function _1({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:L1(a,r,n,t),renderState:s()}}function L1(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=Jn(i[x]);let{initial:l,animate:o}=t;const c=Li(t),d=Wh(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const h=m?o:l;if(h&&typeof h!="boolean"&&!_i(h)){const x=Array.isArray(h)?h:[h];for(let u=0;u<x.length;u++){const g=dc(t,x[u]);if(g){const{transitionEnd:b,transition:f,...y}=g;for(const v in y){let w=y[v];if(Array.isArray(w)){const C=m?w.length-1:0;w=w[C]}w!==null&&(n[v]=w)}for(const v in b)n[v]=b[v]}}}return n}const Jh=t=>(s,a)=>{const r=p.useContext(Fi),n=p.useContext(Ii),i=()=>_1(t,s,r,n);return a?i():_o(i)};function mc(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(js(r[l])||s.style&&js(s.style[l])||Gh(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const M1=Jh({scrapeMotionValuesFromProps:mc,createRenderState:oc});function Qh(t,s,a){const r=mc(t,s,a);for(const n in t)if(js(t[n])||js(s[n])){const i=Gr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const $1=Jh({scrapeMotionValuesFromProps:Qh,createRenderState:Xh}),O1=Symbol.for("motionComponentSymbol");function Tr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function U1(t,s,a){return p.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):Tr(a)&&(a.current=r))},[s])}const uc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),B1="framerAppearId",qh="data-"+uc(B1),ep=p.createContext({});function V1(t,s,a,r,n){var b,f;const{visualElement:i}=p.useContext(Fi),l=p.useContext(zh),o=p.useContext(Ii),c=p.useContext(rc).reducedMotion,d=p.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,h=p.useContext(ep);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&z1(d.current,a,n,h);const x=p.useRef(!1);p.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const u=a[qh],g=p.useRef(!!u&&!((b=window.MotionHandoffIsComplete)!=null&&b.call(window,u))&&((f=window.MotionHasOptimisedAnimation)==null?void 0:f.call(window,u)));return Jx(()=>{m&&(x.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),p.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,u)}),g.current=!1),m.enteringChildren=void 0)}),m}function z1(t,s,a,r){const{layoutId:n,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:tp(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Tr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function tp(t){if(t)return t.options.allowProjection!==!1?t.projection:tp(t.parent)}function ul(t,{forwardMotionProps:s=!1}={},a,r){a&&g1(a);const n=cc(t)?$1:M1;function i(o,c){let d;const m={...p.useContext(rc),...o,layoutId:H1(o)},{isStatic:h}=m,x=j1(o),u=n(o,h);if(!h&&Lo){W1();const g=G1(m);d=g.MeasureLayout,x.visualElement=V1(t,u,m,r,g.ProjectionNode)}return e.jsxs(Fi.Provider,{value:x,children:[d&&x.visualElement?e.jsx(d,{visualElement:x.visualElement,...m}):null,F1(t,o,U1(u,x.visualElement,c),u,h,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=p.forwardRef(i);return l[O1]=t,l}function H1({layoutId:t}){const s=p.useContext(Fo).id;return s&&t!==void 0?s+"-"+t:t}function W1(t,s){p.useContext(zh).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 Y1(t,s){if(typeof Proxy>"u")return ul;const a=new Map,r=(i,l)=>ul(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,ul(l,void 0,t,s)),a.get(l))})}function sp({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function K1({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function X1(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 xl(t){return t===void 0||t===1}function Jl({scale:t,scaleX:s,scaleY:a}){return!xl(t)||!xl(s)||!xl(a)}function or(t){return Jl(t)||ap(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function ap(t){return wm(t.x)||wm(t.y)}function wm(t){return t&&t!=="0%"}function xi(t,s,a){const r=t-a,n=s*r;return a+n}function Cm(t,s,a,r,n){return n!==void 0&&(t=xi(t,n,r)),xi(t,a,r)+s}function Ql(t,s=0,a=1,r,n){t.min=Cm(t.min,s,a,r,n),t.max=Cm(t.max,s,a,r,n)}function rp(t,{x:s,y:a}){Ql(t.x,s.translate,s.scale,s.originPoint),Ql(t.y,a.translate,a.scale,a.originPoint)}const Sm=.999999999999,Am=1.0000000000001;function Z1(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;o<n;o++){i=a[o],l=i.projectionDelta;const{visualElement:c}=i.options;c&&c.props.style&&c.props.style.display==="contents"||(r&&i.options.layoutScroll&&i.scroll&&i!==i.root&&Rr(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),l&&(s.x*=l.x.scale,s.y*=l.y.scale,rp(t,l)),r&&or(i.latestValues)&&Rr(t,i.latestValues))}s.x<Am&&s.x>Sm&&(s.x=1),s.y<Am&&s.y>Sm&&(s.y=1)}function kr(t,s){t.min=t.min+s,t.max=t.max+s}function Tm(t,s,a,r,n=.5){const i=zt(t.min,t.max,n);Ql(t,s,a,i,r)}function Rr(t,s){Tm(t.x,s.x,s.scaleX,s.scale,s.originX),Tm(t.y,s.y,s.scaleY,s.scale,s.originY)}function np(t,s){return sp(X1(t.getBoundingClientRect(),s))}function J1(t,s,a){const r=np(t,a),{scroll:n}=s;return n&&(kr(r.x,n.offset.x),kr(r.y,n.offset.y)),r}const km=()=>({translate:0,scale:1,origin:0,originPoint:0}),Dr=()=>({x:km(),y:km()}),Rm=()=>({min:0,max:0}),Yt=()=>({x:Rm(),y:Rm()}),ql={current:null},ip={current:!1};function Q1(){if(ip.current=!0,!!Lo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>ql.current=t.matches;t.addEventListener("change",s),s()}else ql.current=!1}const q1=new WeakMap;function eC(t,s,a){for(const r in s){const n=s[r],i=a[r];if(js(n))t.addValue(r,n);else if(js(i))t.addValue(r,Mr(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,Mr(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Dm=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class tC{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=qo,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=$s.now();this.renderScheduledAt<x&&(this.renderScheduledAt=x,Mt.render(this.render,!1,!0))};const{latestValues:c,renderState:d}=l;this.latestValues=c,this.baseTarget={...c},this.initialValues=a.initial?{...c}:{},this.renderState=d,this.parent=s,this.props=a,this.presenceContext=r,this.depth=s?s.depth+1:0,this.reducedMotionConfig=n,this.options=o,this.blockInitialAnimation=!!i,this.isControllingVariants=Li(a),this.isVariantNode=Wh(a),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(s&&s.current);const{willChange:m,...h}=this.scrapeMotionValuesFromProps(a,{},this);for(const x in h){const u=h[x];c[x]!==void 0&&js(u)&&u.set(c[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)),ip.current||Q1(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ql.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Wa(this.notifyUpdate),Wa(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=Yr.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&Mt.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):Yt()}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<Dm.length;r++){const n=Dm[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=eC(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=Mr(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"&&(Qx(r)||eh(r))?r=parseFloat(r):!c1(r)&&Ga.test(a)&&(r=_h(s,a)),this.setBaseTarget(s,js(r)?r.get():r)),js(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=dc(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&&!js(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 Bo),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){sc.render(this.render)}}class lp extends tC{constructor(){super(...arguments),this.KeyframeResolver=Jw}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;js(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function op(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 sC(t){return window.getComputedStyle(t)}class aC extends lp{constructor(){super(...arguments),this.type="html",this.renderInstance=op}readValueFromInstance(s,a){var r;if(Yr.has(a))return(r=this.projection)!=null&&r.isProjecting?Hl(a):gw(s,a);{const n=sC(s),i=(Ho(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return np(s,a)}build(s,a,r){lc(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return mc(s,a,r)}}const cp=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 rC(t,s,a,r){op(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(cp.has(n)?n:uc(n),s.attrs[n])}class nC extends lp{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Yt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Yr.has(a)){const r=Fh(a);return r&&r.default||0}return a=cp.has(a)?a:uc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return Qh(s,a,r)}build(s,a,r){Kh(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){rC(s,a,r,n)}mount(s){this.isSVGTag=Zh(s.tagName),super.mount(s)}}const iC=(t,s)=>cc(t)?new nC(s):new aC(s,{allowProjection:t!==p.Fragment});function _r(t,s,a){const r=t.getProps();return dc(r,s,a!==void 0?a:r.custom,t)}const eo=t=>Array.isArray(t);function lC(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,Mr(a))}function oC(t){return eo(t)?t[t.length-1]||0:t}function cC(t,s){const a=_r(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=oC(i[l]);lC(t,l,o)}}function dC(t){return!!(js(t)&&t.add)}function to(t,s){const a=t.getValue("willChange");if(dC(a))return a.add(s);if(!a&&Ia.WillChange){const r=new Ia.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function dp(t){return t.props[qh]}const mC=t=>t!==null;function uC(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(mC),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const xC={type:"spring",stiffness:500,damping:25,restSpeed:10},hC=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),pC={type:"keyframes",duration:.8},gC={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},fC=(t,{keyframes:s})=>s.length>2?pC:Yr.has(t)?t.startsWith("scale")?hC(s[1]):xC:gC;function bC({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:l,repeatDelay:o,from:c,elapsed:d,...m}){return!!Object.keys(m).length}const xc=(t,s,a,r={},n,i)=>l=>{const o=ec(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-ya(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:x=>{s.set(x),o.onUpdate&&o.onUpdate(x)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};bC(o)||Object.assign(m,fC(t,m)),m.duration&&(m.duration=ya(m.duration)),m.repeatDelay&&(m.repeatDelay=ya(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let h=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Xl(m),m.delay===0&&(h=!0)),(Ia.instantAnimations||Ia.skipAnimations)&&(h=!0,Xl(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,h&&!i&&s.get()!==void 0){const x=uC(m.keyframes,o);if(x!==void 0){Mt.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Qo(m):new Ow(m)};function yC({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function mp(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const h=t.getValue(m,t.latestValues[m]??null),x=o[m];if(x===void 0||d&&yC(d,m))continue;const u={delay:a,...ec(i||{},m)},g=h.get();if(g!==void 0&&!h.isAnimating&&!Array.isArray(x)&&x===g&&!u.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const y=dp(t);if(y){const v=window.MotionHandoffAnimation(y,m,Mt);v!==null&&(u.startTime=v,b=!0)}}to(t,m),h.start(xc(m,h,x,t.shouldReduceMotion&&Ph.has(m)?{type:!1}:u,t,b));const f=h.animation;f&&c.push(f)}return l&&Promise.all(c).then(()=>{Mt.update(()=>{l&&cC(t,l)})}),c}function up(t,s,a,r=0,n=1){const i=Array.from(t).sort((d,m)=>d.sortNodePosition(m)).indexOf(s),l=t.size,o=(l-1)*r;return typeof a=="function"?a(i,l):n===1?i*r:o-i*r}function so(t,s,a={}){var c;const r=_r(t,s,a.type==="exit"?(c=t.presenceContext)==null?void 0:c.custom:void 0);let{transition:n=t.getDefaultTransition()||{}}=r||{};a.transitionOverride&&(n=a.transitionOverride);const i=r?()=>Promise.all(mp(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:h,staggerDirection:x}=n;return vC(t,s,d,m,h,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function vC(t,s,a=0,r=0,n=0,i=1,l){const o=[];for(const c of t.variantChildren)c.notify("AnimationStart",s),o.push(so(c,s,{...l,delay:a+(typeof r=="function"?0:r)+up(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function jC(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>so(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=so(t,s,a);else{const n=typeof s=="function"?_r(t,s,a.custom):s;r=Promise.all(mp(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function xp(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 NC=ic.length;function hp(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?hp(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<NC;a++){const r=ic[a],n=t.props[r];(vn(n)||n===!1)&&(s[r]=n)}return s}const wC=[...nc].reverse(),CC=nc.length;function SC(t){return s=>Promise.all(s.map(({animation:a,options:r})=>jC(t,a,r)))}function AC(t){let s=SC(t),a=Pm(),r=!0;const n=c=>(d,m)=>{var x;const h=_r(t,m,c==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(h){const{transition:u,transitionEnd:g,...b}=h;d={...d,...b,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=hp(t.parent)||{},h=[],x=new Set;let u={},g=1/0;for(let f=0;f<CC;f++){const y=wC[f],v=a[y],w=d[y]!==void 0?d[y]:m[y],C=vn(w),k=y===c?v.isActive:null;k===!1&&(g=f);let S=w===m[y]&&w!==d[y]&&C;if(S&&r&&t.manuallyAnimateOnMount&&(S=!1),v.protectedKeys={...u},!v.isActive&&k===null||!w&&!v.prevProp||_i(w)||typeof w=="boolean")continue;const _=TC(v.prevProp,w);let D=_||y===c&&v.isActive&&!S&&C||f>g&&C,A=!1;const N=Array.isArray(w)?w:[w];let P=N.reduce(n(y),{});k===!1&&(P={});const{prevResolvedValues:R={}}=v,O={...R,...P},F=T=>{D=!0,x.has(T)&&(A=!0,x.delete(T)),v.needsAnimating[T]=!0;const j=t.getValue(T);j&&(j.liveStyle=!1)};for(const T in O){const j=P[T],U=R[T];if(u.hasOwnProperty(T))continue;let I=!1;eo(j)&&eo(U)?I=!xp(j,U):I=j!==U,I?j!=null?F(T):x.add(T):j!==void 0&&x.has(T)?F(T):v.protectedKeys[T]=!0}v.prevProp=w,v.prevResolvedValues=P,v.isActive&&(u={...u,...P}),r&&t.blockInitialAnimation&&(D=!1);const $=S&&_;D&&(!$||A)&&h.push(...N.map(T=>{const j={type:y};if(typeof T=="string"&&r&&!$&&t.manuallyAnimateOnMount&&t.parent){const{parent:U}=t,I=_r(U,T);if(U.enteringChildren&&I){const{delayChildren:M}=I.transition||{};j.delay=up(U.enteringChildren,t,M)}}return{animation:T,options:j}}))}if(x.size){const f={};if(typeof d.initial!="boolean"){const y=_r(t,Array.isArray(d.initial)?d.initial[0]:d.initial);y&&y.transition&&(f.transition=y.transition)}x.forEach(y=>{const v=t.getBaseTarget(y),w=t.getValue(y);w&&(w.liveStyle=!0),f[y]=v??null}),h.push({animation:f})}let b=!!h.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(b=!1),r=!1,b?s(h):Promise.resolve()}function o(c,d){var h;if(a[c].isActive===d)return Promise.resolve();(h=t.variantChildren)==null||h.forEach(x=>{var u;return(u=x.animationState)==null?void 0:u.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const x in a)a[x].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Pm()}}}function TC(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!xp(s,t):!1}function nr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Pm(){return{animate:nr(!0),whileInView:nr(),whileHover:nr(),whileTap:nr(),whileDrag:nr(),whileFocus:nr(),exit:nr()}}class Ka{constructor(s){this.isMounted=!1,this.node=s}update(){}}class kC extends Ka{constructor(s){super(s),s.animationState||(s.animationState=AC(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();_i(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 RC=0;class DC extends Ka{constructor(){super(...arguments),this.id=RC++}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 PC={animation:{Feature:kC},exit:{Feature:DC}};function Nn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function En(t){return{point:{x:t.pageX,y:t.pageY}}}const IC=t=>s=>ac(s)&&t(s,En(s));function mn(t,s,a,r){return Nn(t,s,IC(a),r)}const pp=1e-4,EC=1-pp,FC=1+pp,gp=.01,_C=0-gp,LC=0+gp;function Ss(t){return t.max-t.min}function MC(t,s,a){return Math.abs(t-s)<=a}function Im(t,s,a,r=.5){t.origin=r,t.originPoint=zt(s.min,s.max,t.origin),t.scale=Ss(a)/Ss(s),t.translate=zt(a.min,a.max,t.origin)-t.originPoint,(t.scale>=EC&&t.scale<=FC||isNaN(t.scale))&&(t.scale=1),(t.translate>=_C&&t.translate<=LC||isNaN(t.translate))&&(t.translate=0)}function un(t,s,a,r){Im(t.x,s.x,a.x,r?r.originX:void 0),Im(t.y,s.y,a.y,r?r.originY:void 0)}function Em(t,s,a){t.min=a.min+s.min,t.max=t.min+Ss(s)}function $C(t,s,a){Em(t.x,s.x,a.x),Em(t.y,s.y,a.y)}function Fm(t,s,a){t.min=s.min-a.min,t.max=t.min+Ss(s)}function xn(t,s,a){Fm(t.x,s.x,a.x),Fm(t.y,s.y,a.y)}function Qs(t){return[t("x"),t("y")]}const fp=({current:t})=>t?t.ownerDocument.defaultView:null,_m=(t,s)=>Math.abs(t-s);function OC(t,s){const a=_m(t.x,s.x),r=_m(t.y,s.y);return Math.sqrt(a**2+r**2)}class bp{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=pl(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,g=OC(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!u&&!g)return;const{point:b}=x,{timestamp:f}=xs;this.history.push({...b,timestamp:f});const{onStart:y,onMove:v}=this.handlers;u||(y&&y(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,x)},this.handlePointerMove=(x,u)=>{this.lastMoveEvent=x,this.lastMoveEventInfo=hl(u,this.transformPagePoint),Mt.update(this.updatePoint,!0)},this.handlePointerUp=(x,u)=>{this.end();const{onEnd:g,onSessionEnd:b,resumeAnimation:f}=this.handlers;if(this.dragSnapToOrigin&&f&&f(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=pl(x.type==="pointercancel"?this.lastMoveEventInfo:hl(u,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,y),b&&b(x,y)},!ac(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=En(s),c=hl(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=xs;this.history=[{...d,timestamp:m}];const{onSessionStart:h}=a;h&&h(s,pl(c,this.history)),this.removeListeners=Dn(mn(this.contextWindow,"pointermove",this.handlePointerMove),mn(this.contextWindow,"pointerup",this.handlePointerUp),mn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),Wa(this.updatePoint)}}function hl(t,s){return s?{point:s(t.point)}:t}function Lm(t,s){return{x:t.x-s.x,y:t.y-s.y}}function pl({point:t},s){return{point:t,delta:Lm(t,yp(s)),offset:Lm(t,UC(s)),velocity:BC(s,.1)}}function UC(t){return t[0]}function yp(t){return t[t.length-1]}function BC(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=yp(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>ya(s)));)a--;if(!r)return{x:0,y:0};const i=ea(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 VC(t,{min:s,max:a},r){return s!==void 0&&t<s?t=r?zt(s,t,r.min):Math.max(t,s):a!==void 0&&t>a&&(t=r?zt(a,t,r.max):Math.min(t,a)),t}function Mm(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 zC(t,{top:s,left:a,bottom:r,right:n}){return{x:Mm(t.x,a,n),y:Mm(t.y,s,r)}}function $m(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 HC(t,s){return{x:$m(t.x,s.x),y:$m(t.y,s.y)}}function WC(t,s){let a=.5;const r=Ss(t),n=Ss(s);return n>r?a=fn(s.min,s.max-r,t.min):r>n&&(a=fn(t.min,t.max-n,s.min)),Pa(0,1,a)}function GC(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 ao=.35;function YC(t=ao){return t===!1?t=0:t===!0&&(t=ao),{x:Om(t,"left","right"),y:Om(t,"top","bottom")}}function Om(t,s,a){return{min:Um(t,s),max:Um(t,a)}}function Um(t,s){return typeof t=="number"?t:t[s]||0}const KC=new WeakMap;class XC{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=Yt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:a=!1,distanceThreshold:r}={}){const{presenceContext:n}=this.visualElement;if(n&&n.isPresent===!1)return;const i=h=>{const{dragSnapToOrigin:x}=this.getProps();x?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(En(h).point)},l=(h,x)=>{const{drag:u,dragPropagation:g,onDragStart:b}=this.getProps();if(u&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=t1(u),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Qs(y=>{let v=this.getAxisMotionValue(y).get()||0;if(va.test(v)){const{projection:w}=this.visualElement;if(w&&w.layout){const C=w.layout.layoutBox[y];C&&(v=Ss(C)*(parseFloat(v)/100))}}this.originPoint[y]=v}),b&&Mt.postRender(()=>b(h,x)),to(this.visualElement,"transform");const{animationState:f}=this.visualElement;f&&f.setActive("whileDrag",!0)},o=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x;const{dragPropagation:u,dragDirectionLock:g,onDirectionLock:b,onDrag:f}=this.getProps();if(!u&&!this.openDragLock)return;const{offset:y}=x;if(g&&this.currentDirection===null){this.currentDirection=ZC(y),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",x.point,y),this.updateAxis("y",x.point,y),this.visualElement.render(),f&&f(h,x)},c=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x,this.stop(h,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>Qs(h=>{var x;return this.getAnimationState(h)==="paused"&&((x=this.getAxisMotionValue(h).animation)==null?void 0:x.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new bp(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:fp(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&&Mt.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||!Bn(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=VC(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&&Tr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=zC(r.layoutBox,s):this.constraints=!1,this.elastic=YC(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&Qs(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=GC(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Tr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=J1(r,n.root,this.visualElement.getTransformPagePoint());let l=HC(n.layout.layoutBox,i);if(a){const o=a(K1(l));this.hasMutatedConstraints=!!o,o&&(l=sp(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=Qs(m=>{if(!Bn(m,a,this.currentDirection))return;let h=c&&c[m]||{};l&&(h={min:0,max:0});const x=n?200:1e6,u=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:x,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return to(this.visualElement,s),r.start(xc(s,r,0,a,this.visualElement,!1))}stopAnimation(){Qs(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Qs(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){Qs(a=>{const{drag:r}=this.getProps();if(!Bn(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]-zt(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Tr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};Qs(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=WC({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),Qs(l=>{if(!Bn(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(zt(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;KC.set(this.visualElement,this);const s=this.visualElement.current,a=mn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();Tr(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",r);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),Mt.read(r);const l=Nn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(Qs(m=>{const h=this.getAxisMotionValue(m);h&&(this.originPoint[m]+=c[m].translate,h.set(h.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=ao,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Bn(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function ZC(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class JC extends Ka{constructor(s){super(s),this.removeGroupControls=aa,this.removeListeners=aa,this.controls=new XC(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||aa}unmount(){this.removeGroupControls(),this.removeListeners()}}const Bm=t=>(s,a)=>{t&&Mt.postRender(()=>t(s,a))};class QC extends Ka{constructor(){super(...arguments),this.removePointerDownListener=aa}onPointerDown(s){this.session=new bp(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:fp(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Bm(s),onStart:Bm(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&Mt.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=mn(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 Qn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Vm(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const en={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(Je.test(t))t=parseFloat(t);else return t;const a=Vm(t,s.target.x),r=Vm(t,s.target.y);return`${a}% ${r}%`}},qC={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Ga.parse(t);if(n.length>5)return r;const i=Ga.createTransformer(t),l=typeof n[0]!="number"?1:0,o=a.x.scale*s.x,c=a.y.scale*s.y;n[0+l]/=o,n[1+l]/=c;const d=zt(o,c,.5);return typeof n[2+l]=="number"&&(n[2+l]/=d),typeof n[3+l]=="number"&&(n[3+l]/=d),i(n)}};let gl=!1;class e2 extends p.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;N1(t2),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),gl&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Qn.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,gl=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||Mt.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),sc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;gl=!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 vp(t){const[s,a]=Vh(),r=p.useContext(Fo);return e.jsx(e2,{...t,layoutGroup:r,switchLayoutGroup:p.useContext(ep),isPresent:s,safeToRemove:a})}const t2={borderRadius:{...en,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:en,borderTopRightRadius:en,borderBottomLeftRadius:en,borderBottomRightRadius:en,boxShadow:qC};function s2(t,s,a){const r=js(t)?t:Mr(t);return r.start(xc("",r,s,a)),r.animation}const a2=(t,s)=>t.depth-s.depth;class r2{constructor(){this.children=[],this.isDirty=!1}add(s){Mo(this.children,s),this.isDirty=!0}remove(s){$o(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(a2),this.isDirty=!1,this.children.forEach(s)}}function n2(t,s){const a=$s.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Wa(r),t(i-s))};return Mt.setup(r,!0),()=>Wa(r)}const jp=["TopLeft","TopRight","BottomLeft","BottomRight"],i2=jp.length,zm=t=>typeof t=="string"?parseFloat(t):t,Hm=t=>typeof t=="number"||Je.test(t);function l2(t,s,a,r,n,i){n?(t.opacity=zt(0,a.opacity??1,o2(r)),t.opacityExit=zt(s.opacity??1,0,c2(r))):i&&(t.opacity=zt(s.opacity??1,a.opacity??1,r));for(let l=0;l<i2;l++){const o=`border${jp[l]}Radius`;let c=Wm(s,o),d=Wm(a,o);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||Hm(c)===Hm(d)?(t[o]=Math.max(zt(zm(c),zm(d),r),0),(va.test(d)||va.test(c))&&(t[o]+="%")):t[o]=d}(s.rotate||a.rotate)&&(t.rotate=zt(s.rotate||0,a.rotate||0,r))}function Wm(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const o2=Np(0,.5,oh),c2=Np(.5,.95,aa);function Np(t,s,a){return r=>r<t?0:r>s?1:a(fn(t,s,r))}function Gm(t,s){t.min=s.min,t.max=s.max}function Js(t,s){Gm(t.x,s.x),Gm(t.y,s.y)}function Ym(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Km(t,s,a,r,n){return t-=s,t=xi(t,1/a,r),n!==void 0&&(t=xi(t,1/n,r)),t}function d2(t,s=0,a=1,r=.5,n,i=t,l=t){if(va.test(s)&&(s=parseFloat(s),s=zt(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=zt(i.min,i.max,r);t===i&&(o-=s),t.min=Km(t.min,s,a,o,n),t.max=Km(t.max,s,a,o,n)}function Xm(t,s,[a,r,n],i,l){d2(t,s[a],s[r],s[n],s.scale,i,l)}const m2=["x","scaleX","originX"],u2=["y","scaleY","originY"];function Zm(t,s,a,r){Xm(t.x,s,m2,a?a.x:void 0,r?r.x:void 0),Xm(t.y,s,u2,a?a.y:void 0,r?r.y:void 0)}function Jm(t){return t.translate===0&&t.scale===1}function wp(t){return Jm(t.x)&&Jm(t.y)}function Qm(t,s){return t.min===s.min&&t.max===s.max}function x2(t,s){return Qm(t.x,s.x)&&Qm(t.y,s.y)}function qm(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Cp(t,s){return qm(t.x,s.x)&&qm(t.y,s.y)}function eu(t){return Ss(t.x)/Ss(t.y)}function tu(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class h2{constructor(){this.members=[]}add(s){Mo(this.members,s),s.scheduleRender()}remove(s){if($o(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 p2(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:h,rotateY:x,skewX:u,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),h&&(r+=`rotateX(${h}deg) `),x&&(r+=`rotateY(${x}deg) `),u&&(r+=`skewX(${u}deg) `),g&&(r+=`skewY(${g}deg) `)}const o=t.x.scale*s.x,c=t.y.scale*s.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const fl=["","X","Y","Z"],g2=1e3;let f2=0;function bl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Sp(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=dp(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Mt,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Sp(r)}function Ap({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=f2++,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(v2),this.nodes.forEach(C2),this.nodes.forEach(S2),this.nodes.forEach(j2)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new r2)}addEventListener(l,o){return this.eventHandlers.has(l)||this.eventHandlers.set(l,new Bo),this.eventHandlers.get(l).add(o)}notifyListeners(l,...o){const c=this.eventHandlers.get(l);c&&c.notify(...o)}hasListeners(l){return this.eventHandlers.has(l)}mount(l){if(this.instance)return;this.isSVG=Bh(l)&&!l1(l),this.instance=l;const{layoutId:o,layout:c,visualElement:d}=this.options;if(d&&!d.current&&d.mount(l),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||o)&&(this.isLayoutDirty=!0),t){let m,h=0;const x=()=>this.root.updateBlockedByResize=!1;Mt.read(()=>{h=window.innerWidth}),t(l,()=>{const u=window.innerWidth;u!==h&&(h=u,this.root.updateBlockedByResize=!0,m&&m(),m=n2(x,250),Qn.hasAnimatedSinceResize&&(Qn.hasAnimatedSinceResize=!1,this.nodes.forEach(ru)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:h,hasRelativeLayoutChanged:x,layout:u})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||D2,{onLayoutAnimationStart:b,onLayoutAnimationComplete:f}=d.getProps(),y=!this.targetLayout||!Cp(this.targetLayout,u),v=!h&&x;if(this.options.layoutRoot||this.resumeFrom||v||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...ec(g,"layout"),onPlay:b,onComplete:f};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(m,v)}else h||ru(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=u})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Wa(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(A2),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&&Sp(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let m=0;m<this.path.length;m++){const h=this.path[m];h.shouldResetTransform=!0,h.updateScroll("snapshot"),h.options.layoutRoot&&h.willUpdate(!1)}const{layoutId:o,layout:c}=this.options;if(o===void 0&&!c)return;const d=this.getTransformTemplate();this.prevTransformTemplateValue=d?d(this.latestValues,""):void 0,this.updateSnapshot(),l&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(su);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(au);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(w2),this.nodes.forEach(b2),this.nodes.forEach(y2)):this.nodes.forEach(au),this.clearAllSnapshots();const o=$s.now();xs.delta=Pa(0,1e3/60,o-xs.timestamp),xs.timestamp=o,xs.isProcessing=!0,il.update.process(xs),il.preRender.process(xs),il.render.process(xs),xs.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,sc.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(N2),this.sharedNodes.forEach(T2)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Mt.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Mt.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ss(this.snapshot.measuredBox.x)&&!Ss(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c<this.path.length;c++)this.path[c].updateScroll();const l=this.layout;this.layout=this.measure(!1),this.layoutCorrected=Yt(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:o}=this.options;o&&o.notify("LayoutMeasure",this.layout.layoutBox,l?l.layoutBox:void 0)}updateScroll(l="measure"){let o=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===l&&(o=!1),o&&this.instance){const c=r(this.instance);this.scroll={animationId:this.root.animationId,phase:l,isRoot:c,offset:a(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!n)return;const l=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,o=this.projectionDelta&&!wp(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,m=d!==this.prevTransformTemplateValue;l&&this.instance&&(o||or(this.latestValues)||m)&&(n(this.instance,d),this.shouldResetTransform=!1,this.scheduleRender())}measure(l=!0){const o=this.measurePageBox();let c=this.removeElementScroll(o);return l&&(c=this.removeTransform(c)),P2(c),{animationId:this.root.animationId,measuredBox:o,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var d;const{visualElement:l}=this.options;if(!l)return Yt();const o=l.measureViewportBox();if(!(((d=this.scroll)==null?void 0:d.wasRoot)||this.path.some(I2))){const{scroll:m}=this.root;m&&(kr(o.x,m.offset.x),kr(o.y,m.offset.y))}return o}removeElementScroll(l){var c;const o=Yt();if(Js(o,l),(c=this.scroll)!=null&&c.wasRoot)return o;for(let d=0;d<this.path.length;d++){const m=this.path[d],{scroll:h,options:x}=m;m!==this.root&&h&&x.layoutScroll&&(h.wasRoot&&Js(o,l),kr(o.x,h.offset.x),kr(o.y,h.offset.y))}return o}applyTransform(l,o=!1){const c=Yt();Js(c,l);for(let d=0;d<this.path.length;d++){const m=this.path[d];!o&&m.options.layoutScroll&&m.scroll&&m!==m.root&&Rr(c,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),or(m.latestValues)&&Rr(c,m.latestValues)}return or(this.latestValues)&&Rr(c,this.latestValues),c}removeTransform(l){const o=Yt();Js(o,l);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!or(d.latestValues))continue;Jl(d.latestValues)&&d.updateSnapshot();const m=Yt(),h=d.measurePageBox();Js(m,h),Zm(o,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return or(this.latestValues)&&Zm(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!==xs.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(l=!1){var x;const o=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=o.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=o.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=o.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==o;if(!(l||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(x=this.parent)!=null&&x.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:m,layoutId:h}=this.options;if(!(!this.layout||!(m||h))){if(this.resolvedRelativeTargetAt=xs.timestamp,!this.targetDelta&&!this.relativeTarget){const u=this.getClosestProjectingParent();u&&u.layout&&this.animationProgress!==1?(this.relativeParent=u,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Yt(),this.relativeTargetOrigin=Yt(),xn(this.relativeTargetOrigin,this.layout.layoutBox,u.layout.layoutBox),Js(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Yt(),this.targetWithTransforms=Yt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),$C(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Js(this.target,this.layout.layoutBox),rp(this.target,this.targetDelta)):Js(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const u=this.getClosestProjectingParent();u&&!!u.resumingFrom==!!this.resumingFrom&&!u.options.layoutScroll&&u.target&&this.animationProgress!==1?(this.relativeParent=u,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Yt(),this.relativeTargetOrigin=Yt(),xn(this.relativeTargetOrigin,this.target,u.target),Js(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Jl(this.parent.latestValues)||ap(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var g;const l=this.getLead(),o=!!this.resumingFrom||this!==l;let c=!0;if((this.isProjectionDirty||(g=this.parent)!=null&&g.isProjectionDirty)&&(c=!1),o&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===xs.timestamp&&(c=!1),c)return;const{layout:d,layoutId:m}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(d||m))return;Js(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,x=this.treeScale.y;Z1(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=Yt());const{target:u}=l;if(!u){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Ym(this.prevProjectionDelta.x,this.projectionDelta.x),Ym(this.prevProjectionDelta.y,this.projectionDelta.y)),un(this.projectionDelta,this.layoutCorrected,u,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==x||!tu(this.projectionDelta.x,this.prevProjectionDelta.x)||!tu(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",u))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(l=!0){var o;if((o=this.options.visualElement)==null||o.scheduleRender(),l){const c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Dr(),this.projectionDelta=Dr(),this.projectionDeltaWithTransform=Dr()}setAnimationOrigin(l,o=!1){const c=this.snapshot,d=c?c.latestValues:{},m={...this.latestValues},h=Dr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!o;const x=Yt(),u=c?c.source:void 0,g=this.layout?this.layout.source:void 0,b=u!==g,f=this.getStack(),y=!f||f.members.length<=1,v=!!(b&&!y&&this.options.crossfade===!0&&!this.path.some(R2));this.animationProgress=0;let w;this.mixTargetDelta=C=>{const k=C/1e3;nu(h.x,l.x,k),nu(h.y,l.y,k),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(xn(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),k2(this.relativeTarget,this.relativeTargetOrigin,x,k),w&&x2(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=Yt()),Js(w,this.relativeTarget)),b&&(this.animationValues=m,l2(m,d,this.latestValues,k,v,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=k},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(Wa(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Mt.update(()=>{Qn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Mr(0)),this.currentAnimation=s2(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(g2),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:m}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&Tp(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Yt();const h=Ss(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const x=Ss(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}Js(o,c),Rr(o,m),un(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new h2),this.sharedNodes.get(l).add(o);const d=o.options.initialPromotionConfig;o.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.shouldPreserveFollowOpacity(o):void 0})}isLead(){const l=this.getStack();return l?l.lead===this:!0}getLead(){var o;const{layoutId:l}=this.options;return l?((o=this.getStack())==null?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:l}=this.options;return l?(o=this.getStack())==null?void 0:o.prevLead:void 0}getStack(){const{layoutId:l}=this.options;if(l)return this.root.sharedNodes.get(l)}promote({needsReset:l,transition:o,preserveFollowOpacity:c}={}){const d=this.getStack();d&&d.promote(this,c),l&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const l=this.getStack();return l?l.relegate(this):!1}resetSkewAndRotation(){const{visualElement:l}=this.options;if(!l)return;let o=!1;const{latestValues:c}=l;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(o=!0),!o)return;const d={};c.z&&bl("z",l,d,this.animationValues);for(let m=0;m<fl.length;m++)bl(`rotate${fl[m]}`,l,d,this.animationValues),bl(`skew${fl[m]}`,l,d,this.animationValues);l.render();for(const m in d)l.setStaticValue(m,d[m]),this.animationValues&&(this.animationValues[m]=d[m]);l.scheduleRender()}applyProjectionStyles(l,o){if(!this.instance||this.isSVG)return;if(!this.isVisible){l.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,l.visibility="",l.opacity="",l.pointerEvents=Jn(o==null?void 0:o.pointerEvents)||"",l.transform=c?c(this.latestValues,""):"none";return}const d=this.getLead();if(!this.projectionDelta||!this.layout||!d.target){this.options.layoutId&&(l.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,l.pointerEvents=Jn(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!or(this.latestValues)&&(l.transform=c?c({},""):"none",this.hasProjected=!1);return}l.visibility="";const m=d.animationValues||d.latestValues;this.applyTransformsToTarget();let h=p2(this.projectionDeltaWithTransform,this.treeScale,m);c&&(h=c(m,h)),l.transform=h;const{x,y:u}=this.projectionDelta;l.transformOrigin=`${x.origin*100}% ${u.origin*100}% 0`,d.animationValues?l.opacity=d===this?m.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:m.opacityExit:l.opacity=d===this?m.opacity!==void 0?m.opacity:"":m.opacityExit!==void 0?m.opacityExit:0;for(const g in jn){if(m[g]===void 0)continue;const{correct:b,applyTo:f,isCSSVariable:y}=jn[g],v=h==="none"?m[g]:b(m[g],d);if(f){const w=f.length;for(let C=0;C<w;C++)l[f[C]]=v}else y?this.options.visualElement.renderState.vars[g]=v:l[g]=v}this.options.layoutId&&(l.pointerEvents=d===this?Jn(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(su),this.root.sharedNodes.clear()}}}function b2(t){t.updateLayout()}function y2(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"?Qs(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Ss(x);x.min=r[h].min,x.max=x.min+u}):Tp(i,s.layoutBox,r)&&Qs(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Ss(r[h]);x.max=x.min+u,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[h].max=t.relativeTarget[h].min+u)});const o=Dr();un(o,r,s.layoutBox);const c=Dr();l?un(c,t.applyTransform(n,!0),s.measuredBox):un(c,r,s.layoutBox);const d=!wp(o);let m=!1;if(!t.resumeFrom){const h=t.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:x,layout:u}=h;if(x&&u){const g=Yt();xn(g,s.layoutBox,x.layoutBox);const b=Yt();xn(b,r,u.layoutBox),Cp(g,b)||(m=!0),h.options.layoutRoot&&(t.relativeTarget=b,t.relativeTargetOrigin=g,t.relativeParent=h)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function v2(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 j2(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function N2(t){t.clearSnapshot()}function su(t){t.clearMeasurements()}function au(t){t.isLayoutDirty=!1}function w2(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function ru(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function C2(t){t.resolveTargetDelta()}function S2(t){t.calcProjection()}function A2(t){t.resetSkewAndRotation()}function T2(t){t.removeLeadSnapshot()}function nu(t,s,a){t.translate=zt(s.translate,0,a),t.scale=zt(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function iu(t,s,a,r){t.min=zt(s.min,a.min,r),t.max=zt(s.max,a.max,r)}function k2(t,s,a,r){iu(t.x,s.x,a.x,r),iu(t.y,s.y,a.y,r)}function R2(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const D2={duration:.45,ease:[.4,0,.1,1]},lu=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),ou=lu("applewebkit/")&&!lu("chrome/")?Math.round:aa;function cu(t){t.min=ou(t.min),t.max=ou(t.max)}function P2(t){cu(t.x),cu(t.y)}function Tp(t,s,a){return t==="position"||t==="preserve-aspect"&&!MC(eu(s),eu(a),.2)}function I2(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const E2=Ap({attachResizeListener:(t,s)=>Nn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),yl={current:void 0},kp=Ap({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!yl.current){const t=new E2({});t.mount(window),t.setOptions({layoutScroll:!0}),yl.current=t}return yl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),F2={pan:{Feature:QC},drag:{Feature:JC,ProjectionNode:kp,MeasureLayout:vp}};function du(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&&Mt.postRender(()=>i(s,En(s)))}class _2 extends Ka{mount(){const{current:s}=this.node;s&&(this.unmount=s1(s,(a,r)=>(du(this.node,r,"Start"),n=>du(this.node,n,"End"))))}unmount(){}}class L2 extends Ka{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=Dn(Nn(this.node.current,"focus",()=>this.onFocus()),Nn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function mu(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&&Mt.postRender(()=>i(s,En(s)))}class M2 extends Ka{mount(){const{current:s}=this.node;s&&(this.unmount=i1(s,(a,r)=>(mu(this.node,r,"Start"),(n,{success:i})=>mu(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const ro=new WeakMap,vl=new WeakMap,$2=t=>{const s=ro.get(t.target);s&&s(t)},O2=t=>{t.forEach($2)};function U2({root:t,...s}){const a=t||document;vl.has(a)||vl.set(a,{});const r=vl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(O2,{root:t,...s})),r[n]}function B2(t,s,a){const r=U2(s);return ro.set(t,a),r.observe(t),()=>{ro.delete(t),r.unobserve(t)}}const V2={some:0,all:1};class z2 extends Ka{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:V2[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:h}=this.node.getProps(),x=d?m:h;x&&x(c)};return B2(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(H2(s,a))&&this.startObserver()}unmount(){}}function H2({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const W2={inView:{Feature:z2},tap:{Feature:M2},focus:{Feature:L2},hover:{Feature:_2}},G2={layout:{ProjectionNode:kp,MeasureLayout:vp}},Y2={...PC,...W2,...F2,...G2},ts=Y1(Y2,iC),tn=[{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:Gt,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:ex,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 K2({open:t,onClose:s,onSelectTemplate:a}){var d,m,h;const[r,n]=p.useState(null),[i,l]=p.useState(!1);p.useEffect(()=>{const x=tt.getUserData();l((x==null?void 0:x.jobTitle)==="Dealer")},[]);const o=x=>{if(i)return;const u=tn.find(g=>g.id===x);u!=null&&u.disabled||n(x)},c=()=>{r&&(a(r),s())};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"!fixed !inset-0 !top-0 !left-0 !right-0 !bottom-0 !w-screen !h-screen !max-w-none !translate-x-0 !translate-y-0 p-0 gap-0 border-0 !rounded-none bg-gradient-to-br from-gray-50 to-white [&>button]:hidden !m-0",children:[e.jsx(mt,{className:"sr-only",children:"Select a Template"}),e.jsx(Dt,{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(Ns,{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(ts.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(qu,{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:tn.map((x,u)=>{const g=x.icon,b=r===x.id,f=i||x.disabled;return e.jsx(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:u*.1},whileHover:f?{}:{scale:1.03},whileTap:f?{}:{scale:.98},children:e.jsxs(ee,{className:`h-full transition-all duration-300 border-2 ${f?"opacity-50 cursor-not-allowed border-gray-200":b?"cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"cursor-pointer border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>o(x.id),children:[e.jsxs(ge,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${x.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),b&&e.jsx(ts.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(yr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(fe,{className:"text-xl mb-2",children:x.name}),e.jsx($e,{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(ze,{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(ze,{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(se,{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(Ts,{}),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(st,{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(Ot,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[x.steps," steps"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx("p",{className:"text-xs text-gray-500 font-semibold",children:"Key Features:"}),e.jsxs("div",{className:"space-y-1.5",children:[x.features.slice(0,3).map((y,v)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(De,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:y})]},v)),x.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",x.features.length-3," more features"]})]})]})]})]})},x.id)})}),e.jsxs(ts.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(E,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(E,{onClick:c,disabled:!r||i||((d=tn.find(x=>x.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=tn.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(ss,{className:"w-4 h-4"})]})]}),e.jsx(Ei,{children:r&&e.jsx(ts.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"mt-6 text-center",children:e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold text-blue-600",children:(h=tn.find(x=>x.id===r))==null?void 0:h.name})]})})})]})})]})})}function jr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=p.useState(100),[m,h]=p.useState(0),[x,u]=p.useState(null),[g,b]=p.useState(!1),[f,y]=p.useState(null),v=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),w=s.toLowerCase().includes("pdf"),C=v||w;p.useEffect(()=>{if(!l||!C||!a){u(null);return}return(async()=>{b(!0),y(null);try{let R=a;a.startsWith("/")&&!a.startsWith("//")&&(R=`${window.location.origin}${a}`);const F=await fetch(R,{headers:{Accept:w?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!F.ok){const T=await F.text().catch(()=>"");throw new Error(`Failed to load file: ${F.status} ${F.statusText}. ${T}`)}const $=await F.blob();if($.size===0)throw new Error("File is empty or could not be loaded");w&&!$.type.includes("pdf")&&$.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${$.type}`);const V=window.URL.createObjectURL($);u(V)}catch(N){console.error("Failed to load file for preview:",N),y(N instanceof Error?N.message:"Failed to load file for preview")}finally{b(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),u(null))}},[l,a,C,w]);const k=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},S=()=>d(A=>Math.min(A+25,200)),_=()=>d(A=>Math.max(A-25,50)),D=()=>h(A=>(A+90)%360);return e.jsx(pt,{open:l,onOpenChange:o,children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(gt,{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(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`• ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[v&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:_,disabled:c<=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:[c,"%"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:S,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(n0,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(tx,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(E,{variant:"outline",size:"sm",onClick:k,className:"gap-2 h-9",children:[e.jsx(Ct,{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(lt,{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(E,{onClick:k,className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",t]})]}):C&&x?e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:x,alt:t,style:{transform:`scale(${c/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),w&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:x,className:"w-full h-full rounded-lg border-0",title:t,style:{minHeight:"70vh",height:"100%"},onError:()=>{y("Failed to load PDF preview")}})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(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(E,{onClick:k,className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function Fn({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Dt,{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(E,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const Ys=async t=>{const s=t?{category:t}:{};return(await je.get("/users/configurations",{params:s})).data.data},X2=async t=>{const s={};return(await je.get("/admin/configurations",{params:s})).data.data},Z2=async(t,s)=>{await je.put(`/admin/configurations/${t}`,{configValue:s})},J2=async t=>{await je.post(`/admin/configurations/${t}/reset`)},Q2=async t=>{const s=t?{year:t}:{};return(await je.get("/admin/holidays",{params:s})).data.data},q2=async t=>(await je.post("/admin/holidays",t)).data.data,eS=async(t,s)=>(await je.put(`/admin/holidays/${t}`,s)).data.data,tS=async t=>{await je.delete(`/admin/holidays/${t}`)},sS=async()=>(await je.get("/config/activity-types")).data.data,aS=async t=>{const s={activeOnly:t.toString()};return(await je.get("/admin/activity-types",{params:s})).data.data},rS=async t=>(await je.post("/admin/activity-types",t)).data.data,nS=async(t,s)=>(await je.put(`/admin/activity-types/${t}`,s)).data.data,iS=async t=>{await je.delete(`/admin/activity-types/${t}`)},lS={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 oS(t,s,a){const[r,n]=p.useState(lS),[i,l]=p.useState(null),[o,c]=p.useState(t),[d,m]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[h,x]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[u,g]=p.useState([]);return p.useEffect(()=>{(async()=>{var y;try{const v=await Ys("DOCUMENT_POLICY"),w={};v.forEach(P=>{w[P.configKey]=P.configValue});const C=parseInt(w.MAX_FILE_SIZE_MB||"10"),S=(w.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(P=>P.trim().toLowerCase());x({maxFileSizeMB:C,allowedFileTypes:S});const _=await Ys("SYSTEM_SETTINGS"),D=await Ys("WORKFLOW_SHARING"),A=[..._,...D],N={};A.forEach(P=>{N[P.configKey]=P.configValue}),m({maxApprovalLevels:parseInt(N.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(N.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((y=N.ALLOW_ADD_SPECTATOR)==null?void 0:y.toLowerCase())==="true",maxSpectators:parseInt(N.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(v){console.error("Failed to load policies:",v)}})()},[]),p.useEffect(()=>{if(!t||!s)return;let f=!0;return(async()=>{try{c(!0);const y=await vs(s);if(!f||!y)return;const v=y.workflow||{},w=Array.isArray(y.approvals)?y.approvals:[],C=Array.isArray(y.participants)?y.participants:[],k=Array.isArray(y.documents)?y.documents.filter(R=>!R.isDeleted):[];g(k);const S=(v.priority||"").toString().toLowerCase(),_={standard:"standard",express:"express"},D=v.templateType==="TEMPLATE"?"existing-template":"custom",A=a.find(R=>R.id===D)||a[0]||null;l(A);const N=w.sort((R,O)=>(R.levelNumber||0)-(O.levelNumber||0)).map(R=>{const O=Number(R.tatHours||24),F=Math.floor(O/24),$=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:F>0?F:$,tatType:F>0?"days":"hours",userId:R.approverId}}),P=C.filter(R=>(R.participantType||R.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(R.userEmail||R.user_email||R.email):!1).map((R,O)=>{const F=R.userId||R.user_id||R.id,$=R.userName||R.user_name||R.name||"",V=R.userEmail||R.user_email||R.email||"",j=($||V||"XX").split(" ").map(U=>U[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${O}-${Date.now()}`,userId:F,name:$||V||"Spectator",email:V,role:"Spectator",department:R.department||"",avatar:j,level:1,canClose:!1}});n(R=>({...R,template:D,title:v.title||"",description:v.description||"",priority:_[S]||"standard",approvers:N,approverCount:N.length||1,spectators:P,maxLevel:Math.max(...N.map(O=>O.level||1),1)}))}catch(y){console.error("Failed to load draft:",y)}finally{f&&c(!1)}})(),()=>{f=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(f,y)=>{n(v=>({...v,[f]:y}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:h,existingDocuments:u,setExistingDocuments:g}}const uu=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function cS(t,s,a){const[r,n]=p.useState(t?2:1),i=uu.length,l=h=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(h),o=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(h=>{if(!h||!h.email||!l(h.email))return!1;if(!h.userId)return!0;const x=h.tatType||"hours";return x==="hours"?h.tat&&h.tat>0&&h.tat<=720:x==="days"?h.tat&&h.tat>0&&h.tat<=30:!1});case 4:return!0;case 5:return!0;case 6:return!0;default:return!1}};return{currentStep:r,setCurrentStep:n,totalSteps:i,stepNames:uu,isStepValid:o,nextStep:()=>{o()&&(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),r<i&&n(r+1))},prevStep:()=>{r>1&&(n(r-1),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}))},goToStep:h=>{h>=1&&h<=i&&n(h)},validateEmail:l}}function dS(){const[t,s]=p.useState({open:!1,type:"error",email:"",message:""}),[a,r]=p.useState({open:!1,violations:[]}),[n,i]=p.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(x,u,g="")=>{s({open:!0,type:x,email:u,message:g})},closeValidationModal:()=>{s(x=>({...x,open:!1}))},openPolicyViolationModal:x=>{r({open:!0,violations:x})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:x=>{i({open:!0,errors:x})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function mS(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function uS(t,s,a){var n;const r=mS(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 xS(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return uS(a,n,n===s)})}function xu(t,s,a,r=!1){return{templateId:(s==null?void 0:s.id)||null,templateType:(s==null?void 0:s.id)==="custom"?"CUSTOM":"TEMPLATE",title:t.title,description:t.description,priorityUi:t.priority==="express"?"express":"standard",approverCount:t.approverCount||1,approvers:(t.approvers||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",email:(n==null?void 0:n.email)||"",name:n==null?void 0:n.name,tat:(n==null?void 0:n.tat)||24,tatType:(n==null?void 0:n.tatType)||"hours"})),spectators:(t.spectators||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",name:(n==null?void 0:n.name)||"",email:(n==null?void 0:n.email)||""})),ccList:[],participants:[],isDraft:r}}function hu(t,s,a,r=!1){const n=xS(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:n,participants:[],deleteDocumentIds:a.length>0?a:void 0,isDraft:r}}function hS(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 pu(t,s){return{id:(await Io(t,s||[],"SUPPORTING")).id}}async function gu(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)}function pS({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=p.useState(!1),[m,h]=p.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var b,f;if(c||m)return;const g=hS(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const y=hu(t,n,r,!1);await gu(l,y,a,r),K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been submitted and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const y=xu(t,s,n,!1),v=await pu(y,a);K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been created and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:v.id,template:s})}}catch(y){console.error("Failed to submit workflow:",y),K.error("Failed to Submit Request",{description:((f=(b=y==null?void 0:y.response)==null?void 0:b.data)==null?void 0:f.message)||(y==null?void 0:y.message)||"An error occurred while submitting the request.",duration:5e3}),d(!1)}},handleSaveDraft:async()=>{var g,b;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){h(!0);try{if(i&&l){const f=hu(t,n,r,!0);await gu(l,f,a,r),K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const f=xu(t,s,n,!0),y=await pu(f,a);K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:y.id,template:s})}}catch(f){console.error("Failed to save draft:",f),K.error("Failed to Save Draft",{description:((b=(g=f==null?void 0:f.response)==null?void 0:g.data)==null?void 0:b.message)||(f==null?void 0:f.message)||"An error occurred while saving the draft.",duration:5e3}),h(!1)}}}}}async function ia(t,s=10,a="default"){return await je.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ra(t){var a;const s=await je.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function gS(t,s){return await je.post("/admin/users/assign-role",{email:t,role:s})}async function fS(t,s){return await je.put(`/admin/users/${t}/role`,{role:s})}async function bS(t,s=1,a=10){return await je.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function yS(){return await je.get("/admin/users/role-statistics")}async function vS(t){var a;const s=await je.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function jS(){var s,a;return((a=(s=(await je.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const dr={searchUsers:ia,getUserById:vS,ensureUserExists:ra,assignRole:gS,updateUserRole:fS,getUsersByRole:bS,getRoleStatistics:yS,getAllUsers:jS};async function NS(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 ia(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 ra({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 wS(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 NS(l,s);if(!o.success)return{success:!1,error:o.error};try{const m=(((n=(await ia(l.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const h=await ra({userId:m.userId,email:m.email,displayName:m.displayName,firstName:m.firstName,lastName:m.lastName,department:m.department,phone:m.phone,mobilePhone:m.mobilePhone,designation:m.designation,jobTitle:m.jobTitle,manager:m.manager,employeeId:m.employeeId,employeeNumber:m.employeeNumber,secondEmail:m.secondEmail,location:m.location});r[i]={...l,userId:h.userId,name:h.displayName||l.name,department:h.department||l.department,avatar:(h.displayName||h.email).substring(0,2).toUpperCase()}}}catch(c){console.error(`Failed to update approver ${l.email}:`,c)}}return{success:!0,validatedApprovers:r}}function CS({selectedTemplate:t,setSelectedTemplate:s,updateFormData:a,formData:r,currentStep:n,isStepValid:i,wizardNextStep:l,wizardPrevStep:o,user:c,openValidationModal:d,systemPolicy:m,onPolicyViolation:h,onSubmit:x}){const u=Ks(),[g,b]=p.useState(!1),[f,y]=p.useState(null);return{showTemplateModal:g,setShowTemplateModal:b,previewDocument:f,selectTemplate:D=>{s(D),a("template",D.id),a("category",D.category),a("priority",D.priority);const A=new Date;A.setDate(A.getDate()+D.suggestedSLA),a("slaEndDate",A),D.id!=="custom"&&D.id!=="existing-template"&&u(`/create-admin-request/${D.id}`)},handleTemplateSelection:D=>{D==="claim-management"?u("/claim-management"):D==="vendor-payment"?u("/vendor-payment"):x&&x({templateType:D})},nextStep:async()=>{var D;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){b(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&h){const P=r.approverCount||1;if(P>m.maxApprovalLevels){h([{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 A=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",N=await wS(r.approvers,A);if(!N.success&&N.error){d(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,A)=>{if(A){const N=D.documentId||D.document_id||"";y({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:Hr(N),fileSize:Number(D.fileSize||D.file_size||0),documentId:N})}else{const N=URL.createObjectURL(D);y({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),y(null)}}}const fu=[{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:Ni,estimatedTime:"Variable",commonApprovers:[],suggestedSLA:3,priority:"medium",fields:{}},{id:"existing-template",name:"Existing Template",description:"Use a pre-configured template with predefined approval workflows, timelines, and requirements for faster processing",category:"Templates",icon:Re,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let br=null;const bu=()=>br,SS=async t=>{const a=(await je.post("/templates",t)).data.data,r={id:a.templateId||a.id,name:a.templateName||a.name,description:a.templateDescription||a.description,category:a.templateCategory||a.category,priority:a.priority||"medium",estimatedTime:a.estimatedTime||"Variable",approvers:a.approvalLevelsConfig||a.approvers||[],suggestedSLA:a.defaultTatHours||a.suggestedSLA||24,isActive:a.isActive,fields:a.userFieldMappings||a.fields};return br&&br.push(r),r},Mi=async()=>{var r;const a=(((r=(await je.get("/templates")).data)==null?void 0:r.data)||[]).map(n=>({id:n.templateId||n.id,name:n.templateName||n.name,description:n.templateDescription||n.description,category:n.templateCategory||n.category,priority:n.priority||"medium",estimatedTime:n.estimatedTime||"Variable",approvers:n.approvalLevelsConfig||n.approvers||[],suggestedSLA:n.defaultTatHours||n.suggestedSLA||24,isActive:n.isActive,fields:n.userFieldMappings||n.fields}));return br=a,a},AS=async(t,s)=>{const r=(await je.put(`/templates/${t}`,s)).data.data,n={id:r.templateId||r.id,name:r.templateName||r.name,description:r.templateDescription||r.description,category:r.templateCategory||r.category,priority:r.priority||"medium",estimatedTime:r.estimatedTime||"Variable",approvers:r.approvalLevelsConfig||r.approvers||[],suggestedSLA:r.defaultTatHours||r.suggestedSLA||24,isActive:r.isActive,fields:r.userFieldMappings||r.fields};return br&&(br=br.map(i=>i.id===t?n:i)),n};function Rp({currentStep:t,totalSteps:s,stepNames:a}){const r=Math.round(t/s*100),n=a.length<=3?"max-w-xl":"max-w-6xl";return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-2 sm:py-3 flex-shrink-0","data-testid":"wizard-stepper",children:e.jsxs("div",{className:`${n} mx-auto`,children:[e.jsxs("div",{className:"block sm:hidden","data-testid":"wizard-stepper-mobile",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-green-600 text-white flex items-center justify-center text-xs font-semibold","data-testid":"wizard-stepper-mobile-current-step",children:t}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-900","data-testid":"wizard-stepper-mobile-step-name",children:a[t-1]}),e.jsxs("p",{className:"text-xs text-gray-600","data-testid":"wizard-stepper-mobile-step-info",children:["Step ",t," of ",s]})]})]}),e.jsx("div",{className:"text-right",children:e.jsxs("p",{className:"text-xs font-medium text-green-600","data-testid":"wizard-stepper-mobile-progress",children:[r,"%"]})})]}),e.jsx("div",{className:"w-full bg-gray-200 h-1.5 rounded-full overflow-hidden","data-testid":"wizard-stepper-mobile-progress-bar",children:e.jsx("div",{className:"bg-green-600 h-full transition-all duration-300",style:{width:`${r}%`},"data-testid":"wizard-stepper-mobile-progress-fill"})})]}),e.jsxs("div",{className:"hidden sm:block","data-testid":"wizard-stepper-desktop",children:[e.jsx("div",{className:"flex items-center justify-center gap-4 mb-2","data-testid":"wizard-stepper-desktop-steps",children:a.map((i,l)=>e.jsxs("div",{className:"flex items-center flex-1 last:flex-none","data-testid":`wizard-stepper-desktop-step-${l+1}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0 ${l+1<t?"bg-green-500 text-white":l+1===t?"bg-green-500 text-white ring-2 ring-green-500/30 ring-offset-1":"bg-gray-200 text-gray-600"}`,"data-testid":`wizard-stepper-desktop-step-${l+1}-indicator`,children:l+1<t?e.jsx(yr,{className:"w-4 h-4"}):l+1}),l<a.length-1&&e.jsx("div",{className:`flex-1 h-0.5 mx-2 ${l+1<t?"bg-green-500":"bg-gray-200"}`,"data-testid":`wizard-stepper-desktop-step-${l+1}-connector`})]},l))}),e.jsx("div",{className:"hidden lg:flex justify-between text-xs text-gray-600 mt-2 px-1","data-testid":"wizard-stepper-desktop-labels",children:a.map((i,l)=>e.jsx("span",{className:`${l+1===t?"font-semibold text-green-600":""}`,"data-testid":`wizard-stepper-desktop-label-${l+1}`,children:i},l))})]})]})})}function TS({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:c,loadingDraft:d,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(E,{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(Ns,{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(E,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||o||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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(E,{onClick:i,disabled:!a||d||o||c,size:"sm",className:"sm:size-lg bg-green-600 hover:bg-green-700 flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-submit-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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(sx,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(E,{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(ss,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const yu=t=>{switch(t){case"high":return e.jsx(ha,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ot,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(ta,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ot,{className:"w-4 h-4 text-gray-600"})}};function kS({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=p.useState("main"),l=Ks(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},c=n==="main"?[...t]:r;return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"min-h-full flex flex-col items-center justify-center py-8","data-testid":"template-selection-step",children:[e.jsxs("div",{className:"text-center mb-12 max-w-3xl","data-testid":"template-selection-header",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4","data-testid":"template-selection-title",children:n==="main"?"Choose Your Request Type":"Organization Templates"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:n==="main"?"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs.":"Select a pre-configured workflow template defined by your organization."})]}),n==="admin"&&e.jsx("div",{className:"w-full max-w-6xl mb-6 flex justify-start",children:e.jsxs(E,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(Ns,{className:"w-4 h-4"}),"Back to All Types"]})}),e.jsx("div",{className:"w-full max-w-6xl grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8","data-testid":"template-selection-grid",children:c.length===0&&n==="admin"?e.jsxs("div",{className:"col-span-full text-center py-12 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200",children:[e.jsx(i0,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):c.map(m=>{var g;const x=m.id==="admin-templates-category",u=(s==null?void 0:s.id)===m.id;return e.jsx(ts.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(ee,{className:`h-full transition-all duration-300 border-2 ${u?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer":x?"border-blue-200 bg-blue-50/30 hover:border-blue-400 hover:shadow-lg cursor-pointer":"border-gray-200 hover:border-blue-300 hover:shadow-lg cursor-pointer"}`,onClick:()=>o(m),"data-testid":`template-card-${m.id}-clickable`,children:[e.jsxs(ge,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl flex items-center justify-center ${u||x?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${u||x?"text-blue-600":"text-gray-600"}`})}),u&&e.jsx(ts.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},"data-testid":`template-card-${m.id}-selected-indicator`,children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center",children:e.jsx(yr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsx(fe,{className:"text-xl","data-testid":`template-card-${m.id}-name`,children:m.name}),!1]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),yu(m.priority)]})]})]}),e.jsxs(se,{className:"pt-0 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed line-clamp-2","data-testid":`template-card-${m.id}-description`,children:m.description}),!x&&e.jsxs(e.Fragment,{children:[e.jsx(Ts,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-estimated-time`,children:[e.jsx(st,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:m.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-approvers-count`,children:[e.jsx(cs,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[((g=m.commonApprovers)==null?void 0:g.length)||0," approvers"]})]})]})]}),x&&e.jsx("div",{className:"pt-2",children:e.jsx("p",{className:"text-xs text-blue-600 font-medium flex items-center gap-1",children:"Click to browse templates →"})})]})]})},m.id)})}),e.jsx(Ei,{children:s&&e.jsx(ts.div,{initial:{opacity:0,y:20,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:-20,height:0},transition:{duration:.3},className:"w-full max-w-6xl","data-testid":"template-details-card",children:e.jsxs(ee,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Ur,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-sla",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Suggested SLA"}),e.jsxs("p",{className:"text-blue-700 mt-1",children:[s.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-priority",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[yu(s.priority),e.jsx("span",{className:"text-blue-700 capitalize",children:s.priority})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-duration",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Estimated Duration"}),e.jsx("p",{className:"text-blue-700 mt-1",children:s.estimatedTime})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-approvers",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,h)=>e.jsx(ne,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${h}`,children:m},`${s.id}-approver-${h}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function Oe({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:ke("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 RS({className:t,...s}){return e.jsx(uf,{"data-slot":"radio-group",className:ke("grid gap-3",t),...s})}function vu({className:t,...s}){return e.jsx(xf,{"data-slot":"radio-group-item",className:ke("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(l0,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function DS({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"basic-information-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"basic-information-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-green-500 to-blue-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(Re,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(re,{htmlFor:"title",className:"text-base font-semibold",children:"Request Title *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Be specific and descriptive. This will be visible to all participants."}),e.jsx(Oe,{id:"title",placeholder:"e.g., Approval on new office location",value:t.title,onChange:r=>a("title",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-title-input"})]}),e.jsxs("div",{"data-testid":"basic-information-description-field",children:[e.jsx(re,{htmlFor:"description",className:"text-base font-semibold",children:"Detailed Description *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Rn,{value:t.description||"",onChange:r=>a("description",r),placeholder:"Provide comprehensive details about your request including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px","data-testid":"basic-information-description-textarea"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6","data-testid":"basic-information-priority-section",children:e.jsxs("div",{"data-testid":"basic-information-priority-field",children:[e.jsx(re,{className:"text-base font-semibold",children:"Priority Level *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"select priority for your request"}),e.jsxs(RS,{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(vu,{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(xo,{className:"w-4 h-4 text-red-600"}),e.jsx(re,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(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(vu,{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(st,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(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(re,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Oe,{id:"amount",placeholder:"Enter amount",value:t.amount,onChange:r=>a("amount",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-amount-input"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(We,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Ye,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"USD",children:"USD ($)"}),e.jsx(Y,{value:"EUR",children:"EUR (€)"}),e.jsx(Y,{value:"GBP",children:"GBP (£)"}),e.jsx(Y,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(re,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Oe,{id:"vendor",placeholder:"Enter vendor or supplier name",value:t.vendor,onChange:r=>a("vendor",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-vendor-input"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{"data-testid":"basic-information-cost-center-field",children:[e.jsx(re,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Oe,{id:"costCenter",placeholder:"e.g., Marketing, IT, Operations",value:t.costCenter,onChange:r=>a("costCenter",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-cost-center-input"})]}),e.jsxs("div",{"data-testid":"basic-information-project-field",children:[e.jsx(re,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Oe,{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 Dp(){const[t,s]=p.useState([]),[a,r]=p.useState(!1),n=p.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(c,d=10)=>{if(n.current&&clearTimeout(n.current),!c||!c.startsWith("@")||c.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const h=c.slice(1),u=((m=(await ia(h,d)).data)==null?void 0:m.data)||[];s(u)}catch(h){console.error("User search failed:",h),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await ra({userId:c.userId,email:c.email,displayName:c.displayName,firstName:c.firstName,lastName:c.lastName,department:c.department,phone:c.phone,mobilePhone:c.mobilePhone,designation:c.designation,jobTitle:c.jobTitle,manager:c.manager,employeeId:c.employeeId,employeeNumber:c.employeeNumber,secondEmail:c.secondEmail,location:c.location})}catch(d){throw console.error("Failed to ensure user exists:",d),d}}}}function Pp(){const[t,s]=p.useState({}),[a,r]=p.useState({}),n=p.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,c,d=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[o]:[]})),r(m=>({...m,[o]:!1}));return}r(m=>({...m,[o]:!0})),n.current[o]=setTimeout(async()=>{var m;try{const h=c.slice(1),u=((m=(await ia(h,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:u}))}catch(h){console.error(`User search failed for index ${o}:`,h),s(x=>({...x,[o]:[]}))}finally{r(h=>({...h,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function PS({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var h;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=Pp();p.useEffect(()=>{const x=t.approverCount||1,u=t.approvers||[];if(u.length<x){const g=[...u];for(let b=u.length;b<x;b++)g[b]||(g[b]={email:"",name:"",level:b+1,tat:""});s("approvers",g)}else u.length>x&&s("approvers",u.slice(0,x))},[t.approverCount,s]);const d=(x,u)=>{var y,v,w,C,k;const g=[...t.approvers],f=((y=g[x])==null?void 0:y.email)!==u;if(g[x]={...g[x],email:u,level:x+1,userId:f||(v=g[x])==null?void 0:v.userId,name:f||(w=g[x])==null?void 0:w.name,department:f||(C=g[x])==null?void 0:C.department,avatar:f||(k=g[x])==null?void 0:k.avatar},s("approvers",g),!u||!u.startsWith("@")||u.length<2){c(x);return}o(x,u,10)},m=async(x,u)=>{var g,b;try{if((g=t.approvers)==null?void 0:g.some((C,k)=>{var S,_;return k!==x&&(C.userId===u.userId||((S=C.email)==null?void 0:S.toLowerCase())===((_=u.email)==null?void 0:_.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((b=t.spectators)==null?void 0:b.some(C=>{var k,S;return C.userId===u.userId||((k=C.email)==null?void 0:k.toLowerCase())===((S=u.email)==null?void 0:S.toLowerCase())})){a({type:"error",email:u.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const v=await ra({userId:u.userId,email:u.email,displayName:u.displayName,firstName:u.firstName,lastName:u.lastName,department:u.department,phone:u.phone,mobilePhone:u.mobilePhone,designation:u.designation,jobTitle:u.jobTitle,manager:u.manager,employeeId:u.employeeId,employeeNumber:u.employeeNumber,secondEmail:u.secondEmail,location:u.location}),w=[...t.approvers];w[x]={...w[x],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:v.userId,level:x+1},s("approvers",w),c(x)}catch(f){console.error("Failed to ensure user exists:",f),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(ts.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(cs,{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(ee,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(Va,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx($e,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(se,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(re,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const x=t.approverCount||1,u=Math.max(1,x-1);s("approverCount",u),t.approvers.length>u&&s("approvers",t.approvers.slice(0,u))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(ho,{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(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const u=(t.approverCount||1)+1;if(u>r.maxApprovalLevels){n([{type:"Maximum Approval Levels Exceeded",message:`Cannot add more than ${r.maxApprovalLevels} approval levels. Please remove an approver level or contact your administrator.`,currentValue:u,maxValue:r.maxApprovalLevels}]);return}s("approverCount",u)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(gs,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Maximum ",r.maxApprovalLevels," approver",r.maxApprovalLevels!==1?"s":""," allowed. Each approver will review sequentially."]})]})})]}),e.jsxs(ee,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(hs,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs($e,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx("div",{className:"p-4 rounded-lg border-2 border-blue-200 bg-blue-50","data-testid":"approval-workflow-initiator-card",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:e.jsx(Vt,{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,u)=>{var y,v;const g=u+1,b=g===(t.approverCount||1),f=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${g}`,children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-6 bg-gray-300"})}),e.jsx("div",{className:`p-4 rounded-lg border-2 transition-all ${f.email?"border-green-200 bg-green-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${f.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:g})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",g]}),b&&e.jsx(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(re,{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(Oe,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:f.email||"",onChange:w=>d(u,w.target.value),className:"h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full","data-testid":`approval-workflow-approver-${g}-email-input`}),(l[u]||(((y=i[u])==null?void 0:y.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:l[u]?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:(v=i[u])==null?void 0:v.map(w=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(u,w),"data-testid":`approval-workflow-approver-${g}-search-result-${w.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:w.displayName||w.email}),e.jsx("div",{className:"text-xs text-gray-600",children:w.email})]},w.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-tat-field`,children:[e.jsx(re,{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(Oe,{id:`tat-${g}`,type:"number",placeholder:f.tatType==="days"?"7":"24",min:"1",max:f.tatType==="days"?"30":"720",value:f.tat||"",onChange:w=>{const C=[...t.approvers];C[u]={...C[u],tat:parseInt(w.target.value)||"",level:g,tatType:f.tatType||"hours"},s("approvers",C)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(We,{value:f.tatType||"hours",onValueChange:w=>{const C=[...t.approvers];C[u]={...C[u],tatType:w,level:g,tat:""},s("approvers",C)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(Ye,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ur,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," → ",Array.from({length:t.approverCount||1},(x,u)=>`Level ${u+1} Approver`).join(" → "),". The final approver can close the request."]})]})]})}),e.jsx("div",{className:"p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(st,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y:b+y/24},0))||0,u=Math.ceil(x);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[u," ",u===1?"Day":"Days"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Duration"})]})})()})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:(h=t.approvers)==null?void 0:h.map((x,u)=>{const g=Number(x.tat||0),f=(x.tatType||"hours")==="days"?g*24:g;return g?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[f," ",f===1?"hour":"hours"]})]})},u):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y*24:b+y},0))||0,u=Math.ceil(x/8);return x===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[x,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children:u}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Working Days*"})]})]}),e.jsx("p",{className:"text-xs text-emerald-600 mt-2 text-center",children:"*Based on 8-hour working days"})]})})()]})]})]})})]})]})]})}function IS({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=p.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=Dp(),h=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},x=async g=>{var b,f;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(w=>{var C,k;return w.userId===g.userId||((C=w.email)==null?void 0:C.toLowerCase())===((k=g.email)==null?void 0:k.toLowerCase())}),v=(b=t.approvers)==null?void 0:b.some(w=>{var C,k;return w.userId===g.userId||((C=w.email)==null?void 0:C.toLowerCase())===((k=g.email)==null?void 0:k.toLowerCase())});if(y){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(v){a({type:"error",email:g.email,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}try{const w=await m(g),C={id:w.userId,userId:w.userId,name:w.displayName||g.email.split("@")[0],email:w.email,avatar:(w.displayName||w.email).substring(0,2).toUpperCase(),role:"Spectator",department:w.department||"",level:1,canClose:!1},k=[...t.spectators,C];s("spectators",k),i(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(w=>{var C;return((C=w.email)==null?void 0:C.toLowerCase())===n.toLowerCase()}),v=(f=t.approvers)==null?void 0:f.some(w=>{var C;return((C=w.email)==null?void 0:C.toLowerCase())===n.toLowerCase()});if(y){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(v){a({type:"error",email:n,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}}},u=g=>{const b=t.spectators.filter(f=>f.id!==g);s("spectators",b)};return e.jsxs(ts.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(ee,{"data-testid":"participants-spectators-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center justify-between text-base","data-testid":"participants-spectators-title",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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($e,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2","data-testid":"participants-spectators-add-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-full",children:[e.jsx(Oe,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>h(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await x())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(o||l.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:o?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:l.map(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>x(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(E,{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(Ur,{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(Zt,{className:"h-6 w-6",children:e.jsx(Jt,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(ft,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function ES({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const h=b=>{const f=Array.from(b.target.files||[]);if(f.length===0)return;const y=t.maxFileSizeMB*1024*1024,v=[],w=[];f.forEach(C=>{if(C.size>y){v.push({fileName:C.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(C.size/1048576).toFixed(2)}MB`});return}const k=C.name.toLowerCase(),S=k.substring(k.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(S)){v.push({fileName:C.name,reason:`File type "${S}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}w.push(C)}),w.length>0&&i([...a,...w]),v.length>0&&d&&d(v),b.target&&(b.target.value="")},x=b=>{const f=a.filter((y,v)=>v!==b);i(f)},u=b=>{o([...n,b])},g=(b,f=!1)=>{if(f){const y=(b.fileType||b.file_type||"").toLowerCase(),v=(b.originalFileName||b.fileName||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}else{const y=(b.type||"").toLowerCase(),v=(b.name||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}};return e.jsxs(ts.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(zs,{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(ee,{"data-testid":"documents-upload-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs($e,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(se,{children:e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-gray-400 transition-colors","data-testid":"documents-upload-area",children:[e.jsx(zs,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(b=>`.${b}`).join(","),onChange:h,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(E,{variant:"outline",size:"lg",type:"button",onClick:()=>{var b;return(b=m.current)==null?void 0:b.click()},"data-testid":"documents-browse-button",children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Browse Files"]}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Supported formats: ",t.allowedFileTypes.map(b=>b.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(ee,{"data-testid":"documents-existing-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ne,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length," file",r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length!==1?"s":""]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(b=>{const f=b.documentId||b.document_id||"";return n.includes(f)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${f}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.originalFileName||b.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:b.fileSize?(Number(b.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!0)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>c(b,!0),"data-testid":`documents-existing-${f}-preview`,children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(f),"data-testid":`documents-existing-${f}-delete`,children:e.jsx(ft,{className:"h-4 w-4 text-red-600"})})]})]},f)})})})]}),a.length>0&&e.jsxs(ee,{"data-testid":"documents-new-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ne,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((b,f)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${f}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(b.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!1)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>c(b,!1),"data-testid":`documents-new-${f}-preview`,children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>x(f),"data-testid":`documents-new-${f}-remove`,children:e.jsx(ft,{className:"h-4 w-4"})})]})]},f))})})]})]})]})}const FS=t=>{switch(t){case"high":return e.jsx(ha,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ot,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(ta,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ot,{className:"w-4 h-4 text-gray-600"})}};function _S({formData:t,selectedTemplate:s}){return e.jsxs(ts.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(ee,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(sx,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6","data-testid":"review-submit-overview-grid",children:[e.jsxs("div",{"data-testid":"review-submit-overview-type",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(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(re,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[FS(t.priority),e.jsx("span",{className:"text-green-800 capitalize",children:t.priority})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-workflow",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Workflow Type"}),e.jsx("p",{className:"text-green-800 mt-1 capitalize",children:t.workflowType}),e.jsxs("p",{className:"text-sm text-green-700",children:[t.approverCount||1," Level",(t.approverCount||1)>1?"s":""]})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-title",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(ee,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(re,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(sa,{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(Da,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(ee,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(cs,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx($e,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(se,{className:"space-y-6",children:e.jsx("div",{className:"space-y-4","data-testid":"review-submit-approval-levels",children:Array.from({length:t.approverCount||1},(a,r)=>{const n=r+1,i=n===(t.approverCount||1),l=t.approvers[r];return e.jsx("div",{className:"p-4 bg-white rounded-lg border border-orange-200","data-testid":`review-submit-approval-level-${n}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${l!=null&&l.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:n})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",n]}),i&&e.jsx(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(ee,{"data-testid":"review-submit-participants-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(ht,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(se,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(re,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(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(ee,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(zs,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs($e,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"review-submit-documents-list",children:t.documents.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg border","data-testid":`review-submit-document-${r}`,children:[e.jsx(Re,{className:"w-5 h-5 text-gray-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.name}),e.jsx("div",{className:"flex items-center gap-3 text-xs text-gray-500 mt-1",children:e.jsxs("span",{children:[(a.size/(1024*1024)).toFixed(2)," MB"]})})]})]},r))})})]}),e.jsx(ee,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(se,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(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 LS({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(E,{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(Ns,{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 MS({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(Ei,{mode:"wait",children:t})})})}function $S({modal:t,onClose:s}){return e.jsx(pt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Dt,{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(Ni,{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(E,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function OS({modal:t,documentPolicy:s,onClose:a}){return e.jsx(pt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Dt,{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(E,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function ju({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Ea(),i=Ks(),l=n.requestId||a||"",o=r&&!!l,{user:c}=Kt(),[d,m]=p.useState([]);p.useEffect(()=>{(async()=>{try{const rt=(await Mi()).map(ut=>({id:ut.id,name:ut.name,description:ut.description,category:ut.category,icon:Re,estimatedTime:ut.estimatedTime,commonApprovers:ut.approvers.map(nt=>nt.name),workflowApprovers:ut.approvers,suggestedSLA:ut.suggestedSLA,priority:ut.priority,fields:ut.fields||{}}));m(rt)}catch(_e){console.error("Failed to fetch admin templates:",_e)}})()},[]);const h=p.useMemo(()=>[...fu,...d],[d]),{formData:x,updateFormData:u,selectedTemplate:g,setSelectedTemplate:b,loadingDraft:f,systemPolicy:y,documentPolicy:v,existingDocuments:w,setExistingDocuments:C}=oS(o,l,h),{currentStep:k,totalSteps:S,stepNames:_,isStepValid:D,nextStep:A,prevStep:N}=cS(o,g,x),[P,R]=p.useState([]),[O,F]=p.useState([]),$=p.useRef(null),{validationModal:V,policyViolationModal:T,documentErrorModal:j,openValidationModal:U,closeValidationModal:I,openPolicyViolationModal:M,closePolicyViolationModal:W,openDocumentErrorModal:G,closeDocumentErrorModal:ce}=dS(),{submitting:te,savingDraft:L,handleSubmit:z,handleSaveDraft:H}=pS({formData:x,selectedTemplate:g,documents:P,documentsToDelete:O,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:ye,setShowTemplateModal:ae,previewDocument:me,selectTemplate:Q,handleTemplateSelection:oe,nextStep:Ce,prevStep:Ee,handlePreviewDocument:be,closePreview:q}=CS({selectedTemplate:g,setSelectedTemplate:b,updateFormData:u,formData:x,currentStep:k,isStepValid:D,wizardNextStep:A,wizardPrevStep:N,user:c,openValidationModal:U,systemPolicy:y,onPolicyViolation:M,onSubmit:s}),ue=p.useCallback(()=>{if(k===1){i("/dashboard",{replace:!0});return}k===3||k===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Ee()},[k,t,i,Ee]),Ae=p.useRef(!0),Ue=p.useRef(!1);p.useEffect(()=>{Ae.current&&x.documents&&x.documents.length>0&&!Ue.current&&(R(x.documents),Ue.current=!0),Ae.current=!1},[x.documents]);const Z=p.useRef(!1),Te=p.useRef(P);p.useEffect(()=>{if(Z.current){Z.current=!1,Te.current=P;return}Te.current!==P&&(u("documents",P),Te.current=P)},[P]);const Xe=()=>{switch(k){case 1:return e.jsx(kS,{templates:fu,selectedTemplate:g,onSelectTemplate:Q,adminTemplates:d});case 2:return e.jsx(DS,{formData:x,selectedTemplate:g,updateFormData:u});case 3:return e.jsx(PS,{formData:x,updateFormData:u,systemPolicy:y,onValidationError:pe=>U(pe.type,pe.email,pe.message),onPolicyViolation:M});case 4:return e.jsx(IS,{formData:x,updateFormData:u,onValidationError:pe=>U(pe.type,pe.email,pe.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(ES,{documentPolicy:v,isEditing:o,documents:P,existingDocuments:w,documentsToDelete:O,onDocumentsChange:R,onExistingDocumentsChange:C,onDocumentsToDeleteChange:F,onPreviewDocument:be,onDocumentErrors:pe=>G(pe),fileInputRef:$});case 6:return e.jsx(_S,{formData:x,selectedTemplate:g});default:return null}};return f?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center","data-testid":"create-request-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading draft..."})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gradient-to-br from-gray-50 to-white","data-testid":"create-request",children:[e.jsx(LS,{isEditing:o,currentStep:k,totalSteps:S,stepNames:_,onBack:ue}),e.jsx(Rp,{currentStep:k,totalSteps:S,stepNames:_}),e.jsx(MS,{children:Xe()}),e.jsx(TS,{currentStep:k,totalSteps:S,isStepValid:D(),onPrev:Ee,onNext:Ce,onSubmit:z,onSaveDraft:H,submitting:te,savingDraft:L,loadingDraft:f,isEditing:o}),e.jsx(K2,{open:ye,onClose:()=>ae(!1),onSelectTemplate:oe}),me&&e.jsx(jr,{fileName:me.fileName,fileType:me.fileType,fileUrl:me.fileUrl,fileSize:me.fileSize,open:!!me,onClose:q,onDownload:async()=>{if(me.file){const pe=document.createElement("a");pe.href=me.fileUrl,pe.download=me.fileName,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe)}else me.documentId&&await ps(me.documentId)},attachmentId:me.documentId}),e.jsx($S,{modal:V,onClose:I}),e.jsx(OS,{modal:j,documentPolicy:v,onClose:ce}),e.jsx(Fn,{open:T.open,onClose:W,violations:T.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}function $i({className:t,...s}){return e.jsx(pf,{"data-slot":"tabs",className:ke("flex flex-col gap-2",t),...s})}function Oi({className:t,...s}){return e.jsx(gf,{"data-slot":"tabs-list",className:ke("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function qt({className:t,...s}){return e.jsx(ff,{"data-slot":"tabs-trigger",className:ke("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 es({className:t,...s}){return e.jsx(bf,{"data-slot":"tabs-content",className:ke("flex-1 outline-none",t),...s})}function hc(t,s=[],a){const[r,n]=p.useState(null),[i,l]=p.useState(!1),[o,c]=p.useState(!0),[d,m]=p.useState(null),[h,x]=p.useState(null),[u,g]=p.useState(!1),b=(k,S)=>(k||S||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),f=k=>{const S=(k||"").toUpperCase();return S==="IN_PROGRESS"?"in-review":S==="PENDING"?"pending":S==="APPROVED"?"approved":S==="REJECTED"?"rejected":S==="CLOSED"?"closed":S==="SKIPPED"?"skipped":(k||"").toLowerCase()},y=p.useCallback(async()=>{var k,S,_,D,A,N,P,R,O,F,$,V,T;l(!0);try{const j=await ks.getWorkflowDetails(t);if(!j){console.warn("[useRequestDetails] No details returned from API");return}const U=j.workflow||{},I=Array.isArray(j.approvals)?j.approvals:[],M=Array.isArray(j.participants)?j.participants:[],W=Array.isArray(j.documents)?j.documents:[],G=j.summary||{},ce=Array.isArray(j.tatAlerts)?j.tatAlerts:[];ce.length>0;const te=(G==null?void 0:G.currentLevel)||U.currentLevel||1,L=I.map(Z=>{const Te=Z.levelNumber||0,Xe=(Z.status||"").toString().toUpperCase(),pe=Z.levelId||Z.level_id;let _e=f(Z.status);Te>te&&Xe!=="APPROVED"&&Xe!=="REJECTED"?_e="waiting":Te===te&&Xe==="PENDING"&&(_e="pending");const rt=ce.filter(ut=>ut.levelId===pe);return{step:Te,levelId:pe,role:Z.levelName||Z.approverName||"Approver",status:_e,approver:Z.approverName||Z.approverEmail,approverId:Z.approverId||Z.approver_id,approverEmail:Z.approverEmail,tatHours:Number(Z.tatHours||0),elapsedHours:Number(Z.elapsedHours||0),remainingHours:Number(Z.remainingHours||0),tatPercentageUsed:Number(Z.tatPercentageUsed||0),actualHours:Z.levelEndTime&&Z.levelStartTime?Math.max(0,(new Date(Z.levelEndTime).getTime()-new Date(Z.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:Z.comments||void 0,timestamp:Z.actionDate||void 0,levelStartTime:Z.levelStartTime||Z.tatStartTime,tatAlerts:rt,skipReason:Z.skipReason||void 0,isSkipped:Xe==="SKIPPED"||Z.isSkipped||!1}}),z=M.filter(Z=>(Z.participantType||Z.participant_type||"").toUpperCase()==="SPECTATOR").map(Z=>({name:Z.userName||Z.user_name||Z.userEmail||Z.user_email,role:"Spectator",email:Z.userEmail||Z.user_email,avatar:b(Z.userName||Z.user_name,Z.userEmail||Z.user_email)})),H=Z=>{var Xe,pe;if(!Z)return;const Te=M.find(_e=>_e.userId===Z||_e.user_id===Z);return Te!=null&&Te.userName||Te!=null&&Te.user_name?Te.userName||Te.user_name:U.initiatorId===Z?((Xe=U.initiator)==null?void 0:Xe.displayName)||((pe=U.initiator)==null?void 0:pe.email):Z},ye=W.map(Z=>{const Te=Number(Z.fileSize||Z.file_size||0),Xe=(Te/(1024*1024)).toFixed(2)+" MB";return{documentId:Z.documentId||Z.document_id,name:Z.originalFileName||Z.fileName||Z.file_name,fileType:Z.fileType||Z.file_type||"",size:Xe,sizeBytes:Te,uploadedBy:H(Z.uploadedBy||Z.uploaded_by),uploadedAt:Z.uploadedAt||Z.uploaded_at}}),ae=Array.isArray(j.activities)?j.activities.filter(Z=>(Z.type||"").toLowerCase()!=="sla_warning"):[];let me=null;if(U.isPaused||!1)try{me=await Zd(U.requestId)}catch{}let oe=null,Ce=null,Ee=null,be=null;if(U.workflowType==="CLAIM_MANAGEMENT"||U.templateType==="claim-management")try{const Z=await je.get(`/dealer-claims/${U.requestId}`),Te=((k=Z.data)==null?void 0:k.data)||Z.data;if(Te){oe=Te.claimDetails||Te.claim_details,Ce=Te.proposalDetails||Te.proposal_details,Ee=Te.completionDetails||Te.completion_details,be=Te.internalOrder||Te.internal_order||null;const Xe=Te.budgetTracking||Te.budget_tracking||null,pe=Te.invoice||null,_e=Te.creditNote||Te.credit_note||null,rt=Te.completionExpenses||Te.completion_expenses||null;oe&&(oe.budgetTracking=Xe,oe.invoice=pe,oe.creditNote=_e,oe.completionExpenses=rt)}else console.warn("[useRequestDetails] No claimData found in response")}catch(Z){console.error("[useRequestDetails] Error fetching claim details:",{error:(Z==null?void 0:Z.message)||Z,status:(S=Z==null?void 0:Z.response)==null?void 0:S.status,statusText:(_=Z==null?void 0:Z.response)==null?void 0:_.statusText,responseData:(D=Z==null?void 0:Z.response)==null?void 0:D.data,requestId:U.requestId})}const q={...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:L,approvals:I,participants:M,documents:ye,spectators:z,summary:G,sla:(G==null?void 0:G.sla)||U.sla||null,initiator:{name:((A=U.initiator)==null?void 0:A.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:((F=U.initiator)==null?void 0:F.phone)||void 0,avatar:b(($=U.initiator)==null?void 0:$.displayName,(V=U.initiator)==null?void 0:V.email)},createdAt:U.createdAt,updatedAt:U.updatedAt,totalSteps:U.totalLevels||1,currentStepRaw:(G==null?void 0:G.currentLevel)||U.currentLevel||1,currentStep:Math.min(Math.max(1,(G==null?void 0:G.currentLevel)||U.currentLevel||1),U.totalLevels||1),auditTrail:ae,conclusionRemark:U.conclusionRemark||null,closureDate:U.closureDate||null,pauseInfo:me||null,claimDetails:oe||null,proposalDetails:Ce||null,completionDetails:Ee||null,internalOrder:be||null,budgetTracking:(oe==null?void 0:oe.budgetTracking)||null,invoice:(oe==null?void 0:oe.invoice)||null,creditNote:(oe==null?void 0:oe.creditNote)||null,completionExpenses:(oe==null?void 0:oe.completionExpenses)||null};n(q);const ue=(T=a==null?void 0:a.email)==null?void 0:T.toLowerCase(),Ae=I.find(Z=>{const Te=(Z.status||"").toString().toUpperCase(),Xe=(Z.approverEmail||"").toLowerCase(),pe=Z.levelNumber||0;return(Te==="PENDING"||Te==="IN_PROGRESS"||Te==="PAUSED")&&Xe===ue&&pe===te});x(Ae||null);const Ue=a==null?void 0:a.userId;if(Ue){const Z=M.some(Te=>(Te.participantType||Te.participant_type||"").toUpperCase()==="SPECTATOR"&&(Te.userId||Te.user_id)===Ue);g(Z)}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]);p.useEffect(()=>{if(!t){c(!1);return}let k=!0;return c(!0),m(null),(async()=>{var S,_,D,A,N,P,R,O,F,$,V,T,j,U;try{const I=await ks.getWorkflowDetails(t);if(!k||!I){k&&c(!1);return}const M=I.workflow||{},W=Array.isArray(I.approvals)?I.approvals:[],G=Array.isArray(I.participants)?I.participants:[],ce=Array.isArray(I.documents)?I.documents:[],te=I.summary||{},L=Array.isArray(I.tatAlerts)?I.tatAlerts:[],z=(M.priority||"").toString().toLowerCase(),H=(te==null?void 0:te.currentLevel)||M.currentLevel||1,ye=W.map(pe=>{const _e=pe.levelNumber||0,rt=(pe.status||"").toString().toUpperCase(),ut=pe.levelId||pe.level_id;let nt=f(pe.status);rt==="PAUSED"?nt="paused":_e>H&&rt!=="APPROVED"&&rt!=="REJECTED"?nt="waiting":_e===H&&(rt==="PENDING"||rt==="IN_PROGRESS")&&(nt=rt==="IN_PROGRESS"?"in-review":"pending");const Ps=L.filter(Xs=>Xs.levelId===ut);return{step:_e,levelId:ut,role:pe.levelName||pe.approverName||"Approver",status:nt,approver:pe.approverName||pe.approverEmail,approverId:pe.approverId||pe.approver_id,approverEmail:pe.approverEmail,tatHours:Number(pe.tatHours||0),elapsedHours:Number(pe.elapsedHours||0),remainingHours:Number(pe.remainingHours||0),tatPercentageUsed:Number(pe.tatPercentageUsed||0),actualHours:pe.elapsedHours!==void 0&&pe.elapsedHours!==null?Number(pe.elapsedHours):void 0,comment:pe.comments||void 0,timestamp:pe.actionDate||void 0,levelStartTime:pe.levelStartTime||pe.tatStartTime,tatAlerts:Ps}}),ae=G.filter(pe=>(pe.participantType||"").toUpperCase()==="SPECTATOR").map(pe=>({name:pe.userName||pe.userEmail,role:"Spectator",avatar:b(pe.userName,pe.userEmail)})),me=pe=>{var rt,ut;if(!pe)return;const _e=G.find(nt=>nt.userId===pe);return _e!=null&&_e.userName?_e.userName:M.initiatorId===pe?((rt=M.initiator)==null?void 0:rt.displayName)||((ut=M.initiator)==null?void 0:ut.email):pe},Q=ce.map(pe=>{const _e=Number(pe.fileSize||0),rt=(_e/(1024*1024)).toFixed(2)+" MB";return{documentId:pe.documentId||pe.document_id,name:pe.originalFileName||pe.fileName,fileType:pe.fileType||pe.file_type||"",size:rt,sizeBytes:_e,uploadedBy:me(pe.uploadedBy),uploadedAt:pe.uploadedAt}}),oe=Array.isArray(I.activities)?I.activities.filter(pe=>(pe.type||"").toLowerCase()!=="sla_warning"):[];let Ce=null;if(M.isPaused||!1)try{Ce=await Zd(M.requestId)}catch{}let be=null,q=null,ue=null,Ae=null;if(M.workflowType==="CLAIM_MANAGEMENT"||M.templateType==="claim-management")try{const pe=await je.get(`/dealer-claims/${M.requestId}`),_e=((S=pe.data)==null?void 0:S.data)||pe.data;if(_e){be=_e.claimDetails||_e.claim_details,q=_e.proposalDetails||_e.proposal_details,ue=_e.completionDetails||_e.completion_details,Ae=_e.internalOrder||_e.internal_order||null;const rt=_e.budgetTracking||_e.budget_tracking||null,ut=_e.invoice||null,nt=_e.creditNote||_e.credit_note||null,Ps=_e.completionExpenses||_e.completion_expenses||null;be&&(be.budgetTracking=rt,be.invoice=ut,be.creditNote=nt,be.completionExpenses=Ps)}}catch(pe){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(pe==null?void 0:pe.message)||pe,status:(_=pe==null?void 0:pe.response)==null?void 0:_.status,requestId:M.requestId})}const Ue={id:M.requestNumber||M.requestId,requestId:M.requestId,title:M.title,description:M.description,priority:z,status:f(M.status),workflowType:M.workflowType||(M.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:te,initiator:{name:((D=M.initiator)==null?void 0:D.displayName)||((A=M.initiator)==null?void 0:A.email),role:((N=M.initiator)==null?void 0:N.designation)||void 0,department:((P=M.initiator)==null?void 0:P.department)||void 0,email:((R=M.initiator)==null?void 0:R.email)||void 0,phone:((O=M.initiator)==null?void 0:O.phone)||void 0,avatar:b((F=M.initiator)==null?void 0:F.displayName,($=M.initiator)==null?void 0:$.email)},createdAt:M.createdAt,updatedAt:M.updatedAt,totalSteps:M.totalLevels||1,currentStepRaw:(te==null?void 0:te.currentLevel)||M.currentLevel||1,currentStep:Math.min(Math.max(1,(te==null?void 0:te.currentLevel)||M.currentLevel||1),M.totalLevels||1),approvalFlow:ye,approvals:W,documents:Q,spectators:ae,auditTrail:oe,conclusionRemark:M.conclusionRemark||null,closureDate:M.closureDate||null,pauseInfo:Ce||null,claimDetails:be||null,proposalDetails:q||null,completionDetails:ue||null,internalOrder:Ae||null,budgetTracking:(be==null?void 0:be.budgetTracking)||null,invoice:(be==null?void 0:be.invoice)||null,creditNote:(be==null?void 0:be.creditNote)||null,completionExpenses:(be==null?void 0:be.completionExpenses)||null};n(Ue);const Z=(V=a==null?void 0:a.email)==null?void 0:V.toLowerCase(),Te=W.find(pe=>{const _e=(pe.status||"").toString().toUpperCase(),rt=(pe.approverEmail||"").toLowerCase(),ut=pe.levelNumber||0;return(_e==="PENDING"||_e==="IN_PROGRESS"||_e==="PAUSED")&&rt===Z&&ut===H});x(Te||null);const Xe=a==null?void 0:a.userId;if(Xe){const pe=G.some(_e=>(_e.participantType||"").toUpperCase()==="SPECTATOR"&&_e.userId===Xe);g(pe)}else g(!1)}catch(I){if(console.error("[useRequestDetails] Error loading request details:",I),k){if(((T=I==null?void 0:I.response)==null?void 0:T.status)===403){const M=((U=(j=I==null?void 0:I.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:M})}n(null)}}finally{k&&c(!1)}})(),()=>{k=!1}},[t,a]);const v=p.useMemo(()=>{if(r)return r;const k=s.find(S=>S.id===t||S.requestNumber===t||S.request_number===t);return k||null},[t,s,r]),w=p.useMemo(()=>{var _,D,A;if(!v||!a)return!1;const k=(_=a==null?void 0:a.email)==null?void 0:_.toLowerCase(),S=(A=(D=v.initiator)==null?void 0:D.email)==null?void 0:A.toLowerCase();return k===S},[v,a]),C=p.useMemo(()=>{var S;if(!v)return[];const k=[];return(S=v.initiator)!=null&&S.email&&k.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(_=>{_.approverEmail&&k.push({email:_.approverEmail.toLowerCase(),participantType:"APPROVER",name:_.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(_=>{_.email&&k.push({email:_.email.toLowerCase(),participantType:"SPECTATOR",name:_.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(_=>{const D=(_.userEmail||_.email||"").toLowerCase(),A=(_.participantType||_.participant_type||"").toUpperCase(),N=_.userName||_.user_name||_.name;D&&A&&!k.find(P=>P.email===D)&&k.push({email:D,participantType:A,name:N})}),k},[v]);return p.useEffect(()=>{if(!t||!r)return;const k=Lr();if(!k)return;const S=_=>{((_==null?void 0:_.requestId)===r.requestId||(_==null?void 0:_.requestNumber)===t)&&y()};return k.on("request:updated",S),()=>{k.off("request:updated",S)}},[t,r,y]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:y,currentApprovalLevel:h,isSpectator:u,isInitiator:w,existingParticipants:C,accessDenied:d}}function Ip(t,s,a,r){const[n,i]=p.useState([]),[l,o]=p.useState(0),[c,d]=p.useState([]);return p.useEffect(()=>{if(!t){console.warn("[useRequestSocket] No requestIdentifier, cannot join socket room");return}let m=!0,h=t;return(async()=>{var b;try{const f=await ks.getWorkflowDetails(t);(b=f==null?void 0:f.workflow)!=null&&b.requestId&&m&&(h=f.workflow.requestId)}catch(f){console.error("[useRequestSocket] Failed to resolve UUID:",f)}if(!m)return;const x=Lr();if(!x){console.error("[useRequestSocket] Socket not available");return}const u=r==null?void 0:r.userId,g=()=>{Ml(x,h,u)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Ax(x,h))}})(),()=>{m=!1}},[t,r]),p.useEffect(()=>{!t||!s||(async()=>{try{const m=await Fr(t),h=s.auditTrail||[],x=[...m,...h];x.sort((u,g)=>{const b=new Date(u.createdAt||u.created_at||u.timestamp||0).getTime(),f=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return b-f}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),p.useEffect(()=>{if(!t)return;const m=Lr();if(!m)return;const h=u=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await Fr(t),b=(s==null?void 0:s.auditTrail)||[],f=[...g,...b].sort((y,v)=>{const w=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime(),C=new Date(v.createdAt||v.created_at||v.timestamp||0).getTime();return w-C});i(f)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=u=>{const g=u.type==="breach"?"⏰":u.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const b=await ks.getWorkflowDetails(t);b&&(Array.isArray(b.tatAlerts)&&b.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:u.message,icon:"/favicon.ico",tag:`tat-${u.requestId}-${u.type}`,requireInteraction:!1}))}catch(b){console.error("[useRequestSocket] Failed to refresh after TAT alert:",b)}})()};return m.on("noteHandler",h),m.on("worknote:new",h),m.on("tat:alert",x),()=>{m.off("noteHandler",h),m.off("worknote:new",h),m.off("tat:alert",x)}},[t,a,s]),p.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function nn(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 je.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 Ep(t,s){const[a,r]=p.useState(!1),[n,i]=p.useState(null),[l,o]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=p.useState({show:!1,errors:[]});p.useEffect(()=>{(async()=>{try{const g=await Ys("DOCUMENT_POLICY"),b={};g.forEach(w=>{b[w.configKey]=w.configValue});const f=parseInt(b.MAX_FILE_SIZE_MB||"10"),v=(b.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(w=>w.trim().toLowerCase());o({maxFileSizeMB:f,allowedFileTypes:v})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=u=>{const g=l.maxFileSizeMB*1024*1024;if(u.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(u.size/(1024*1024)).toFixed(2)}MB`};const b=u.name.toLowerCase(),f=b.substring(b.lastIndexOf(".")+1);return l.allowedFileTypes.includes(f)?{valid:!0}:{valid:!1,reason:`File type "${f}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},h=async u=>{var v,w;const g=u.target.files;if(!g||g.length===0)return;const b=Array.from(g),f=[],y=[];if(b.forEach(C=>{const k=m(C);k.valid?y.push(C):f.push({fileName:C.name,reason:k.reason||"Unknown validation error"})}),f.length>0&&d({show:!0,errors:f}),y.length===0){u.target&&(u.target.value="");return}r(!0);try{const C=y[0],k=t==null?void 0:t.requestId;if(!k){K.error("Request ID not found");return}C&&await nn(C,k,"SUPPORTING"),await s(),y.length<b.length?K.warning(`${y.length} of ${b.length} file(s) were uploaded. ${f.length} file(s) were rejected.`):K.success("Document uploaded successfully")}catch(C){console.error("[useDocumentUpload] Upload error:",C),K.error(((w=(v=C==null?void 0:C.response)==null?void 0:v.data)==null?void 0:w.error)||"Failed to upload document")}finally{r(!1),u.target&&(u.target.value="")}};return{uploadingDocument:a,handleDocumentUpload:h,triggerFileInput:()=>{const u=document.createElement("input");u.type="file",u.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),u.onchange=h,u.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const US="modulepreload",BS=function(t){return"/"+t},Nu={},jl=function(s,a,r){let n=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));n=Promise.allSettled(a.map(c=>{if(c=BS(c),c in Nu)return;Nu[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":US,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((x,u)=>{h.addEventListener("load",x),h.addEventListener("error",()=>u(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return n.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};function Fp(t,s,a,r,n,i,l){const[o,c]=p.useState(""),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(0),[y,v]=p.useState(!1),[w,C]=p.useState(!1),[k,S]=p.useState(0),_=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){c(N||P),g(!!P);return}try{const{getConclusion:O}=await jl(async()=>{const{getConclusion:$}=await import("./conclusionApi-C_Bd1V1u.js");return{getConclusion:$}},__vite__mapDeps([0,1,2,3,4,5,6,7])),F=await O(t.requestId||s);F&&(F.aiGeneratedRemark||F.finalRemark)&&(c(F.finalRemark||F.aiGeneratedRemark||""),g(!!F.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(!w)try{m(!0),v(!1);const{generateConclusion:N}=await jl(async()=>{const{generateConclusion:F}=await import("./conclusionApi-C_Bd1V1u.js");return{generateConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7])),P=await N(t.requestId||s),R=b+1;if(f(R),!(P!=null&&P.aiGeneratedRemark)||P.aiGeneratedRemark.toLowerCase().includes("unable to generate")||P.aiGeneratedRemark.toLowerCase().includes("sorry")){const F=k+1;S(F),F>=2?(C(!0),i==null||i({success:!1,title:"AI Generation Limit Reached",message:"We're unable to process a conclusion remark at this time after 2 attempts. Please proceed with a manual approach using the editor below."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process a conclusion remark at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0),c((P==null?void 0:P.aiGeneratedRemark)||""),g(!1);return}c(P.aiGeneratedRemark),g(!0),S(0),R>=2&&(C(!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=k+1;S(P),g(!1),P>=2?(C(!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)}},A=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 jl(async()=>{const{finalizeConclusion:F}=await import("./conclusionApi-C_Bd1V1u.js");return{finalizeConclusion:F}},__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 p.useEffect(()=>{var F;const N=(F=t==null?void 0:t.status)==null?void 0:F.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?(c(R||O),g(!!O)):_()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:h,aiGenerated:u,handleGenerateConclusion:D,handleFinalizeConclusion:A,generationAttempts:b,generationFailed:y,maxAttemptsReached:w}}function _p(t,s,a){const[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState(!1),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(null),[y,v]=p.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:h,setShowSkipApproverModal:x,showActionStatusModal:u,setShowActionStatusModal:g,skipApproverData:b,setSkipApproverData:f,actionStatus:y,setActionStatus:v,handleApproveConfirm:async D=>{var N,P;const A=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!A){alert("Approval level not found");return}await an(t,A,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 A=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!A){alert("Approval level not found");return}await Sr(t,A,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,A,N)=>{var P,R;try{await Vx(t,D,A,N),await a(),c(!1),v==null||v({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${A}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 A,N;if(b)try{await Zj(t,b.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=(A=P==null?void 0:P.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),P}},handleAddSpectator:async D=>{var A,N;try{await zx(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=(A=P==null?void 0:P.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),P}}}}const VS=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 Or({document:t,onPreview:s,onDownload:a,showPreview:r=!0,testId:n="document-card"}){return e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors","data-testid":`${n}-${t.documentId}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Re,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900","data-testid":`${n}-name`,children:t.name}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${n}-metadata`,children:[t.size&&e.jsxs("span",{children:[t.size," • "]}),t.uploadedBy&&e.jsxs("span",{children:["Uploaded by ",t.uploadedBy," on "]}),Qt(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&VS(t.fileType)&&s&&e.jsx(E,{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(E,{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(Ct,{className:"w-4 h-4"})})]})]})}function zS({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(ee,{children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx($e,{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(E,{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(zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a?"Uploading...":t.status==="closed"?"Closed":"Upload",e.jsx("span",{className:"hidden sm:inline",children:t.status==="closed"?"":"Document"})]}),e.jsxs("p",{className:"text-xs text-gray-500 whitespace-nowrap",children:["Max ",r.maxFileSizeMB,"MB"]})]})]})}),e.jsx(se,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((o,c)=>e.jsx(Or,{document:o,onPreview:d=>i(d),onDownload:l,testId:"request-document"},c))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(As,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(se,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((o,c)=>e.jsx(Or,{document:{documentId:o.attachmentId||"",name:o.name,fileType:o.type||"",size:o.size?`${(o.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:o.size,uploadedBy:o.uploadedBy,uploadedAt:o.uploadedAt},onPreview:d=>i(d),onDownload:async d=>{const{downloadWorkNoteAttachment:m}=require("@/services/workflowApi");await m(d)},testId:"worknote-attachment"},o.attachmentId||c))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-attachments",children:"No files shared in work notes yet"})})]})]})}const HS=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"}}},WS=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}}},GS=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(wt,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(As,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx($t,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(wi,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Re,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(st,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(vi,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(as,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(kt,{className:"w-5 h-5 text-gray-600"})}};function YS({request:t}){return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(kt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(se,{children:e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.auditTrail&&t.auditTrail.length>0?t.auditTrail.map((s,a)=>e.jsxs("div",{className:"flex items-start gap-4","data-testid":`activity-item-${a}`,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center",children:GS(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:Qt(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(kt,{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 Lp({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsx(gt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[a?e.jsx(De,{className:"w-5 h-5 text-green-600"}):e.jsx(ze,{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(wt,{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(E,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function Mp({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=p.useState(""),[l,o]=p.useState(!1),[c,d]=p.useState([]),[m,h]=p.useState(!1),[x,u]=p.useState(null),g=p.useRef(null),b=p.useRef(null),[f,y]=p.useState({open:!1,type:"error",email:"",message:""}),[v,w]=p.useState({open:!1,violations:[]}),[C,k]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});p.useEffect(()=>{t&&(async()=>{var P;try{const R=await Ys("WORKFLOW_SHARING"),O=await Ys("TAT_SETTINGS"),F=[...R,...O],$={};F.forEach(V=>{$[V.configKey]=V.configValue}),k({maxApprovalLevels:parseInt($.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt($.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((P=$.ALLOW_ADD_SPECTATOR)==null?void 0:P.toLowerCase())==="true",maxSpectators:parseInt($.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(R){console.error("Failed to load system policy:",R)}})()},[t]);const S=async()=>{var T,j;const N=n.trim().toLowerCase();if(!N){y({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){y({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=((T=R.participantType)==null?void 0:T.toUpperCase())||"PARTICIPANT",I=R.name||N;if(U==="INITIATOR"){y({open:!0,type:"error",email:N,message:`${I} is the request initiator and cannot be added as a spectator.`});return}else if(U==="APPROVER"){y({open:!0,type:"error",email:N,message:`${I} is already an approver on this request and cannot be added as a spectator.`});return}else if(U==="SPECTATOR"){y({open:!0,type:"error",email:N,message:`${I} is already a spectator on this request.`});return}else{y({open:!0,type:"error",email:N,message:`${I} is already a participant on this request.`});return}}const O=[];C.allowSpectators||O.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const $=r.filter(U=>(U.participantType||"").toUpperCase()==="SPECTATOR").length;$>=C.maxSpectators&&O.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:$,maxValue:C.maxSpectators});const V=r.length+1;if(V>C.maxParticipants&&O.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:V,maxValue:C.maxParticipants}),O.length>0){w({open:!0,violations:O});return}if(!x||x.email.toLowerCase()!==N)try{const I=((j=(await ia(N,1)).data)==null?void 0:j.data)||[];if(I.length===0){y({open:!0,type:"not-found",email:N,message:""});return}const M=I[0];await ra({userId:M.userId,email:M.email,displayName:M.displayName,firstName:M.firstName,lastName:M.lastName,department:M.department,phone:M.phone,mobilePhone:M.mobilePhone,designation:M.designation,jobTitle:M.jobTitle,manager:M.manager,employeeId:M.employeeId,employeeNumber:M.employeeNumber,secondEmail:M.secondEmail,location:M.location})}catch(U){console.error("Failed to validate spectator:",U),y({open:!0,type:"error",email:N,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(N),i(""),u(null),s()}catch(U){console.error("Failed to add spectator:",U)}finally{o(!1)}},_=()=>{l||(i(""),u(null),d([]),h(!1),s())};p.useEffect(()=>{c.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[c.length]),p.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const D=N=>{if(i(N),x&&x.email.toLowerCase()!==N.toLowerCase()&&u(null),g.current&&clearTimeout(g.current),!N||!N.startsWith("@")||N.length<2){d([]),h(!1);return}h(!0),g.current=setTimeout(async()=>{var P;try{const R=N.slice(1),F=((P=(await ia(R,10)).data)==null?void 0:P.data)||[];d(F)}catch(R){console.error("Search failed:",R),d([])}finally{h(!1)}},300)},A=async N=>{try{await ra({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),u(N),d([]),h(!1)}catch(P){console.error("Failed to ensure user exists:",P),y({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(pt,{open:t,onOpenChange:_,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:_,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:l,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{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(mt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:b,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a spectator to this request. They will receive notifications but cannot approve or reject."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{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||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>A(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(N.displayName||N.email).split(" ").map(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(E,{type:"button",variant:"outline",onClick:_,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:S,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(pt,{open:f.open,onOpenChange:N=>y(P=>({...P,open:N})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:f.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Dt,{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(Ni,{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(E,{onClick:()=>y(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Fn,{open:v.open,onClose:()=>w({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:C.maxApprovalLevels,maxParticipants:C.maxParticipants,allowSpectators:C.allowSpectators,maxSpectators:C.maxSpectators}})]})}function $p({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=p.useState(""),[d,m]=p.useState(24),[h,x]=p.useState(null),[u,g]=p.useState(!1),[b,f]=p.useState([]),[y,v]=p.useState(!1),[w,C]=p.useState(null),k=p.useRef(null),S=p.useRef(null),[_,D]=p.useState({open:!1,type:"error",email:"",message:""}),A=n.filter(j=>j&&(j.status==="approved"||j.status==="rejected"||j.status==="skipped")),N=Math.max(1,A.length+1),P=Math.max(1,n.length+1),R=P>=N?Array.from({length:P-N+1},(j,U)=>N+U):[N];p.useEffect(()=>{R.length>0&&h===null&&x(R[0]||null)},[R.length,h]);const O=async()=>{var G,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(!d||d<=0){D({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(d>720){D({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!h){D({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(h<N){D({open:!0,type:"error",email:"",message:`Cannot add approver at level ${h}. Minimum allowed level is ${N} (after completed levels)`});return}const I=n.length>0?Math.max(...n.map(te=>te.levelNumber),0):0,M=h>I?h:I+1;if(i&&M>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${h} would result in ${M} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:M,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${I} level(s).`});return}const W=r.find(te=>(te.email||"").toLowerCase()===j);if(W){const te=((G=W.participantType)==null?void 0:G.toUpperCase())||"PARTICIPANT",L=W.name||j;if(te==="INITIATOR"){D({open:!0,type:"error",email:j,message:`${L} is the request initiator and cannot be added as an approver.`});return}else if(te==="APPROVER"){D({open:!0,type:"error",email:j,message:`${L} is already an approver on this request.`});return}else if(te==="SPECTATOR"){D({open:!0,type:"error",email:j,message:`${L} 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:`${L} is already a participant on this request.`});return}}if(!w||w.email.toLowerCase()!==j)try{const L=((ce=(await ia(j,1)).data)==null?void 0:ce.data)||[];if(L.length===0){D({open:!0,type:"not-found",email:j,message:""});return}const z=L[0];await ra({userId:z.userId,email:z.email,displayName:z.displayName,firstName:z.firstName,lastName:z.lastName,department:z.department,phone:z.phone,mobilePhone:z.mobilePhone,designation:z.designation,jobTitle:z.jobTitle,manager:z.manager,employeeId:z.employeeId,employeeNumber:z.employeeNumber,secondEmail:z.secondEmail,location:z.location})}catch(te){console.error("Failed to validate approver:",te),D({open:!0,type:"error",email:j,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(j,d,h),c(""),m(24),x(null),C(null),s()}catch(te){console.error("Failed to add approver:",te)}finally{g(!1)}},F=()=>{u||(c(""),m(24),x(null),C(null),f([]),v(!1),s())},$=j=>{const U=j.toLowerCase();return U==="approved"?e.jsx(De,{className:"w-4 h-4 text-green-600"}):U==="rejected"?e.jsx(wt,{className:"w-4 h-4 text-red-600"}):U==="skipped"?e.jsx(ze,{className:"w-4 h-4 text-orange-600"}):U==="in-review"||U==="pending"?e.jsx(st,{className:"w-4 h-4 text-blue-600"}):e.jsx(st,{className:"w-4 h-4 text-gray-400"})};p.useEffect(()=>{b.length>0&&S.current&&S.current.scrollTo({top:S.current.scrollHeight,behavior:"smooth"})},[b.length]),p.useEffect(()=>()=>{k.current&&clearTimeout(k.current)},[]);const V=j=>{if(c(j),w&&w.email.toLowerCase()!==j.toLowerCase()&&C(null),k.current&&clearTimeout(k.current),!j||!j.startsWith("@")||j.length<2){f([]),v(!1);return}v(!0),k.current=setTimeout(async()=>{var U;try{const I=j.slice(1),W=((U=(await ia(I,10)).data)==null?void 0:U.data)||[];f(W)}catch(I){console.error("Search failed:",I),f([])}finally{v(!1)}},300)},T=async j=>{try{await ra({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}),c(j.email),C(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(pt,{open:t,onOpenChange:F,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:F,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:u,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{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(cs,{className:"w-5 h-5 text-blue-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:S,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(re,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(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:[$(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(re,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(We,{value:(h==null?void 0:h.toString())||"",onValueChange:j=>x(Number(j)),disabled:u,children:[e.jsx(Ye,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select level"})}),e.jsx(Ke,{children:R.map(j=>e.jsx(Y,{value:j.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{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(re,{className:"text-sm font-medium text-gray-700",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{type:"number",min:"1",max:"720",value:d,onChange:j=>m(Number(j.target.value)),className:"h-11 border-gray-300 flex-1",disabled:u,placeholder:"24"}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-600 bg-gray-100 px-3 h-11 rounded-md border border-gray-300",children:[e.jsx(st,{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(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:j=>V(j.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(y||b.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:y?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):b.length>0?e.jsx("ul",{className:"divide-y",children:b.map(j=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>T(j),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{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(E,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:O,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!o.trim()||!h||!d,children:[e.jsx(cs,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${h||"?"}`]})]})]}),e.jsx(pt,{open:_.open,onOpenChange:j=>D(U=>({...U,open:j})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:_.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[_.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:_.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ni,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),_.type==="error"&&e.jsxs(e.Fragment,{children:[_.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:_.email}),"."]}),_.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:_.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:()=>D(j=>({...j,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const KS=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"}},XS=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},ZS=t=>{const s=t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(a,r,n,i)=>{const l=n+a.length,o=i[l];return!o||/\s|[.,!?;:]|@/.test(o)?'<span class="inline-flex items-center px-2.5 py-0.5 rounded-md bg-blue-50 text-blue-800 font-black text-base border-2 border-blue-400 shadow-sm">@'+r+"</span>":a}).replace(/\n/g,"<br />");return ba(s)},JS=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",wu=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Re,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(d0,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Re,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Re,{className:`${s} text-blue-600`}):a.includes("image")||a.includes("png")||a.includes("jpg")||a.includes("jpeg")||a.includes("gif")||a.includes("webp")?e.jsx(Wn,{className:`${s} text-purple-600`}):e.jsx(vi,{className:`${s} text-gray-600`})};function Op({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d,maxApprovalLevels:m,onPolicyViolation:h}){const x=Ea(),u=t||x.requestId||"",[g,b]=p.useState(""),[f,y]=p.useState(""),[v,w]=p.useState(!1),[C,k]=p.useState([]),[S,_]=p.useState(!1),[D,A]=p.useState([]),[N,P]=p.useState(null),[R,O]=p.useState(null),[F,$]=p.useState(!1),[V,T]=p.useState(!1),[j,U]=p.useState(!1),[I,M]=p.useState({success:!0,title:"",message:""}),W=p.useRef(null),G=p.useRef(null),ce=p.useRef(null),te=p.useRef(!1),[L,z]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[H,ye]=p.useState({open:!1,errors:[]}),ae=p.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[me,Q]=p.useState([]),oe=me.filter(X=>X.status==="online"),Ce=C.filter(X=>X.content.toLowerCase().includes(f.toLowerCase())||X.user.name.toLowerCase().includes(f.toLowerCase())),Ee=p.useMemo(()=>o!==void 0?o:!N||me.length===0?!1:me.some(X=>{const we=X.userId||X.user_id,J=(X.role||"").toString().toUpperCase(),Le=(X.participantType||X.participant_type||"").toString().toUpperCase();return we===N&&(J==="SPECTATOR"||Le==="SPECTATOR")}),[o,N,me]);p.useEffect(()=>{},[me]),p.useEffect(()=>{!u||!N||s||(async()=>{try{const X=await Fr(u),we=Array.isArray(X)?X.map(J=>{const Le=J.userId||J.user_id;return{id:J.noteId||J.id||String(Math.random()),user:{name:J.userName||"User",avatar:(J.userName||"U").slice(0,2).toUpperCase(),role:J.userRole||"Participant"},content:J.message||"",timestamp:J.createdAt||new Date().toISOString(),isCurrentUser:Le===N,attachments:Array.isArray(J.attachments)?J.attachments.map(Fe=>({attachmentId:Fe.attachmentId||Fe.attachment_id,name:Fe.fileName||Fe.file_name||Fe.name,fileName:Fe.fileName||Fe.file_name||Fe.name,url:Fe.storageUrl||Fe.storage_url||Fe.url||"#",type:Fe.fileType||Fe.file_type||Fe.type||"file",fileType:Fe.fileType||Fe.file_type||Fe.type||"file",fileSize:Fe.fileSize||Fe.file_size})):void 0}}):[];k(we)}catch(X){console.error("[WorkNoteChat] Failed to load messages:",X)}})()},[u,N,s]);const be=p.useMemo(()=>{const X=[];return C.forEach(we=>{we.attachments&&we.attachments.length>0&&we.attachments.forEach(J=>{X.push({attachmentId:J.attachmentId||J.attachment_id,name:J.fileName||J.file_name||J.name||"Untitled",fileName:J.fileName||J.file_name||J.name||"Untitled",size:J.fileSize||J.file_size,type:J.fileType||J.file_type||J.type||"file",uploadedBy:we.user.name,uploadedAt:we.timestamp,url:J.storageUrl||J.storage_url||J.url||"#"})})}),X},[C]);p.useEffect(()=>{i&&be.length>=0&&i(be)},[be,i]);const q=p.useMemo(()=>me.map(X=>({email:(X.email||"").toLowerCase(),participantType:X.role==="Initiator"?"INITIATOR":X.role==="Approver"?"APPROVER":X.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:X.name})),[me]),ue=X=>{if(!X)return"Participant";switch(X.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()}},Ae=()=>{var X;(X=W.current)==null||X.scrollIntoView({behavior:"smooth"})};p.useEffect(()=>{Ae()},[C]);const Ue=X=>{switch(X.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()}};p.useEffect(()=>{te.current||u&&(async()=>{try{const X=await vs(u),we=Array.isArray(X==null?void 0:X.participants)?X.participants:[];if(we.length===0)return;const J=we.map(Me=>{const Ze=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(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ue(Ze.toString()),status:"offline",email:Me.userEmail||Me.user_email||"",permissions:["read","write","mention"],userId:Be}});te.current=!0,Q(J);let Le=0;const Fe=3,Ve=()=>{ce.current&&ce.current.connected?(ce.current.emit("request:online-users",{requestId:u}),Le++,Le<Fe&&setTimeout(Ve,500)):(Le++,Le<Fe&&setTimeout(Ve,200))};setTimeout(Ve,100)}catch(X){console.error("[WorkNoteChat] ❌ Failed to load participants:",X)}})()},[u]),p.useEffect(()=>()=>{u&&(te.current=!1)},[u]),p.useEffect(()=>{const X=localStorage.getItem("userData");if(X)try{const we=JSON.parse(X),J=(we==null?void 0:we.id)||(we==null?void 0:we.userId)||(we==null?void 0:we.user_id)||null;P(J)}catch(we){console.error("[WorkNoteChat] Failed to parse userData:",we)}},[]),p.useEffect(()=>{(async()=>{try{const we=await Ys("DOCUMENT_POLICY"),J={};we.forEach(Me=>{J[Me.configKey]=Me.configValue});const Le=parseInt(J.MAX_FILE_SIZE_MB||"10"),Ve=(J.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Me=>Me.trim().toLowerCase());z({maxFileSizeMB:Le,allowedFileTypes:Ve})}catch(we){console.error("Failed to load document policy:",we)}})()},[]),p.useEffect(()=>{if(!N)return;let X=u;return(async()=>{var we;try{const J=await vs(u);(we=J==null?void 0:J.workflow)!=null&&we.requestId&&(X=J.workflow.requestId)}catch{}try{const J=Lr();r?Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)):(Ml(J,X,N),Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)));const Le=at=>{const et=(at==null?void 0:at.note)||at;if(!et)return;const yt=et.noteId||et.id;k(rs=>{if(rs.some(St=>St.id===yt))return rs;const Pt=et.userName||et.user_name||"User",la=et.userRole||et.user_role,pa=ue(la),Fa=et.userId||et.user_id,wa={id:yt||String(Date.now()),user:{name:Pt,avatar:Pt.split(" ").map(St=>St[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:pa},content:et.message||"",timestamp:et.createdAt||new Date().toISOString(),isCurrentUser:Fa===N,attachments:Array.isArray(et.attachments)?et.attachments.map(St=>({attachmentId:St.attachmentId||St.attachment_id,name:St.fileName||St.file_name||St.name,fileName:St.fileName||St.file_name||St.name,url:St.storageUrl||St.storage_url||St.url||"#",type:St.fileType||St.file_type||St.type||"file",fileType:St.fileType||St.file_type||St.type||"file",fileSize:St.fileSize||St.file_size})):void 0};return[...rs,wa]})},Fe=at=>{Q(et=>et.length===0||!et.find(Pt=>Pt.userId===at.userId)?et:et.map(Pt=>Pt.userId===at.userId?{...Pt,status:"online"}:Pt))},Ve=at=>{at.userId!==N&&Q(et=>et.length===0||!et.find(Pt=>Pt.userId===at.userId)?et:et.map(Pt=>Pt.userId===at.userId?{...Pt,status:"offline"}:Pt))},Me=at=>{Q(et=>et.length===0?et:et.map(rs=>{const Pt=rs.userId||"";if(Pt===N)return{...rs,status:"online"};const pa=at.userIds.includes(Pt);return{...rs,status:pa?"online":"offline"}}))},Ze=()=>{Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)),r||Ml(J,X,N),te.current&&(J.emit("request:online-users",{requestId:X}),setTimeout(()=>J.emit("request:online-users",{requestId:X}),300),setTimeout(()=>J.emit("request:online-users",{requestId:X}),800))},Be=at=>{console.error("[WorkNoteChat] ❌ Socket error:",at)},qe=at=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",at),Q(et=>et.map(yt=>yt.userId===N?yt:{...yt,status:"offline"}))},fs=at=>{at.includes("presence")||at.includes("worknote")||at.includes("request")};J.on("connect",Ze),J.on("disconnect",qe),J.on("error",Be),J.on("worknote:new",Le),J.on("presence:join",Fe),J.on("presence:leave",Ve),J.on("presence:online",Me),J.onAny(fs),ce.current=J,J.connected&&te.current&&(J.emit("request:online-users",{requestId:X}),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},300),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},800),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},1500));const Ht=()=>{J.off("connect",Ze),J.off("disconnect",qe),J.off("error",Be),J.off("worknote:new",Le),J.off("presence:join",Fe),J.off("presence:leave",Ve),J.off("presence:online",Me),J.offAny(fs),r||Ax(J,X),ce.current=null};window.__wn_cleanup=Ht}catch{}})(),()=>{var we;try{(we=window.__wn_cleanup)==null||we.call(window)}catch{}}},[u,N,r]);const Z=async()=>{if(g.trim()||D.length>0){const X=Xs(g),we=X.map(Fe=>{const Ve=me.find(Me=>Me.name.toLowerCase().includes(Fe.toLowerCase()));return Ve==null?void 0:Ve.userId}).filter(Boolean),J=D.map(Fe=>({name:Fe.name,url:URL.createObjectURL(Fe),type:Fe.type.split("/")[1]||"file"})),Le={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:X,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:J.length>0?J:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await Bx(u,{message:g,mentions:we},D);const Fe=await Fr(u),Ve=Array.isArray(Fe)?Fe.map(Me=>{const Ze=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:Ze===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}}):[];k(Ve)}catch{k(Fe=>[...Fe,Le])}b(""),A([])}};p.useEffect(()=>{if(s&&Array.isArray(s))try{const we=s.filter(J=>(J.type||"").toLowerCase()!=="sla_warning").map(J=>{var Fe;if(J.type||J.activityType||J.isSystem)return{id:J.id||`activity-${J.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:J.details||J.action||J.content||"",timestamp:J.timestamp||J.createdAt||J.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const Ve=J.userName||J.user_name||((Fe=J.user)==null?void 0:Fe.name)||"User",Me=J.userRole||J.user_role,Ze=ue(Me),Be=J.userId||J.user_id;return{id:J.noteId||J.note_id||J.id||String(Math.random()),user:{name:Ve,avatar:Ve.split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ze},content:J.message||J.content||"",timestamp:J.createdAt||J.created_at||J.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(J.attachments)?J.attachments.map(qe=>({attachmentId:qe.attachmentId||qe.attachment_id,name:qe.fileName||qe.file_name||qe.name,fileName:qe.fileName||qe.file_name||qe.name,url:qe.storageUrl||qe.storage_url||qe.url||"#",type:qe.fileType||qe.file_type||qe.type||"file",fileType:qe.fileType||qe.file_type||qe.type||"file",fileSize:qe.fileSize||qe.file_size})):void 0,isCurrentUser:Be===N}}}).sort((J,Le)=>new Date(J.timestamp).getTime()-new Date(Le.timestamp).getTime());k(we)}catch(X){console.error("[WorkNoteChat] Error mapping messages:",X)}else(async()=>{try{const X=await Fr(u),we=Array.isArray(X)?X.map(J=>{const Le=J.userName||J.user_name||"User",Fe=J.userRole||J.user_role,Ve=ue(Fe),Me=J.userId||J.user_id;return{id:J.noteId||J.note_id||J.id||String(Math.random()),user:{name:Le,avatar:Le.split(" ").map(Ze=>Ze[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ve},content:J.message||"",timestamp:J.createdAt||J.created_at||new Date().toISOString(),attachments:Array.isArray(J.attachments)?J.attachments.map(Ze=>({attachmentId:Ze.attachmentId||Ze.attachment_id,name:Ze.fileName||Ze.file_name||Ze.name,fileName:Ze.fileName||Ze.file_name||Ze.name,url:Ze.storageUrl||Ze.storage_url||Ze.url||"#",type:Ze.fileType||Ze.file_type||Ze.type||"file",fileType:Ze.fileType||Ze.file_type||Ze.type||"file",fileSize:Ze.fileSize||Ze.file_size})):void 0,isCurrentUser:Me===N}}):[];k(we)}catch(X){console.error("[WorkNoteChat] Error loading work notes:",X)}})()},[s,u,me]);const Te=X=>{const we=L.maxFileSizeMB*1024*1024;if(X.size>we)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${L.maxFileSizeMB}MB. Current size: ${(X.size/(1024*1024)).toFixed(2)}MB`};const J=X.name.toLowerCase(),Le=J.substring(J.lastIndexOf(".")+1);return L.allowedFileTypes.includes(Le)?{valid:!0}:{valid:!1,reason:`File type "${Le}" is not allowed. Allowed types: ${L.allowedFileTypes.join(", ")}`}},Xe=X=>{if(!X.target.files||X.target.files.length===0)return;const we=Array.from(X.target.files),J=[],Le=[];we.forEach(Fe=>{const Ve=Te(Fe);Ve.valid?Le.push(Fe):J.push({fileName:Fe.name,reason:Ve.reason||"Unknown validation error"})}),J.length>0&&ye({open:!0,errors:J}),Le.length>0&&(A(Fe=>[...Fe,...Le]),Le.length<we.length?K.warning(`${Le.length} of ${we.length} file(s) were added. ${J.length} file(s) were rejected.`):K.success(`${Le.length} file(s) added successfully`)),X.target&&(X.target.value="")},pe=X=>{A(we=>we.filter((J,Le)=>Le!==X)),G.current&&(G.current.value="")},_e=X=>{b(we=>we+X),w(!1)},rt=()=>{var X;(X=G.current)==null||X.click()},ut=async X=>{var we,J;try{await zx(u,X);const Le=await vs(u),Fe=Array.isArray(Le==null?void 0:Le.participants)?Le.participants:[];if(Fe.length){const Ve=Fe.map(Me=>{const Ze=Me.participantType||Me.participant_type||"participant",Be=Me.userId||Me.user_id||"",qe=Me.userName||Me.user_name||Me.userEmail||Me.user_email||"User",fs=Me.userEmail||Me.user_email||"",Ht=qe.split(" ").map(at=>at[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:qe,avatar:Ht,role:Ue(Ze),status:"offline",email:fs,lastSeen:void 0,permissions:["read"],userId:Be}});Q(Ve),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:u})}$(!1),M({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),U(!0)}catch(Le){throw console.error("Failed to add spectator:",Le),M({success:!1,title:"Failed to Add Spectator",message:((J=(we=Le==null?void 0:Le.response)==null?void 0:we.data)==null?void 0:J.error)||"Failed to add spectator. Please try again."}),U(!0),Le}},nt=async(X,we,J)=>{var Le,Fe;if(d)await d(X,we,J),T(!1);else try{await Vx(u,X,we,J);const Ve=await vs(u),Me=Array.isArray(Ve==null?void 0:Ve.participants)?Ve.participants:[];if(Me.length){const Ze=Me.map(Be=>{const qe=Be.participantType||Be.participant_type||"participant",fs=Be.userId||Be.user_id||"",Ht=Be.userName||Be.user_name||Be.userEmail||Be.user_email||"User",at=Be.userEmail||Be.user_email||"",et=Ht.split(" ").map(yt=>yt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Ht,avatar:et,role:Ue(qe),status:"offline",email:at,lastSeen:void 0,permissions:["read"],userId:fs}});Q(Ze),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:u})}T(!1),M({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${J} with ${we}h TAT`}),U(!0)}catch(Ve){throw console.error("Failed to add approver:",Ve),M({success:!1,title:"Failed to Add Approver",message:((Fe=(Le=Ve==null?void 0:Ve.response)==null?void 0:Le.data)==null?void 0:Fe.error)||"Failed to add approver. Please try again."}),U(!0),Ve}},Ps=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","","","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],Xs=X=>{const we=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,J=[];let Le;for(;(Le=we.exec(X))!==null;)if(Le[1]){const Fe=Le.index+Le[0].length,Ve=X.slice(Fe),Me=X[Fe];(Ve.startsWith("@")||!Me||/\s|[.,!?;:]|@/.test(Me))&&J.push(Le[1].trim())}return J},Na=X=>{X.key==="Enter"&&!X.shiftKey&&(X.preventDefault(),Z())},Xa=(X,we)=>{k(J=>J.map(Le=>{if(Le.id===X){const Fe=Le.reactions||[],Ve=Fe.find(Me=>Me.emoji===we);if(Ve)if(Ve.users.includes("You")){if(Ve.users=Ve.users.filter(Me=>Me!=="You"),Ve.users.length===0)return{...Le,reactions:Fe.filter(Me=>Me.emoji!==we)}}else Ve.users.push("You");else Fe.push({emoji:we,users:["You"]});return{...Le,reactions:Fe}}return Le}))};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(As,{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:ae.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:[oe.slice(0,3).map((X,we)=>e.jsx(Zt,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:"bg-blue-500 text-white text-xs font-semibold",children:X.avatar})},we)),oe.length>3&&e.jsxs("div",{className:"h-8 w-8 rounded-full bg-gray-100 ring-2 ring-white flex items-center justify-center text-xs font-medium text-gray-600",children:["+",oe.length-3]})]})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>_(!S),className:"lg:hidden",children:e.jsx(cs,{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(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search messages...",value:f,onChange:X=>y(X.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:[Ce.map(X=>{const we=X.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${X.isSystem?"justify-center":we?"justify-end":""}`,children:[!X.isSystem&&!we&&e.jsx(Zt,{className:"h-8 w-8 sm:h-10 sm:w-10 lg:h-12 lg:w-12 flex-shrink-0 ring-1 sm:ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:`text-white font-semibold text-xs sm:text-sm ${X.user.role==="Initiator"?"bg-green-600":X.user.role==="Current User"?"bg-blue-500":X.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:X.user.avatar})}),e.jsx("div",{className:`${we?"max-w-[70%]":"flex-1"} min-w-0 ${X.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:X.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(kt,{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:X.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:Qt(X.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:[X.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:X.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(st,{className:"w-3 h-3"}),Qt(X.timestamp)]}),X.isHighPriority&&e.jsxs(ne,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(o0,{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:ZS(X.content)}}),X.attachments&&X.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:X.attachments.map((J,Le)=>{const Fe=J.fileSize||J.file_size,Ve=J.fileName||J.file_name||J.name,Me=J.fileType||J.file_type||J.type||"",Ze=J.attachmentId||J.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(wu,{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:Ve}),Fe&&e.jsx("p",{className:"text-xs text-gray-500",children:JS(Fe)})]}),Ze&&(()=>{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(E,{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 qe=eN(Ze);O({fileName:Ve,fileType:Me,fileUrl:qe,fileSize:Fe,attachmentId:Ze})},title:"Preview file",children:e.jsx(ht,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(E,{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(),!Ze){K.error("Cannot download: Attachment ID missing");return}try{await Jd(Ze)}catch{K.error("Failed to download file")}},title:"Download file",children:e.jsx(Ct,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Le)})})}),X.reactions&&X.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:[X.reactions.map((J,Le)=>e.jsxs("button",{onClick:()=>Xa(X.id,J.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${J.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:J.emoji}),e.jsx("span",{className:"text-xs font-medium",children:J.users.length})]},Le)),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>w(!v),children:e.jsx(gs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!X.isSystem&&we&&e.jsx(Zt,{className:"h-8 w-8 sm:h-10 sm:w-10 lg:h-12 lg:w-12 flex-shrink-0 ring-1 sm:ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:X.user.avatar})})]},X.id)}),e.jsx("div",{ref:W})]})}),e.jsx("div",{className:"bg-white border-t border-gray-200 p-2 sm:p-3 lg:p-6 flex-shrink-0",children:e.jsxs("div",{className:"max-w-full",children:[e.jsx("input",{type:"file",ref:G,onChange:Xe,className:"hidden",multiple:!0,accept:L.allowedFileTypes.map(X=>`.${X}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((X,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(wu,{type:X.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:X.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(X.size/1024).toFixed(1)," KB"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>pe(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 X=g.lastIndexOf("@"),we=X>=0;if(!we)return null;const J=g.slice(X+1),Le=J.trim(),Fe=J.endsWith(" "),Ve=Le.length>0,Me=Le.includes(" ")&&!Fe,Ze=Fe&&Ve;if(!(we&&J.length<=20&&!Me&&!Ze))return null;const qe=Le.toLowerCase(),fs=me.filter(Ht=>Ht.userId===N?!1:qe?Ht.name.toLowerCase().includes(qe):!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:fs.length>0?fs.map((Ht,at)=>e.jsxs("button",{type:"button",onClick:et=>{et.preventDefault(),et.stopPropagation();const yt=g.lastIndexOf("@"),rs=g.slice(0,yt);b(rs+"@"+Ht.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(Zt,{className:"h-10 w-10",children:e.jsx(Jt,{className:`text-white text-sm font-semibold ${Ht.role==="Initiator"?"bg-green-600":Ht.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:Ht.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:Ht.name}),e.jsx("p",{className:"text-xs text-gray-600",children:Ht.role})]})]},at)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:qe?`No participants found matching "${qe}"`:"No other participants available"})})]})})(),e.jsx(Ds,{placeholder:"Type your message... Use @username to mention someone",value:g,onChange:X=>b(X.target.value),onKeyPress:Na,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(E,{variant:"ghost",size:"sm",onClick:()=>w(!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:Ps.map((X,we)=>e.jsx("button",{onClick:()=>_e(X),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:X,children:X},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(E,{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:rt,title:"Attach file",children:e.jsx(vi,{className:"h-4 w-4"})}),e.jsx(E,{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:()=>w(!v),title:"Add emoji",children:e.jsx(c0,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>b(X=>X+"@"),title:"Mention someone",children:e.jsx(Ci,{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(E,{onClick:Z,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(ax,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),S&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>_(!1)}),e.jsxs("div",{className:`
w-72 sm:w-80 bg-white border-l border-gray-200 flex flex-col
lg:relative lg:translate-x-0 lg:shadow-none
${S?"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(E,{variant:"ghost",size:"sm",onClick:()=>_(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(ft,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:me.map((X,we)=>{const J=X.userId===N;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(Jt,{className:`text-white font-semibold text-sm ${X.role==="Initiator"?"bg-green-600":J?"bg-blue-500":"bg-slate-600"}`,children:X.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${KS(X.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:[X.name," ",J&&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:X.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:XS(X.status)})]}),X.lastSeen&&X.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:X.lastSeen})]})]},we)})})]}),!Ee&&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(E,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>T(!0),children:[e.jsx(wi,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>$(!0),children:[e.jsx(ht,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),R&&e.jsx(jr,{fileName:R.fileName,fileType:R.fileType,fileUrl:R.fileUrl,fileSize:R.fileSize,attachmentId:R.attachmentId,onDownload:Jd,open:!!R,onClose:()=>O(null)}),!Ee&&e.jsx(Mp,{open:F,onClose:()=>$(!1),onConfirm:ut,requestIdDisplay:u,requestTitle:ae.title,existingParticipants:q}),!Ee&&l&&e.jsx($p,{open:V,onClose:()=>T(!1),onConfirm:nt,requestIdDisplay:u,requestTitle:ae.title,existingParticipants:q,currentLevels:c,maxApprovalLevels:m,onPolicyViolation:h}),e.jsx(pt,{open:H.open,onOpenChange:X=>ye(we=>({...we,open:X})),children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:H.errors.map((X,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:X.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:X.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: ",L.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",L.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:()=>ye({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Lp,{open:j,onClose:()=>U(!1),success:I.success,title:I.title,message:I.message})]})}function QS({requestId:t,requestTitle:s,mergedMessages:a,setWorkNoteAttachments:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d}){return e.jsx("div",{className:"h-[calc(100vh-300px)] min-h-[600px]",children:e.jsx(Op,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d})})}function qS({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const c=o.toLowerCase();return c==="approved"?e.jsx(De,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(wt,{className:"h-4 w-4 text-red-600"}):c==="pending"||c==="in progress"?e.jsx(st,{className:"h-4 w-4 text-orange-600"}):e.jsx(Re,{className:"h-4 w-4 text-gray-600"})},i=o=>{const c=o.toLowerCase();return c==="approved"?"bg-green-100 text-green-700 border-green-300":c==="rejected"?"bg-red-100 text-red-700 border-red-300":c==="pending"||c==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},l=(o,c)=>o&&o.trim()&&o.trim().toUpperCase()!=="N/A"?o:c&&c.trim()&&c.trim().toUpperCase()!=="N/A"?c:"N/A";return s?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(lt,{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(E,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(wn,{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(sa,{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:He(new Date(t.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),t.approvers&&t.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),t.approvers.map((o,c)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsx("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:o.levelName||`Approver ${o.levelNumber}`}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l(o.designation,o.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[n(o.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o.status})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:He(new Date(o.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:o.remarks||"—"})]})]},c))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),t.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(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(sa,{content:t.closingRemarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]})]})]})}):e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Re,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-bold text-gray-900 mb-2",children:"Summary Not Available"}),e.jsx("p",{className:"text-gray-600",children:"Summary has not been generated for this request yet."})]})})}function eA({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(pn,{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(wt,{className:"h-4 w-4 text-red-600"}):e.jsx(st,{className:"h-4 w-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-medium text-gray-700",children:s==="closed"?"Request Closed":s==="approved"?"Request Approved":s==="rejected"?"Request Rejected":"SLA Not Available"})]});const i=t.percentageUsed!==void 0?t.percentageUsed:0,l=t.status||"on_track",c=a?{badge:"bg-gray-500 text-white",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-500"}:i>=100?{badge:"bg-red-600 text-white animate-pulse",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:i>=75?{badge:"bg-orange-500 text-white",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:i>=50?{badge:"bg-amber-500 text-white",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{badge:"bg-green-600 text-white",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"},d=l==="on_track"||l==="normal"?"normal":l;return e.jsxs("div",{"data-testid":r,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[a?e.jsx(pn,{className:`h-4 w-4 ${c.icon}`}):e.jsx(st,{className:`h-4 w-4 ${c.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(ne,{className:`text-xs ${c.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(na,{value:i,className:"h-3 mb-2",indicatorClassName:c.progress,"data-testid":`${r}-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("span",{className:"text-gray-600","data-testid":`${r}-elapsed`,children:[Ft(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${d==="breached"||d==="critical"?c.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[Ft(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",xa(t.deadline,!0)," • ",i,"% elapsed"]}),d==="critical"&&e.jsxs("p",{className:"text-xs text-orange-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-critical`,children:[e.jsx(as,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),d==="breached"&&e.jsxs("p",{className:"text-xs text-red-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-breached`,children:[e.jsx(ni,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function tA({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var m;const c=HS((t==null?void 0:t.priority)||"standard"),d=WS((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(E,{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(Ns,{className:"h-4 w-4 sm:h-5 sm:h-5"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 min-w-0 flex-1",children:[e.jsx("h1",{className:"text-sm sm:text-base md:text-lg font-bold text-gray-900 truncate","data-testid":"request-id",children:t.id||"N/A"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2",children:[e.jsx(ne,{className:`${c.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:c.label}),e.jsx(ne,{className:`${d.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:d.label}),(()=>{const h=(t==null?void 0:t.workflowType)||(t==null?void 0:t.workflow_type),x=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",u=(x==null?void 0:x.toUpperCase())||"",g=h==="CLAIM_MANAGEMENT"||h==="DEALER_CLAIM"||x==="claim-management"||u==="DEALER CLAIM"||u==="DEALER_CLAIM";let b="Non-Templatized",f="bg-purple-100 !text-purple-600 border-purple-200";return g?(b="Dealer Claim",f="bg-blue-100 !text-blue-700 border-blue-200"):u==="TEMPLATE"&&(b="Template"),e.jsx(ne,{className:`${f} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:b})})()]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&i&&((m=t==null?void 0:t.status)==null?void 0:m.toLowerCase())==="closed"&&e.jsxs(E,{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(wn,{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(E,{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($t,{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(eA,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function pc(t){return(await je.get(`/summaries/${t}`)).data.data}async function sA(t,s){return(await je.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function aA(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await je.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 Up(t){await je.patch(`/summaries/shared/${t}/view`)}async function Bp(t){var s;try{return(await je.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 rA(t){return(await je.get(`/summaries/${t}/recipients`)).data.data||[]}function nA({activityInfo:t,className:s,createdAt:a,updatedAt:r}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(ee,{className:s,children:e.jsx(se,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Activity information not available"})})});const n=l=>{const o=typeof l=="string"?parseFloat(l):l;return isNaN(o)?"N/A":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`},i=l=>{if(!l)return"N/A";try{return He(new Date(l),"MMM d, yyyy")}catch{return l}};return e.jsxs(ee,{className:s,children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(ot,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.activityName})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Type"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.activityType})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Location"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(po,{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(Da,{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(Gt,{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.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-xs sm:text-sm",children:[e.jsx("thead",{className:"bg-blue-100/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left font-semibold text-blue-900",children:"Description"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-24",children:"Base"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-24",children:"GST"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-28",children:"Total"})]})}),e.jsxs("tbody",{className:"divide-y divide-blue-200/50",children:[t.closedExpensesBreakdown.map((l,o)=>e.jsxs("tr",{className:"hover:bg-blue-100/30",children:[e.jsxs("td",{className:"px-3 py-2 text-gray-700",children:[l.description,l.gstRate?e.jsxs("span",{className:"text-[10px] text-gray-400 block",children:[l.gstRate,"% GST"]}):null]}),e.jsx("td",{className:"px-3 py-2 text-right text-gray-900",children:n(l.amount)}),e.jsx("td",{className:"px-3 py-2 text-right text-gray-900",children:n(l.gstAmt||0)}),e.jsx("td",{className:"px-3 py-2 text-right font-medium text-gray-900",children:n(l.totalAmt||l.amount+(l.gstAmt||0))})]},o)),e.jsxs("tr",{className:"bg-blue-100/50 font-bold",children:[e.jsx("td",{colSpan:3,className:"px-3 py-2 text-blue-900",children:"Final Claim Amount"}),e.jsx("td",{className:"px-3 py-2 text-right text-blue-700",children:n(t.closedExpensesBreakdown.reduce((l,o)=>l+(o.totalAmt||o.amount+(o.gstAmt||0)),0))})]})]})]})})]}),t.description&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Description"}),e.jsx("div",{className:"mt-2 bg-gray-50 p-3 rounded-lg border border-gray-200",children:e.jsx(sa,{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:Qt(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:Qt(r)})]})]})]})]})}function iA({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(ee,{className:s,children:e.jsx(se,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(ee,{className:s,children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(Si,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Code"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.dealerCode})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.dealerName})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Contact Information"}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx(Ra,{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(ji,{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(po,{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(ee,{className:s,children:e.jsx(se,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function lA({ioDetails:t,dmsDetails:s,claimAmount:a,estimatedBudgetBreakdown:r,closedExpensesBreakdown:n,visibility:i,onEditClaimAmount:l,className:o}){const c=x=>x==null||Number.isNaN(x)?"₹0.00":`₹${x.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,d=x=>{if(!x)return"";try{return He(new Date(x),"MMM d, yyyy, h:mm a")}catch{return x||""}},m=x=>!x||x.length===0?0:x.reduce((u,g)=>u+(g.totalAmt??g.amount+(g.gstAmt??0)),0);return i.showIODetails&&t||i.showDMSDetails&&s||i.showClaimAmount&&a&&a.amount!==void 0&&a.amount!==null||r&&r.length>0||n&&n.length>0?e.jsxs(ee,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${o}`,children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx($e,{children:"Workflow reference numbers"})]}),e.jsxs(se,{className:"space-y-3",children:[i.showIODetails&&t&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Gt,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{className:"text-xs font-semibold text-blue-900 uppercase tracking-wide",children:"IO Number"})]}),e.jsx("p",{className:"font-bold text-gray-900 mb-2",children:t.ioNumber}),t.remarks&&e.jsxs("div",{className:"pt-2 border-t border-blue-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Remark:"}),e.jsx("p",{className:"text-xs text-gray-900",children:t.remarks})]}),(t.availableBalance!==void 0||t.blockedAmount!==void 0)&&e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2 space-y-1",children:[t.availableBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Available Balance:"}),e.jsx("span",{className:"font-medium text-gray-900",children:c(t.availableBalance)})]}),t.blockedAmount!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Blocked Amount:"}),e.jsx("span",{className:"font-medium text-blue-700",children:c(t.blockedAmount)})]}),t.remainingBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Remaining Balance:"}),e.jsx("span",{className:"font-medium text-green-700",children:c(t.remainingBalance)})]})]}),e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["By ",t.blockedByName]}),e.jsx("p",{className:"text-xs text-gray-500",children:d(t.blockedAt)})]})]}),i.showDMSDetails&&s&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(kt,{className:"w-4 h-4 text-purple-600"}),e.jsx(re,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice Details"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-2",children:s.ackNo&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Ack No"}),e.jsx("p",{className:"font-bold text-sm text-purple-700",children:s.ackNo})]})}),s.irn&&e.jsxs("div",{className:"mb-2 p-2 bg-purple-50 rounded border border-purple-100",children:[e.jsx("p",{className:"text-[10px] text-purple-600 uppercase font-semibold",children:"IRN"}),e.jsx("p",{className:"text-[10px] font-mono break-all text-gray-700 leading-tight",children:s.irn})]}),s.signedInvoiceUrl&&e.jsxs(E,{variant:"outline",size:"sm",className:"w-full h-8 text-xs gap-2 mb-2 border-purple-200 text-purple-700 hover:bg-purple-50",onClick:()=>window.open(s.signedInvoiceUrl,"_blank"),children:[e.jsx(Gt,{className:"w-3.5 h-3.5"}),"View E-Invoice"]}),s.remarks&&e.jsxs("div",{className:"pt-2 border-t border-purple-100",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase mb-1",children:"Remarks"}),e.jsx("p",{className:"text-xs text-gray-900",children:s.remarks})]}),e.jsxs("div",{className:"pt-2 border-t border-purple-100 mt-2",children:[e.jsxs("p",{className:"text-[10px] text-gray-500",children:["By ",s.createdByName]}),e.jsx("p",{className:"text-[10px] text-gray-500",children:d(s.createdAt)})]})]}),i.showClaimAmount&&a&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"w-4 h-4 text-green-600"}),e.jsx(re,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),i.canEditClaimAmount&&l&&e.jsxs(E,{variant:"outline",size:"sm",onClick:l,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(ii,{className:"w-3 h-3 mr-1 text-green-700"}),"Edit"]})]}),e.jsx("p",{className:"text-2xl font-bold text-green-700",children:c(a.amount)}),a.lastUpdatedBy&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-green-100",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["Last updated by ",a.lastUpdatedBy]}),a.lastUpdatedAt&&e.jsx("p",{className:"text-xs text-gray-500",children:d(a.lastUpdatedAt)})]})]}),r&&r.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-amber-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Gt,{className:"w-4 h-4 text-amber-600"}),e.jsx(re,{className:"text-xs font-semibold text-amber-900 uppercase tracking-wide",children:"Estimated Budget Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[r.map((x,u)=>e.jsxs("div",{className:"flex justify-between items-center text-[10px] sm:text-xs",children:[e.jsx("div",{className:"text-gray-700 truncate mr-2",title:x.description,children:x.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:c(x.totalAmt??x.amount+(x.gstAmt??0))})]},u)),e.jsxs("div",{className:"pt-2 border-t border-amber-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-amber-700",children:c(m(r))})]})]})]}),n&&n.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-indigo-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Gt,{className:"w-4 h-4 text-indigo-600"}),e.jsx(re,{className:"text-xs font-semibold text-indigo-900 uppercase tracking-wide",children:"Closed Expenses Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[n.map((x,u)=>e.jsxs("div",{className:"flex justify-between items-center text-[10px] sm:text-xs",children:[e.jsx("div",{className:"text-gray-700 truncate mr-2",title:x.description,children:x.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:c(x.totalAmt??x.amount+(x.gstAmt??0))})]},u)),e.jsxs("div",{className:"pt-2 border-t border-indigo-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-indigo-700",children:c(m(n))})]})]})]})]})]}):null}function oA({proposalDetails:t,className:s}){const r=(()=>{const o=t.totalEstimatedBudget??t.estimatedBudgetTotal;return o??(t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((d,m)=>{const h=m.amount||0;return d+(Number.isNaN(h)?0:h)},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 He(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return He(new Date(o),"MMM d, yyyy")}catch{return o||"-"}};return e.jsxs(ee,{className:s,children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(Gt,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs($e,{children:["Submitted on ",i(t.submittedOn)]})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Cost Breakup"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Item Description"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Base Amount"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"GST"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Total"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-200",children:[(t.costBreakup||[]).map((o,c)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsxs("td",{className:"px-4 py-3 text-sm text-gray-900",children:[e.jsx("div",{children:o.description}),o.gstRate?e.jsx("div",{className:"text-[10px] text-gray-400",children:o.cgstAmt?`CGST: ${o.gstRate/2}%, SGST: ${o.gstRate/2}%`:`IGST: ${o.gstRate}%`}):null]}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.amount)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.gstAmt)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right font-medium",children:n(o.totalAmt||(o.amount||0)+(o.gstAmt||0))})]},c)),e.jsxs("tr",{className:"bg-green-50 font-semibold",children:[e.jsx("td",{colSpan:3,className:"px-4 py-3 text-sm text-gray-900",children:"Estimated Budget (Total Inclusive of GST)"}),e.jsx("td",{className:"px-4 py-3 text-sm text-green-700 text-right",children:n(r)})]})]})]})})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Timeline for Closure"}),e.jsx("div",{className:"mt-2 bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{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 cA({initiatorInfo:t,className:s}){const a=r=>r.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2);return e.jsxs(ee,{className:s,children:[e.jsx(ge,{children:e.jsx(fe,{className:"text-base",children:"Request Initiator"})}),e.jsx(se,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Zt,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(Jt,{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(Ra,{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(ji,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function gc(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 Vp(t,s){var a,r;try{if(!gc(t))return null;const n=t.claimDetails||{},i=t.proposalDetails||{},l=t.completionDetails||{},o=t.internalOrder||t.internal_order||{},c=t.budgetTracking||t.budget_tracking||{},d=t.invoice||{},m=t.creditNote||t.credit_note||{},h=t.completionExpenses||t.completion_expenses||[],x=n.periodStartDate||n.period_start_date,u=n.periodEndDate||n.period_end_date,g=n.activityName||n.activity_name||"",b=n.activityType||n.activity_type||"",f=n.location||"",y=c.proposalEstimatedBudget||c.proposal_estimated_budget||c.initialEstimatedBudget||c.initial_estimated_budget||n.estimatedBudget||n.estimated_budget,v=(c==null?void 0:c.closedExpenses)||(c==null?void 0:c.closed_expenses)||(l==null?void 0:l.totalClosedExpenses)||(l==null?void 0:l.total_closed_expenses)||(n==null?void 0:n.closedExpenses)||(n==null?void 0:n.closed_expenses),w=v!=null?Number(v):void 0,C=Array.isArray(h)&&h.length>0?h.map(R=>({description:R.description||R.itemDescription||R.item_description||"",amount:Number(R.amount)||0,gstRate:R.gstRate??R.gst_rate,gstAmt:R.gstAmt??R.gst_amt,cgstAmt:R.cgstAmt??R.cgst_amt,sgstAmt:R.sgstAmt??R.sgst_amt,igstAmt:R.igstAmt??R.igst_amt,totalAmt:R.totalAmt??R.total_amt})):(l==null?void 0:l.closedExpenses)||(l==null?void 0:l.closed_expenses)||(l==null?void 0:l.closedExpensesBreakdown)||[],k={activityName:g,activityType:b,requestedDate:n.activityDate||n.activity_date||t.createdAt,location:f,period:x&&u?{startDate:x,endDate:u}:void 0,estimatedBudget:y,closedExpenses:w,closedExpensesBreakdown:C,description:t.description||""},S={dealerCode:(n==null?void 0:n.dealerCode)||(n==null?void 0:n.dealer_code)||(n==null?void 0:n.DealerCode)||"",dealerName:(n==null?void 0:n.dealerName)||(n==null?void 0:n.dealer_name)||(n==null?void 0:n.DealerName)||"",email:(n==null?void 0:n.dealerEmail)||(n==null?void 0:n.dealer_email)||(n==null?void 0:n.DealerEmail)||"",phone:(n==null?void 0:n.dealerPhone)||(n==null?void 0:n.dealer_phone)||(n==null?void 0:n.DealerPhone)||"",address:(n==null?void 0:n.dealerAddress)||(n==null?void 0:n.dealer_address)||(n==null?void 0:n.DealerAddress)||""};(!S.dealerCode||!S.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!n,dealerCode:S.dealerCode,dealerName:S.dealerName,rawClaimDetails:n,availableKeys:n?Object.keys(n):[]});const _=(i==null?void 0:i.expectedCompletionDate)||(i==null?void 0:i.expected_completion_date),D=i?{proposalDocumentUrl:i.proposalDocumentUrl||i.proposal_document_url,costBreakup:Array.isArray(i.costBreakup||i.cost_breakup)?(i.costBreakup||i.cost_breakup).map(R=>({description:R.description||R.itemDescription||R.item_description||"",amount:Number(R.amount)||0,gstRate:R.gstRate??R.gst_rate,gstAmt:R.gstAmt??R.gst_amt,cgstAmt:R.cgstAmt??R.cgst_amt,sgstAmt:R.sgstAmt??R.sgst_amt,igstAmt:R.igstAmt??R.igst_amt,totalAmt:R.totalAmt??R.total_amt})):[],totalEstimatedBudget:i.totalEstimatedBudget||i.total_estimated_budget||0,timelineMode:i.timelineMode||i.timeline_mode,expectedCompletionDate:_,expectedCompletionDays:i.expectedCompletionDays||i.expected_completion_days,timelineForClosure:_,dealerComments:i.dealerComments||i.dealer_comments,submittedOn:i.submittedAt||i.submitted_at||i.submittedOn}:void 0,A={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:d.invoiceNumber||d.invoice_number||n.eInvoiceNumber||n.e_invoice_number,eInvoiceDate:d.invoiceDate||d.invoice_date||n.eInvoiceDate||n.e_invoice_date,dmsNumber:d.dmsNumber||d.dms_number||n.dmsNumber||n.dms_number,creditNoteNumber:m.creditNoteNumber||m.credit_note_number||n.creditNoteNumber||n.credit_note_number,creditNoteDate:m.creditNoteDate||m.credit_note_date||n.creditNoteDate||n.credit_note_date,creditNoteAmount:m.creditNoteAmount?Number(m.creditNoteAmount):m.credit_note_amount?Number(m.credit_note_amount):m.creditNoteAmount?Number(m.creditNoteAmount):n.creditNoteAmount?Number(n.creditNoteAmount):n.credit_note_amount?Number(n.credit_note_amount):void 0,irn:d.irn||n.irn,ackNo:d.ackNo||n.ackNo,ackDate:d.ackDate||n.ackDate,signedInvoiceUrl:d.signedInvoiceUrl||n.signedInvoiceUrl,taxBreakdown:d.taxBreakdown||n.taxBreakdown},P={estimated:k.estimatedBudget||0,closed:k.closedExpenses||0};return{activityInfo:k,dealerInfo:S,proposalDetails:D,ioDetails:Object.keys(A).some(R=>A[R])?A: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 zp(t,s){var a,r;try{if(t.initiatorId===s||((a=t.initiator)==null?void 0:a.userId)===s||((r=t.requestedBy)==null?void 0:r.userId)===s)return"INITIATOR";if((t.participants||[]).find(d=>{var m;return(d.userId===s||((m=d.user)==null?void 0:m.userId)===s)&&(d.participantType==="DEALER"||d.type==="DEALER")}))return"DEALER";const l=t.approvalLevels||[];return l.find(d=>{var m;return d.levelNumber===3&&(d.approverId===s||((m=d.approver)==null?void 0:m.userId)===s)})?"DEPARTMENT_LEAD":l.find(d=>{var m;return(d.approverId===s||((m=d.approver)==null?void 0:m.userId)===s)&&d.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(n){return console.error("[claimDataMapper] Error determining user role:",n),"SPECTATOR"}}function Hp(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 dA({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:l,onReject:o,onPause:c,onResume:d,onRetrigger:m,summaryId:h,refreshTrigger:x,pausedByUserId:u,currentUserId:g,apiRequest:b,onEditClaimAmount:f}){var V,T,j,U,I;const{user:y}=Kt(),[v,w]=p.useState([]),[C,k]=p.useState(!1),[S,_]=p.useState(!1),D=(t==null?void 0:t.status)==="closed",A=((V=t==null?void 0:t.pauseInfo)==null?void 0:V.isPaused)||!1,N=u||((j=(T=t==null?void 0:t.pauseInfo)==null?void 0:T.pausedBy)==null?void 0:j.userId),P=g||(y==null?void 0:y.userId)||"",R=!A&&!D&&(r||s),O=A&&d&&(r||s),F=A&&s&&N&&N!==P&&m;p.useEffect(()=>{if(!A||!r||!(t!=null&&t.requestId)){_(!1);return}(async()=>{var W;try{const te=(((W=(await Ba.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:W.notifications)||[]).some(L=>L.requestId===t.requestId&&L.notificationType==="pause_retrigger_request");_(te)}catch(G){console.error("Failed to check retrigger notifications:",G),_(!1)}})()},[A,r,t==null?void 0:t.requestId,x]),p.useEffect(()=>{(async()=>{if(!D||!h||!s){w([]);return}try{k(!0);const W=await rA(h);w(W)}catch(W){console.error("Failed to fetch shared recipients:",W),w([])}finally{k(!1)}})()},[D,h,s,x]);const $=p.useMemo(()=>{if(!b||!gc(b))return null;const M=Vp(b);if(!M)return null;const W=zp(b,P),G=Hp(W);return{claimRequest:M,visibility:G}},[b,P]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(ee,{"data-testid":"quick-actions-card",children:[e.jsx(ge,{className:"pb-2",children:e.jsx(fe,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(se,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(E,{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(wi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(E,{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&&c&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:c,"data-testid":"pause-workflow-button",children:[e.jsx(za,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),O&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-green-700 border-green-300 hover:bg-green-50 hover:text-green-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:d,"data-testid":"resume-workflow-button",children:[e.jsx(ri,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),F&&e.jsxs(E,{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(ze,{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&&!A&&e.jsxs(e.Fragment,{children:[e.jsxs(E,{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(E,{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(wt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),A&&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:[S&&e.jsx(ze,{className:"w-3.5 h-3.5"}),S?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:S?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&N!==P&&S?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[e.jsx(ze,{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:F?'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(ee,{"data-testid":"spectators-card",children:[e.jsx(ge,{className:"pb-2",children:e.jsx(fe,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(se,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((M,W)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${W}`,children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:M.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:M.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:M.role})]})]},W)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),D&&s&&e.jsxs(ee,{"data-testid":"shared-recipients-card",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs(fe,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(wn,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(se,{className:"space-y-3",children:C?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):v.length>0?v.map((M,W)=>{const G=(M.displayName||"NA").split(" ").map(ce=>ce[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${W}`,children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:G})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:M.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:M.email}),M.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},M.userId||W)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),$&&e.jsx(lA,{ioDetails:$.claimRequest.ioDetails,dmsDetails:$.claimRequest.dmsDetails,claimAmount:{amount:$.claimRequest.claimAmount.closed||$.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(U=$.claimRequest.proposalDetails)==null?void 0:U.costBreakup,closedExpensesBreakdown:(I=$.claimRequest.activityInfo)==null?void 0:I.closedExpensesBreakdown,visibility:$.visibility,onEditClaimAmount:f})]})}function mA({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=p.useState(r),[d,m]=p.useState(!1),h=(o==null?void 0:o.length)||0,x=p.useMemo(()=>o.slice(0,500),[o]),u=async()=>{try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(pt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(dt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(gt,{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(mt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide your approval comments and remarks"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:l||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(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(Ds,{value:x,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(h,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-green-50 border-green-200 text-green-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(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(E,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(E,{onClick:u,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function uA({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=p.useState(r),[d,m]=p.useState(!1),h=(o==null?void 0:o.length)||0,x=p.useMemo(()=>o.slice(0,500),[o]),u=async()=>{if(!x.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(pt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(dt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(gt,{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(wt,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(mt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide detailed reasons for rejection"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:l||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(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(Ds,{value:x,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(h,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-red-50 border-red-200 text-red-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(ze,{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(E,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(E,{variant:"destructive",onClick:u,disabled:d,children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function xA({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,c]=p.useState(""),[d,m]=p.useState(!1),h=async()=>{if(o.trim())try{m(!0),await a(o.trim()),c(""),s()}catch(u){console.error("Failed to skip approver:",u)}finally{m(!1)}},x=()=>{d||(c(""),s())};return e.jsx(pt,{open:t,onOpenChange:x,children:e.jsxs(dt,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:x,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:d,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{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(ze,{className:"w-5 h-5 text-orange-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Skip Approver"})]})}),e.jsxs("div",{className:"space-y-4 px-6 py-4 overflow-y-auto flex-1",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ze,{className:"w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-orange-900 mb-1",children:"Important Notice"}),e.jsx("p",{className:"text-sm text-orange-800",children:"You are about to skip the current approver. The request will be moved to the next approval level."})]})]})}),(i||l)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-semibold text-gray-700",children:"Request Details"}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3 space-y-1",children:[i&&e.jsxs("p",{className:"text-sm text-gray-900",children:[e.jsx("span",{className:"font-medium",children:"Request ID:"})," ",i]}),l&&e.jsxs("p",{className:"text-sm text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Title:"})," ",l]})]})]}),(r||n)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-semibold text-gray-700",children:"Approver Being Skipped"}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-1",children:[n&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Level:"})," ",n]}),r&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Approver:"})," ",r]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(Ds,{id:"skip-reason",placeholder:"Please provide a detailed reason for skipping this approver (e.g., 'Approver is on leave until [date]', 'Approver unavailable - escalating to next level')",value:o,onChange:u=>c(u.target.value),className:"min-h-[100px] border-2 border-gray-300 focus:border-orange-500",disabled:d,autoFocus:!0}),e.jsx("p",{className:"text-xs text-gray-500",children:"This reason will be recorded in the activity log and all participants will be notified."})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:x,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:h,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:d||!o.trim(),children:[e.jsx(ze,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function hA({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:l,documentError:o,request:c,skipApproverData:d,actionStatus:m,existingParticipants:h,currentLevels:x,maxApprovalLevels:u,onPolicyViolation:g,setShowApproveModal:b,setShowRejectModal:f,setShowAddApproverModal:y,setShowAddSpectatorModal:v,setShowSkipApproverModal:w,setShowActionStatusModal:C,setPreviewDocument:k,setDocumentError:S,setSkipApproverData:_,setActionStatus:D,handleApproveConfirm:A,handleRejectConfirm:N,handleAddApprover:P,handleAddSpectator:R,handleSkipApprover:O,downloadDocument:F,documentPolicy:$}){return e.jsxs(e.Fragment,{children:[e.jsx(mA,{open:t,onClose:()=>b(!1),onConfirm:A,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(uA,{open:s,onClose:()=>f(!1),onConfirm:N,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx($p,{open:a,onClose:()=>y(!1),onConfirm:P,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:h,currentLevels:x,maxApprovalLevels:u,onPolicyViolation:g}),e.jsx(Mp,{open:r,onClose:()=>v(!1),onConfirm:R,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:h}),e.jsx(xA,{open:n,onClose:()=>{w(!1),_(null)},onConfirm:O,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),l&&e.jsx(jr,{fileName:l.fileName,fileType:l.fileType,fileUrl:Hr(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:F,open:!!l,onClose:()=>k(null)}),m&&e.jsx(Lp,{open:i,onClose:()=>{C(!1),D(null)},success:m.success,title:m.title,message:m.message}),e.jsx(pt,{open:o.show,onOpenChange:V=>S(T=>({...T,show:V})),children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:o.errors.map((V,T)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:V.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:V.reason})]},T))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",$.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",$.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:()=>S({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Wp={DocumentsTab:zS,ActivityTab:YS,WorkNotesTab:QS,SummaryTab:qS,RequestDetailHeader:tA,QuickActionsSidebar:dA,RequestDetailModals:hA};function pA({className:t,...s}){return e.jsx(yf,{"data-slot":"checkbox",className:ke("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(yr,{className:"size-3.5"})})})}function Gp({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,l]=p.useState(""),[o,c]=p.useState([]),[d,m]=p.useState(new Set),[h,x]=p.useState(!1),[u,g]=p.useState(!1);p.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),x(!1);return}const v=setTimeout(async()=>{var w;try{x(!0);const C=i.slice(1),k=await ia(C,10),S=((w=k==null?void 0:k.data)==null?void 0:w.data)||(k==null?void 0:k.data)||[];c(Array.isArray(S)?S:[])}catch(C){console.error("Failed to search users:",C),K.error("Failed to search users")}finally{x(!1)}},300);return()=>clearTimeout(v)},[i,t]);const b=v=>{m(w=>{const C=new Set(w);return C.has(v)?C.delete(v):C.add(v),C})},f=async()=>{var v,w;if(d.size===0){K.error("Please select at least one user to share with");return}try{g(!0),await sA(a,Array.from(d)),K.success(`Summary shared with ${d.size} user(s)`),m(new Set),l(""),c([]),n==null||n(),s()}catch(C){console.error("Failed to share summary:",C),K.error(((w=(v=C==null?void 0:C.response)==null?void 0:v.data)==null?void 0:w.message)||"Failed to share summary")}finally{g(!1)}},y=()=>{m(new Set),l(""),c([]),s()};return e.jsx(pt,{open:t,onOpenChange:y,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(gt,{children:e.jsx(mt,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Request"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:r})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Oe,{id:"user-search",placeholder:"Type @ to search users...",value:i,onChange:v=>l(v.target.value),className:"pl-10"})]}),i&&!i.startsWith("@")&&e.jsx("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:"Start with @ to search users (e.g., @john)"})]}),h&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(lt,{className:"h-5 w-5 animate-spin text-blue-600"})}),!h&&o.length>0&&e.jsx("div",{className:"border rounded-lg max-h-[300px] overflow-y-auto",children:o.map(v=>{const w=d.has(v.userId);return e.jsxs("div",{className:"flex items-center gap-3 p-3 hover:bg-gray-50 border-b last:border-b-0 cursor-pointer",onClick:()=>b(v.userId),children:[e.jsx("div",{onClick:C=>C.stopPropagation(),onMouseDown:C=>C.stopPropagation(),className:"flex items-center",children:e.jsx(pA,{checked:w,onCheckedChange:()=>b(v.userId)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:v.displayName||v.email})]}),(v.designation||v.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:v.designation||v.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:v.email})]})]},v.userId)})}),!h&&i&&i.startsWith("@")&&o.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),!h&&i&&!i.startsWith("@")&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"Start typing with @ to search users"}),d.size>0&&e.jsxs("div",{className:"border rounded-lg p-3 bg-blue-50",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-700 mb-2",children:["Selected (",d.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(d).map(v=>{const w=o.find(C=>C.userId===v);return e.jsxs("div",{className:"flex items-center gap-1 bg-white px-2 py-1 rounded-full text-xs",children:[e.jsx("span",{children:(w==null?void 0:w.displayName)||(w==null?void 0:w.email)||v}),e.jsx("button",{onClick:()=>b(v),className:"ml-1 hover:text-red-600",children:e.jsx(ft,{className:"h-3 w-3"})})]},v)})})]})]}),e.jsxs(Tt,{children:[e.jsx(E,{variant:"outline",onClick:y,disabled:u,children:"Cancel"}),e.jsx(E,{onClick:f,disabled:u||d.size===0,children:u?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function Yp({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=p.useState(""),[o,c]=p.useState(""),[d,m]=p.useState(!1),h=()=>Bt().add(1,"month").format("YYYY-MM-DD"),x=()=>Bt().add(1,"month").format("YYYY-MM-DD"),u=()=>Bt().add(1,"day").format("YYYY-MM-DD");p.useEffect(()=>{t&&!o&&c(h())},[t]);const g=async()=>{var w,C,k,S;if(!i.trim()){K.error("Please provide a reason for pausing");return}if(!o){K.error("Please select a resume date");return}const f=Bt(o),y=Bt().add(1,"month"),v=Bt().add(1,"day");if(f.isAfter(y)){K.error("Resume date cannot be more than 1 month from now");return}if(f.isBefore(v,"day")){K.error("Resume date must be at least 1 day from now");return}try{m(!0),await Jj(a,r,i.trim(),f.toDate()),K.success("Workflow paused successfully"),n&&await n(),l(""),c(h()),s()}catch(_){console.error("Failed to pause workflow:",_),K.error(((C=(w=_==null?void 0:_.response)==null?void 0:w.data)==null?void 0:C.error)||((S=(k=_==null?void 0:_.response)==null?void 0:k.data)==null?void 0:S.message)||"Failed to pause workflow")}finally{m(!1)}},b=()=>{d||(l(""),c(h()),s())};return e.jsx(pt,{open:t,onOpenChange:b,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(gt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(za,{className:"w-5 h-5 text-orange-600"}),"Pause Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-orange-800",children:[e.jsx("strong",{children:"Note:"})," Pausing will temporarily halt TAT calculations and notifications. The workflow will automatically resume on the selected date."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ds,{id:"pause-reason",value:i,onChange:f=>l(f.target.value),placeholder:"Enter the reason for pausing this workflow...",className:"min-h-[100px] text-sm",disabled:d}),e.jsxs("p",{className:"text-xs text-gray-500",children:[i.length," / 1000 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Oe,{id:"resume-date",type:"date",value:o,onChange:f=>c(f.target.value),min:u(),max:x(),className:"text-sm",disabled:d}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum 1 month from today. The workflow will automatically resume on this date."})]})]}),e.jsxs(Tt,{children:[e.jsx(E,{variant:"outline",onClick:b,disabled:d,children:"Cancel"}),e.jsx(E,{onClick:g,disabled:d||!i.trim()||!o,className:"bg-orange-600 hover:bg-orange-700 text-white",children:d?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(za,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function Kp({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=p.useState(""),[l,o]=p.useState(!1),c=async()=>{var m,h,x,u;try{o(!0),await Qj(a,n.trim()||void 0),K.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),K.error(((h=(m=g==null?void 0:g.response)==null?void 0:m.data)==null?void 0:h.error)||((u=(x=g==null?void 0:g.response)==null?void 0:x.data)==null?void 0:u.message)||"Failed to resume workflow")}finally{o(!1)}},d=()=>{l||(i(""),s())};return e.jsx(pt,{open:t,onOpenChange:d,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(gt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ri,{className:"w-5 h-5 text-green-600"}),"Resume Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-green-50 border border-green-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-green-800",children:[e.jsx("strong",{children:"Note:"})," Resuming will restart TAT calculations and notifications. The workflow will continue from where it was paused."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(Ds,{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(E,{variant:"outline",onClick:d,disabled:l,children:"Cancel"}),e.jsx(E,{onClick:c,disabled:l,className:"bg-green-600 hover:bg-green-700 text-white",children:l?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ri,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function Xp({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=p.useState(!1),o=async()=>{var c,d,m,h;try{l(!0),await qj(a),K.success("Retrigger request sent to approver"),n&&await n(),s()}catch(x){console.error("Failed to retrigger pause:",x),K.error(((d=(c=x==null?void 0:x.response)==null?void 0:c.data)==null?void 0:d.error)||((h=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:h.message)||"Failed to send retrigger request")}finally{l(!1)}};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[450px]",children:[e.jsx(gt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ze,{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(E,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(E,{onClick:o,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:gA,ActivityTab:fA,WorkNotesTab:bA,SummaryTab:yA,RequestDetailHeader:vA,QuickActionsSidebar:jA,RequestDetailModals:NA}=Wp;let wA=class extends p.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("Custom RequestDetail Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(as,{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(E,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(E,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function CA({requestId:t,onBack:s,dynamicRequests:a=[]}){var Ja,Qa,qa,er,tr,_a,ga,La;const n=Ea().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=p.useState(l),[d,m]=p.useState(!1),[h,x]=p.useState(null),[u,g]=p.useState(null),[b,f]=p.useState(!1),[y,v]=p.useState(0),[w,C]=p.useState(!1),[k,S]=p.useState(!1),[_,D]=p.useState(!1),[A,N]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[P,R]=p.useState({open:!1,violations:[]}),{user:O}=Kt(),{request:F,apiRequest:$,loading:V,refreshing:T,refreshDetails:j,currentApprovalLevel:U,isSpectator:I,isInitiator:M,existingParticipants:W,accessDenied:G}=hc(n,a,O),{mergedMessages:ce,unreadWorkNotes:te,workNoteAttachments:L,setWorkNoteAttachments:z}=Ip(n,$,o,O),{uploadingDocument:H,triggerFileInput:ye,previewDocument:ae,setPreviewDocument:me,documentPolicy:Q,documentError:oe,setDocumentError:Ce}=Ep($,j),{showApproveModal:Ee,setShowApproveModal:be,showRejectModal:q,setShowRejectModal:ue,showAddApproverModal:Ae,setShowAddApproverModal:Ue,showAddSpectatorModal:Z,setShowAddSpectatorModal:Te,showSkipApproverModal:Xe,setShowSkipApproverModal:pe,showActionStatusModal:_e,setShowActionStatusModal:rt,skipApproverData:ut,setSkipApproverData:nt,actionStatus:Ps,setActionStatus:Xs,handleApproveConfirm:Na,handleRejectConfirm:Xa,handleAddApprover:X,handleSkipApprover:we,handleAddSpectator:J}=_p(n,U,j),{conclusionRemark:Le,setConclusionRemark:Fe,conclusionLoading:Ve,conclusionSubmitting:Me,aiGenerated:Ze,handleGenerateConclusion:Be,handleFinalizeConclusion:qe,generationAttempts:fs,generationFailed:Ht,maxAttemptsReached:at}=Fp(F,n,M,j,s,Xs,rt);p.useEffect(()=>{(async()=>{var ns;try{const Os=await Ys("SYSTEM_SETTINGS"),sr=await Ys("WORKFLOW_SHARING"),ar=[...Os,...sr],oa={};ar.forEach(vt=>{oa[vt.configKey]=vt.configValue}),N({maxApprovalLevels:parseInt(oa.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(oa.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((ns=oa.ALLOW_ADD_SPECTATOR)==null?void 0:ns.toLowerCase())==="true",maxSpectators:parseInt(oa.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Os){console.error("Failed to load system policy:",Os)}})()},[]),p.useEffect(()=>{const ns=new URLSearchParams(window.location.search).get("tab");ns&&c(ns)},[n]);const et=()=>{j()},yt=()=>{C(!0)},rs=()=>{S(!0)},Pt=async()=>{await j()},la=()=>{D(!0)},pa=async()=>{await j()},Fa=async()=>{await j()},wa=async()=>{if(!($!=null&&$.requestId)){K.error("Request ID not found");return}if(!h){K.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},St=((F==null?void 0:F.status)==="approved"||(F==null?void 0:F.status)==="rejected")&&M,Ca=(F==null?void 0:F.status)==="closed";p.useEffect(()=>{(async()=>{if(!Ca||!($!=null&&$.requestId)){g(null),x(null);return}try{f(!0);const ns=await Bp($.requestId);if(ns!=null&&ns.summaryId){x(ns.summaryId);try{const Os=await pc(ns.summaryId);g(Os)}catch(Os){console.error("Failed to fetch summary details:",Os),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{f(!1)}})()},[Ca,$==null?void 0:$.requestId]);const Za=((F==null?void 0:F.approvalFlow)||[]).filter(It=>It&&typeof It.step=="number").map(It=>({levelNumber:It.step||0,approverName:It.approver||"Unknown",status:It.status||"pending",tatHours:It.tatHours||24}));return V&&!F&&!$?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($t,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading custom request details..."})]})}):G!=null&&G.denied?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"access-denied-state",children:e.jsxs("div",{className:"max-w-lg w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(rx,{className:"w-10 h-10 text-red-500"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Access Denied"}),e.jsx("p",{className:"text-gray-600 mb-6 leading-relaxed",children:G.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):F?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"custom-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(vA,{request:F,refreshing:T,onBack:s||(()=>window.history.back()),onRefresh:et,onShareSummary:wa,isInitiator:M,slaData:((Ja=F==null?void 0:F.summary)==null?void 0:Ja.sla)||(F==null?void 0:F.sla)||null,isPaused:((Qa=F==null?void 0:F.pauseInfo)==null?void 0:Qa.isPaused)||!1}),e.jsxs($i,{value:o,onValueChange:c,className:"w-full","data-testid":"custom-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(Oi,{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(qt,{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(nx,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Ca&&u&&e.jsxs(qt,{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(ix,{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(qt,{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(ta,{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(qt,{value:"documents",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-documents",children:[e.jsx(Re,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Docs"})]}),e.jsxs(qt,{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(kt,{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(qt,{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(As,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),te>0&&e.jsx(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:te>9?"9+":te})]})]})}),e.jsxs("div",{className:o==="worknotes"?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:o==="worknotes"?"":"lg:col-span-2",children:[e.jsx(es,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(cN,{request:F,isInitiator:M,needsClosure:St,conclusionRemark:Le,setConclusionRemark:Fe,conclusionLoading:Ve,conclusionSubmitting:Me,aiGenerated:Ze,handleGenerateConclusion:Be,handleFinalizeConclusion:qe,onPause:yt,onResume:rs,onRetrigger:la,currentUserIsApprover:!!U,pausedByUserId:(er=(qa=F==null?void 0:F.pauseInfo)==null?void 0:qa.pausedBy)==null?void 0:er.userId,currentUserId:O==null?void 0:O.userId,generationAttempts:fs,generationFailed:Ht,maxAttemptsReached:at})}),Ca&&e.jsx(es,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(yA,{summary:u,loading:b,onShare:wa,isInitiator:M})}),e.jsx(es,{value:"workflow",className:"mt-0",children:e.jsx(xN,{request:F,user:O,isInitiator:M,onSkipApprover:It=>{if(!It.levelId){alert("Level ID not available");return}nt(It),pe(!0)},onRefresh:j})}),e.jsx(es,{value:"documents",className:"mt-0",children:e.jsx(gA,{request:F,workNoteAttachments:L,uploadingDocument:H,documentPolicy:Q,triggerFileInput:ye,setPreviewDocument:me,downloadDocument:ps})}),e.jsx(es,{value:"activity",className:"mt-0",children:e.jsx(fA,{request:F})}),e.jsx(es,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(bA,{requestId:n,requestTitle:F.title,mergedMessages:ce,setWorkNoteAttachments:z,isInitiator:M,isSpectator:I,currentLevels:Za,onAddApprover:X,maxApprovalLevels:A.maxApprovalLevels,onPolicyViolation:It=>R({open:!0,violations:It})})})]}),o!=="worknotes"&&e.jsx(jA,{request:F,isInitiator:M,isSpectator:I,currentApprovalLevel:U,onAddApprover:()=>Ue(!0),onAddSpectator:()=>Te(!0),onApprove:()=>be(!0),onReject:()=>ue(!0),onPause:yt,onResume:rs,onRetrigger:la,summaryId:h,refreshTrigger:y,pausedByUserId:(_a=(tr=F==null?void 0:F.pauseInfo)==null?void 0:tr.pausedBy)==null?void 0:_a.userId,currentUserId:O==null?void 0:O.userId,apiRequest:$})]})]})]})}),d&&h&&e.jsx(Gp,{isOpen:d,onClose:()=>m(!1),summaryId:h,requestTitle:(F==null?void 0:F.title)||"N/A",onSuccess:()=>{j(),v(It=>It+1)}}),w&&($==null?void 0:$.requestId)&&e.jsx(Yp,{isOpen:w,onClose:()=>C(!1),requestId:$.requestId,levelId:(U==null?void 0:U.levelId)||null,onSuccess:pa}),k&&($==null?void 0:$.requestId)&&e.jsx(Kp,{isOpen:k,onClose:()=>S(!1),requestId:$.requestId,onSuccess:Pt}),_&&($==null?void 0:$.requestId)&&e.jsx(Xp,{isOpen:_,onClose:()=>D(!1),requestId:$.requestId,approverName:(La=(ga=F==null?void 0:F.pauseInfo)==null?void 0:ga.pausedBy)==null?void 0:La.name,onSuccess:Fa}),e.jsx(NA,{showApproveModal:Ee,showRejectModal:q,showAddApproverModal:Ae,showAddSpectatorModal:Z,showSkipApproverModal:Xe,showActionStatusModal:_e,previewDocument:ae,documentError:oe,request:F,skipApproverData:ut,actionStatus:Ps,existingParticipants:W,currentLevels:Za,maxApprovalLevels:A.maxApprovalLevels,onPolicyViolation:It=>R({open:!0,violations:It}),setShowApproveModal:be,setShowRejectModal:ue,setShowAddApproverModal:Ue,setShowAddSpectatorModal:Te,setShowSkipApproverModal:pe,setShowActionStatusModal:rt,setPreviewDocument:me,setDocumentError:Ce,setSkipApproverData:nt,setActionStatus:Xs,handleApproveConfirm:Na,handleRejectConfirm:Xa,handleAddApprover:X,handleAddSpectator:J,handleSkipApprover:we,downloadDocument:ps,documentPolicy:Q}),e.jsx(Fn,{open:P.open,onClose:()=>R({open:!1,violations:[]}),violations:P.violations,policyDetails:{maxApprovalLevels:A.maxApprovalLevels,maxParticipants:A.maxParticipants,allowSpectators:A.allowSpectators,maxSpectators:A.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(Re,{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(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function SA(t){return e.jsx(wA,{children:e.jsx(CA,{...t})})}function AA({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,sortBy:n,sortOrder:i,onSearchChange:l,onStatusFilterChange:o,onPriorityFilterChange:c,onTemplateTypeFilterChange:d,onSortByChange:m,onSortOrderChange:h,onClearFilters:x,activeFiltersCount:u}){return e.jsxs(ee,{className:"shadow-lg border-0",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Ya,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx($e,{className:"text-xs sm:text-sm",children:u>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[u," filter",u>1?"s":""," active"]})})]})]}),u>0&&e.jsxs(E,{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(se,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{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(Oe,{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(We,{value:a,onValueChange:c,children:[e.jsx(Ye,{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(Ge,{placeholder:"All Priorities"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Priorities"}),e.jsx(Y,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(Y,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ot,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(We,{value:s,onValueChange:o,children:[e.jsx(Ye,{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(Ge,{placeholder:"All Statuses"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Statuses"}),e.jsx(Y,{value:"pending",children:"Pending (In Approval)"}),e.jsx(Y,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs(We,{value:r,onValueChange:d,children:[e.jsx(Ye,{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(Ge,{placeholder:"All Templates"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(We,{value:n,onValueChange:g=>m(g),children:[e.jsx(Ye,{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(Ge,{placeholder:"Sort by"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"due",children:"Due Date"}),e.jsx(Y,{value:"created",children:"Date Created"}),e.jsx(Y,{value:"priority",children:"Priority"}),e.jsx(Y,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>h(i==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:i==="asc"?e.jsx(Ai,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Ti,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function TA({searchTerm:t,priorityFilter:s,statusFilter:a,templateTypeFilter:r,sortBy:n,sortOrder:i,activeFiltersCount:l,onSearchChange:o,onPriorityChange:c,onStatusChange:d,onTemplateTypeChange:m,onSortByChange:h,onSortOrderChange:x,onClearFilters:u}){return e.jsxs(ee,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Ya,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx($e,{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(E,{variant:"ghost",size:"sm",onClick:u,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3","data-testid":"closed-requests-clear-filters",children:[e.jsx(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(se,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{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(Oe,{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(We,{value:s,onValueChange:c,children:[e.jsx(Ye,{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(Ge,{placeholder:"All Priorities"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Priorities"}),e.jsx(Y,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(Y,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ot,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(We,{value:a,onValueChange:d,children:[e.jsx(Ye,{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(Ge,{placeholder:"Closure Type"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Closures"}),e.jsx(Y,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(Y,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wt,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs(We,{value:r,onValueChange:m,children:[e.jsx(Ye,{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(Ge,{placeholder:"All Templates"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(We,{value:n,onValueChange:g=>h(g),children:[e.jsx(Ye,{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(Ge,{placeholder:"Sort by"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"due",children:"Due Date"}),e.jsx(Y,{value:"created",children:"Date Created"}),e.jsx(Y,{value:"priority",children:"Priority"})]})]}),e.jsx(E,{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(Ai,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Ti,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function kA({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,departmentFilter:n,slaComplianceFilter:i,initiatorFilter:l,approverFilter:o,approverFilterType:c,dateRange:d,customStartDate:m,customEndDate:h,showCustomDatePicker:x,departments:u,loadingDepartments:g,initiatorSearch:b,approverSearch:f,onSearchChange:y,onStatusChange:v,onPriorityChange:w,onTemplateTypeChange:C,onDepartmentChange:k,onSlaComplianceChange:S,onInitiatorChange:_,onApproverChange:D,onApproverTypeChange:A,onDateRangeChange:N,onCustomStartDateChange:P,onCustomEndDateChange:R,onShowCustomDatePickerChange:O,onApplyCustomDate:F,onClearFilters:$,hasActiveFilters:V}){return e.jsx(ee,{className:"border-gray-200 shadow-md","data-testid":"user-all-requests-filters",children:e.jsx(se,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),V&&e.jsx(ne,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),V&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:$,className:"gap-2",children:[e.jsx($t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Ts,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search requests...",value:t,onChange:T=>y(T.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(We,{value:s,onValueChange:v,children:[e.jsx(Ye,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"paused",children:"Paused"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(We,{value:a,onValueChange:w,children:[e.jsx(Ye,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"All Priority"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(We,{value:r,onValueChange:C,children:[e.jsx(Ye,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Custom"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs(We,{value:n,onValueChange:k,disabled:g||u.length===0,children:[e.jsx(Ye,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ge,{placeholder:g?"Loading...":"All Departments"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Departments"}),u.map(T=>e.jsx(Y,{value:T,children:T},T))]})]}),e.jsxs(We,{value:i,onValueChange:S,children:[e.jsx(Ye,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"All SLA Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All SLA Status"}),e.jsx(Y,{value:"compliant",children:"Compliant"}),e.jsx(Y,{value:"on-track",children:"On Track"}),e.jsx(Y,{value:"approaching",children:"Approaching"}),e.jsx(Y,{value:"critical",children:"Critical"}),e.jsx(Y,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:b.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:b.selectedUser.displayName||b.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:b.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{placeholder:"Search initiator...",value:b.searchQuery,onChange:T=>b.handleSearch(T.target.value),onFocus:()=>{b.searchResults.length>0&&b.setShowResults(!0)},onBlur:()=>setTimeout(()=>b.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),b.showResults&&b.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:b.searchResults.map(T=>e.jsx("button",{type:"button",onClick:()=>b.handleSelect(T),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:T.displayName||T.email}),T.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:T.email})]})},T.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approver"}),o!=="all"&&A&&e.jsxs(We,{value:c,onValueChange:T=>A(T),children:[e.jsx(Ye,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"current",children:"Current Only"}),e.jsx(Y,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:f.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:f.selectedUser.displayName||f.selectedUser.email}),e.jsx(E,{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(Oe,{placeholder:"Search approver...",value:f.searchQuery,onChange:T=>f.handleSearch(T.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(T=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(T),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:T.displayName||T.email}),T.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:T.email})]})},T.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:d,onValueChange:T=>N(T),children:[e.jsx(Ye,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),d==="custom"&&e.jsxs(Hs,{open:x,onOpenChange:O,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ot,{className:"w-4 h-4"}),m&&h?`${He(m,"MMM d, yyyy")} - ${He(h,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Ms,{value:m||null,onChange:T=>{const j=T?new Date(T):void 0;j?(P==null||P(j),h&&j>h&&(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(re,{htmlFor:"end-date",children:"End Date"}),e.jsx(Ms,{value:h||null,onChange:T=>{const j=T?new Date(T):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(E,{size:"sm",onClick:F,disabled:!m||!h,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply Range"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>{O==null||O(!1),P==null||P(void 0),R==null||R(void 0),N("month")},children:"Cancel"})]})]})})]})]})]})})})}function RA({request:t,apiRequest:s,currentUserId:a,isInitiator:r,onEditClaimAmount:n,className:i="",needsClosure:l=!1,conclusionRemark:o="",setConclusionRemark:c,conclusionLoading:d=!1,conclusionSubmitting:m=!1,aiGenerated:h=!1,handleGenerateConclusion:x,handleFinalizeConclusion:u,generationAttempts:g=0,generationFailed:b=!1,maxAttemptsReached:f=!1}){var k,S,_,D,A,N,P,R,O;if(!gc(s))return e.jsx("div",{className:"text-center py-8 text-gray-500",children:e.jsx("p",{children:"This is not a claim management request."})});const y=Vp(s);if(!y)return console.warn("[ClaimManagementOverviewTab] Failed to map claim data:",{apiRequest:s,hasClaimDetails:!!(s!=null&&s.claimDetails),hasProposalDetails:!!(s!=null&&s.proposalDetails),hasCompletionDetails:!!(s!=null&&s.completionDetails)}),e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx("p",{children:"Unable to load claim management data."}),e.jsx("p",{className:"text-xs mt-2",children:"Please ensure the request has been properly initialized."})]});const v=zp(s,a),w=Hp(v),C={name:((k=s.initiator)==null?void 0:k.name)||((S=s.initiator)==null?void 0:S.displayName)||((_=s.initiator)==null?void 0:_.email)||"Unknown",role:((D=s.initiator)==null?void 0:D.role)||((A=s.initiator)==null?void 0:A.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(nA,{activityInfo:y.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(iA,{dealerInfo:y.dealerInfo}),w.showProposalDetails&&y.proposalDetails&&e.jsx(oA,{proposalDetails:y.proposalDetails}),e.jsx(cA,{initiatorInfo:C}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(De,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx($e,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(se,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(sa,{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 ",Qt(s.closureDate)]}),e.jsxs("span",{children:["By ",C.name]})]})]})]}),l&&e.jsxs(ee,{"data-testid":"conclusion-remark-card",children:[e.jsx(ge,{className:`bg-gradient-to-r border-b ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:`flex items-center gap-2 text-base sm:text-lg ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(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($e,{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(E,{variant:"outline",size:"sm",onClick:x,disabled:d||f,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx($t,{className:`w-3.5 h-3.5 ${d?"animate-spin":""}`}),h?"Regenerate":"Generate with AI"]}),h&&!f&&!b&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-g," attempts remaining"]})]})]})}),e.jsx(se,{className:"pt-4",children:d?e.jsx("div",{className:"flex items-center justify-center py-8","data-testid":"conclusion-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx(lt,{className:"w-8 h-8 text-blue-600 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Preparing conclusion remark..."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Conclusion Remark"}),h&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),c&&e.jsx(Rn,{value:o,onChange:F=>c(F),placeholder:"Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals...",className:"text-sm",minHeight:"160px","data-testid":"conclusion-remark-textarea"}),e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"This will be the final summary for this request"}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":"character-count",children:[o?o.replace(/<[^>]*>/g,"").length:0," / 2000 characters"]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-blue-900 mb-1.5",children:"Finalizing this request will:"}),e.jsxs("ul",{className:"text-xs sm:text-sm text-blue-800 space-y-0.5 pl-4",children:[e.jsx("li",{className:"list-disc",children:'Change request status to "CLOSED"'}),e.jsx("li",{className:"list-disc",children:"Notify all participants of closure"}),e.jsx("li",{className:"list-disc",children:"Move request to Closed Requests"}),e.jsx("li",{className:"list-disc",children:"Save conclusion remark permanently"})]})]}),u&&e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(E,{onClick:u,disabled:m||!o.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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 DA({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n="Request",requestDescription:i="",requestId:l,levelName:o="Approval Level",approverName:c="Approver"}){const[d,m]=p.useState(""),[h,x]=p.useState(!1),[u,g]=p.useState(null),b=async()=>{if(!d.trim()){K.error("Please provide approval comments");return}try{x(!0),g("approve"),await a(d),y(),s()}catch(w){console.error("Failed to approve request:",w),K.error("Failed to approve request. Please try again.")}finally{x(!1),g(null)}},f=async()=>{if(!d.trim()){K.error("Please provide rejection reason");return}try{x(!0),g("reject"),await r(d),y(),s()}catch(w){console.error("Failed to reject request:",w),K.error("Failed to reject request. Please try again.")}finally{x(!1),g(null)}},y=()=>{m(""),g(null)},v=()=>{h||(y(),s())};return t?e.jsx(pt,{open:t,onOpenChange:v,children:e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(gt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(De,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(Dt,{className:"text-xs lg:text-sm",children:[o,": Review request details and make a decision"]}),e.jsx("div",{className:"space-y-1 mt-2 text-xs text-gray-600",children:e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Request ID:"})," ",l||"N/A"]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Approver:"})," ",c]})]})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden py-3 lg:py-4 px-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(Re,{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(As,{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(sa,{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(Ds,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:d,onChange:w=>m(w.target.value),className:"min-h-[80px] lg:min-h-[90px] text-xs lg:text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[d.length," characters"]})]}),!d.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2",children:[e.jsx(wt,{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(E,{variant:"outline",onClick:v,disabled:h,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{onClick:f,disabled:!d.trim()||h,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:h&&u==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"Reject"]})}),e.jsx(E,{onClick:b,disabled:!d.trim()||h,className:"bg-green-600 hover:bg-green-700 text-white",children:h&&u==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function PA({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:c,dueDate:d}){const[m,h]=p.useState(!1),[x,u]=p.useState(!1),g=(n==null?void 0:n.creditNoteNumber)&&(n==null?void 0:n.creditNoteNumber)!=="",b=(n==null?void 0:n.creditNoteNumber)||"",f=n!=null&&n.creditNoteDate?Qt(n.creditNoteDate,{includeTime:!1,format:"short"}):"",y=(n==null?void 0:n.creditNoteAmount)||0,v=(n==null?void 0:n.status)||"PENDING",w=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",C=(i==null?void 0:i.dealerCode)||"RE-JP-009",k=l||"Activity",S=o||"RE-REQ-2024-CM-101",_=d?Qt(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",D=async()=>{if(a)try{h(!0),await a(),K.success("Credit note downloaded successfully")}catch(P){console.error("Failed to download credit note:",P),K.error("Failed to download credit note. Please try again.")}finally{h(!1)}else K.info("Credit note will be automatically saved to Documents tab")},A=async()=>{if(r)try{u(!0),await r(),K.success("Credit note sent to dealer successfully"),s()}catch(P){console.error("Failed to send credit note to dealer:",P),K.error("Failed to send credit note. Please try again.")}finally{u(!1)}else K.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(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"font-semibold flex items-center gap-2 text-2xl",children:[e.jsx(Gt,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note from SAP"]}),e.jsx(Dt,{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(re,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(m0,{className:"w-3 h-3"}),"Credit Note Number"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1 text-lg",children:b})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(re,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(ot,{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(re,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-3",children:[e.jsx(Da,{className:"w-4 h-4"}),"Credit Note Amount"]}),e.jsx("p",{className:"text-4xl font-bold text-blue-700",children:N(y)})]})]}):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(Gt,{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(Si,{className:"w-5 h-5"}),"Dealer Information"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(re,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:w})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(re,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:C})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(re,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Activity"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:k})]})]})]}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:[e.jsxs("h3",{className:"font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4"}),"Reference Details"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx(re,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Request ID"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:S})]}),e.jsxs("div",{children:[e.jsx(re,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Due Date"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:_})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Re,{className:"w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-blue-800",children:[e.jsx("p",{className:"font-semibold mb-2",children:"Available Actions"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-xs",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Download:"})," Credit note will be automatically saved to Documents tab"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Send to Dealer:"})," Email notification will be sent to dealer with credit note attachment"]}),e.jsx("li",{children:"All actions will be recorded in activity trail for audit purposes"})]})]})]})]}),e.jsxs(Tt,{className:"flex-col-reverse gap-2 sm:flex-row flex items-center justify-between sm:justify-between",children:[e.jsx(E,{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(E,{variant:"outline",onClick:D,disabled:m||x,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),m?"Downloading...":"Download"]}),e.jsxs(E,{onClick:A,disabled:m||x,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(ax,{className:"w-4 h-4 mr-2"}),x?"Sending...":"Send to Dealer"]})]})})]})]})})}function IA({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",activityName:n="Activity",requestId:i,documentPolicy:l}){var Ee,be;const[o,c]=p.useState(""),[d,m]=p.useState(""),[h,x]=p.useState([]),[u,g]=p.useState([]),[b,f]=p.useState([]),[y,v]=p.useState([]),[w,C]=p.useState(null),[k,S]=p.useState(""),[_,D]=p.useState(!1),[A,N]=p.useState(null),P=p.useRef(null),R=p.useRef(null),O=p.useRef(null),F=p.useRef(null),$=q=>{const ue=q.type.toLowerCase(),Ae=q.name.toLowerCase();return ue.includes("image")||ue.includes("pdf")||Ae.endsWith(".pdf")||Ae.endsWith(".jpg")||Ae.endsWith(".jpeg")||Ae.endsWith(".png")||Ae.endsWith(".gif")||Ae.endsWith(".webp")};p.useEffect(()=>()=>{A!=null&&A.url&&URL.revokeObjectURL(A.url)},[A]);const V=q=>{if(!$(q)){K.error("Preview is only available for images and PDF files");return}A!=null&&A.url&&URL.revokeObjectURL(A.url);const ue=URL.createObjectURL(q);N({file:q,url:ue})},T=q=>{const ue=URL.createObjectURL(q),Ae=document.createElement("a");Ae.href=ue,Ae.download=q.name,document.body.appendChild(Ae),Ae.click(),document.body.removeChild(Ae),URL.revokeObjectURL(ue)},j=p.useMemo(()=>h.reduce((q,ue)=>q+(ue.totalAmt||ue.amount||0),0),[h]),U=(q,ue,Ae="CGST_SGST")=>{const Ue=q*ue/100,Z=q+Ue;if(Ae==="IGST")return{gstAmt:Ue,igstRate:ue,igstAmt:Ue,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,totalAmt:Z};{const Te=ue/2,Xe=Ue/2;return{gstAmt:Ue,igstRate:0,igstAmt:0,cgstRate:Te,cgstAmt:Xe,sgstRate:Te,sgstAmt:Xe,totalAmt:Z}}},I=p.useMemo(()=>{const q=o!=="",ue=u.length>0,Ae=b.length>0,Ue=k.trim().length>0;return q&&ue&&Ae&&Ue},[o,u,b,k]),M=new Date().toISOString().split("T")[0],W=()=>{x([...h,{id:Date.now().toString(),description:"",amount:0,gstRate:0,gstAmt:0,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},G=(q,ue,Ae)=>{x(h.map(Ue=>{if(Ue.id===q){const Z={...Ue,[ue]:Ae};if(ue==="amount"||ue==="gstRate"){const Te=ue==="amount"?parseFloat(Ae)||0:Ue.amount,Xe=ue==="gstRate"?parseFloat(Ae)||0:Ue.gstRate,pe=U(Te,Xe);return{...Z,amount:Te,gstRate:Xe,...pe}}return Z}return Ue}))},ce=q=>{x(h.filter(ue=>ue.id!==q))},te=q=>{const ue=Array.from(q.target.files||[]);if(ue.length>0){const Ae=[],Ue=l.maxFileSizeMB*1024*1024,Z=[".pdf",".doc",".docx",".zip",".rar"];ue.forEach(Te=>{var _e,rt;const Xe="."+((_e=Te.name.split(".").pop())==null?void 0:_e.toLowerCase()),pe=((rt=Te.name.split(".").pop())==null?void 0:rt.toLowerCase())||"";if(Te.size>Ue){K.error(`"${Te.name}" exceeds ${l.maxFileSizeMB}MB limit and was not added.`);return}if(!Z.includes(Xe)){K.error(`"${Te.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!l.allowedFileTypes.includes(pe)){K.error(`"${Te.name}" has an unallowed file type according to system policy.`);return}Ae.push(Te)}),Ae.length>0&&g([...u,...Ae]),P.current&&(P.current.value="")}},L=q=>{g(u.filter((ue,Ae)=>Ae!==q))},z=q=>{const ue=Array.from(q.target.files||[]);if(ue.length>0){const Ae=[],Ue=l.maxFileSizeMB*1024*1024;ue.forEach(Z=>{var Xe;const Te=((Xe=Z.name.split(".").pop())==null?void 0:Xe.toLowerCase())||"";if(Z.size>Ue){K.error(`Photo "${Z.name}" exceeds ${l.maxFileSizeMB}MB limit.`);return}if(!Z.type.startsWith("image/")){K.error(`"${Z.name}" is not an image file.`);return}if(!l.allowedFileTypes.includes(Te)){K.error(`"${Z.name}" has an unsupported image format.`);return}Ae.push(Z)}),Ae.length>0&&f([...b,...Ae]),R.current&&(R.current.value="")}},H=q=>{f(b.filter((ue,Ae)=>Ae!==q))},ye=q=>{const ue=Array.from(q.target.files||[]);if(ue.length>0){const Ae=[],Ue=l.maxFileSizeMB*1024*1024,Z=[".pdf",".jpg",".jpeg",".png"];ue.forEach(Te=>{var _e,rt;const Xe="."+((_e=Te.name.split(".").pop())==null?void 0:_e.toLowerCase()),pe=((rt=Te.name.split(".").pop())==null?void 0:rt.toLowerCase())||"";if(Te.size>Ue){K.error(`Invoice "${Te.name}" exceeds ${l.maxFileSizeMB}MB limit.`);return}if(!Z.includes(Xe)){K.error(`"${Te.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!l.allowedFileTypes.includes(pe)){K.error(`"${Te.name}" format is not allowed by system policy.`);return}Ae.push(Te)}),Ae.length>0&&v([...y,...Ae]),O.current&&(O.current.value="")}},ae=q=>{v(y.filter((ue,Ae)=>Ae!==q))},me=q=>{var Ae,Ue,Z;const ue=(Ae=q.target.files)==null?void 0:Ae[0];if(ue){const Te=l.maxFileSizeMB*1024*1024,Xe=[".pdf",".xlsx",".xls",".csv"],pe="."+((Ue=ue.name.split(".").pop())==null?void 0:Ue.toLowerCase()),_e=((Z=ue.name.split(".").pop())==null?void 0:Z.toLowerCase())||"";if(ue.size>Te){K.error(`Attendance file exceeds ${l.maxFileSizeMB}MB limit.`),F.current&&(F.current.value="");return}if(!Xe.includes(pe)){K.error("Please upload PDF, Excel, or CSV files only"),F.current&&(F.current.value="");return}if(!l.allowedFileTypes.includes(_e)){K.error(`"${ue.name}" format is not allowed by system policy.`),F.current&&(F.current.value="");return}C(ue)}},Q=async()=>{if(!I){K.error("Please fill all required fields");return}const q=h.filter(ue=>ue.description.trim()!==""&&ue.amount>0);try{D(!0),await a({activityCompletionDate:o,numberOfParticipants:d?parseInt(d):void 0,closedExpenses:q,totalClosedExpenses:j,completionDocuments:u,activityPhotos:b,invoicesReceipts:y.length>0?y:void 0,attendanceSheet:w||void 0,completionDescription:k}),oe(),s()}catch(ue){console.error("Failed to submit completion documents:",ue),K.error("Failed to submit completion documents. Please try again.")}finally{D(!1)}},oe=()=>{A!=null&&A.url&&URL.revokeObjectURL(A.url),N(null),c(""),m(""),x([{id:"1",description:"",amount:0,gstRate:0,gstAmt:0,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),g([]),f([]),v([]),C(null),S(""),P.current&&(P.current.value=""),R.current&&(R.current.value=""),O.current&&(O.current.value=""),F.current&&(F.current.value="")},Ce=()=>{_||(oe(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(pt,{open:t,onOpenChange:Ce,children:e.jsxs(dt,{className:"dealer-completion-documents-modal overflow-hidden flex flex-col",children:[e.jsxs(gt,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs(mt,{className:"font-semibold flex items-center gap-2 text-xl sm:text-2xl",children:[e.jsx(zs,{className:"w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]"}),"Activity Completion Documents"]}),e.jsx(Dt,{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.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-6 py-3",children:[e.jsxs("div",{className:"space-y-5 sm:space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"space-y-1.5 sm:space-y-2",children:[e.jsxs(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(ot,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Completion Date *"]}),e.jsx(Ms,{value:o||null,onChange:q=>c(q||""),maxDate:M,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(E,{type:"button",onClick:W,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(gs,{className:"w-4 h-4 mr-1"}),"Add Expense"]})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 max-h-[400px] overflow-y-auto pr-1",children:h.map(q=>e.jsxs("div",{className:"p-4 border rounded-lg bg-gray-50/50 space-y-4 relative group",children:[e.jsxs("div",{className:"flex gap-3 items-start w-full",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item description"}),e.jsx(Oe,{placeholder:"e.g., Venue rental, Refreshments",value:q.description,onChange:ue=>G(q.id,"description",ue.target.value),className:"w-full bg-white text-sm"})]}),e.jsxs("div",{className:"w-28 sm:w-36 flex-shrink-0",children:[e.jsx(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(ln,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Oe,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:q.amount||"",onChange:ue=>G(q.id,"amount",ue.target.value),className:"w-full bg-white text-sm pl-8"})]})]}),e.jsxs("div",{className:"w-20 sm:w-24 flex-shrink-0",children:[e.jsx(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"GST %"}),e.jsx(Oe,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:q.gstRate||"",onChange:ue=>G(q.id,"gstRate",ue.target.value),className:"w-full bg-white text-sm"})]}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"mt-5 hover:bg-red-100 hover:text-red-700 flex-shrink-0 h-9 w-9 p-0",onClick:()=>ce(q.id),children:e.jsx(ft,{className:"w-4 h-4"})})]}),q.gstAmt>0&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 pt-3 border-t border-dashed border-gray-200",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("span",{className:"text-[10px] text-gray-500 uppercase",children:["CGST (",q.cgstRate,"%)"]}),e.jsxs("span",{className:"text-xs font-semibold",children:["₹",q.cgstAmt.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("span",{className:"text-[10px] text-gray-500 uppercase",children:["SGST (",q.sgstRate,"%)"]}),e.jsxs("span",{className:"text-xs font-semibold",children:["₹",q.sgstAmt.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] text-gray-500 uppercase",children:"GST Total"}),e.jsxs("span",{className:"text-xs font-semibold",children:["₹",q.gstAmt.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"flex flex-col items-end",children:[e.jsx("span",{className:"text-[10px] text-gray-500 uppercase",children:"Item Total"}),e.jsxs("span",{className:"text-sm font-bold text-[#2d4a3e]",children:["₹",q.totalAmt.toLocaleString("en-IN")]})]})]})]},q.id))}),h.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.'}),h.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(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Re,{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 ${u.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(q=>l.allowedFileTypes.includes(q.replace(".",""))).join(","),className:"hidden",id:"completionDocs",onChange:te}),e.jsx("label",{htmlFor:"completionDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:u.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ls,{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:[u.length," document",u.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(zs,{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"})]})})]}),u.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 (",u.length,"):"]}),u.map((q,ue)=>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(Re,{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:q.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[$(q)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>V(q),title:"Preview file",children:e.jsx(ht,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>T(q),title:"Download file",children:e.jsx(Ct,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>L(ue),title:"Remove document",children:e.jsx(ft,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},ue))]})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Wn,{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 ${b.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(q=>l.allowedFileTypes.includes(q.replace(".",""))).join(","),className:"hidden",id:"completionPhotos",onChange:z}),e.jsx("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:b.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ls,{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:[b.length," photo",b.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(Wn,{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)"})]})})]}),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 Photos (",b.length,"):"]}),b.map((q,ue)=>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(Wn,{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:q.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[$(q)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>V(q),title:"Preview photo",children:e.jsx(ht,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>T(q),title:"Download photo",children:e.jsx(Ct,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>H(ue),title:"Remove photo",children:e.jsx(ft,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},ue))]})]})]})]}),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(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Gt,{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 ${y.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(q=>l.allowedFileTypes.includes(q.replace(".",""))).join(","),className:"hidden",id:"invoiceReceipts",onChange:ye}),e.jsx("label",{htmlFor:"invoiceReceipts",className:"cursor-pointer flex flex-col items-center gap-2",children:y.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ls,{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:[y.length," document",y.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(Gt,{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)"})]})})]}),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 Documents (",y.length,"):"]}),y.map((q,ue)=>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(Gt,{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:q.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[$(q)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>V(q),title:"Preview file",children:e.jsx(ht,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>T(q),title:"Download file",children:e.jsx(Ct,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>ae(ue),title:"Remove document",children:e.jsx(ft,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},ue))]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm sm:text-base font-semibold",children:"Attendance Sheet / Participant List"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload attendance records or participant lists (if applicable)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${w?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:F,type:"file",accept:[".pdf",".xlsx",".xls",".csv"].filter(q=>l.allowedFileTypes.includes(q.replace(".",""))).join(","),className:"hidden",id:"attendanceDoc",onChange:me}),e.jsx("label",{htmlFor:"attendanceDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:w?e.jsxs(e.Fragment,{children:[e.jsx(Ls,{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:w.name}),e.jsx("span",{className:"text-xs text-blue-600",children:"Document selected"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(zs,{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)"})]})})]}),w&&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(Re,{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:w.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[$(w)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>V(w),title:"Preview file",children:e.jsx(ht,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>T(w),title:"Download file",children:e.jsx(Ct,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>{C(null),F.current&&(F.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(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(Ds,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:k,onChange:q=>S(q.target.value),className:"min-h-[100px] sm:min-h-[120px] text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[k.length," characters"]})]}),!I&&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(ze,{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(E,{variant:"outline",onClick:Ce,disabled:_,className:"border-2",children:"Cancel"}),e.jsx(E,{onClick:Q,disabled:_||!I,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:_?"Submitting...":"Submit Documents"})]})]})}),A&&e.jsx(pt,{open:!!A,onOpenChange:()=>{A!=null&&A.url&&URL.revokeObjectURL(A.url),N(null)},children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(gt,{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(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:A.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[A.file.type||"Unknown type"," • ",(A.file.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>T(A.file),className:"gap-2 h-9",children:[e.jsx(Ct,{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:(Ee=A.file.type)!=null&&Ee.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:A.url,alt:A.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(be=A.file.type)!=null&&be.includes("pdf")||A.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:A.url,className:"w-full h-full rounded-lg border-0",title:A.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(E,{onClick:()=>T(A.file),className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",A.file.name]})]})})]})})})]})}function EA({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",activityName:n="Activity",requestId:i,previousProposalData:l,documentPolicy:o}){const[c,d]=p.useState(null),[m,h]=p.useState([{id:"1",description:"",amount:0,gstRate:0,gstAmt:0,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),x=(Q,oe,Ce="CGST_SGST")=>{const Ee=Q*oe/100,be=Q+Ee;if(Ce==="IGST")return{gstAmt:Ee,igstRate:oe,igstAmt:Ee,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,totalAmt:be};{const q=oe/2,ue=Ee/2;return{gstAmt:Ee,igstRate:0,igstAmt:0,cgstRate:q,cgstAmt:ue,sgstRate:q,sgstAmt:ue,totalAmt:be}}},[u,g]=p.useState("date"),[b,f]=p.useState(""),[y,v]=p.useState(""),[w,C]=p.useState([]),[k,S]=p.useState(""),[_,D]=p.useState(!1),[A,N]=p.useState(null),[P,R]=p.useState(!1),O=p.useRef(null),F=p.useRef(null),$=Q=>{if(!Q)return!1;const oe=Q.toLowerCase();return oe.endsWith(".pdf")||!!oe.match(/\.(jpg|jpeg|png|gif|webp)$/i)},V=Q=>$(Q.name);p.useEffect(()=>()=>{A!=null&&A.fileUrl&&A.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(A.fileUrl)},[A]);const T=Q=>{if(!V(Q)){K.error("Preview is only available for images and PDF files");return}A!=null&&A.fileUrl&&A.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(A.fileUrl);const oe=URL.createObjectURL(Q);N({fileName:Q.name,fileType:Q.type,documentId:"",fileUrl:oe,fileSize:Q.size})},j=Q=>{const oe=Q.originalFileName||Q.fileName||Q.name||"Document",Ce=Q.documentId||Q.id||"",Ee=oe.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let be="";if(Ce)be=Hr(Ce);else if(be=Q.storageUrl||Q.documentUrl||"",be&&!be.startsWith("http")){const q="https://reflow-uat.royalenfield.com",ue=q.endsWith("/")?q.slice(0,-1):q,Ae=be.startsWith("/")?be:`/${be}`;be=`${ue}${Ae}`}N({fileName:oe,fileType:Ee,documentId:Ce,fileUrl:be})},U=Q=>{const oe=URL.createObjectURL(Q),Ce=document.createElement("a");Ce.href=oe,Ce.download=Q.name,document.body.appendChild(Ce),Ce.click(),document.body.removeChild(Ce),URL.revokeObjectURL(oe)},I=p.useMemo(()=>m.reduce((Q,oe)=>Q+(oe.totalAmt||oe.amount||0),0),[m]),M=p.useMemo(()=>{const Q=c!==null,oe=m.length>0&&m.every(be=>be.description.trim()!==""&&be.amount>0),Ce=u==="date"?b!=="":y!==""&&parseInt(y)>0,Ee=k.trim().length>0;return Q&&oe&&Ce&&Ee},[c,m,u,b,y,k]),W=Q=>{var Ce,Ee,be;const oe=(Ce=Q.target.files)==null?void 0:Ce[0];if(oe){const q=o.maxFileSizeMB*1024*1024;if(oe.size>q){K.error(`File size exceeds the maximum allowed size of ${o.maxFileSizeMB}MB. Current size: ${(oe.size/(1024*1024)).toFixed(2)}MB`),O.current&&(O.current.value="");return}const ue=[".pdf",".doc",".docx"],Ae="."+((Ee=oe.name.split(".").pop())==null?void 0:Ee.toLowerCase()),Ue=((be=oe.name.split(".").pop())==null?void 0:be.toLowerCase())||"";if(!ue.includes(Ae)||!o.allowedFileTypes.includes(Ue)){K.error("Please upload a valid PDF, DOC, or DOCX file as per system policy"),O.current&&(O.current.value="");return}d(oe)}},G=Q=>{const oe=Array.from(Q.target.files||[]),Ce=[],Ee=o.maxFileSizeMB*1024*1024;oe.forEach(be=>{var ue;if(be.size>Ee){K.error(`"${be.name}" exceeds ${o.maxFileSizeMB}MB limit and was not added.`);return}const q=((ue=be.name.split(".").pop())==null?void 0:ue.toLowerCase())||"";if(!o.allowedFileTypes.includes(q)){K.error(`"${be.name}" has an unsupported file type and was not added.`);return}Ce.push(be)}),Ce.length>0&&C(be=>[...be,...Ce]),F.current&&(F.current.value="")},ce=()=>{h(Q=>[...Q,{id:Date.now().toString(),description:"",amount:0,gstRate:0,gstAmt:0,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},te=Q=>{m.length>1&&h(oe=>oe.filter(Ce=>Ce.id!==Q))},L=(Q,oe,Ce)=>{h(Ee=>Ee.map(be=>{if(be.id===Q){const q={...be,[oe]:Ce};if(oe==="amount"||oe==="gstRate"){const ue=oe==="amount"?parseFloat(Ce)||0:be.amount,Ae=oe==="gstRate"?parseFloat(Ce)||0:be.gstRate,Ue=x(ue,Ae);return{...q,amount:ue,gstRate:Ae,...Ue}}return q}return be}))},z=Q=>{C(oe=>oe.filter((Ce,Ee)=>Ee!==Q))},H=async()=>{if(!M){K.error("Please fill all required fields");return}let Q=b||"";if(u==="days"&&y){const oe=parseInt(y),Ce=new Date;Ce.setDate(Ce.getDate()+oe),Q=Ce.toISOString().split("T")[0]}try{D(!0),await a({proposalDocument:c,costBreakup:m.filter(oe=>oe.description.trim()!==""&&oe.amount>0),expectedCompletionDate:Q,otherDocuments:w,dealerComments:k}),ye(),s()}catch(oe){console.error("Failed to submit proposal:",oe),K.error("Failed to submit proposal. Please try again.")}finally{D(!1)}},ye=()=>{A!=null&&A.fileUrl&&A.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(A.fileUrl),N(null),d(null),h([{id:"1",description:"",amount:0,gstRate:0,gstAmt:0,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),g("date"),f(""),v(""),C([]),S(""),O.current&&(O.current.value=""),F.current&&(F.current.value="")},ae=()=>{_||(ye(),s())},me=new Date().toISOString().split("T")[0];return e.jsxs(pt,{open:t,onOpenChange:ae,children:[e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(gt,{className:"flex-shrink-0 pb-3 lg:pb-4",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-xl lg:text-2xl",children:[e.jsx(zs,{className:"w-5 h-5 lg:w-6 lg:h-6 text-[--re-green]"}),"Dealer Proposal Submission"]}),e.jsx(Dt,{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:()=>R(!P),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(Re,{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(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:P?e.jsx(ho,{className:"w-4 h-4"}):e.jsx(gs,{className:"w-4 h-4"})})]}),P&&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(ot,{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:$(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(Ct,{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(Re,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:l.otherDocuments.map((Q,oe)=>e.jsx(Or,{document:{documentId:Q.documentId||Q.id||"",name:Q.originalFileName||Q.fileName||Q.name||"Supporting Document",fileType:(Q.originalFileName||Q.fileName||Q.name||"").split(".").pop()||"file",uploadedAt:Q.uploadedAt||new Date().toISOString()},onPreview:$(Q.originalFileName||Q.fileName||Q.name||"")?()=>j(Q):void 0,onDownload:async Ce=>{if(Ce)await ps(Ce);else{let Ee=Q.storageUrl||Q.documentUrl;if(Ee&&!Ee.startsWith("http")){const be="https://reflow-uat.royalenfield.com",q=be.endsWith("/")?be.slice(0,-1):be,ue=Ee.startsWith("/")?Ee:`/${Ee}`;Ee=`${q}${ue}`}Ee&&window.open(Ee,"_blank")}}},oe))})]})]}),(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((Q,oe)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:Q.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(Q.amount).toLocaleString("en-IN")]})]},oe)),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(re,{className:"text-sm lg:text-base font-semibold flex items-center gap-2",children:"Proposal Document *"}),e.jsx("p",{className:"text-xs lg:text-sm text-gray-600 mb-2",children:"Detailed proposal with activity details and requested information"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${c?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:O,type:"file",accept:[".pdf",".doc",".docx"].filter(Q=>o.allowedFileTypes.includes(Q.replace(".",""))).join(","),className:"hidden",id:"proposalDoc",onChange:W}),e.jsx("label",{htmlFor:"proposalDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:c?e.jsxs("div",{className:"flex flex-col items-center gap-2 w-full",children:[e.jsx(Ls,{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:c.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:[V(c)&&e.jsxs(E,{type:"button",variant:"outline",size:"sm",onClick:()=>T(c),className:"h-8 text-xs",children:[e.jsx(ht,{className:"w-3.5 h-3.5 mr-1"}),"Preview"]}),e.jsxs(E,{type:"button",variant:"outline",size:"sm",onClick:()=>U(c),className:"h-8 text-xs",children:[e.jsx(Ct,{className:"w-3.5 h-3.5 mr-1"}),"Download"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(zs,{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(re,{className:"flex items-center gap-2 text-sm lg:text-base font-semibold",children:"Additional Documents"}),e.jsx("p",{className:"text-xs lg:text-sm text-gray-600 mb-2",children:"Any other supporting documents (invoices, receipts, photos, etc.)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${w.length>0?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:F,type:"file",multiple:!0,accept:o.allowedFileTypes.map(Q=>`.${Q}`).join(","),className:"hidden",id:"otherDocs",onChange:G}),e.jsx("label",{htmlFor:"otherDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:w.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ls,{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:[w.length," document",w.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(zs,{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()]})]})})]}),w.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 (",w.length,"):"]}),w.map((Q,oe)=>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(Re,{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:Q.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[V(Q)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>T(Q),title:"Preview file",children:e.jsx(ht,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>U(Q),title:"Download file",children:e.jsx(Ct,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>z(oe),title:"Remove document",children:e.jsx(ft,{className:"w-4 h-4"})})]})]},oe))]})]})]})]}),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(E,{type:"button",onClick:ce,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(gs,{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-3 lg:space-y-4 max-h-[300px] lg:max-h-[280px] overflow-y-auto pr-1",children:m.map(Q=>e.jsxs("div",{className:"p-3 border rounded-lg bg-gray-50/50 space-y-3 relative group",children:[e.jsxs("div",{className:"flex gap-2 items-start w-full",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Description"}),e.jsx(Oe,{placeholder:"Item description",value:Q.description,onChange:oe=>L(Q.id,"description",oe.target.value),className:"w-full bg-white"})]}),e.jsxs("div",{className:"w-24 lg:w-28 flex-shrink-0",children:[e.jsx(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsx(Oe,{type:"number",placeholder:"Amount",min:"0",step:"0.01",value:Q.amount||"",onChange:oe=>L(Q.id,"amount",oe.target.value),className:"w-full bg-white"})]}),e.jsxs("div",{className:"w-20 lg:w-24 flex-shrink-0",children:[e.jsx(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"GST %"}),e.jsx(Oe,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:Q.gstRate||"",onChange:oe=>L(Q.id,"gstRate",oe.target.value),className:"w-full bg-white"})]}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"mt-5 hover:bg-red-100 hover:text-red-700 flex-shrink-0 h-9 w-9 p-0",onClick:()=>te(Q.id),disabled:m.length===1,children:e.jsx(ft,{className:"w-4 h-4"})})]}),Q.gstAmt>0&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 pt-1 border-t border-dashed border-gray-200",children:[e.jsxs("div",{className:"text-[10px]",children:[e.jsxs("span",{className:"text-gray-500",children:["CGST (",Q.cgstRate,"%):"]}),e.jsxs("span",{className:"ml-1 font-semibold",children:["₹",Q.cgstAmt.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"text-[10px]",children:[e.jsxs("span",{className:"text-gray-500",children:["SGST (",Q.sgstRate,"%):"]}),e.jsxs("span",{className:"ml-1 font-semibold",children:["₹",Q.sgstAmt.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"text-[10px]",children:[e.jsx("span",{className:"text-gray-500",children:"GST Total:"}),e.jsxs("span",{className:"ml-1 font-semibold",children:["₹",Q.gstAmt.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"text-[10px] text-right",children:[e.jsx("span",{className:"text-gray-500",children:"Item Total:"}),e.jsxs("span",{className:"ml-1 font-bold text-gray-900",children:["₹",Q.totalAmt.toLocaleString("en-IN")]})]})]})]},Q.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(ln,{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:["₹",I.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(E,{type:"button",onClick:()=>g("date"),className:u==="date"?"bg-[#2d4a3e] hover:bg-[#1f3329] text-white":"border-2 hover:bg-gray-50",size:"sm",children:[e.jsx(ot,{className:"w-4 h-4 mr-1"}),"Specific Date"]}),e.jsx(E,{type:"button",onClick:()=>g("days"),className:u==="days"?"bg-[#2d4a3e] hover:bg-[#1f3329] text-white":"border-2 hover:bg-gray-50",size:"sm",children:"Number of Days"})]}),u==="date"?e.jsxs("div",{className:"w-full",children:[e.jsx(re,{className:"text-xs lg:text-sm font-medium mb-1.5 lg:mb-2 block",children:"Expected Completion Date"}),e.jsx(Ms,{value:b||null,onChange:Q=>f(Q||""),minDate:me,placeholderText:"dd/mm/yyyy",className:"w-full"})]}):e.jsxs("div",{className:"w-full",children:[e.jsx(re,{className:"text-xs lg:text-sm font-medium mb-1.5 lg:mb-2 block",children:"Number of Days"}),e.jsx(Oe,{type:"number",placeholder:"Enter number of days",min:"1",value:y,onChange:Q=>v(Q.target.value),className:"h-9 lg:h-10 w-full"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"dealerComments",className:"text-sm lg:text-base font-semibold flex items-center gap-2",children:"Dealer Comments / Details *"}),e.jsx(Ds,{id:"dealerComments",placeholder:"Provide detailed comments about this claim request, including any special considerations, execution details, or additional information...",value:k,onChange:Q=>S(Q.target.value),className:"min-h-[80px] lg:min-h-[100px] text-sm w-full"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[k.length," characters"]})]})]}),!M&&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(ze,{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(E,{variant:"outline",onClick:ae,disabled:_,className:"border-2",children:"Cancel"}),e.jsx(E,{onClick:H,disabled:!M||_,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:_?"Submitting...":"Submit Documents"})]})]}),A&&e.jsx(jr,{fileName:A.fileName,fileType:A.fileType,fileUrl:A.fileUrl,fileSize:A.fileSize,attachmentId:A.documentId,onDownload:ps,open:!!A,onClose:()=>N(null)})]})}function FA({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n,requestId:i,preFilledIONumber:l,preFilledBlockedAmount:o,preFilledRemainingBalance:c}){const[d,m]=p.useState("approve"),[h,x]=p.useState(""),[u,g]=p.useState(!1),b=l||"";p.useEffect(()=>{t&&(x(""),m("approve"))},[t]);const f=h.length,y=500,v=p.useMemo(()=>(d==="reject"||b.trim().length>0)&&h.trim().length>0,[d,b,h]),w=async()=>{if(!v){if(d==="approve"&&!b.trim()){K.error("IO number is required. Please block amount from IO tab first.");return}if(!h.trim()){K.error("Please provide comments");return}return}try{g(!0),d==="approve"?await a({ioNumber:b.trim(),comments:h.trim()}):await r(h.trim()),C(),s()}catch(S){console.error(`Failed to ${d} request:`,S),K.error(`Failed to ${d} request. Please try again.`)}finally{g(!1)}},C=()=>{m("approve"),x("")},k=()=>{u||(C(),s())};return e.jsx(pt,{open:t,onOpenChange:k,children:e.jsxs(dt,{className:"dept-lead-io-modal overflow-hidden flex flex-col",children:[e.jsxs(gt,{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(mt,{className:"font-semibold text-lg lg:text-xl",children:"Review and Approve"}),e.jsx(Dt,{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(E,{type:"button",onClick:()=>m("approve"),className:`flex-1 text-sm lg:text-base ${d==="approve"?"bg-green-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:d==="approve"?"default":"ghost",children:[e.jsx(De,{className:"w-4 h-4 mr-1"}),"Approve"]}),e.jsxs(E,{type:"button",onClick:()=>m("reject"),className:`flex-1 text-sm lg:text-base ${d==="reject"?"bg-red-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:d==="reject"?"destructive":"ghost",children:[e.jsx(wt,{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:[d==="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(Gt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),e.jsx("h4",{className:"font-semibold text-sm lg:text-base text-blue-900",children:"IO Organisation Details"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(re,{htmlFor:"ioNumber",className:"text-xs lg:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["IO Number ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Oe,{id:"ioNumber",value:b||"—",disabled:!0,readOnly:!0,className:"bg-gray-100 h-8 lg:h-9 cursor-not-allowed text-xs lg:text-sm"}),!b&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:"⚠️ IO number not found. Please block amount from IO tab first."}),b&&e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"✓ Loaded from IO table"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o!==void 0&&o>0&&e.jsx("div",{className:"p-2 bg-green-50 border border-green-200 rounded",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs font-semibold text-gray-700",children:"Blocked Amount:"}),e.jsxs("span",{className:"text-xs lg:text-sm font-bold text-green-700 mt-1",children:["₹",o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})}),c!=null&&e.jsx("div",{className:"p-2 bg-blue-50 border border-blue-200 rounded",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs font-semibold text-gray-700",children:"Remaining Balance:"}),e.jsxs("span",{className:"text-xs lg:text-sm font-bold text-blue-700 mt-1",children:["₹",c.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]})]}),e.jsxs("div",{className:`space-y-1.5 ${d==="approve"?"":"lg:col-span-2"}`,children:[e.jsxs(re,{htmlFor:"comment",className:"text-xs lg:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Comments & Remarks ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ds,{id:"comment",placeholder:d==="approve"?"Enter your approval comments and any conditions or notes...":"Enter detailed reasons for rejection...",value:h,onChange:S=>{const _=S.target.value;_.length<=y&&x(_)},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(as,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[f,"/",y]})]})]})]})]})}),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(E,{variant:"outline",onClick:k,disabled:u,className:"text-sm lg:text-base",children:"Cancel"}),e.jsx(E,{onClick:w,disabled:!v||u,className:`text-sm lg:text-base ${d==="approve"?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700"} text-white`,children:u?`${d==="approve"?"Approving":"Rejecting"}...`:e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),d==="approve"?"Approve Request":"Reject Request"]})})]})]})})}function _A({isOpen:t,onClose:s,onPush:a,completionDetails:r,ioDetails:n,completionDocuments:i,requestTitle:l,requestNumber:o}){var N,P;const[c,d]=p.useState(""),[m,h]=p.useState(!1),[x,u]=p.useState(null),[g,b]=p.useState(!1),f=c.length,y=500,v=p.useMemo(()=>r!=null&&r.totalClosedExpenses?r.totalClosedExpenses:r!=null&&r.closedExpenses&&Array.isArray(r.closedExpenses)?r.closedExpenses.reduce((R,O)=>{const F=typeof O=="object"&&O.amount||0;return R+(Number(F)||0)},0):0,[r]),w=R=>{if(!R)return"—";try{return new Date(R).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return R}},C=R=>`₹${R.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,k=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")},S=async R=>{if(!R.id){K.error("Document preview not available - document ID missing");return}b(!0);try{const O=Hr(R.id),F=R.name.toLowerCase(),$=F.endsWith(".pdf"),V=F.match(/\.(jpg|jpeg|png|gif|webp)$/i),T=!0,j=T?null:localStorage.getItem("accessToken"),I=await fetch(O,{headers:{Accept:$?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!I.ok)throw new Error(`Failed to load file: ${I.status} ${I.statusText}`);const M=await I.blob();if(M.size===0)throw new Error("File is empty or could not be loaded");const W=window.URL.createObjectURL(M);u({name:R.name,url:W,type:M.type||($?"application/pdf":V?"image":void 0),size:M.size})}catch(O){console.error("Failed to load document preview:",O),K.error("Failed to load document preview")}finally{b(!1)}};p.useEffect(()=>()=>{x!=null&&x.url&&x.url.startsWith("blob:")&&window.URL.revokeObjectURL(x.url)},[x]);const _=async()=>{if(!c.trim()){K.error("Please provide comments before proceeding");return}try{h(!0),await a(c.trim()),D(),s()}catch(R){console.error("Failed to generate e-invoice:",R),K.error("Failed to generate e-invoice. Please try again.")}finally{h(!1)}},D=()=>{d("")},A=()=>{m||(D(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(pt,{open:t,onOpenChange:A,children:e.jsxs(dt,{className:"settlement-push-modal overflow-hidden flex flex-col w-full max-w-none",children:[e.jsxs(gt,{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(kt,{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(mt,{className:"font-semibold text-lg sm:text-xl",children:"E-Invoice Generation & Sync"}),e.jsx(Dt,{className:"text-xs sm:text-sm mt-1",children:"Review completion details and expenses before generating e-invoice and initiating SAP settlement"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 p-3 sm:p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between sm:flex-col sm:items-start sm:gap-1",children:[e.jsx("span",{className:"font-medium text-xs sm:text-sm text-gray-600",children:"Workflow Step:"}),e.jsx(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(kt,{className:"w-3 h-3 mr-1"}),"SYNC TO SAP"]})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-6 py-3",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6",children:[r&&e.jsxs(ee,{children:[e.jsxs(ge,{className:"pb-3",children:[e.jsxs(fe,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Ls,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Details"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Review activity completion information"})]}),e.jsxs(se,{className:"space-y-2 sm:space-y-3",children:[r.activityCompletionDate&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Activity Completion Date:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:w(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(ee,{children:[e.jsxs(ge,{className:"pb-3",children:[e.jsxs(fe,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Gt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"IO Details"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Internal Order information for budget reference"})]}),e.jsxs(se,{className:"space-y-2 sm:space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"IO Number:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900 font-mono",children:n.ioNumber})]}),n.blockedAmount!==void 0&&n.blockedAmount>0&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Blocked Amount:"}),e.jsx("span",{className:"text-xs sm:text-sm font-bold text-green-700",children:C(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:C(n.remainingBalance)})]})]})]}),(r==null?void 0:r.closedExpenses)&&r.closedExpenses.length>0&&e.jsxs(ee,{children:[e.jsxs(ge,{className:"pb-3",children:[e.jsxs(fe,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Da,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Expense Breakdown"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Review closed expenses before generation"})]}),e.jsxs(se,{children:[e.jsx("div",{className:"space-y-1.5 sm:space-y-2 max-h-[200px] overflow-y-auto",children:r.closedExpenses.map((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:C(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:C(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(Ls,{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(Ls,{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:[k(R)&&e.jsx("button",{type:"button",onClick:()=>S(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(lt,{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 ps(R.id)}catch(F){console.error("Failed to download document:",F),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Ct,{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(kt,{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(kt,{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:[k(R)&&e.jsx("button",{type:"button",onClick:()=>S(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(lt,{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 ps(R.id)}catch(F){console.error("Failed to download document:",F),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download photo",children:e.jsx(Ct,{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(Gt,{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(Gt,{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:[k(R)&&e.jsx("button",{type:"button",onClick:()=>S(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(lt,{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 ps(R.id)}catch(F){console.error("Failed to download document:",F),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Ct,{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(kt,{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(kt,{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:[k(i.attendanceSheet)&&e.jsx("button",{type:"button",onClick:()=>S(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(lt,{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 ps(i.attendanceSheet.id)}catch(O){console.error("Failed to download document:",O),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Ct,{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(as,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-yellow-900",children:"Please verify all details before generation"}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1",children:"Once submitted, the system will generate an e-invoice and initiate the SAP settlement process."})]})]})}),e.jsxs("div",{className:"space-y-1.5 max-w-2xl",children:[e.jsxs(re,{htmlFor:"comment",className:"text-xs sm:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Comments & Remarks ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ds,{id:"comment",placeholder:"Enter your comments about e-invoice generation (e.g., verified expenses, ready for settlement)...",value:c,onChange:R=>{const O=R.target.value;O.length<=y&&d(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(as,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[f,"/",y]})]})]})]})}),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(E,{variant:"outline",onClick:A,disabled:m,children:"Cancel"}),e.jsx(E,{onClick:_,disabled:!c.trim()||m,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:m?"Processing...":e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Generate & Sync"]})})]})]})}),x&&e.jsx(pt,{open:!!x,onOpenChange:()=>u(null),children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(gt,{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(mt,{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(E,{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(Ct,{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(lt,{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(E,{onClick:()=>{const R=document.createElement("a");R.href=x.url,R.download=x.name,R.click()},className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",x.name]})]})})]})})})]})}function LA({isOpen:t,onClose:s,stepNumber:a,stepName:r,requestNumber:n="RE-REQ-2024-CM-101",recipientEmail:i="system@undefined",subject:l,emailBody:o}){const c=`System Notification: Activity Created - ${n}`,d=l||c,m=`System Notification
Activity has been automatically created for claim ${n}.
All stakeholders have been notified.
This is an automated message.`,h=o||m;return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(gt,{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(Ra,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(mt,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(Dt,{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(Vt,{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(Ra,{className:"w-4 h-4 text-gray-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-gray-600",children:"Subject:"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:d})]})]})]})}),e.jsx("div",{className:"bg-white rounded-lg border border-gray-200 p-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-3 border-b border-gray-200",children:[e.jsx(Si,{className:"w-5 h-5 text-purple-600"}),e.jsx("span",{className:"font-semibold text-gray-900",children:"Royal Enfield"})]}),e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans text-sm text-gray-700 leading-relaxed bg-transparent p-0 border-0",children:h})}),e.jsx("div",{className:"pt-3 border-t border-gray-200",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx(ot,{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(E,{variant:"outline",onClick:s,className:"h-9",children:[e.jsx(ft,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function MA({isOpen:t,onClose:s,onApprove:a,onReject:r,onRequestRevision:n,proposalData:i,dealerName:l="Dealer",activityName:o="Activity",requestId:c,request:d,previousProposalData:m}){const[h,x]=p.useState(""),[u,g]=p.useState(!1),[b,f]=p.useState(null),[y,v]=p.useState(!1),w=(d==null?void 0:d.internalOrder)||(d==null?void 0:d.internal_order),k=((w==null?void 0:w.ioBlockedAmount)||(w==null?void 0:w.io_blocked_amount)||0)>0,[S,_]=p.useState(null),D=p.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const T=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(T)?T.reduce((j,U)=>{const I=typeof U=="object"&&U.amount||0;return j+(Number(I)||0)},0):0},[i]),A=T=>{if(!T)return"—";try{return new Date(T).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return T}},N=T=>{if(!T.name)return!1;const j=T.name.toLowerCase();return j.endsWith(".pdf")||j.endsWith(".jpg")||j.endsWith(".jpeg")||j.endsWith(".png")||j.endsWith(".gif")||j.endsWith(".webp")},P=T=>{let j=T.url||T.storageUrl||"";const U=T.id||T.documentId||"";if(!U&&!j){K.error("Document preview not available");return}if(j&&!j.startsWith("http")&&!j.startsWith("blob:")){const I="https://reflow-uat.royalenfield.com",M=I.endsWith("/")?I.slice(0,-1):I,W=j.startsWith("/")?j:`/${j}`;j=`${M}${W}`}_({name:T.name||"Document",url:j||(U?Hr(U):""),type:(T.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:U})};p.useEffect(()=>()=>{S!=null&&S.url&&S.url.startsWith("blob:")&&window.URL.revokeObjectURL(S.url)},[S]);const R=async()=>{if(!h.trim()){K.error("Please provide approval comments");return}try{g(!0),f("approve"),await a(h),$(),s()}catch(T){console.error("Failed to approve proposal:",T),K.error("Failed to approve proposal. Please try again.")}finally{g(!1),f(null)}},O=async()=>{if(!h.trim()){K.error("Please provide rejection reason");return}try{g(!0),f("reject"),await r(h),$(),s()}catch(T){console.error("Failed to reject proposal:",T),K.error("Failed to reject proposal. Please try again.")}finally{g(!1),f(null)}},F=async()=>{if(!h.trim()){K.error("Please provide reasons for requesting a revision");return}if(!n){K.error("Revision feature is not available");return}try{g(!0),f("revision"),await n(h),$(),s()}catch(T){console.error("Failed to request revision:",T),K.error("Failed to request revision. Please try again.")}finally{g(!1),f(null)}},$=()=>{x(""),f(null)},V=()=>{u||($(),s())};return t?e.jsxs(pt,{open:t,onOpenChange:V,children:[e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(gt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(De,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),e.jsx(Dt,{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(!y),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(Re,{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(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:y?e.jsx(ho,{className:"w-4 h-4"}):e.jsx(gs,{className:"w-4 h-4"})})]}),y&&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(ot,{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(Ct,{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(ln,{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((T,j)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:T.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(T.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(Re,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:m.otherDocuments.map((T,j)=>e.jsx(Or,{document:{documentId:T.documentId||T.id||"",name:T.originalFileName||T.fileName||T.name||"Supporting Document",fileType:(T.originalFileName||T.fileName||T.name||"").split(".").pop()||"file",uploadedAt:T.uploadedAt||new Date().toISOString()},onPreview:N({name:T.originalFileName||T.fileName||T.name||""})?()=>P(T):void 0,onDownload:async U=>{if(U)await ps(U);else{let I=T.storageUrl||T.documentUrl;if(I&&!I.startsWith("http")){const M="https://reflow-uat.royalenfield.com",W=M.endsWith("/")?M.slice(0,-1):M,G=I.startsWith("/")?I:`/${I}`;I=`${W}${G}`}I&&window.open(I,"_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(As,{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(Re,{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(Re,{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 ",A(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 T;try{(T=i.proposalDocument)!=null&&T.id&&await ps(i.proposalDocument.id)}catch(j){console.error("Failed to download document:",j),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Ct,{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(Re,{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((T,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(Re,{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:T.name,children:T.name})]}),T.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[N(T)&&e.jsx("button",{type:"button",onClick:()=>P(T),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{T.id&&await ps(T.id)}catch(U){console.error("Failed to download document:",U),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Ct,{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(ln,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const T=i!=null&&i.costBreakup?Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[]:[];return T&&Array.isArray(T)&&T.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:T.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(ln,{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(ot,{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?A(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(As,{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(Ds,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:h,onChange:T=>x(T.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:[h.length," characters"]})]})]})}),!h.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(wt,{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(E,{variant:"outline",onClick:V,disabled:u,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(E,{onClick:F,disabled:!h.trim()||u,variant:"secondary",className:"bg-amber-100 hover:bg-amber-200 text-amber-900 border border-amber-200 w-full sm:w-auto",children:u&&b==="revision"?"Requesting...":e.jsxs(e.Fragment,{children:[e.jsx(As,{className:"w-4 h-4 mr-2"}),"Request Revised Quotation"]})}),e.jsx(E,{onClick:O,disabled:!h.trim()||u,variant:"destructive",className:"bg-red-600 hover:bg-red-700 w-full sm:w-auto",children:u&&b==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(E,{onClick:R,disabled:!h.trim()||!k||u,className:"bg-green-600 hover:bg-green-700 text-white disabled:opacity-50 disabled:cursor-not-allowed w-full sm:w-auto",title:k?"":"Please block IO budget before approving",children:u&&b==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Approve (Continue to Dept Lead)"]})})]}),!k&&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"})]})]})]}),S&&e.jsx(jr,{fileName:S.name,fileType:S.type||"",fileUrl:S.url,fileSize:S.size,attachmentId:S.id,onDownload:ps,open:!!S,onClose:()=>_(null)})]}):null}function $A({isOpen:t,onClose:s,snapshot:a,type:r,title:n}){const[i,l]=p.useState(null);if(!a)return null;const o=r==="PROPOSAL",c=u=>Number(u||0).toLocaleString("en-IN",{maximumFractionDigits:2,style:"currency",currency:"INR"}),d=u=>{if(!u)return null;try{return new Date(u).toLocaleDateString("en-IN",{day:"numeric",month:"short",year:"numeric"})}catch{return u}},m=u=>{if(!u)return!1;const g=u.toLowerCase();return g.endsWith(".pdf")||!!g.match(/\.(jpg|jpeg|png|gif|webp)$/i)},h=u=>{var b;const g=(b=(u||"").split(".").pop())==null?void 0:b.toLowerCase();return g==="pdf"?"pdf":["jpg","jpeg","png","gif","webp"].includes(g||"")?"image":"file"},x=u=>{const g=u.fileName||u.originalFileName||(o?"Proposal Document":"Completion Document"),b=u.documentId||"",f=g.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let y="";if(b)y=Hr(b);else if(y=u.storageUrl||u.documentUrl||"",y&&!y.startsWith("http")){const v="https://reflow-uat.royalenfield.com",w=v.endsWith("/")?v.slice(0,-1):v,C=y.startsWith("/")?y:`/${y}`;y=`${w}${C}`}l({fileName:g,fileType:f,documentId:b,fileUrl:y,fileSize:u.sizeBytes})};return e.jsxs(e.Fragment,{children:[e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs(gt,{className:"px-6 py-4 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[o?e.jsx(Re,{className:"w-5 h-5 text-blue-600"}):e.jsx(Gt,{className:"w-5 h-5 text-green-600"}),n||(o?"Proposal Snapshot Details":"Completion Snapshot Details")]}),e.jsxs(Dt,{children:["View detailed snapshot of the ",o?"proposal":"completion request"," at this version."]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 px-6 py-4",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium mb-1",children:o?"Total Budget":"Total Expenses"}),e.jsx("p",{className:`text-lg font-bold ${o?"text-blue-700":"text-green-700"}`,children:c(a.totalBudget||a.totalExpenses)})]}),o&&a.expectedCompletionDate&&e.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsxs("p",{className:"text-xs text-gray-500 font-medium mb-1 flex items-center gap-1",children:[e.jsx(ot,{className:"w-3 h-3"}),"Expected Completion"]}),e.jsx("p",{className:"text-sm font-semibold text-gray-700",children:d(a.expectedCompletionDate)})]})]}),a.documentUrl&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1",children:"Primary Document"}),e.jsx(Or,{document:{documentId:"",name:o?"Proposal Document":"Completion Document",fileType:h(a.documentUrl),uploadedAt:new Date().toISOString()},onPreview:m(a.documentUrl)?()=>x({fileName:o?"Proposal Document":"Completion Document",documentUrl:a.documentUrl}):void 0,onDownload:async()=>{let u=a.documentUrl;if(!u.startsWith("http")){const g="https://reflow-uat.royalenfield.com",b=g.endsWith("/")?g.slice(0,-1):g,f=u.startsWith("/")?u:`/${u}`;u=`${b}${f}`}window.open(u,"_blank")}})]}),a.otherDocuments&&a.otherDocuments.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1 flex items-center justify-between",children:[e.jsx("span",{children:"Supporting Documents"}),e.jsxs(ne,{variant:"secondary",className:"text-[10px] h-5",children:[a.otherDocuments.length," Files"]})]}),e.jsx("div",{className:"space-y-2",children:a.otherDocuments.map((u,g)=>e.jsx(Or,{document:{documentId:u.documentId||"",name:u.originalFileName||u.fileName||"Supporting Document",fileType:h(u.originalFileName||u.fileName||""),uploadedAt:u.uploadedAt||new Date().toISOString()},onPreview:m(u.originalFileName||u.fileName||"")?()=>x(u):void 0,onDownload:u.documentId?ps:async()=>{let b=u.storageUrl||u.documentUrl;if(b&&!b.startsWith("http")){const f="https://reflow-uat.royalenfield.com",y=f.endsWith("/")?f.slice(0,-1):f,v=b.startsWith("/")?b:`/${b}`;b=`${y}${v}`}b&&window.open(b,"_blank")}},g))})]}),(a.costItems||a.expenses)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1",children:o?"Cost Breakdown":"Expenses Breakdown"}),e.jsx("div",{className:"border rounded-md overflow-hidden text-sm",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-600 text-xs uppercase",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-3 font-medium",children:"Description"}),e.jsx("th",{className:"p-3 font-medium text-right",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-100",children:[(a.costItems||a.expenses).length>0?(a.costItems||a.expenses).map((u,g)=>e.jsxs("tr",{className:"bg-white hover:bg-gray-50/50",children:[e.jsx("td",{className:"p-3 text-gray-800",children:u.description}),e.jsx("td",{className:"p-3 text-right text-gray-900 font-medium tabular-nums",children:c(u.amount)})]},g)):e.jsx("tr",{children:e.jsx("td",{colSpan:2,className:"p-4 text-center text-gray-500 italic text-xs",children:"No breakdown items available"})}),e.jsxs("tr",{className:"bg-gray-50/80 font-semibold text-gray-900 border-t-2 border-gray-100",children:[e.jsx("td",{className:"p-3",children:"Total"}),e.jsx("td",{className:"p-3 text-right tabular-nums",children:c(a.totalBudget||a.totalExpenses)})]})]})]})})]}),a.comments&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1 flex items-center gap-1",children:[e.jsx(Ju,{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(E,{onClick:s,children:"Close"})})]})}),i&&e.jsx(jr,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:ps,open:!!i,onClose:()=>l(null)})]})}async function OA(t){var s;try{const a=await je.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 UA(t){var s;try{const a=await je.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 BA(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 je.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 VA(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 je.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 zA(t,s){var a;try{const r=await je.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 Zp(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 je.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 HA(t,s){var a;try{const r=await je.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 WA(t){var s;try{const a=await je.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 GA(t,s,a){var r;try{const n={};t&&(n.dateRange=t),s&&(n.startDate=s),a&&(n.endDate=a);const i=await je.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 Qt(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}}},YA=t=>{switch(t){case"approved":return e.jsx(De,{className:"w-5 h-5 text-green-600"});case"pending":return e.jsx(st,{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(st,{className:"w-5 h-5 text-gray-400"})}},KA=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"}},XA=(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",ZA=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 JA({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i}){var pa,Fa,wa,St,Ca,Za,Ja,Qa,qa,er,tr,_a,ga,La,It,ns,Os,sr,ar,oa,vt,is,Is,Zs,Nr,ca,Ma,Kr,Xr,Zr,yc,vc,jc,Nc,wc,Cc,Sc,Ac,Tc,kc,Rc,Dc,Pc,Ic,Ec,Fc,_c,Lc,Mc,$c,Oc,Uc,Bc,Vc,zc,Hc,Wc,Gc,Yc,Kc,Xc,Zc,Jc,Qc,qc,ed,td,sd,ad,rd,nd,id,ld,od,cd,dd,md,ud,xd,hd,pd,gd,fd,bd,yd,vd,jd,Nd,wd,Cd,Sd,Ad;const[l,o]=p.useState(!1),[c,d]=p.useState(!1),[m,h]=p.useState(!1),[x,u]=p.useState(!1),[g,b]=p.useState(!1),[f,y]=p.useState(!1),[v,w]=p.useState(!1),[C,k]=p.useState(null),[S,_]=p.useState(!1),[D,A]=p.useState(null),[N,P]=p.useState([]),[R,O]=p.useState(!1),[F,$]=p.useState(new Set),[V,T]=p.useState(null),[j,U]=p.useState([]),[I,M]=p.useState(0);p.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Ie=t.id||t.requestId;try{const xe=await vs(Ie),ie=(xe==null?void 0:xe.approvalLevels)||(xe==null?void 0:xe.approvals)||[];if(ie&&ie.length>0){const he=ie.map(de=>{var Se;return{step:de.levelNumber||de.level_number||0,levelNumber:de.levelNumber||de.level_number||0,levelName:de.levelName||de.level_name,approver:de.approverName||de.approver_name||"",approverEmail:(de.approverEmail||de.approver_email||"").toLowerCase(),status:((Se=de.status)==null?void 0:Se.toLowerCase())||"waiting",tatHours:de.tatHours||de.tat_hours||24,elapsedHours:de.elapsedHours||de.elapsed_hours,approvedAt:de.actionDate||de.action_date,comment:de.comments||de.comment,levelId:de.levelId||de.level_id}}).sort((de,Se)=>(de.levelNumber||0)-(Se.levelNumber||0));U(de=>de.length!==he.length||de.some((Ne,ve)=>{const bt=he[ve];return!bt||Ne.levelNumber!==bt.levelNumber||Ne.levelName!==bt.levelName||Ne.approverEmail!==bt.approverEmail||Ne.status!==bt.status})?he:de)}else U([])}catch(xe){console.warn("Failed to load approval flows from API:",xe),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,I]),p.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const B=t.id||t.requestId;(async()=>{try{const xe=await vs(B),ie=(xe==null?void 0:xe.approvalLevels)||(xe==null?void 0:xe.approvals)||[];if(ie&&ie.length>0){const he=ie.map(de=>{var Se;return{step:de.levelNumber||de.level_number||0,levelNumber:de.levelNumber||de.level_number||0,levelName:de.levelName||de.level_name,approver:de.approverName||de.approver_name||"",approverEmail:(de.approverEmail||de.approver_email||"").toLowerCase(),status:((Se=de.status)==null?void 0:Se.toLowerCase())||"waiting",tatHours:de.tatHours||de.tat_hours||24,elapsedHours:de.elapsedHours||de.elapsed_hours,approvedAt:de.actionDate||de.action_date,comment:de.comments||de.comment,levelId:de.levelId||de.level_id}}).sort((de,Se)=>(de.levelNumber||0)-(Se.levelNumber||0));U(he)}}catch(xe){console.warn("Failed to load approval flows from API:",xe)}})()}},[t==null?void 0:t.currentStep,t==null?void 0:t.totalLevels]);const W=async()=>{M(B=>B+1),await new Promise(B=>setTimeout(B,500)),n==null||n(),G()},G=async()=>{if(t!=null&&t.id||t!=null&&t.requestId)try{const Ie=[...await rN(t.id||t.requestId)||[]].sort((xe,ie)=>new Date(ie.createdAt).getTime()-new Date(xe.createdAt).getTime());P(Ie)}catch(B){console.warn("Failed to load version history:",B)}};p.useEffect(()=>{G()},[t==null?void 0:t.id,t==null?void 0:t.requestId,I]);const ce=(B,Ie,xe)=>{var de;const ie=((t==null?void 0:t.totalLevels)||0)>5||(((de=t==null?void 0:t.approvalLevels)==null?void 0:de.length)||0)>5;if(Ie&&Ie.trim()&&(Ie.toLowerCase().includes("additional approver")||!/^step\s+\d+$/i.test(Ie)))return Ie;const he=ie?{1:"Dealer - Proposal Submission",2:"Requestor Evaluation & Confirmation",3:"Department Lead Approval",4:"Activity Creation",5:"Dealer - Completion Documents",6:"Requestor - Claim Approval",7:"E-Invoice Generation",8:"Credit Note from SAP"}:{1:"Dealer - Proposal Submission",2:"Requestor Evaluation & Confirmation",3:"Department Lead Approval",4:"Dealer - Completion Documents",5:"Requestor - Claim Approval",6:"E-Invoice Generation",7:"Credit Note from SAP"};return he[B]?he[B]:xe&&xe!=="Unknown"&&xe!=="System"?`Additional Approver - ${xe}`:`Additional Approver - Step ${B}`},te=(B,Ie,xe)=>{var Se;if(Ie&&Ie.toLowerCase().includes("additional approver"))return xe&&xe!=="Unknown"&&xe!=="System"?`${xe} will review and approve this request as an additional approver.`:"Additional approver will review and approve this request.";const he=((t==null?void 0:t.totalLevels)||0)>5||(((Se=t==null?void 0:t.approvalLevels)==null?void 0:Se.length)||0)>5;if(Ie&&Ie.trim()){const Ne=Ie.toLowerCase();if(Ne.includes("dealer")&&Ne.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(Ne.includes("requestor")&&(Ne.includes("evaluation")||Ne.includes("confirmation")))return"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)";if(Ne.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(Ne.includes("activity creation"))return"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.";if(Ne.includes("dealer")&&(Ne.includes("completion")||Ne.includes("documents")))return"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description";if(Ne.includes("requestor")&&(Ne.includes("claim")||Ne.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(Ne.includes("e-invoice")||Ne.includes("invoice generation")||Ne.includes("dms"))return"E-Invoice will be generated upon settlement initiation.";if(Ne.includes("credit note")||Ne.includes("sap"))return"Got credit note from SAP. Review and send to dealer to complete the claim management process."}const de=he?{1:"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests",2:"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)",3:"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)",4:"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.",5:"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description",6:"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.",7:"E-Invoice will be generated upon settlement initiation.",8:"Got credit note from SAP. Review and send to dealer to complete the claim management process."}:{1:"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests",2:"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)",3:"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)",4:"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description",5:"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.",6:"E-Invoice will be generated upon settlement initiation.",7:"Got credit note from SAP. Review and send to dealer to complete the claim management process."};return de[B]?de[B]:xe&&xe!=="Unknown"&&xe!=="System"?`${xe} will review and approve this request.`:`Step ${B} approval required.`},L=B=>{if(!N||N.length===0||!B)return{current:null,previous:null};const ie=[...N.filter(Se=>{var Ne;return!!(Se.levelName&&Se.levelName.trim()===B.trim()||(Ne=Se.snapshotData)!=null&&Ne.levelName&&Se.snapshotData.levelName.trim()===B.trim())})].sort((Se,Ne)=>{if(Ne.version!==Se.version)return Ne.version-Se.version;const ve=Se.snapshotType==="APPROVE"?1:Se.snapshotType==="PROPOSAL"||Se.snapshotType==="COMPLETION"?2:3,bt=Ne.snapshotType==="APPROVE"?1:Ne.snapshotType==="PROPOSAL"||Ne.snapshotType==="COMPLETION"?2:3;return ve-bt}).filter((Se,Ne,ve)=>Se.snapshotType==="WORKFLOW"?!ve.some(xt=>xt.snapshotType==="APPROVE"&&xt.levelName===Se.levelName&&xt.version>=Se.version):!0),he=ie.length>0?ie[0]:null,de=ie.length>1?ie[1]:null;return{current:he,previous:de,all:ie}},z=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),H=z!=null?Number(z):null,ye=((t==null?void 0:t.status)||"").toUpperCase(),ae=ye==="REJECTED",me=ye==="CLOSED",Q=!ae&&!me&&(ye==="PENDING"||ye==="IN_PROGRESS"||ye==="IN-PROGRESS"),oe=j.find(B=>{var ie,he;const Ie=B.levelId||B.level_id,xe=(ie=t==null?void 0:t.approvals)==null?void 0:ie.find(de=>de.levelId===Ie);return((he=xe==null?void 0:xe.status)==null?void 0:he.toLowerCase())==="rejected"}),Ce=oe?Number(oe.levelNumber||oe.level_number||oe.step||0):null,Ee=j.map((B,Ie)=>{var da,ds,le,ct,Ut,ms,Nt;const xe=Number(B.levelNumber||B.level_number||B.step||Ie+1),ie=B.levelName||B.level_name,he=(da=t==null?void 0:t.approvals)==null?void 0:da.find(Pe=>Pe.levelId===B.levelId);let de;if(ie&&ie.toLowerCase().includes("department lead")||xe===3){const Pe=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);(Pe!=null&&Pe.ioNumber||Pe!=null&&Pe.io_number)&&(de={ioNumber:Pe.ioNumber||Pe.io_number||"",blockedAmount:Pe.ioBlockedAmount||Pe.io_blocked_amount||0,availableBalance:Pe.ioAvailableBalance||Pe.io_available_balance||0,remainingBalance:Pe.ioRemainingBalance||Pe.io_remaining_balance||0,organizedBy:((ds=Pe.organizer)==null?void 0:ds.displayName)||((le=Pe.organizer)==null?void 0:le.name)||Pe.organizedBy||B.approver||"N/A",organizedAt:Pe.organizedAt||Pe.organized_at||B.approvedAt||(t==null?void 0:t.updatedAt)||""})}let Ne;xe===6&&(he!=null&&he.dmsDetails?Ne={dmsNumber:he.dmsDetails.dmsNumber||"",dmsRemarks:he.dmsDetails.dmsRemarks||"",pushedBy:he.dmsDetails.pushedBy||B.approver,pushedAt:he.dmsDetails.pushedAt||B.approvedAt||""}:t!=null&&t.dmsNumber&&(Ne={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((ct=t.dmsDetails)==null?void 0:ct.dmsRemarks)||"",pushedBy:B.approver,pushedAt:B.approvedAt||t.updatedAt||""}));let ve;if(ae||me)((Ut=he==null?void 0:he.status)==null?void 0:Ut.toLowerCase())==="rejected"?ve="rejected":Ce!==null&&xe>Ce?ve="waiting":((ms=he==null?void 0:he.status)==null?void 0:ms.toLowerCase())==="approved"?ve="approved":Ce!==null&&xe<Ce?((Nt=he==null?void 0:he.status)==null?void 0:Nt.toLowerCase())==="approved"?ve="approved":ve="waiting":(H!==null&&xe>H,ve="waiting");else if(Q&&H!==null&&H>0)if(xe>H)ve="waiting";else if(xe<H)if(he!=null&&he.status){const Pe=he.status.toLowerCase();Pe==="approved"?ve="approved":Pe==="rejected"?ve="rejected":ve="waiting"}else ve="waiting";else if(he!=null&&he.status){const Pe=he.status.toLowerCase();Pe==="approved"?ve="approved":Pe==="rejected"?ve="rejected":ve="in_progress"}else{const Pe=(B.status||"pending").toLowerCase();Pe==="in-review"||Pe==="in_review"||Pe==="in review"||Pe==="pending"?ve="in_progress":ve=Pe}else if(he!=null&&he.status){const Pe=he.status.toLowerCase();Pe==="approved"?ve="approved":Pe==="rejected"?ve="rejected":Pe==="pending"||Pe==="in_progress"||Pe==="in-progress"?ve="in_progress":ve=(B.status||"waiting").toLowerCase()}else{const Pe=(B.status||"waiting").toLowerCase();Pe==="in-review"||Pe==="in_review"||Pe==="in review"||Pe==="pending"?ve="in_progress":ve=Pe}const xt=ve==="waiting"?0:B.elapsedHours||0,ls=B.approver||B.approverName||"Unknown",jt=ie?L(ie):{current:null,previous:null};return{step:xe,title:ce(xe,ie,ls),approver:ls,description:te(xe,ie,ls)||B.description||"",tatHours:B.tatHours||24,status:ve,comment:B.comment||(he==null?void 0:he.comment),approvedAt:B.approvedAt||(he==null?void 0:he.timestamp),elapsedHours:xt,ioDetails:de,dmsDetails:Ne,einvoiceUrl:xe===7?he==null?void 0:he.einvoiceUrl:void 0,emailTemplateUrl:(he==null?void 0:he.emailTemplateUrl)||void 0,versionHistory:jt}});let be=null,q=1;if(ae||me)Ce!==null?q=Ce:H!==null?q=H:q=(t==null?void 0:t.currentStep)||1;else if(Q){const B=H!==null?Ee.find(Ie=>Ie.step===H):null;be=B&&(B.status==="pending"||B.status==="in_progress")?B:Ee.find(Ie=>{var ie;const xe=((ie=Ie.status)==null?void 0:ie.toLowerCase())||"";return xe==="pending"||xe==="in_progress"||xe==="in-review"||xe==="in_review"}),q=be?be.step:H||(t==null?void 0:t.currentStep)||1}else q=H||(t==null?void 0:t.currentStep)||1;const ue=((pa=s==null?void 0:s.email)==null?void 0:pa.toLowerCase())||"",Ae=((Fa=t==null?void 0:t.dealerEmail)==null?void 0:Fa.toLowerCase())||((St=(wa=t==null?void 0:t.dealer)==null?void 0:wa.email)==null?void 0:St.toLowerCase())||((Za=(Ca=t==null?void 0:t.claimDetails)==null?void 0:Ca.dealerEmail)==null?void 0:Za.toLowerCase())||((Qa=(Ja=t==null?void 0:t.claimDetails)==null?void 0:Ja.dealer_email)==null?void 0:Qa.toLowerCase())||"",Ue=Ae&&ue===Ae,Z=j.find(B=>(B.step||B.levelNumber||B.level_number)===q),Te=((Z==null?void 0:Z.approverEmail)||"").toLowerCase(),Xe=Te&&ue===Te,pe=((er=(qa=t==null?void 0:t.initiator)==null?void 0:qa.email)==null?void 0:er.toLowerCase())||((tr=t==null?void 0:t.initiatorEmail)==null?void 0:tr.toLowerCase())||"",_e=j.find(B=>{const Ie=(B.approverEmail||"").toLowerCase(),xe=(B.levelName||"").toLowerCase();return pe&&Ie===pe||xe.includes("requestor evaluation")||xe.includes("requestor")&&xe.includes("confirmation")}),rt=_e&&(_e.step||_e.levelNumber||_e.level_number)||2,ut=_e||j.find(B=>(B.step||B.levelNumber||B.level_number)===2),nt=((ut==null?void 0:ut.approverEmail)||"").toLowerCase(),Ps=nt&&ue===nt,Xs=j.find(B=>(B.step||B.levelNumber||B.level_number)===1),Na=((Xs==null?void 0:Xs.approverEmail)||"").toLowerCase(),Xa=Na&&ue===Na,X=j.find(B=>(B.levelName||"").toLowerCase().includes("department lead")),we=((X==null?void 0:X.approverEmail)||"").toLowerCase(),J=we&&ue===we,Le=async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId;B.proposalDocument&&await nn(B.proposalDocument,ie,"APPROVAL");for(const de of B.otherDocuments)await nn(de,ie,"SUPPORTING");const he=B.costBreakup.reduce((de,Se)=>de+(Se.totalAmt||Se.amount||0),0);await BA(ie,{proposalDocument:B.proposalDocument||void 0,costBreakup:B.costBreakup.map(de=>({description:de.description,amount:de.amount,gstRate:de.gstRate,gstAmt:de.gstAmt,cgstRate:de.cgstRate,cgstAmt:de.cgstAmt,sgstRate:de.sgstRate,sgstAmt:de.sgstAmt,igstRate:de.igstRate,igstAmt:de.igstAmt,utgstRate:de.utgstRate,utgstAmt:de.utgstAmt,cessRate:de.cessRate,cessAmt:de.cessAmt,totalAmt:de.totalAmt})),totalEstimatedBudget:he,expectedCompletionDate:B.expectedCompletionDate,dealerComments:B.dealerComments}),K.success("Proposal submitted successfully"),W()}catch(ie){console.error("Failed to submit proposal:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to submit proposal. Please try again.";throw K.error(he),ie}},Fe=async B=>{var Ie,xe,ie,he,de;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Se=t.id||t.requestId,Ne=await vs(Se),ve=(Ne==null?void 0:Ne.approvalLevels)||(Ne==null?void 0:Ne.approvals)||[],bt=((xe=(Ie=t==null?void 0:t.initiator)==null?void 0:Ie.email)==null?void 0:xe.toLowerCase())||((ie=t==null?void 0:t.initiatorEmail)==null?void 0:ie.toLowerCase())||"",xt=ve.find(jt=>{const da=(jt.approverEmail||jt.approver_email||"").toLowerCase(),ds=(jt.levelName||jt.level_name||"").toLowerCase(),le=jt.levelNumber||jt.level_number;return bt&&da===bt||ds.includes("requestor evaluation")||ds.includes("requestor")&&ds.includes("confirmation")||le===rt})||ve.find(jt=>(jt.levelNumber||jt.level_number)===2);if(!(xt!=null&&xt.levelId)&&!(xt!=null&&xt.level_id))throw new Error("Initiator approval level not found");const ls=xt.levelId||xt.level_id;await an(Se,ls,B),K.success("Proposal approved successfully"),W()}catch(Se){console.error("Failed to approve proposal:",Se);const Ne=((de=(he=Se==null?void 0:Se.response)==null?void 0:he.data)==null?void 0:de.message)||(Se==null?void 0:Se.message)||"Failed to approve proposal. Please try again.";throw K.error(Ne),Se}},Ve=async B=>{var Ie,xe,ie,he,de;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Se=t.id||t.requestId,Ne=await vs(Se),ve=(Ne==null?void 0:Ne.approvalLevels)||(Ne==null?void 0:Ne.approvals)||[],bt=((xe=(Ie=t==null?void 0:t.initiator)==null?void 0:Ie.email)==null?void 0:xe.toLowerCase())||((ie=t==null?void 0:t.initiatorEmail)==null?void 0:ie.toLowerCase())||"",xt=ve.find(jt=>{const da=(jt.approverEmail||jt.approver_email||"").toLowerCase(),ds=(jt.levelName||jt.level_name||"").toLowerCase(),le=jt.levelNumber||jt.level_number;return bt&&da===bt||ds.includes("requestor evaluation")||ds.includes("requestor")&&ds.includes("confirmation")||le===rt})||ve.find(jt=>(jt.levelNumber||jt.level_number)===2);if(!(xt!=null&&xt.levelId)&&!(xt!=null&&xt.level_id))throw new Error("Initiator approval level not found");const ls=xt.levelId||xt.level_id;await Sr(Se,ls,"Proposal rejected by requestor",B),K.success("Proposal rejected. Request has been cancelled."),W()}catch(Se){console.error("Failed to reject proposal:",Se);const Ne=((de=(he=Se==null?void 0:Se.response)==null?void 0:he.data)==null?void 0:de.message)||(Se==null?void 0:Se.message)||"Failed to reject proposal. Please try again.";throw K.error(Ne),Se}},Me=async B=>{var Ie,xe,ie,he,de;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Se=t.id||t.requestId,Ne=await vs(Se),ve=(Ne==null?void 0:Ne.approvalLevels)||(Ne==null?void 0:Ne.approvals)||[],bt=((xe=(Ie=t==null?void 0:t.initiator)==null?void 0:Ie.email)==null?void 0:xe.toLowerCase())||((ie=t==null?void 0:t.initiatorEmail)==null?void 0:ie.toLowerCase())||"",xt=ve.find(jt=>{const da=(jt.approverEmail||jt.approver_email||"").toLowerCase(),ds=(jt.levelName||jt.level_name||"").toLowerCase(),le=jt.levelNumber||jt.level_number;return bt&&da===bt||ds.includes("requestor evaluation")||ds.includes("requestor")&&ds.includes("confirmation")||le===rt})||ve.find(jt=>(jt.levelNumber||jt.level_number)===2);if(!(xt!=null&&xt.levelId)&&!(xt!=null&&xt.level_id))throw new Error("Initiator approval level not found");const ls=xt.levelId||xt.level_id;await Sr(Se,ls,"Revised Quotation Requested",B),K.success("Revision requested. Request returned to dealer."),W()}catch(Se){console.error("Failed to request revision:",Se);const Ne=((de=(he=Se==null?void 0:Se.response)==null?void 0:he.data)==null?void 0:de.message)||(Se==null?void 0:Se.message)||"Failed to request revision. Please try again.";throw K.error(Ne),Se}},Ze=async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=await vs(ie),de=(he==null?void 0:he.approvalLevels)||(he==null?void 0:he.approvals)||[],Se=de.find(ve=>(ve.levelName||ve.level_name||"").toLowerCase().includes("department lead"))||de.find(ve=>(ve.levelNumber||ve.level_number)===3);if(!(Se!=null&&Se.levelId)&&!(Se!=null&&Se.level_id))throw new Error("Department Lead approval level not found");const Ne=Se.levelId||Se.level_id;await Zp(ie,{ioNumber:B.ioNumber}),await an(ie,Ne,B.comments),K.success("Request approved and IO organized successfully"),W()}catch(ie){console.error("Failed to approve and organize IO:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to approve request. Please try again.";throw K.error(he),ie}},Be=async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=B.closedExpenses.map(de=>({description:de.description,amount:de.amount,gstRate:de.gstRate,gstAmt:de.gstAmt,cgstRate:de.cgstRate,cgstAmt:de.cgstAmt,sgstRate:de.sgstRate,sgstAmt:de.sgstAmt,igstRate:de.igstRate,igstAmt:de.igstAmt,utgstRate:de.utgstRate,utgstAmt:de.utgstAmt,cessRate:de.cessRate,cessAmt:de.cessAmt,totalAmt:de.totalAmt}));if(await VA(ie,{activityCompletionDate:B.activityCompletionDate,numberOfParticipants:B.numberOfParticipants,closedExpenses:he,totalClosedExpenses:B.totalClosedExpenses,completionDocuments:B.completionDocuments,activityPhotos:B.activityPhotos,completionDescription:B.completionDescription}),B.invoicesReceipts&&B.invoicesReceipts.length>0)for(const de of B.invoicesReceipts)await nn(de,ie,"SUPPORTING");B.attendanceSheet&&await nn(B.attendanceSheet,ie,"SUPPORTING"),K.success("Completion documents submitted successfully"),W()}catch(ie){console.error("Failed to submit completion documents:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to submit completion documents. Please try again.";throw K.error(he),ie}},qe=async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=new Date().toISOString().slice(0,10);await HA(ie,{eInvoiceDate:he}),K.success("E-Invoice generation initiated successfully."),W()}catch(ie){console.error("[DealerClaimWorkflowTab] Error generating e-invoice:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to generate e-invoice. Please try again.";throw K.error(he),ie}},fs=async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=await vs(ie),de=(he==null?void 0:he.approvalLevels)||(he==null?void 0:he.approvals)||[],Se=de.find(ve=>(ve.levelName||ve.level_name||"").toLowerCase().includes("department lead"))||de.find(ve=>(ve.levelNumber||ve.level_number)===3);if(!(Se!=null&&Se.levelId)&&!(Se!=null&&Se.level_id))throw new Error("Department Lead approval level not found");const Ne=Se.levelId||Se.level_id;await Sr(ie,Ne,"Dept Lead rejected - More clarification required",B),K.success("Request rejected. Request has been cancelled."),W()}catch(ie){console.error("Failed to reject request:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to reject request. Please try again.";throw K.error(he),ie}},[Ht,at]=p.useState(null);p.useEffect(()=>{if(!t){at(null);return}(async()=>{try{const Ie=t.id||t.requestId;if(!Ie){at(null);return}const xe=await vs(Ie),ie=(xe==null?void 0:xe.documents)||[],he=t.proposalDetails||(xe==null?void 0:xe.proposalDetails)||{},de=ie.find(ve=>ve.category==="APPROVAL"||ve.type==="proposal"||ve.documentCategory==="APPROVAL"),Se=ie.filter(ve=>ve.category==="SUPPORTING"||ve.type==="supporting"||ve.documentCategory==="SUPPORTING");let Ne=he.costBreakup||[];if(typeof Ne=="string")try{Ne=JSON.parse(Ne)}catch(ve){console.warn("Failed to parse costBreakup JSON:",ve),Ne=[]}Array.isArray(Ne)||(Ne=[]),at({proposalDocument:de?{name:de.fileName||de.file_name||de.name,id:de.documentId||de.document_id||de.id}:void 0,costBreakup:Ne,expectedCompletionDate:he.expectedCompletionDate||"",otherDocuments:Se.map(ve=>({name:ve.fileName||ve.file_name||ve.name,id:ve.documentId||ve.document_id||ve.id})),dealerComments:he.dealerComments||"",submittedAt:he.submittedAt})}catch(Ie){console.warn("Failed to load proposal data:",Ie);const xe=t.proposalDetails||{};let ie=xe.costBreakup||[];if(typeof ie=="string")try{ie=JSON.parse(ie)}catch(he){console.warn("Failed to parse costBreakup JSON:",he),ie=[]}Array.isArray(ie)||(ie=[]),at({proposalDocument:void 0,costBreakup:ie,expectedCompletionDate:xe.expectedCompletionDate||"",otherDocuments:[],dealerComments:xe.dealerComments||"",submittedAt:xe.submittedAt})}})()},[t]);const[et,yt]=p.useState(null);p.useEffect(()=>{if(!t){yt(null);return}(async()=>{try{const Ie=t.id||t.requestId;if(!Ie){yt(null);return}const xe=await vs(Ie),ie=(xe==null?void 0:xe.documents)||[],he=[],de=[],Se=[];let Ne=null;ie.forEach(ve=>{const bt=(ve.category||ve.documentCategory||ve.type||"").toUpperCase(),xt=(ve.fileName||ve.file_name||ve.name||"").toLowerCase(),ls={name:ve.fileName||ve.file_name||ve.name,id:ve.documentId||ve.document_id||ve.id,url:ve.url||ve.storageUrl||ve.storage_url};bt==="COMPLETION"||bt==="COMPLETION_DOCUMENT"?he.push(ls):bt==="ACTIVITY_PHOTO"||bt==="PHOTO"||bt==="IMAGE"?de.push(ls):bt==="ATTENDANCE"||bt==="ATTENDANCE_SHEET"?Ne=ls:(bt==="SUPPORTING"||bt==="INVOICE"||bt==="RECEIPT")&&(!Ne&&(xt.includes("attendance")||xt.includes("participant"))?Ne=ls:Se.push(ls))}),he.length===0&&de.length===0&&t.completionDetails,yt({completionDocuments:he,activityPhotos:de,invoicesReceipts:Se,attendanceSheet:Ne})}catch(Ie){console.warn("Failed to load completion documents:",Ie),yt(null)}})()},[t]);const rs=async()=>{try{const B=t.id||t.requestId;if(!B){K.error("Request ID not found");return}if(!t.invoice&&!t.irn){K.error("Invoice not generated yet");return}const Ie=tt.getAccessToken(),xe=`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${B}/e-invoice/pdf?token=${Ie}`;window.open(xe,"_blank")}catch(B){console.error("Failed to preview invoice:",B),K.error("Failed to open invoice preview")}},Pt=((_a=t==null?void 0:t.claimDetails)==null?void 0:_a.dealerName)||((ga=t==null?void 0:t.dealerInfo)==null?void 0:ga.name)||"Dealer",la=((La=t==null?void 0:t.claimDetails)==null?void 0:La.activityName)||((It=t==null?void 0:t.activityInfo)==null?void 0:It.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(ee,{children:[e.jsx(ge,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx($e,{className:"mt-2",children:"Approval process for dealer claim management"})]})})}),e.jsxs(se,{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(as,{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:Ee.map((B,Ie)=>{var xt,ls,jt,da,ds;const ie=(((xt=B.status)==null?void 0:xt.toLowerCase())||"")==="in_progress",he=B.step===q,de=Q&&ie&&he,Se=B.status==="approved",Ne=j.find(le=>(le.step||le.levelNumber||le.level_number)===B.step),ve=Ne!=null&&Ne.levelId?(ls=t==null?void 0:t.approvals)==null?void 0:ls.find(le=>le.levelId===Ne.levelId||le.level_id===Ne.levelId):null,bt=(ve==null?void 0:ve.status)==="PAUSED"||((jt=t==null?void 0:t.pauseInfo)==null?void 0:jt.isPaused)&&(((da=t==null?void 0:t.pauseInfo)==null?void 0:da.levelId)===(ve==null?void 0:ve.levelId)||((ds=t==null?void 0:t.pauseInfo)==null?void 0:ds.level_id)===(ve==null?void 0:ve.levelId));return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${XA(B.status,de)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${ZA(B.status)}`,children:YA(B.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:B.title}),e.jsx(ne,{className:KA(B.status),children:B.status.toLowerCase()}),B.emailTemplateUrl&&B.status==="approved"&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>{k({stepNumber:B.step,stepName:B.title}),w(!0)},children:e.jsx(Ra,{className:"w-3.5 h-3.5 text-blue-600"})}),B.step===7&&B.einvoiceUrl&&Se&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",title:"Download E-Invoice",onClick:()=>window.open(B.einvoiceUrl,"_blank"),children:e.jsx(Ct,{className:"w-3.5 h-3.5 text-green-600"})}),(()=>{const le=(B.levelName||B.title||"").toLowerCase().includes("requestor claim")||(B.levelName||B.title||"").toLowerCase().includes("requestor - claim"),ct=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&B.status==="approved";return le&&ct&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-amber-100",title:"Preview Invoice",onClick:rs,children:e.jsx(Gt,{className:"w-3.5 h-3.5 text-amber-600"})})})()]}),e.jsx("p",{className:"text-sm text-gray-600",children:B.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:B.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",Ft(B.tatHours)]}),B.elapsedHours&&(de||Se)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",Ft(B.elapsedHours)]})]})]}),B.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:B.comment})}),B.versionHistory&&B.versionHistory.all&&B.versionHistory.all.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsxs(E,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs text-amber-700 hover:text-amber-800 hover:bg-amber-50",onClick:()=>{const le=new Set(F);le.has(B.step)?le.delete(B.step):le.add(B.step),$(le)},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"}),B.versionHistory.all&&B.versionHistory.all.length>0&&e.jsxs(ne,{className:"bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0",children:[B.versionHistory.all.length," Versions"]})]}),F.has(B.step)?e.jsx(Xu,{className:"w-4 h-4"}):e.jsx(uo,{className:"w-4 h-4"})]}),F.has(B.step)&&B.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:B.versionHistory.all.map((le,ct)=>{var Ut,ms,Nt,Pe;return e.jsxs("div",{className:`space-y-2 ${ct>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:`${ct===0?"bg-amber-500":"bg-gray-400"} text-white text-[10px] px-2 py-0.5`,children:[ct===0?"Current":"Previous",": v",le.version]}),e.jsx("span",{className:"text-[10px] text-gray-600 font-medium",children:Cr(le.createdAt)})]})}),e.jsx("p",{className:"text-xs text-gray-700 font-medium",children:le.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${ct===0?"bg-blue-100":"bg-gray-100"} flex items-center justify-center`,children:e.jsx("span",{className:`text-[8px] font-bold ${ct===0?"text-blue-600":"text-gray-600"}`,children:((ms=(Ut=le.changer)==null?void 0:Ut.displayName)==null?void 0:ms.charAt(0))||"U"})}),e.jsxs("span",{className:"text-[10px] text-gray-600",children:["By ",((Nt=le.changer)==null?void 0:Nt.displayName)||((Pe=le.changer)==null?void 0:Pe.email)||"Unknown User"]})]}),le.snapshotType==="PROPOSAL"&&le.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(le.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:()=>T({data:le.snapshotData,type:"PROPOSAL",title:`Proposal (v${le.version})`}),children:[e.jsx(ht,{className:"w-3 h-3"}),"View Details"]})]}),le.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",le.snapshotData.comments]})]}),le.snapshotType==="INTERNAL_ORDER"&&le.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: ",le.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Blocked Amount: ₹",Number(le.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),le.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-[10px] text-gray-600",children:["SAP Doc: ",le.snapshotData.sapDocumentNumber]})]}),le.snapshotType==="COMPLETION"&&le.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(le.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:()=>T({data:le.snapshotData,type:"COMPLETION",title:`Completion (v${le.version})`}),children:[e.jsx(ht,{className:"w-3 h-3"}),"View Details"]})]}),le.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",le.snapshotData.comments]})]}),le.snapshotType==="APPROVE"&&le.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:[le.snapshotData.action==="APPROVE"?"Approval":"Rejection"," Snapshot:"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["By: ",le.snapshotData.approverName||le.snapshotData.approverEmail||"Unknown"]}),le.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1",children:["Comments: ",le.snapshotData.comments.substring(0,100),le.snapshotData.comments.length>100?"...":""]}),le.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-[10px] text-red-600 mt-1",children:["Rejection Reason: ",le.snapshotData.rejectionReason.substring(0,100),le.snapshotData.rejectionReason.length>100?"...":""]})]}),le.snapshotType==="WORKFLOW"&&le.snapshotData&&le.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:[le.snapshotData.comments.substring(0,100),le.snapshotData.comments.length>100?"...":""]})]})]},ct)})})]}),de&&(ve==null?void 0:ve.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:ve.sla.deadline?xa(ve.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${bt?"bg-gray-100 border-gray-300":(ve.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(ve.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(ve.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(st,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",bt&&"(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:ve.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:[ve.sla.elapsedText||"0 hours"," / ",Ft(B.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const le=ve.sla.percentageUsed||0,ct=()=>bt?"bg-gray-500":le>=100?"bg-red-600":le>=75?"bg-orange-500":le>=50?"bg-amber-500":"bg-green-600",Ut=()=>bt?"text-gray-600":le>=100?"text-red-600":le>=75?"text-orange-600":le>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(na,{value:le,className:"h-3",indicatorClassName:ct()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${Ut()}`,children:["Progress: ",Math.min(100,le),"% of TAT used"]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[ve.sla.remainingText||"0 hours"," remaining"]})]})]})})(),ve.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(ni,{className:"w-4 h-4"}),"Deadline Breached"]}),ve.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(as,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),(()=>{const le=B.levelName||B.level_name;return(le&&le.toLowerCase().includes("department lead")||B.title&&B.title.toLowerCase().includes("department lead"))&&B.status==="approved"&&B.ioDetails&&B.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(Gt,{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:B.ioDetails.ioNumber})]}),B.ioDetails.blockedAmount!==void 0&&B.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:["₹",B.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),B.ioDetails.remainingBalance!==void 0&&B.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:["₹",B.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 ",B.ioDetails.organizedBy||B.approver||"N/A"," on"," ",B.ioDetails.organizedAt?Cr(B.ioDetails.organizedAt):B.approvedAt?Cr(B.approvedAt):"N/A"]})]})]})})(),B.step===6&&B.dmsDetails&&B.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(kt,{className:"w-4 h-4 text-purple-600"}),e.jsx("p",{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice & Settlement Details"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"Settlement ID:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:B.dmsDetails.dmsNumber})]}),B.dmsDetails.dmsRemarks&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Settlement Remarks:"}),e.jsx("p",{className:"text-sm text-gray-900",children:B.dmsDetails.dmsRemarks})]}),B.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Initiated by ",B.dmsDetails.pushedBy," on"," ",Cr(B.dmsDetails.pushedAt)]})]})]}),(()=>{const le=j.find(Pe=>(Pe.step||Pe.levelNumber||Pe.level_number)===B.step),ct=((le==null?void 0:le.approverEmail)||"").toLowerCase(),Ut=ct&&ue===ct,ms=B.step===1||(le==null?void 0:le.levelName)&&le.levelName.toLowerCase().includes("dealer");return de&&(Ut||ms&&Ue)})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[(()=>{const le=((Ne==null?void 0:Ne.levelName)||B.title||"").toLowerCase();return(B.step===1||le.includes("proposal")||le.includes("submission"))&&(Ue||Xa)})()&&e.jsxs(E,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{o(!0)},children:[e.jsx(zs,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),(()=>{const le=((Ne==null?void 0:Ne.levelName)||B.title||"").toLowerCase();return(le.includes("requestor evaluation")||le.includes("confirmation")||B.step===rt)&&(a||Ps)})()&&e.jsxs(E,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{d(!0)},children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const le=j.find(Pe=>(Pe.step||Pe.levelNumber||Pe.level_number)===B.step);if(!((le==null?void 0:le.levelName)||B.title||"").toLowerCase().includes("initiator action")||!(a||ue===pe))return null;const Nt=async Pe=>{var bs,_t;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const us=t.requestId||t.id;await Gx(us,Pe,{reason:""}),K.success(`Action "${Pe==="REVISE"?"Revision Requested":"Request Reopened"}" performed successfully`),W()}catch(us){console.error("Failed to perform initiator action:",us);const vg=((_t=(bs=us==null?void 0:us.response)==null?void 0:bs.data)==null?void 0:_t.message)||(us==null?void 0:us.message)||"Failed to perform action";K.error(vg)}};return e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(E,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:()=>Nt("REVISE"),children:[e.jsx($t,{className:"w-4 h-4 mr-2"}),"Request Re-quotation"]}),e.jsxs(E,{variant:"outline",className:"border-blue-500 text-blue-600 hover:bg-blue-50",onClick:()=>Nt("REOPEN"),children:[e.jsx(tx,{className:"w-4 h-4 mr-2"}),"Reopen"]})]})})(),(()=>{const le=j.find(_t=>(_t.levelName||"").toLowerCase().includes("department lead"));if(!(le&&B.step===(le.step||le.levelNumber||le.level_number)))return null;const Ut=((le==null?void 0:le.approverEmail)||"").toLowerCase();if(!(Ut&&ue===Ut||J||Xe))return null;const Nt=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),Pe=(Nt==null?void 0:Nt.ioNumber)||(Nt==null?void 0:Nt.io_number)||(t==null?void 0:t.ioNumber)||"",bs=Pe&&Pe.trim()!=="";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(E,{className:"bg-green-600 hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>{h(!0)},disabled:!bs,children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Review and Approve"]}),!bs&&e.jsx("p",{className:"text-xs text-amber-600",children:"Please add an IO number in the IO tab before approving this step."})]})})(),(()=>{const le=j.find(Pe=>(Pe.step||Pe.levelNumber||Pe.level_number)===B.step),ct=((le==null?void 0:le.approverEmail)||"").toLowerCase(),Ut=Ue&&ct===Ae,ms=((le==null?void 0:le.levelName)||B.title||"").toLowerCase(),Nt=ms.includes("dealer completion")||ms.includes("completion documents");return Ut&&Nt})()&&e.jsxs(E,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{u(!0)},children:[e.jsx(zs,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const le=j.find(Nt=>{const Pe=(Nt.levelName||"").toLowerCase();return Pe.includes("requestor claim")||Pe.includes("requestor - claim")});if(!(le&&B.step===(le.step||le.levelNumber||le.level_number)))return null;const Ut=((le==null?void 0:le.approverEmail)||"").toLowerCase();return a||Ut&&ue===Ut?e.jsxs(E,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{b(!0)},children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Generate E-Invoice & Sync"]}):null})(),(()=>{var bs;const le=((Ne==null?void 0:Ne.levelName)||B.title||"").toLowerCase(),ct=le.includes("credit note")||le.includes("sap")||B.step===8&&!le.includes("additional"),Ut=((Ne==null?void 0:Ne.approverEmail)||"").toLowerCase(),ms=Ut&&ue===Ut,Nt=((bs=s==null?void 0:s.role)==null?void 0:bs.toUpperCase())||"";return ct&&(ms||(Nt==="FINANCE"||Nt==="ADMIN"))})()&&e.jsxs(E,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{y(!0)},children:[e.jsx(Gt,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]}),(()=>{const le=j.find(Nt=>(Nt.step||Nt.levelNumber||Nt.level_number)===B.step),ct=((le==null?void 0:le.levelName)||B.title||"").toLowerCase(),Ut=ct.includes("additional approver"),ms=B.step===1||ct.includes("proposal")||ct.includes("submission")||ct.includes("requestor evaluation")||ct.includes("confirmation")||ct.includes("department lead")||ct.includes("dealer completion")||ct.includes("completion documents")||ct.includes("requestor claim")||ct.includes("requestor - claim")||ct.includes("credit note")||ct.includes("sap");if(Ut||!ms){const Nt=(le==null?void 0:le.levelId)||(le==null?void 0:le.level_id);if(Nt){const Pe=(le==null?void 0:le.levelName)||(le==null?void 0:le.level_name)||B.title||"Approval Level",bs=(le==null?void 0:le.approverName)||(le==null?void 0:le.approver_name)||B.approver||"Approver";return e.jsxs(E,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{A({levelId:Nt,levelName:Pe,approverName:bs}),_(!0)},children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Review Request"]})}return e.jsxs(e.Fragment,{children:[e.jsxs(E,{className:"bg-green-600 hover:bg-green-700",onClick:async()=>{var Pe,bs;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const _t=t.id||t.requestId;if(!Nt){K.error("Approval level not found");return}await an(_t,Nt,""),K.success("Request approved successfully"),W()}catch(_t){console.error("Failed to approve:",_t);const us=((bs=(Pe=_t==null?void 0:_t.response)==null?void 0:Pe.data)==null?void 0:bs.message)||(_t==null?void 0:_t.message)||"Failed to approve request. Please try again.";K.error(us)}},children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(E,{variant:"destructive",onClick:async()=>{var Pe,bs;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const _t=t.id||t.requestId;if(!Nt){K.error("Approval level not found");return}const us=prompt("Please provide a reason for rejection:");if(us===null)return;await Sr(_t,Nt,"Request rejected",us),K.success("Request rejected successfully"),W()}catch(_t){console.error("Failed to reject:",_t);const us=((bs=(Pe=_t==null?void 0:_t.response)==null?void 0:Pe.data)==null?void 0:bs.message)||(_t==null?void 0:_t.message)||"Failed to reject request. Please try again.";K.error(us)}},children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),B.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",Cr(B.approvedAt)]})]})]})},Ie)})})]})]}),e.jsx(EA,{isOpen:l,onClose:()=>o(!1),onSubmit:Le,dealerName:Pt,activityName:la,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),previousProposalData:(ns=N==null?void 0:N.find(B=>B.snapshotType==="PROPOSAL"))==null?void 0:ns.snapshotData,documentPolicy:i}),e.jsx(MA,{isOpen:c,onClose:()=>{d(!1)},onApprove:Fe,onReject:Ve,onRequestRevision:Me,proposalData:Ht,dealerName:Pt,activityName:la,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const B=(N==null?void 0:N.filter(Ie=>Ie.snapshotType==="PROPOSAL"))||[];return B.length>1?B[1].snapshotData:null})()}),e.jsx(FA,{isOpen:m,onClose:()=>h(!1),onApprove:Ze,onReject:fs,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((Os=t==null?void 0:t.internalOrder)==null?void 0:Os.ioNumber)||((sr=t==null?void 0:t.internalOrder)==null?void 0:sr.io_number)||((ar=t==null?void 0:t.internal_order)==null?void 0:ar.ioNumber)||((oa=t==null?void 0:t.internal_order)==null?void 0:oa.io_number)||void 0,preFilledBlockedAmount:((vt=t==null?void 0:t.internalOrder)==null?void 0:vt.ioBlockedAmount)||((is=t==null?void 0:t.internalOrder)==null?void 0:is.io_blocked_amount)||((Is=t==null?void 0:t.internal_order)==null?void 0:Is.ioBlockedAmount)||((Zs=t==null?void 0:t.internal_order)==null?void 0:Zs.io_blocked_amount)||void 0,preFilledRemainingBalance:((Nr=t==null?void 0:t.internalOrder)==null?void 0:Nr.ioRemainingBalance)||((ca=t==null?void 0:t.internalOrder)==null?void 0:ca.io_remaining_balance)||((Ma=t==null?void 0:t.internal_order)==null?void 0:Ma.ioRemainingBalance)||((Kr=t==null?void 0:t.internal_order)==null?void 0:Kr.io_remaining_balance)||void 0}),e.jsx(IA,{isOpen:x,onClose:()=>u(!1),onSubmit:Be,dealerName:Pt,activityName:la,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i}),e.jsx(_A,{isOpen:g,onClose:()=>b(!1),onPush:qe,completionDetails:{activityCompletionDate:((Xr=t==null?void 0:t.completionDetails)==null?void 0:Xr.activityCompletionDate)||((Zr=t==null?void 0:t.completionDetails)==null?void 0:Zr.activity_completion_date),numberOfParticipants:((yc=t==null?void 0:t.completionDetails)==null?void 0:yc.numberOfParticipants)||((vc=t==null?void 0:t.completionDetails)==null?void 0:vc.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((jc=t==null?void 0:t.completionDetails)==null?void 0:jc.closedExpenses)||((Nc=t==null?void 0:t.completionDetails)==null?void 0:Nc.closed_expenses),totalClosedExpenses:((wc=t==null?void 0:t.budgetTracking)==null?void 0:wc.closedExpenses)||((Cc=t==null?void 0:t.budgetTracking)==null?void 0:Cc.closed_expenses)||((Sc=t==null?void 0:t.completionDetails)==null?void 0:Sc.totalClosedExpenses)||((Ac=t==null?void 0:t.completionDetails)==null?void 0:Ac.total_closed_expenses),completionDescription:((Tc=t==null?void 0:t.completionDetails)==null?void 0:Tc.completionDescription)||((kc=t==null?void 0:t.completionDetails)==null?void 0:kc.completion_description)},ioDetails:{ioNumber:((Rc=t==null?void 0:t.internalOrder)==null?void 0:Rc.ioNumber)||((Dc=t==null?void 0:t.internalOrder)==null?void 0:Dc.io_number)||((Pc=t==null?void 0:t.internal_order)==null?void 0:Pc.ioNumber)||((Ic=t==null?void 0:t.internal_order)==null?void 0:Ic.io_number),blockedAmount:((Ec=t==null?void 0:t.internalOrder)==null?void 0:Ec.ioBlockedAmount)||((Fc=t==null?void 0:t.internalOrder)==null?void 0:Fc.io_blocked_amount)||((_c=t==null?void 0:t.internal_order)==null?void 0:_c.ioBlockedAmount)||((Lc=t==null?void 0:t.internal_order)==null?void 0:Lc.io_blocked_amount),availableBalance:((Mc=t==null?void 0:t.internalOrder)==null?void 0:Mc.ioAvailableBalance)||(($c=t==null?void 0:t.internalOrder)==null?void 0:$c.io_available_balance)||((Oc=t==null?void 0:t.internal_order)==null?void 0:Oc.ioAvailableBalance)||((Uc=t==null?void 0:t.internal_order)==null?void 0:Uc.io_available_balance),remainingBalance:((Bc=t==null?void 0:t.internalOrder)==null?void 0:Bc.ioRemainingBalance)||((Vc=t==null?void 0:t.internalOrder)==null?void 0:Vc.io_remaining_balance)||((zc=t==null?void 0:t.internal_order)==null?void 0:zc.ioRemainingBalance)||((Hc=t==null?void 0:t.internal_order)==null?void 0:Hc.io_remaining_balance)},completionDocuments:et,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(PA,{isOpen:f,onClose:()=>y(!1),onDownload:async()=>{K.info("Download functionality will be implemented")},onSendToDealer:async()=>{var B,Ie;try{const xe=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!xe){K.error("Request ID not found");return}await WA(xe),K.success("Credit note sent to dealer successfully. Step 8 has been approved."),n&&n()}catch(xe){console.error("Failed to send credit note to dealer:",xe);const ie=((Ie=(B=xe==null?void 0:xe.response)==null?void 0:B.data)==null?void 0:Ie.message)||(xe==null?void 0:xe.message)||"Failed to send credit note to dealer";K.error(ie)}},creditNoteData:{creditNoteNumber:((Wc=t==null?void 0:t.creditNote)==null?void 0:Wc.creditNoteNumber)||((Gc=t==null?void 0:t.creditNote)==null?void 0:Gc.credit_note_number)||((Kc=(Yc=t==null?void 0:t.claimDetails)==null?void 0:Yc.creditNote)==null?void 0:Kc.creditNoteNumber)||((Xc=t==null?void 0:t.claimDetails)==null?void 0:Xc.creditNoteNumber)||((Zc=t==null?void 0:t.claimDetails)==null?void 0:Zc.credit_note_number),creditNoteDate:((Jc=t==null?void 0:t.creditNote)==null?void 0:Jc.creditNoteDate)||((Qc=t==null?void 0:t.creditNote)==null?void 0:Qc.credit_note_date)||((ed=(qc=t==null?void 0:t.claimDetails)==null?void 0:qc.creditNote)==null?void 0:ed.creditNoteDate)||((td=t==null?void 0:t.claimDetails)==null?void 0:td.creditNoteDate)||((sd=t==null?void 0:t.claimDetails)==null?void 0:sd.credit_note_date),creditNoteAmount:(ad=t==null?void 0:t.creditNote)!=null&&ad.creditNoteAmount?Number((rd=t==null?void 0:t.creditNote)==null?void 0:rd.creditNoteAmount):(nd=t==null?void 0:t.creditNote)!=null&&nd.credit_note_amount?Number((id=t==null?void 0:t.creditNote)==null?void 0:id.credit_note_amount):(od=(ld=t==null?void 0:t.claimDetails)==null?void 0:ld.creditNote)!=null&&od.creditNoteAmount?Number((dd=(cd=t==null?void 0:t.claimDetails)==null?void 0:cd.creditNote)==null?void 0:dd.creditNoteAmount):(md=t==null?void 0:t.claimDetails)!=null&&md.creditNoteAmount?Number((ud=t==null?void 0:t.claimDetails)==null?void 0:ud.creditNoteAmount):(xd=t==null?void 0:t.claimDetails)!=null&&xd.credit_note_amount?Number((hd=t==null?void 0:t.claimDetails)==null?void 0:hd.credit_note_amount):void 0,status:((pd=t==null?void 0:t.creditNote)==null?void 0:pd.status)||((fd=(gd=t==null?void 0:t.claimDetails)==null?void 0:gd.creditNote)==null?void 0:fd.status)||((bd=t==null?void 0:t.creditNote)!=null&&bd.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((yd=t==null?void 0:t.claimDetails)==null?void 0:yd.dealerName)||((vd=t==null?void 0:t.claimDetails)==null?void 0:vd.dealer_name),dealerCode:((jd=t==null?void 0:t.claimDetails)==null?void 0:jd.dealerCode)||((Nd=t==null?void 0:t.claimDetails)==null?void 0:Nd.dealer_code),dealerEmail:((wd=t==null?void 0:t.claimDetails)==null?void 0:wd.dealerEmail)||((Cd=t==null?void 0:t.claimDetails)==null?void 0:Cd.dealer_email)},activityName:((Sd=t==null?void 0:t.claimDetails)==null?void 0:Sd.activityName)||((Ad=t==null?void 0:t.claimDetails)==null?void 0:Ad.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(LA,{isOpen:v,onClose:()=>{w(!1),k(null)},stepNumber:(C==null?void 0:C.stepNumber)||4,stepName:(C==null?void 0:C.stepName)||"Activity Creation",requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.id)||(t==null?void 0:t.request_number),recipientEmail:"system@undefined"}),D&&e.jsx(DA,{isOpen:S,onClose:()=>{_(!1),A(null)},onApprove:async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=D.levelId;if(!he){K.error("Approval level not found");return}await an(ie,he,B),K.success("Request approved successfully"),W(),_(!1),A(null)}catch(ie){console.error("Failed to approve:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to approve request. Please try again.";throw K.error(he),ie}},onReject:async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=D.levelId;if(!he){K.error("Approval level not found");return}await Sr(ie,he,"Request rejected",B),K.success("Request rejected successfully"),W(),_(!1),A(null)}catch(ie){console.error("Failed to reject:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to reject request. Please try again.";throw K.error(he),ie}},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(ee,{className:"mt-6 border-amber-100 bg-amber-50/30",children:[e.jsxs(ge,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(fe,{className:"text-sm font-bold flex items-center gap-2 text-amber-900",children:[e.jsx(kt,{className:"w-4 h-4"}),"Revision History & Audit Trail"]}),e.jsx(E,{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($e,{className:"text-xs text-amber-700",children:"Records of all revisions and actions taken on this request"})]}),R&&e.jsx(se,{children:e.jsx("div",{className:"space-y-4",children:N.map((B,Ie)=>{var xe,ie,he,de;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 ",B.version]}),B.snapshotType&&e.jsx(ne,{className:"bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0",children:B.snapshotType}),B.levelNumber&&e.jsxs(ne,{className:"bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0",children:["Step ",B.levelNumber]})]}),e.jsx("span",{className:"text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full",children:Cr(B.createdAt)})]}),e.jsx("p",{className:"text-xs font-medium text-gray-800",children:B.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:((ie=(xe=B.changer)==null?void 0:xe.displayName)==null?void 0:ie.charAt(0))||"U"})}),e.jsxs("span",{className:"text-xs text-gray-500",children:["By ",((he=B.changer)==null?void 0:he.displayName)||((de=B.changer)==null?void 0:de.email)||"Unknown User"]})]}),B.snapshotType==="PROPOSAL"&&B.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:"}),B.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(E,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-small flex items-center gap-1",onClick:()=>T({data:B.snapshotData,type:"PROPOSAL",title:`Historical Proposal (Version ${B.version})`}),children:["View Details",e.jsx(ht,{className:"w-2 h-2"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Budget: ₹",Number(B.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),B.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",B.snapshotData.comments.substring(0,80),B.snapshotData.comments.length>80?"...":""]})]}),B.snapshotType==="COMPLETION"&&B.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:"}),B.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(E,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-medium flex items-center gap-1",onClick:()=>T({data:B.snapshotData,type:"COMPLETION",title:`Historical Completion (Version ${B.version})`}),children:["View Details",e.jsx(ht,{className:"w-3 h-3"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Total Expenses: ₹",Number(B.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),B.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",B.snapshotData.comments.substring(0,80),B.snapshotData.comments.length>80?"...":""]})]}),B.snapshotType==="INTERNAL_ORDER"&&B.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: ",B.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-gray-600",children:["Blocked: ₹",Number(B.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),B.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-gray-600",children:["SAP Doc: ",B.snapshotData.sapDocumentNumber]})]}),B.snapshotType==="APPROVE"&&B.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:[B.snapshotData.action==="APPROVE"?"Approval":"Rejection",":"]}),e.jsxs("p",{className:"text-gray-600",children:["By: ",B.snapshotData.approverName||B.snapshotData.approverEmail||"Unknown"]}),B.snapshotData.levelName&&e.jsxs("p",{className:"text-gray-600",children:["Level: ",B.snapshotData.levelName]}),B.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",B.snapshotData.comments.substring(0,80),B.snapshotData.comments.length>80?"...":""]}),B.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-red-600 mt-1",children:["Rejection Reason: ",B.snapshotData.rejectionReason.substring(0,80),B.snapshotData.rejectionReason.length>80?"...":""]})]}),B.snapshotType==="WORKFLOW"&&B.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: ",B.snapshotData.status||"N/A"]}),B.snapshotData.currentLevel&&e.jsxs("p",{className:"text-gray-600",children:["Current Level: ",B.snapshotData.currentLevel]})]})]})]},B.historyId||Ie)})})})]}),e.jsx($A,{isOpen:!!V,onClose:()=>T(null),snapshot:V==null?void 0:V.data,type:(V==null?void 0:V.type)||"PROPOSAL",title:V==null?void 0:V.title})]})}function QA({request:t,apiRequest:s,onRefresh:a}){const{user:r}=Kt(),n=(s==null?void 0:s.requestId)||(t==null?void 0:t.requestId),i=(s==null?void 0:s.internalOrder)||(s==null?void 0:s.internal_order)||null,l=(i==null?void 0:i.ioNumber)||(i==null?void 0:i.io_number)||(t==null?void 0:t.ioNumber)||"",o=(i==null?void 0:i.ioBlockedAmount)||(i==null?void 0:i.io_blocked_amount)||0,c=(i==null?void 0:i.ioAvailableBalance)||(i==null?void 0:i.io_available_balance)||0,d=(i==null?void 0:i.ioRemainingBalance)||(i==null?void 0:i.io_remaining_balance)||0,m=(i==null?void 0:i.sapDocumentNumber)||(i==null?void 0:i.sap_document_number)||"",h=(i==null?void 0:i.organizer)||null,x=(s==null?void 0:s.proposalDetails)||{},u=Number((x==null?void 0:x.totalEstimatedBudget)||(x==null?void 0:x.total_estimated_budget)||0),[g,b]=p.useState(l),[f,y]=p.useState(!1),[v,w]=p.useState(null),[C,k]=p.useState(""),[S,_]=p.useState(null),[D,A]=p.useState(!1);p.useEffect(()=>{if(i&&l){const R=Number(c)||0,O=(h==null?void 0:h.displayName)||(h==null?void 0:h.display_name)||(h==null?void 0:h.name)||(h!=null&&h.firstName&&(h!=null&&h.lastName)?`${h.firstName} ${h.lastName}`.trim():null)||(h==null?void 0:h.email)||"Unknown User";if(b(l),o>0){const F=Number(o)||0,$=Number(d)||0,V=R-F;Math.abs($-V)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:R,blockedAmount:F,expectedRemaining:V,backendRemaining:$,difference:$-V}),_({ioNumber:l,blockedAmount:F,availableBalance:R,remainingBalance:$,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&&w(R)}}},[i,l,o,c,d,m,h]);const N=async()=>{var R,O;if(!g.trim()){K.error("Please enter an IO number");return}if(!n){K.error("Request ID not found");return}y(!0);try{const F=await zA(n,g.trim());F.isValid&&F.availableBalance>0?(w(F.availableBalance),u>0?k(String(u)):k(String(F.availableBalance)),K.success(`IO fetched from SAP. Available balance: ₹${F.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)):(K.error("Invalid IO number or no available balance found"),w(null),k(""))}catch(F){console.error("Failed to fetch IO budget:",F);const $=((O=(R=F==null?void 0:F.response)==null?void 0:R.data)==null?void 0:O.message)||(F==null?void 0:F.message)||"Failed to validate IO number or fetch budget from SAP";K.error($),w(null)}finally{y(!1)}},P=async()=>{var F,$;if(!g.trim()||v===null){K.error("Please fetch IO amount first");return}if(!n){K.error("Request ID not found");return}const R=parseFloat(C);if(!C||isNaN(R)||R<=0){K.error("Please enter a valid amount to block");return}const O=parseFloat(R.toFixed(2));if(O>v){K.error("Amount to block exceeds available IO budget");return}if(u>0){const V=parseFloat(u.toFixed(2));if(Math.abs(O-V)>.01){K.error(`Amount to block must be exactly equal to the estimated budget (₹${V.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})})`);return}}A(!0);try{const V=parseFloat(v.toFixed(2)),T=parseFloat((V-O).toFixed(2)),j={ioNumber:g.trim(),ioAvailableBalance:V,ioBlockedAmount:O,ioRemainingBalance:T};await Zp(n,j);const U=await UA(n),I=(U==null?void 0:U.internalOrder)||(U==null?void 0:U.internal_order);if(I){const M=Number(I.ioBlockedAmount||I.io_blocked_amount||O),W=Number(I.ioRemainingBalance||I.io_remaining_balance||0),G=v-M;Math.abs(M-O)>.01&&console.warn("[IOTab] ⚠️ Amount mismatch! Sent:",O,"Saved:",M),Math.abs(W-G)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:v,blockedAmount:M,expectedRemaining:G,backendRemaining:W,difference:W-G});const ce=r,te=(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",L={ioNumber:I.ioNumber||I.io_number||g,blockedAmount:M,availableBalance:v,remainingBalance:W,blockedDate:I.organizedAt||I.organized_at||new Date().toISOString(),blockedBy:te,sapDocumentNumber:I.sapDocumentNumber||I.sap_document_number||"",status:"blocked"};_(L),k(""),K.success("IO budget blocked successfully in SAP"),a==null||a()}else K.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(V){console.error("Failed to block IO budget:",V);const T=(($=(F=V==null?void 0:V.response)==null?void 0:F.data)==null?void 0:$.message)||(V==null?void 0:V.message)||"Failed to block IO budget in SAP";K.error(T)}finally{A(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx($e,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Oe,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:g,onChange:R=>b(R.target.value),disabled:f||!!S,className:"flex-1"}),e.jsxs(E,{onClick:N,disabled:!g.trim()||f||!!S,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),f?"Fetching...":"Fetch Amount"]})]})]}),!v&&!S&&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&&!S&&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(re,{htmlFor:"blockAmount",children:"Amount to Block *"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",children:"₹"}),e.jsx(Oe,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:C,onChange:R=>k(R.target.value),className:"pl-8"})]}),u>0&&e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-xs text-amber-800",children:[e.jsx("strong",{children:"Required:"})," Amount must be exactly equal to the estimated budget: ",e.jsxs("strong",{children:["₹",u.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs(E,{onClick:P,disabled:D||!C||parseFloat(C)<=0||parseFloat(C)>v||u>0&&Math.abs(parseFloat(C)-u)>.01,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Ot,{className:"w-4 h-4 mr-2"}),D?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx($e,{children:"Details of IO blocked in SAP system"})]}),e.jsx(se,{children:S?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:S.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:S.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:["₹",S.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:["₹",S.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:["₹",S.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:S.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(S.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(Da,{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 qA(t,s=10){var a;try{const r={limit:s};t&&(r.q=t);const n=await je.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 je.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 Fs=[{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:c}){const{userSearchResults:d,userSearchLoading:m,searchUsersForIndex:h,clearSearchForIndex:x}=Pp(),[u,g]=p.useState(!1),[b,f]=p.useState(""),[y,v]=p.useState(24),[w,C]=p.useState("hours"),[k,S]=p.useState(3),[_,D]=p.useState([]),[A,N]=p.useState(!1),[P,R]=p.useState(null),O=p.useRef(null),F=()=>{const L=t.approvers||[],z=[];return Fs.forEach(H=>{if(H.isAuto||H.approverType==="dealer"||H.approverType==="initiator")return;const ye=L.find(ae=>ae.level===H.level);(!ye||!ye.email||!ye.userId||!ye.tat)&&z.push(`${H.name}`)}),{isValid:z.length===0,missingSteps:z}};p.useEffect(()=>{if(l){const L=F();l(L.isValid)}},[t.approvers]),p.useEffect(()=>{const L=t.approvers||[];if(L.length>0){const z=[],H=L.filter(ae=>ae.isAdditional);Fs.forEach(ae=>{const me=L.find(Q=>Q.originalStepLevel===ae.level||!Q.originalStepLevel&&!Q.isAdditional&&Q.level===ae.level);if(me)z.push(me);else if(ae.isAuto){const Q=ae.level===8?"finance@royalenfield.com":"system@royalenfield.com",oe=ae.level===8?"System/Finance":"System";z.push({email:Q,name:oe,level:ae.level,tat:ae.defaultTat,tatType:"hours",originalStepLevel:ae.level})}else ae.approverType==="dealer"?z.push({email:t.dealerEmail||"",name:t.dealerName||"",level:ae.level,tat:ae.defaultTat,tatType:"hours",originalStepLevel:ae.level}):ae.approverType==="initiator"?z.push({email:r||"",name:i||r||"User",userId:n,level:ae.level,tat:ae.defaultTat,tatType:"hours",originalStepLevel:ae.level}):z.push({email:"",name:"",level:ae.level,tat:ae.defaultTat,tatType:"hours",originalStepLevel:ae.level})}),H.forEach(ae=>{z.push(ae)}),z.sort((ae,me)=>ae.level-me.level),JSON.stringify(L.map(ae=>({level:ae.level,originalStepLevel:ae.originalStepLevel})))!==JSON.stringify(z.map(ae=>({level:ae.level,originalStepLevel:ae.originalStepLevel})))&&s("approvers",z)}else{const z=[];Fs.forEach(H=>{H.isAuto||(H.approverType==="dealer"?z.push({email:t.dealerEmail||"",name:t.dealerName||"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}):H.approverType==="initiator"?z.push({email:r||"",name:i||r||"User",userId:n,level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}):z.push({email:"",name:"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}))}),s("approvers",z)}},[t.dealerEmail,t.dealerName,r,n,i]);const $=(L,z)=>{const H=[...t.approvers||[]],ye=H.findIndex(ae=>ae.originalStepLevel===L||!ae.originalStepLevel&&ae.level===L&&!ae.isAdditional);if(ye===-1){const ae=Fs.find(me=>me.level===L);H.push({email:z,name:"",level:L,tat:(ae==null?void 0:ae.defaultTat)||48,tatType:"hours",originalStepLevel:L})}else{const ae=H[ye];if(ae){const me=ae.email;H[ye]={...ae,email:z,name:z!==me?"":ae.name,userId:z!==me?void 0:ae.userId}}}if(s("approvers",H),!z||!z.startsWith("@")||z.length<2){x(L-1);return}h(L-1,z,10)},V=async(L,z)=>{var H,ye;try{const ae=Fs.find(be=>be.level===L);if(ae&&!ae.isAuto&&ae.approverType!=="initiator"&&((H=z.email)==null?void 0:H.toLowerCase())===(r==null?void 0:r.toLowerCase())){K.error(`You cannot assign yourself as ${ae.name} approver.`),a&&a({type:"self-assign",email:z.email,message:`You cannot assign yourself as ${ae.name} approver.`});return}if((t.approvers||[]).some(be=>{var q,ue;return be.level!==L&&(be.userId===z.userId||((q=be.email)==null?void 0:q.toLowerCase())===((ue=z.email)==null?void 0:ue.toLowerCase()))})){K.error("This user is already assigned to another step."),a&&a({type:"error",email:z.email,message:"This user is already assigned to another step."});return}const oe=await ra({userId:z.userId,email:z.email,displayName:z.displayName,firstName:z.firstName,lastName:z.lastName,department:z.department,phone:z.phone,mobilePhone:z.mobilePhone,designation:z.designation,jobTitle:z.jobTitle,manager:z.manager,employeeId:z.employeeId,employeeNumber:z.employeeNumber,secondEmail:z.secondEmail,location:z.location}),Ce=[...t.approvers||[]],Ee=Ce.findIndex(be=>be.originalStepLevel===L||!be.originalStepLevel&&be.level===L&&!be.isAdditional);if(Ee===-1){const be=Fs.find(q=>q.level===L);Ce.push({email:z.email,name:z.displayName||[z.firstName,z.lastName].filter(Boolean).join(" "),userId:oe.userId,level:L,tat:(be==null?void 0:be.defaultTat)||48,tatType:"hours",originalStepLevel:L})}else{const be=Ce[Ee];be&&(Ce[Ee]={...be,email:z.email,name:z.displayName||[z.firstName,z.lastName].filter(Boolean).join(" "),userId:oe.userId,originalStepLevel:be.originalStepLevel||L})}s("approvers",Ce),x(L-1),K.success(`Approver for ${(ye=Fs.find(be=>be.level===L))==null?void 0:ye.name} selected successfully.`)}catch(ae){console.error("Failed to ensure user exists:",ae),K.error("Failed to validate user. Please try again."),a&&a({type:"error",email:z.email,message:"Failed to validate user. Please try again."})}},T=(L,z)=>{const H=[...t.approvers||[]],ye=H.findIndex(ae=>ae.originalStepLevel===L||!ae.originalStepLevel&&ae.level===L&&!ae.isAdditional);if(ye!==-1){const ae=H[ye];ae&&(H[ye]={...ae,tat:z},s("approvers",H))}},j=(L,z)=>{const H=[...t.approvers||[]],ye=H.findIndex(ae=>ae.originalStepLevel===L||!ae.originalStepLevel&&ae.level===L&&!ae.isAdditional);if(ye!==-1){const ae=H[ye];ae&&(H[ye]={...ae,tatType:z,tat:""},s("approvers",H))}},U=L=>{if(f(L),P&&P.email.toLowerCase()!==L.toLowerCase()&&R(null),O.current&&clearTimeout(O.current),!L||!L.startsWith("@")||L.length<2){D([]),N(!1);return}N(!0),O.current=setTimeout(async()=>{var z;try{const H=L.slice(1),ae=((z=(await ia(H,10)).data)==null?void 0:z.data)||[];D(ae)}catch(H){console.error("Search failed:",H),D([])}finally{N(!1)}},300)},I=async L=>{try{await ra({userId:L.userId,email:L.email,displayName:L.displayName,firstName:L.firstName,lastName:L.lastName,department:L.department,phone:L.phone,mobilePhone:L.mobilePhone,designation:L.designation,jobTitle:L.jobTitle,manager:L.manager,employeeId:L.employeeId,employeeNumber:L.employeeNumber,secondEmail:L.secondEmail,location:L.location}),f(L.email),R(L),D([]),N(!1)}catch(z){console.error("Failed to ensure user exists:",z),K.error("Failed to verify user. Please try again.")}},M=async()=>{var q,ue;const L=b.trim().toLowerCase();if(!L){K.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(L)){K.error("Please enter a valid email address");return}const H=typeof y=="string"?Number(y):y;if(!H||H<=0||isNaN(H)){K.error("Please enter valid TAT (minimum 1)");return}const ye=w==="days"?30:720;if((w==="days"?H*24:H)>720){K.error(`TAT cannot exceed ${ye} ${w==="days"?"days":"hours"}`);return}const me=Fs.find(Ae=>Ae.name==="Requestor Claim Approval");if(me&&k>=me.level){K.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if(L===(r==null?void 0:r.toLowerCase())){K.error("You cannot add yourself as an additional approver.");return}const Q=t.approvers||[];if(Q.some(Ae=>{var Ue;return Ae.userId&&(P==null?void 0:P.userId)&&Ae.userId===P.userId||((Ue=Ae.email)==null?void 0:Ue.toLowerCase())===L})){K.error("This user is already assigned as an approver.");return}const Ce=Q.find(Ae=>Ae.originalStepLevel===k||!Ae.originalStepLevel&&!Ae.isAdditional&&Ae.level===k),be=(Ce?Ce.level:k)+1;if(o){const Ue=new Set(Q.map(Z=>Z.level)).size+1;if(Ue>o){const Z=[{type:"max_approval_levels",message:`Adding this approver would create ${Ue} approval levels, which exceeds the maximum allowed (${o}). Please remove some approvers before adding a new one.`,currentValue:Ue,maxValue:o}];c?c(Z):K.error(((q=Z[0])==null?void 0:q.message)||"Maximum approval levels exceeded");return}}if(!P||P.email.toLowerCase()!==L)try{const Ue=((ue=(await ia(L,1)).data)==null?void 0:ue.data)||[];if(Ue.length===0){K.error("User not found in organization directory. Please use @ to search for users.");return}const Z=Ue[0];await ra({userId:Z.userId,email:Z.email,displayName:Z.displayName,firstName:Z.firstName,lastName:Z.lastName,department:Z.department,phone:Z.phone,mobilePhone:Z.mobilePhone,designation:Z.designation,jobTitle:Z.jobTitle,manager:Z.manager,employeeId:Z.employeeId,employeeNumber:Z.employeeNumber,secondEmail:Z.secondEmail,location:Z.location});const Te={email:Z.email,name:Z.displayName||[Z.firstName,Z.lastName].filter(Boolean).join(" "),userId:Z.userId,level:be,tat:typeof y=="string"?Number(y):y,tatType:w,isAdditional:!0,insertAfterLevel:k,stepName:`Additional Approver - ${Z.displayName||Z.email}`},Xe=Q.map(pe=>pe.level>=be?{...pe,level:pe.level+1}:pe);Xe.push(Te),Xe.sort((pe,_e)=>pe.level-_e.level),s("approvers",Xe),K.success("Additional approver added and subsequent steps shifted")}catch(Ae){console.error("Failed to validate approver:",Ae),K.error("Failed to validate user. Please try again.");return}else{const Ae={email:P.email,name:P.displayName||[P.firstName,P.lastName].filter(Boolean).join(" "),userId:P.userId,level:be,tat:y,tatType:w,isAdditional:!0,insertAfterLevel:k,stepName:`Additional Approver - ${P.displayName||P.email}`},Ue=Q.map(Z=>Z.level>=be?{...Z,level:Z.level+1}:Z);Ue.push(Ae),Ue.sort((Z,Te)=>Z.level-Te.level),s("approvers",Ue),K.success("Additional approver added and subsequent steps shifted")}f(""),v(24),C("hours"),S(3),R(null),D([]),g(!1)},W=L=>{const z=[...t.approvers||[]];if(!z.find(me=>me.level===L))return;const ae=z.filter(me=>me.level!==L).map(me=>me.level>L&&!me.isAdditional?{...me,level:me.level-1}:me);ae.sort((me,Q)=>me.level-Q.level),s("approvers",ae),K.success("Additional approver removed and subsequent steps shifted back")},G=()=>[...t.approvers||[]].sort((z,H)=>z.level-H.level),ce=t.approvers||[],te=G();return e.jsxs(ts.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(cs,{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(ee,{className:"border-2 border-blue-200 bg-blue-50",children:e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(Ur,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsxs($e,{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 L=t.approvers||[],H=new Set(L.map(ye=>ye.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]})]})]})}),e.jsxs(ee,{className:"border-2",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx($e,{children:'Define approvers and TAT for each step. Some steps are pre-filled (Dealer, Initiator, System). Only "Department Lead Approval" requires manual assignment.'})]}),e.jsxs(se,{className:"space-y-2 pt-4",children:[e.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 L=t.approvers||[],H=new Set(L.map(ye=>ye.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]}),e.jsxs(E,{type:"button",variant:"outline",onClick:()=>g(!0),className:"flex items-center gap-2",children:[e.jsx(gs,{className:"w-4 h-4"}),"Add Additional Approver"]})]}),e.jsx("div",{className:"p-3 rounded-lg border-2 border-blue-200 bg-blue-50",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center flex-shrink-0",children:e.jsx(Vt,{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 L=te.filter(H=>H.isAdditional&&H.insertAfterLevel===0);let z=L.length;return Fs.filter(H=>!H.isAuto).map((H,ye,ae)=>{const me=ce.find(q=>q.originalStepLevel===H.level||!q.originalStepLevel&&q.level===H.level&&!q.isAdditional)||{email:"",name:"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level},Q=ye===ae.length-1,oe=H.isAuto||H.approverType==="dealer"||H.approverType==="initiator",Ce=!H.isAuto,Ee=te.filter(q=>q.isAdditional&&q.insertAfterLevel===H.level).sort((q,ue)=>q.level-ue.level),be=z+1;return z++,z+=Ee.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"})}),ye===0&&L.map((q,ue)=>{const Ae=ue+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:Ae})}),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(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>W(q.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(ft,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:q.name||q.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",q.email]}),e.jsxs("div",{children:["TAT: ",q.tat," ",q.tatType]})]})]})]})})]},`additional-${q.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${me.email&&me.userId?"border-green-200 bg-green-50":oe?"border-blue-200 bg-blue-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${me.email&&me.userId?"bg-green-600":oe?"bg-blue-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold text-sm",children:be})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:H.name}),Q&&e.jsx(ne,{variant:"destructive",className:"text-xs",children:"FINAL"}),oe&&e.jsx(ne,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:H.description}),Ce&&(()=>{var Ae,Ue;const q=!!(me.email&&me.userId),ue=!me.email&&!oe;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs(re,{htmlFor:`approver-${H.level}`,className:`text-xs font-bold ${ue?"text-blue-900":q?"text-green-900":"text-gray-900"}`,children:["Approver Email ",!oe&&"*",ue&&e.jsx("span",{className:"ml-2 text-[10px] font-semibold italic text-blue-600",children:"(Required)"})]}),q&&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(Oe,{id:`approver-${H.level}`,type:"text",placeholder:oe?me.email:"@username or email...",value:me.email||"",onChange:Z=>{const Te=Z.target.value;oe||$(H.level,Te)},disabled:oe||H.isAuto,className:`h-9 border-2 transition-all mt-1 w-full text-sm ${oe?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":q?"bg-green-50/50 border-green-600 focus:border-green-700 ring-offset-green-50 focus:ring-1 focus:ring-green-100 font-semibold text-gray-900":"bg-white border-blue-300 shadow-sm shadow-blue-100/50 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`}),!oe&&!H.isAuto&&(m[H.level-1]||(((Ae=d[H.level-1])==null?void 0:Ae.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:m[H.level-1]?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:(Ue=d[H.level-1])==null?void 0:Ue.map(Z=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>V(H.level,Z),children:[e.jsx("div",{className:"font-medium text-gray-900",children:Z.displayName||Z.email}),e.jsx("div",{className:"text-xs text-gray-600",children:Z.email}),Z.department&&e.jsx("div",{className:"text-xs text-gray-500",children:Z.department})]},Z.userId))})})]}),me.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:me.name})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:`tat-${H.level}`,className:`text-xs font-bold ${ue?"text-blue-900":q?"text-green-900":"text-gray-900"}`,children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Oe,{id:`tat-${H.level}`,type:"number",placeholder:me.tatType==="days"?"7":"24",min:"1",max:me.tatType==="days"?"30":"720",value:me.tat||"",onChange:Z=>T(H.level,parseInt(Z.target.value)||""),disabled:H.isAuto,className:`h-9 border-2 transition-all flex-1 text-sm ${oe?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":q?"bg-green-50/50 border-green-600 focus:border-green-700 focus:ring-1 focus:ring-green-100 font-semibold text-gray-900":"bg-white border-blue-300 shadow-sm shadow-blue-100/50 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`}),e.jsxs(We,{value:me.tatType||"hours",onValueChange:Z=>j(H.level,Z),disabled:H.isAuto,children:[e.jsx(Ye,{className:`w-20 h-9 border-2 transition-all text-sm ${oe?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed":q?"bg-green-50/50 border-green-600 focus:border-green-700 focus:ring-1 focus:ring-green-100 text-gray-900 font-medium":"bg-white border-blue-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`,children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})]})})()]})]})}),Ee.map((q,ue)=>{const Ae=be+ue+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:Ae})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:q.stepName||"Additional Approver"}),e.jsx(ne,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),q.email&&q.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(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>W(q.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(ft,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:q.name||q.email||"No approver assigned"}),q.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",q.email]}),q.tat&&e.jsxs("div",{children:["TAT: ",q.tat," ",q.tatType]})]})]})]})})]},`additional-${q.level}`)})]},H.level)})})()]})]}),e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(st,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3",children:te.map(L=>{const z=L.originalStepLevel?Fs.find(me=>me.level===L.originalStepLevel):Fs.find(me=>me.level===L.level&&!L.isAdditional);if(z!=null&&z.isAuto)return null;const H=Number(L.tat||0),ae=(L.tatType||"hours")==="days"?H*24:H;if(!H)return null;if(L.isAdditional){const me=Fs.find(Q=>Q.level===L.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:L.stepName||`Additional Approver (after "${(me==null?void 0:me.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[ae," hours"]})]},L.level)}return e.jsxs("div",{className:"flex items-center justify-between p-2 bg-gray-50 rounded",children:[e.jsx("span",{className:"text-sm font-medium",children:(z==null?void 0:z.name)||"Unknown"}),e.jsxs("span",{className:"text-sm text-gray-600",children:[ae," hours"]})]},L.level)})})})]})]}),e.jsx(pt,{open:u,onOpenChange:g,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(gs,{className:"w-5 h-5 text-blue-600"}),"Add Additional Approver"]}),e.jsx(Dt,{children:'Add an additional approver between workflow steps. The approver will be inserted after the selected step. Additional approvers cannot be added after "Requestor Claim Approval".'})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(We,{value:k.toString(),onValueChange:L=>S(Number(L)),children:[e.jsx(Ye,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select step"})}),e.jsx(Ke,{children:Fs.filter(L=>{if(L.isAuto)return!1;const z=Fs.find(H=>H.name==="Requestor Claim Approval");return!(z&&L.level>=z.level)}).map(L=>e.jsx(Y,{value:L.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:L.name})]})},L.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 L=t.approvers||[],H=new Set(L.map(ye=>ye.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{type:"number",min:"1",max:w==="days"?"30":"720",value:y,onChange:L=>{const z=L.target.value;if(z==="")v("");else{const H=Number(z);!isNaN(H)&&H>=0&&v(H)}},onBlur:L=>{const z=L.target.value;(!z||z===""||Number(z)<=0)&&v(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(We,{value:w,onValueChange:L=>C(L),children:[e.jsx(Ye,{className:"w-24 h-11 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum time for this approver to respond (1-",w==="days"?"30 days":"720 hours",")"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{type:"text",placeholder:"@username or user@example.com",value:b,onChange:L=>U(L.target.value),className:"pl-10 h-11 border-gray-300",autoFocus:!0}),(A||_.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:A?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):_.length>0?e.jsx("ul",{className:"divide-y",children:_.map(L=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>I(L),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:L.displayName||[L.firstName,L.lastName].filter(Boolean).join(" ")||L.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:L.email}),L.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:L.designation})]})})},L.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(E,{type:"button",variant:"outline",onClick:()=>{g(!1),f(""),v(24),C("hours"),S(3),R(null),D([])},className:"flex-1",children:"Cancel"}),e.jsxs(E,{type:"button",onClick:M,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!b.trim()||!y,children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const Nl=[{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"}],wl=["Claim Details","Approver Selection","Review & Submit"];function sT({onBack:t,onSubmit:s}){const{user:a}=Kt(),[r,n]=p.useState(1),[i,l]=p.useState(!1),[o,c]=p.useState([]),[d,m]=p.useState(!1),[h,x]=p.useState(""),u=p.useRef(null),[g,b]=p.useState(!1),f=p.useRef(null),[y,v]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[w,C]=p.useState({open:!1,violations:[]}),[k,S]=p.useState([]),[_,D]=p.useState(!0);p.useEffect(()=>{(async()=>{try{D(!0);const M=await sS();S(M)}catch(M){console.error("Failed to load activity types:",M),K.error("Failed to load activity types. Please refresh the page.")}finally{D(!1)}})()},[]),p.useEffect(()=>{(async()=>{var M;try{const W=await Ys("SYSTEM_SETTINGS"),G=await Ys("WORKFLOW_SHARING"),ce=[...W,...G],te={};ce.forEach(L=>{te[L.configKey]=L.configValue}),v({maxApprovalLevels:parseInt(te.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(te.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((M=te.ALLOW_ADD_SPECTATOR)==null?void 0:M.toLowerCase())==="true",maxSpectators:parseInt(te.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(W){console.error("Failed to load system policy:",W)}})()},[]),p.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const[A,N]=p.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),P=wl.length,R=I=>{if(x(I),u.current&&clearTimeout(u.current),!I||I.trim().length<2){c([]),m(!1);return}m(!0),u.current=setTimeout(async()=>{try{const M=await qA(I,10);c(M)}catch(M){console.error("Error searching dealers:",M),c([])}finally{m(!1)}},300)},O=(I,M)=>{N(W=>{const G={...W,[I]:M};if(I==="periodStartDate")M&&G.periodEndDate&&M>G.periodEndDate&&(G.periodEndDate=void 0,K.error("End date must be on or after the start date. End date has been cleared."));else if(I==="periodEndDate"&&M&&G.periodStartDate&&M<G.periodStartDate)return K.error("End date must be on or after the start date."),W;return G})},F=()=>{switch(r){case 1:return A.activityName&&A.activityType&&A.dealerCode&&A.dealerName&&A.activityDate&&A.location&&A.requestDescription;case 2:const M=(A.approvers||[]).find(W=>W.originalStepLevel===3||!W.originalStepLevel&&W.level===3&&!W.isAdditional);return(M==null?void 0:M.email)&&(M==null?void 0:M.userId)&&(M==null?void 0:M.tat);case 3:return!0;default:return!1}},$=()=>{if(r<P){if(!F()){if(r===2){const M=(A.approvers||[]).find(G=>G.originalStepLevel===3||!G.originalStepLevel&&G.level===3&&!G.isAdditional),W=[];(!(M!=null&&M.email)||!(M!=null&&M.userId)||!(M!=null&&M.tat))&&W.push("Department Lead Approval"),W.length>0?K.error(`Please add missing approvers: ${W.join(", ")}`):K.error("Please complete all required approver selections (email, user verification, and TAT) before proceeding.")}else K.error("Please complete all required fields before proceeding.");return}n(r+1)}},V=()=>{r>1&&n(r-1)},T=async I=>{l(!0);try{const M=await eT(I.dealerCode);if(!M.isLoggedIn){K.error(`Dealer "${M.dealerName||M.displayName}" (${M.dealerCode}) is not mapped to the system.`,{duration:5e3}),x(""),c([]),O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress",""),l(!1);return}O("dealerCode",M.dealerCode),O("dealerName",M.dealerName||M.displayName),O("dealerEmail",M.email||""),O("dealerPhone",M.phone||""),O("dealerAddress",""),x(M.dealerName||M.displayName),c([]),K.success(`Dealer "${M.dealerName||M.displayName}" verified and mapped to the System`)}catch{K.error("Dealer is not mapped to the system",{duration:5e3}),x(""),c([]),O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress","")}finally{l(!1)}},j=()=>{if(g)return;const M=[...A.approvers||[]].sort((L,z)=>L.level-z.level),W=new Map,G=[];if(M.forEach(L=>{W.has(L.level)?G.push(L.level):W.set(L.level,L)}),G.length>0){K.error(`Duplicate approver levels detected: ${G.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",G,M);return}const ce=M.map(L=>{const z={email:L.email,name:L.name,userId:L.userId,level:L.level,tat:L.tat,tatType:L.tatType};return L.isAdditional&&L.stepName&&(z.stepName=L.stepName,z.isAdditional=!0),L.originalStepLevel&&(z.originalStepLevel=L.originalStepLevel),z}),te={...A,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:ce};if(b(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{b(!1),f.current=null},3e4),s)try{s(te)}catch(L){f.current&&(clearTimeout(f.current),f.current=null),b(!1),console.error("Error submitting claim:",L)}else f.current&&(clearTimeout(f.current),f.current=null),b(!1)},U=()=>{switch(r){case 1:return e.jsxs(ts.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(Gt,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Claim Details"}),e.jsx("p",{className:"text-gray-600",children:"Provide comprehensive information about your claim request"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(Oe,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:A.activityName,onChange:I=>O("activityName",I.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(We,{value:A.activityType,onValueChange:I=>O("activityType",I),disabled:_,children:[e.jsx(Ye,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(Ge,{placeholder:_?"Loading activity types...":"Select activity type"})}),e.jsx(Ke,{children:k.length>0?k.map(I=>e.jsx(Y,{value:I.title,children:I.title},I.activityTypeId)):e.jsx("div",{className:"px-2 py-1.5 text-sm text-gray-500 text-center",children:"No activity types available"})})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsx("div",{className:"mt-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Oe,{placeholder:"Type dealer code, name, or email to search...",value:A.dealerCode?`${A.dealerName} (${A.dealerCode})`:h,onChange:I=>{A.dealerCode?(O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress",""),x(I.target.value)):R(I.target.value)},onFocus:()=>{h&&h.length>=2&&R(h)},className:"h-12 border-2 border-gray-300 focus:border-blue-500",disabled:i}),A.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"]})}),(d||o.length>0)&&!A.dealerCode&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:d?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:o.map(I=>e.jsx("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>T(I),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:I.dealerName||I.displayName}),e.jsxs("div",{className:"text-xs text-gray-600",children:[e.jsx("span",{className:"font-mono",children:I.dealerCode}),I.email&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1",children:"•"}),e.jsx("span",{children:I.email})]})]}),I.city&&I.state&&e.jsxs("div",{className:"text-xs text-gray-500",children:[I.city,", ",I.state]})]}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:I.isLoggedIn?e.jsx(De,{className:"w-4 h-4 text-green-600"}):e.jsx(wt,{className:"w-4 h-4 text-red-500"})})]})},I.dealerId))})})]})}),A.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:A.dealerName})," (",A.dealerCode,")"]}),A.dealerEmail&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Email: ",A.dealerEmail]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(Hs,{children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(ot,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:A.activityDate?He(A.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(Gs,{className:"w-auto p-0",align:"start",children:e.jsx(Yn,{mode:"single",selected:A.activityDate,onSelect:I=>O("activityDate",I),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(Oe,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:A.location,onChange:I=>O("location",I.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Rn,{value:A.requestDescription||"",onChange:I=>O("requestDescription",I),placeholder:"Provide comprehensive details about your claim requirement including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(re,{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(re,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(Hs,{children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(ot,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:A.periodStartDate?He(A.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(Gs,{className:"w-auto p-0",align:"start",children:e.jsx(Yn,{mode:"single",selected:A.periodStartDate,onSelect:I=>O("periodStartDate",I),initialFocus:!0,toDate:A.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(Hs,{children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",disabled:!A.periodStartDate,children:[e.jsx(ot,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:A.periodEndDate?He(A.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(Gs,{className:"w-auto p-0",align:"start",children:e.jsx(Yn,{mode:"single",selected:A.periodEndDate,onSelect:I=>O("periodEndDate",I),initialFocus:!0,fromDate:A.periodStartDate||void 0})})]}),!A.periodStartDate&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Please select start date first"})]})]}),(A.periodStartDate||A.periodEndDate)&&e.jsx("div",{className:"mt-2",children:A.periodStartDate&&A.periodEndDate?e.jsxs("p",{className:"text-xs text-gray-600",children:["Period: ",He(A.periodStartDate,"d MMM yyyy")," - ",He(A.periodEndDate,"d MMM yyyy")]}):e.jsx("p",{className:"text-xs text-gray-500",children:A.periodStartDate?"Please select end date for the period":"Please select start date first"})})]})]})]});case 2:return e.jsx(tT,{formData:A,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:y.maxApprovalLevels,onPolicyViolation:I=>C({open:!0,violations:I})});case 3:return e.jsxs(ts.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(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:A.activityName})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(ne,{variant:"secondary",className:"mt-1",children:A.activityType})]})]})})]}),e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Si,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1 font-mono",children:A.dealerCode})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:A.dealerName})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:A.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:A.dealerPhone})]}),A.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:A.dealerAddress})]})]})})]}),e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-5 h-5 text-purple-600"}),"Selected Approvers"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsx("div",{className:"space-y-3",children:[...A.approvers||[]].filter(M=>{var W,G;return!((W=M.email)!=null&&W.includes("system@"))&&!((G=M.email)!=null&&G.includes("finance@"))}).sort((M,W)=>M.level-W.level).map(M=>{const W=Number(M.tat||0),ce=(M.tatType||"hours")==="days"?W*24:W;let te="Unknown",L="";if(M.isAdditional){te=M.stepName||"Additional Approver";const z=Nl.find(H=>H.level===M.insertAfterLevel);L=M.stepName||`Additional Approver (after "${(z==null?void 0:z.name)||"Unknown"}")`}else{const z=M.originalStepLevel?Nl.find(H=>H.level===M.originalStepLevel):Nl.find(H=>H.level===M.level&&!H.isAuto);te=(z==null?void 0:z.name)||"Unknown",L=te}return e.jsx("div",{className:`p-3 rounded-lg border ${M.isAdditional?"bg-purple-50 border-purple-200":"bg-gray-50 border-gray-200"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:L}),M.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:M.name||M.email||"Not selected"}),M.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:M.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[ce," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${M.level}-${M.email}`)})})})]}),e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:A.activityDate?He(A.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Location"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(po,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:A.location})]})]}),A.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Estimated Budget"}),e.jsx("p",{className:"text-xl font-bold text-blue-900 mt-1",children:A.estimatedBudget})]})]})})]}),e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Brief Requirement"}),e.jsx("div",{className:"mt-2 p-4 bg-gray-50 rounded-lg border",children:e.jsx(sa,{content:A.requestDescription||"",className:"text-sm"})})]})})]}),(A.periodStartDate||A.periodEndDate)&&e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(st,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:A.periodStartDate?He(A.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:A.periodEndDate?He(A.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(Ur,{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(E,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Ns,{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:wl[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(na,{value:r/P*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:wl.map((I,M)=>e.jsx("span",{className:`text-xs sm:text-sm ${M+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:M+1},M))})]})]}),e.jsx(ee,{className:"mb-6 sm:mb-8",children:e.jsx(se,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(Ei,{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(E,{variant:"outline",onClick:V,disabled:r===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Ns,{className:"w-4 h-4"}),"Previous"]}),r<P?e.jsxs(E,{onClick:$,className:`gap-2 w-full sm:w-auto order-1 sm:order-2 ${F()?"":"opacity-50 cursor-pointer hover:opacity-60"}`,children:["Next",e.jsx(ss,{className:"w-4 h-4"})]}):e.jsx(E,{onClick:j,disabled:!F()||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(lt,{className:"w-4 h-4 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yr,{className:"w-4 h-4"}),"Submit Claim Request"]})})]})]}),e.jsx(Fn,{open:w.open,onClose:()=>C({open:!1,violations:[]}),violations:w.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}const{DocumentsTab:aT,ActivityTab:rT,WorkNotesTab:nT,SummaryTab:iT,RequestDetailHeader:lT,QuickActionsSidebar:oT,RequestDetailModals:cT}=Wp;let dT=class extends p.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("Dealer Claim RequestDetail Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(as,{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(E,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(E,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function mT({requestId:t,onBack:s,dynamicRequests:a=[]}){var It,ns,Os,sr,ar,oa;const n=Ea().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=p.useState(l),[d,m]=p.useState(!1),[h,x]=p.useState(null),[u,g]=p.useState(null),[b,f]=p.useState(!1),[y,v]=p.useState(0),[w,C]=p.useState(!1),[k,S]=p.useState(!1),[_,D]=p.useState(!1),[A,N]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[P,R]=p.useState({open:!1,violations:[]}),{user:O}=Kt(),{request:F,apiRequest:$,loading:V,refreshing:T,refreshDetails:j,currentApprovalLevel:U,isSpectator:I,isInitiator:M,existingParticipants:W,accessDenied:G}=hc(n,a,O),ce=(O==null?void 0:O.userId)||"",te=M,{mergedMessages:L,unreadWorkNotes:z,workNoteAttachments:H,setWorkNoteAttachments:ye}=Ip(n,$,o,O),{uploadingDocument:ae,triggerFileInput:me,previewDocument:Q,setPreviewDocument:oe,documentPolicy:Ce,documentError:Ee,setDocumentError:be}=Ep($,j),[q,ue]=p.useState(null),Ae=q||U,{showApproveModal:Ue,setShowApproveModal:Z,showRejectModal:Te,setShowRejectModal:Xe,showAddApproverModal:pe,setShowAddApproverModal:_e,showAddSpectatorModal:rt,setShowAddSpectatorModal:ut,showSkipApproverModal:nt,setShowSkipApproverModal:Ps,showActionStatusModal:Xs,setShowActionStatusModal:Na,skipApproverData:Xa,setSkipApproverData:X,actionStatus:we,setActionStatus:J,handleApproveConfirm:Le,handleRejectConfirm:Fe,handleAddApprover:Ve,handleSkipApprover:Me,handleAddSpectator:Ze}=_p(n,Ae,j),Be=async vt=>{await Le(vt),ue(null)},qe=async vt=>{await Fe(vt),ue(null)},fs=((F==null?void 0:F.status)||($==null?void 0:$.status)||"").toLowerCase(),Ht=(fs==="approved"||fs==="rejected")&&M,{conclusionRemark:at,setConclusionRemark:et,conclusionLoading:yt,conclusionSubmitting:rs,aiGenerated:Pt,handleGenerateConclusion:la,handleFinalizeConclusion:pa,generationAttempts:Fa,generationFailed:wa,maxAttemptsReached:St}=Fp(F,n,M,j,s,J,Na);p.useEffect(()=>{(async()=>{var is;try{const Is=await Ys("SYSTEM_SETTINGS"),Zs=await Ys("WORKFLOW_SHARING"),Nr=[...Is,...Zs],ca={};Nr.forEach(Ma=>{ca[Ma.configKey]=Ma.configValue}),N({maxApprovalLevels:parseInt(ca.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(ca.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((is=ca.ALLOW_ADD_SPECTATOR)==null?void 0:is.toLowerCase())==="true",maxSpectators:parseInt(ca.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Is){console.error("Failed to load system policy:",Is)}})()},[]),p.useEffect(()=>{const is=new URLSearchParams(window.location.search).get("tab");is&&c(is)},[n]);const Ca=()=>{j()},Za=()=>{C(!0)},Ja=()=>{S(!0)},Qa=async()=>{await j()},qa=()=>{D(!0)},er=async()=>{await j()},tr=async()=>{await j()},_a=async()=>{if(!($!=null&&$.requestId)){K.error("Request ID not found");return}if(!h){K.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},ga=(F==null?void 0:F.status)==="closed";p.useEffect(()=>{(async()=>{if(!ga||!($!=null&&$.requestId)){g(null),x(null);return}try{f(!0);const is=await Bp($.requestId);if(is!=null&&is.summaryId){x(is.summaryId);try{const Is=await pc(is.summaryId);g(Is)}catch(Is){console.error("Failed to fetch summary details:",Is),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{f(!1)}})()},[ga,$==null?void 0:$.requestId]),p.useEffect(()=>{if(!ce||!($!=null&&$.requestId))return;const vt=Lr();if(!vt)return;Tx(vt,ce);const is=Is=>{var Ma,Kr,Xr,Zr;const Zs=Is==null?void 0:Is.notification;if(!Zs)return;const Nr=Zs.requestId||Zs.request_id,ca=((Ma=Zs.metadata)==null?void 0:Ma.requestNumber)||((Kr=Zs.metadata)==null?void 0:Kr.request_number);Nr!==$.requestId&&ca!==n&&ca!==$.requestNumber||((Xr=Zs.metadata)!=null&&Xr.creditNoteNumber||(Zr=Zs.metadata)!=null&&Zr.credit_note_number)&&j()};return vt.on("notification:new",is),()=>{vt.off("notification:new",is)}},[ce,$==null?void 0:$.requestId,n,j]);const La=((F==null?void 0:F.approvalFlow)||[]).filter(vt=>vt&&typeof vt.step=="number").map(vt=>({levelNumber:vt.step||0,approverName:vt.approver||"Unknown",status:vt.status||"pending",tatHours:vt.tatHours||24}));return V&&!F&&!$?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($t,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading dealer claim request details..."})]})}):G!=null&&G.denied?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"access-denied-state",children:e.jsxs("div",{className:"max-w-lg w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(rx,{className:"w-10 h-10 text-red-500"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Access Denied"}),e.jsx("p",{className:"text-gray-600 mb-6 leading-relaxed",children:G.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):F?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"dealer-claim-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(lT,{request:F,refreshing:T,onBack:s||(()=>window.history.back()),onRefresh:Ca,onShareSummary:_a,isInitiator:M,slaData:((It=F==null?void 0:F.summary)==null?void 0:It.sla)||(F==null?void 0:F.sla)||null,isPaused:((ns=F==null?void 0:F.pauseInfo)==null?void 0:ns.isPaused)||!1}),e.jsxs($i,{value:o,onValueChange:c,className:"w-full","data-testid":"dealer-claim-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(Oi,{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(qt,{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(nx,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),ga&&u&&e.jsxs(qt,{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(ix,{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(qt,{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(ta,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),te&&e.jsxs(qt,{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(Da,{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(qt,{value:"documents",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-documents",children:[e.jsx(Re,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Docs"})]}),e.jsxs(qt,{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(kt,{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(qt,{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(As,{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(es,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(RA,{request:F,apiRequest:$,currentUserId:ce,isInitiator:M,needsClosure:Ht,conclusionRemark:at,setConclusionRemark:et,conclusionLoading:yt,conclusionSubmitting:rs,aiGenerated:Pt,handleGenerateConclusion:la,handleFinalizeConclusion:pa,generationAttempts:Fa,generationFailed:wa,maxAttemptsReached:St})}),ga&&e.jsx(es,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(iT,{summary:u,loading:b,onShare:_a,isInitiator:M})}),e.jsx(es,{value:"workflow",className:"mt-0",children:e.jsx(JA,{request:F,user:O,isInitiator:M,onSkipApprover:vt=>{if(!vt.levelId){alert("Level ID not available");return}X(vt),Ps(!0)},onRefresh:j,documentPolicy:Ce})}),te&&e.jsx(es,{value:"io",className:"mt-0",children:e.jsx(QA,{request:F,apiRequest:$,onRefresh:j})}),e.jsx(es,{value:"documents",className:"mt-0",children:e.jsx(aT,{request:F,workNoteAttachments:H,uploadingDocument:ae,documentPolicy:Ce,triggerFileInput:me,setPreviewDocument:oe,downloadDocument:ps})}),e.jsx(es,{value:"activity",className:"mt-0",children:e.jsx(rT,{request:F})}),e.jsx(es,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(nT,{requestId:n,requestTitle:F.title,mergedMessages:L,setWorkNoteAttachments:ye,isInitiator:M,isSpectator:I,currentLevels:La,onAddApprover:Ve,maxApprovalLevels:A.maxApprovalLevels,onPolicyViolation:vt=>R({open:!0,violations:vt})})})]}),o!=="worknotes"&&e.jsx(oT,{request:F,isInitiator:M,isSpectator:I,currentApprovalLevel:U,onAddApprover:()=>_e(!0),onAddSpectator:()=>ut(!0),onApprove:()=>Z(!0),onReject:()=>Xe(!0),onPause:Za,onResume:Ja,onRetrigger:qa,summaryId:h,refreshTrigger:y,pausedByUserId:(sr=(Os=F==null?void 0:F.pauseInfo)==null?void 0:Os.pausedBy)==null?void 0:sr.userId,currentUserId:ce,apiRequest:$})]})]})]})}),d&&h&&e.jsx(Gp,{isOpen:d,onClose:()=>m(!1),summaryId:h,requestTitle:(F==null?void 0:F.title)||"N/A",onSuccess:()=>{j(),v(vt=>vt+1)}}),w&&($==null?void 0:$.requestId)&&e.jsx(Yp,{isOpen:w,onClose:()=>C(!1),requestId:$.requestId,levelId:(U==null?void 0:U.levelId)||null,onSuccess:er}),k&&($==null?void 0:$.requestId)&&e.jsx(Kp,{isOpen:k,onClose:()=>S(!1),requestId:$.requestId,onSuccess:Qa}),_&&($==null?void 0:$.requestId)&&e.jsx(Xp,{isOpen:_,onClose:()=>D(!1),requestId:$.requestId,approverName:(oa=(ar=F==null?void 0:F.pauseInfo)==null?void 0:ar.pausedBy)==null?void 0:oa.name,onSuccess:tr}),e.jsx(cT,{showApproveModal:Ue,showRejectModal:Te,showAddApproverModal:pe,showAddSpectatorModal:rt,showSkipApproverModal:nt,showActionStatusModal:Xs,previewDocument:Q,documentError:Ee,request:F,skipApproverData:Xa,actionStatus:we,existingParticipants:W,currentLevels:La,maxApprovalLevels:A.maxApprovalLevels,onPolicyViolation:vt=>R({open:!0,violations:vt}),setShowApproveModal:Z,setShowRejectModal:Xe,setShowAddApproverModal:_e,setShowAddSpectatorModal:ut,setShowSkipApproverModal:Ps,setShowActionStatusModal:Na,setPreviewDocument:oe,setDocumentError:be,setSkipApproverData:X,setActionStatus:J,handleApproveConfirm:Be,handleRejectConfirm:qe,handleAddApprover:Ve,handleAddSpectator:Ze,handleSkipApprover:Me,downloadDocument:ps,documentPolicy:Ce}),e.jsx(Fn,{open:P.open,onClose:()=>R({open:!1,violations:[]}),violations:P.violations,policyDetails:{maxApprovalLevels:A.maxApprovalLevels,maxParticipants:A.maxParticipants,allowSpectators:A.allowSpectators,maxSpectators:A.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(Re,{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(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{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]=p.useState(!0),[n,i]=p.useState(!1),[l,o]=p.useState({totalClaims:0,totalValue:0,approved:0,rejected:0,pending:0,credited:0,pendingCredit:0,approvedValue:0,rejectedValue:0,pendingValue:0,creditedValue:0,pendingCreditValue:0}),[c,d]=p.useState([]),[m,h]=p.useState("all"),[x,u]=p.useState(),[g,b]=p.useState(),f=async(R=!1)=>{try{R?i(!0):r(!0);const O=await GA(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}),d(O.categoryData||[])}catch(O){console.error("[DealerDashboard] Error fetching data:",O),K.error("Failed to load dashboard data. Please try again later."),o({totalClaims:0,totalValue:0,approved:0,rejected:0,pending:0,credited:0,pendingCredit:0,approvedValue:0,rejectedValue:0,pendingValue:0,creditedValue:0,pendingCreditValue:0}),d([])}finally{r(!1),i(!1)}};p.useEffect(()=>{f()},[]);const y=(R,O=!1)=>{if(R==null||isNaN(R))return"₹0";const F=typeof R=="string"?parseFloat(R):Number(R);return F<=0?"₹0":O||F<1e4?`₹${Math.round(F).toLocaleString("en-IN")}`:F>=1e5?`₹${(F/1e5).toFixed(1)}L`:F>=1e3?`₹${(F/1e3).toFixed(1)}K`:`₹${Math.round(F).toLocaleString("en-IN")}`},v=R=>R.toLocaleString("en-IN"),w=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),C=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),k=p.useMemo(()=>{const R=c.reduce((O,F)=>O+F.raised,0);return R===0?[]:c.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)}))},[c]),S=p.useMemo(()=>c.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})),[c]),_=p.useMemo(()=>c.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})),[c]),D=["#166534","#15803d","#16a34a","#22c55e","#4ade80","#86efac","#bbf7d0"],A=p.useMemo(()=>c.length===0?null:c.reduce((R,O)=>O.approvalRate>((R==null?void 0:R.approvalRate)||0)?O:R),[c]),N=p.useMemo(()=>c.length===0?null:c.reduce((R,O)=>O.raisedValue>((R==null?void 0:R.raisedValue)||0)?O:R),[c]);return a?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx($t,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):l.totalClaims===0&&c.length===0?e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(ee,{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(se,{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(hs,{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(E,{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(Re,{className:"w-5 h-5 mr-2"}),"Create New Claim"]}),e.jsxs(E,{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($t,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh"]})]})]})})})]}),e.jsx(ee,{className:"shadow-lg",children:e.jsxs(se,{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(Pl,{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(E,{onClick:()=>t==null?void 0:t("/new-request"),className:"bg-blue-600 hover:bg-blue-700 text-white",children:[e.jsx(Re,{className:"w-5 h-5 mr-2"}),"Create Your First Claim"]}),e.jsxs(E,{onClick:()=>{i(!0),f(!0)},disabled:n,variant:"outline",children:[e.jsx($t,{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(ee,{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(se,{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(hs,{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(E,{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(st,{className:"w-5 h-5 mr-2"}),"View Pending Claims"]}),e.jsxs(E,{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(Re,{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(Il,{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(ee,{className:"border-l-4 border-l-blue-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Raised Claims"}),e.jsx("div",{className:"p-2 rounded-lg bg-blue-50",children:e.jsx(Re,{className:"h-4 w-4 text-blue-600"})})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.totalClaims)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(l.totalValue,!0)})]})]}),e.jsxs(ee,{className:"border-l-4 border-l-green-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Approved"}),e.jsx("div",{className:"p-2 rounded-lg bg-green-50",children:e.jsx(De,{className:"h-4 w-4 text-green-600"})})]})}),e.jsxs(se,{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(ta,{className:"h-3 w-3 text-green-600"}),e.jsxs("p",{className:"text-xs text-green-600",children:[w(),"% approval rate"]})]})]})]}),e.jsxs(ee,{className:"border-l-4 border-l-red-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Rejected"}),e.jsx("div",{className:"p-2 rounded-lg bg-red-50",children:e.jsx(wt,{className:"h-4 w-4 text-red-600"})})]})}),e.jsxs(se,{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(u0,{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(ee,{className:"border-l-4 border-l-orange-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Pending"}),e.jsx("div",{className:"p-2 rounded-lg bg-orange-50",children:e.jsx(st,{className:"h-4 w-4 text-orange-600"})})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.pending)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(l.pendingValue)})]})]}),e.jsxs(ee,{className:"border-l-4 border-l-emerald-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Credited"}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-50",children:e.jsx(x0,{className:"h-4 w-4 text-emerald-600"})})]})}),e.jsxs(se,{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(ta,{className:"h-3 w-3 text-emerald-600"}),e.jsxs("p",{className:"text-xs text-emerald-600",children:[C(),"% credit rate"]})]})]})]}),e.jsxs(ee,{className:"border-l-4 border-l-amber-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Pending Credit"}),e.jsx("div",{className:"p-2 rounded-lg bg-amber-50",children:e.jsx(as,{className:"h-4 w-4 text-amber-600"})})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.pendingCredit)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(l.pendingCreditValue)})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(ee,{className:"shadow-lg",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(Pl,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(fe,{children:"Claims Distribution by Activity Type"}),e.jsx($e,{children:"Total claims raised across activity types"})]})]})}),e.jsxs(se,{children:[e.jsx(Pr,{width:"100%",height:300,children:e.jsxs(Uu,{children:[e.jsx(Bu,{data:k,cx:"50%",cy:"50%",labelLine:!1,label:({name:R,percentage:O})=>`${R}: ${O}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:k.map((R,O)=>e.jsx(Vu,{fill:D[O%D.length]},`cell-${O}`))}),e.jsx(Ir,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:k.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(ee,{className:"shadow-lg",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Il,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{children:"Claims Status by Activity Type"}),e.jsx($e,{children:"Count comparison across workflow stages"})]})]})}),e.jsx(se,{children:e.jsx(Pr,{width:"100%",height:300,children:e.jsxs(kl,{data:S,children:[e.jsx(ei,{strokeDasharray:"3 3"}),e.jsx(ti,{dataKey:"name"}),e.jsx(si,{}),e.jsx(Ir,{}),e.jsx(ai,{}),e.jsx(fa,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(fa,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(fa,{dataKey:"Rejected",fill:"#ef4444"}),e.jsx(fa,{dataKey:"Pending",fill:"#f59e0b"})]})})})]})]}),e.jsxs(ee,{className:"shadow-lg",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-emerald-100 rounded-lg",children:e.jsx(kt,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(fe,{children:"Detailed Activity Type Breakdown"}),e.jsx($e,{children:"In-depth analysis of claims by type and status"})]})]})}),e.jsx(se,{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(Pr,{width:"100%",height:350,children:e.jsxs(kl,{data:_,children:[e.jsx(ei,{strokeDasharray:"3 3"}),e.jsx(ti,{dataKey:"name"}),e.jsx(si,{tickFormatter:R=>y(R)}),e.jsx(Ir,{formatter:R=>y(R),labelFormatter:R=>R}),e.jsx(ai,{}),e.jsx(fa,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(fa,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(fa,{dataKey:"Credited",fill:"#10b981"})]})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-6",children:c.slice(0,3).map((R,O)=>e.jsxs(ee,{className:"shadow-md hover:shadow-lg transition-shadow",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-base",children:R.activityType}),e.jsxs(ne,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[R.approvalRate.toFixed(1),"% approved"]})]})}),e.jsxs(se,{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)," (",y(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)," (",y(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)," (",y(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)," (",y(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)," (",y(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)," (",y(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(na,{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(ee,{className:"border-t-4 border-t-green-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{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(Ot,{className:"h-6 w-6 text-green-600"})}),e.jsx(ta,{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:(A==null?void 0:A.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-green-600",children:[(A==null?void 0:A.approvalRate.toFixed(2))||0,"% approval rate"]})]})}),e.jsx(ee,{className:"border-t-4 border-t-blue-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{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(Da,{className:"h-6 w-6 text-blue-600"})}),e.jsx(kt,{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?y(N.raisedValue,!0):"₹0"," raised"]})]})}),e.jsx(ee,{className:"border-t-4 border-t-emerald-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{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(xo,{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:[C(),"%"]}),e.jsxs("p",{className:"text-sm text-emerald-600",children:[v(l.credited)," claims credited"]})]})}),e.jsx(ee,{className:"border-t-4 border-t-amber-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{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(ex,{className:"h-6 w-6 text-amber-600"})}),e.jsx(as,{className:"h-5 w-5 text-amber-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Pending Action"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:v(l.pendingCredit)}),e.jsxs("p",{className:"text-sm text-amber-600",children:[y(l.pendingCreditValue)," awaiting credit"]})]})})]})]})}function hT({searchTerm:t,sortBy:s,sortOrder:a,onSearchChange:r,onSortByChange:n,onSortOrderChange:i,onClearFilters:l,activeFiltersCount:o,...c}){return e.jsxs(ee,{className:"shadow-lg border-0",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Ya,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx($e,{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(E,{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(se,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{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(Oe,{placeholder:"Search requests, IDs...",value:t,onChange:d=>r(d.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(We,{value:s,onValueChange:d=>n(d),children:[e.jsx(Ye,{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(Ge,{placeholder:"Sort by"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"due",children:"Due Date"}),e.jsx(Y,{value:"created",children:"Date Created"}),e.jsx(Y,{value:"priority",children:"Priority"}),e.jsx(Y,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(E,{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(Ai,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Ti,{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:c,activeFiltersCount:d,...m}){return e.jsxs(ee,{className:"shadow-lg border-0","data-testid":"dealer-closed-requests-filters",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Ya,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx($e,{className:"text-xs sm:text-sm",children:d>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[d," filter",d>1?"s":""," active"]})})]})]}),d>0&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:c,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3","data-testid":"dealer-closed-requests-clear-filters",children:[e.jsx(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(se,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{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(Oe,{placeholder:"Search requests, IDs...",value:t,onChange:h=>n(h.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors","data-testid":"dealer-closed-requests-search"})]}),i&&e.jsxs(We,{value:s,onValueChange:i,children:[e.jsx(Ye,{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(Ge,{placeholder:"Closure Type"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Closures"}),e.jsx(Y,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(Y,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wt,{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(We,{value:a,onValueChange:h=>l(h),children:[e.jsx(Ye,{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(Ge,{placeholder:"Sort by"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"due",children:"Due Date"}),e.jsx(Y,{value:"created",children:"Date Created"}),e.jsx(Y,{value:"priority",children:"Priority"})]})]}),e.jsx(E,{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(Ai,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Ti,{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:c,initiatorSearch:d,approverSearch:m,onSearchChange:h,onStatusChange:x,onInitiatorChange:u,onApproverChange:g,onApproverTypeChange:b,onDateRangeChange:f,onCustomStartDateChange:y,onCustomEndDateChange:v,onShowCustomDatePickerChange:w,onApplyCustomDate:C,onClearFilters:k,hasActiveFilters:S,..._}){return e.jsx(ee,{className:"border-gray-200 shadow-md","data-testid":"dealer-user-all-requests-filters",children:e.jsx(se,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),S&&e.jsx(ne,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),S&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:k,className:"gap-2",children:[e.jsx($t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Ts,{}),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(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search requests...",value:t,onChange:D=>h(D.target.value),className:"pl-10 h-10","data-testid":"dealer-search-input"})]}),e.jsxs(We,{value:s,onValueChange:x,children:[e.jsx(Ye,{className:"h-10","data-testid":"dealer-status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"paused",children:"Paused"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:d.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:d.selectedUser.displayName||d.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:d.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{placeholder:"Search initiator...",value:d.searchQuery,onChange:D=>d.handleSearch(D.target.value),onFocus:()=>{d.searchResults.length>0&&d.setShowResults(!0)},onBlur:()=>setTimeout(()=>d.setShowResults(!1),200),className:"h-10","data-testid":"dealer-initiator-search-input"}),d.showResults&&d.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:d.searchResults.map(D=>e.jsx("button",{type:"button",onClick:()=>d.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(re,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r!=="all"&&b&&e.jsxs(We,{value:n,onValueChange:D=>b(D),children:[e.jsx(Ye,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"current",children:"Current Only"}),e.jsx(Y,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:m.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:m.selectedUser.displayName||m.selectedUser.email}),e.jsx(E,{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(Oe,{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(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:i,onValueChange:D=>f(D),children:[e.jsx(Ye,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),i==="custom"&&e.jsxs(Hs,{open:c,onOpenChange:w,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ot,{className:"w-4 h-4"}),l&&o?`${He(l,"MMM d, yyyy")} - ${He(o,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Ms,{value:l||null,onChange:D=>{const A=D?new Date(D):void 0;A?(y==null||y(A),o&&A>o&&(v==null||v(A))):y==null||y(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",children:"End Date"}),e.jsx(Ms,{value:o||null,onChange:D=>{const A=D?new Date(D):void 0;A?(v==null||v(A),l&&A<l&&(y==null||y(A))):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(E,{size:"sm",onClick:C,disabled:!l||!o,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>{w==null||w(!1),y==null||y(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 SA}}function bT(t){switch(t){case"DEALER":return hT;case"STANDARD":default:return AA}}function yT(t){switch(t){case"DEALER":return pT;case"STANDARD":default:return TA}}function vT(t){switch(t){case"DEALER":return gT;case"STANDARD":default:return kA}}const jT=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ha,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ot,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ot,iconColor:"text-gray-600"}}},NT=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:ze,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:wt,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:ze,iconColor:"text-gray-600",label:t}}};function wT({onViewRequest:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState(1),[d,m]=p.useState(0),[h]=p.useState(10),x=p.useRef(null),u=Vj(),g=p.useMemo(()=>{try{const A=tt.getUserData();return Eo(A)}catch(A){return console.error("[OpenRequests] Error getting user filter type:",A),"STANDARD"}},[]),b=p.useMemo(()=>bT(g),[g]),f=g==="DEALER",y=A=>({search:u.searchTerm||void 0,status:A&&!f&&u.statusFilter!=="all"?u.statusFilter:void 0,priority:!f&&u.priorityFilter!=="all"?u.priorityFilter:void 0,templateType:!f&&u.templateTypeFilter!=="all"?u.templateTypeFilter:void 0,sortBy:u.sortBy,sortOrder:u.sortOrder}),v=p.useCallback(async(A=1,N)=>{try{A===1&&(n(!0),a([]));const P=await ks.listOpenForMe({page:A,limit:h,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&&(u.setCurrentPage(O.page||1),c(O.totalPages||1),m(O.total||0));const F=R.map($=>{var T,j,U,I;const V=$.submittedAt||$.submitted_at||$.createdAt||$.created_at;return{id:$.requestNumber||$.request_number||$.requestId,requestId:$.requestId,displayId:$.requestNumber||$.request_number||$.requestId,title:$.title,description:$.description,status:($.status||"").toString().toLowerCase().replace("_","-"),priority:($.priority||"").toString().toLowerCase(),initiator:{name:((T=$.initiator)==null?void 0:T.displayName)||((j=$.initiator)==null?void 0:j.email)||"—",avatar:(((U=$.initiator)==null?void 0:U.displayName)||((I=$.initiator)==null?void 0:I.email)||"NA").split(" ").map(M=>M[0]).join("").slice(0,2).toUpperCase()},currentApprover:$.currentApprover?{name:$.currentApprover.name||$.currentApprover.email||"—",avatar:($.currentApprover.name||$.currentApprover.email||"CA").split(" ").map(M=>M[0]).join("").slice(0,2).toUpperCase(),sla:$.currentApprover.sla}:void 0,createdAt:V||"—",approvalStep:$.currentLevel?`Step ${$.currentLevel} of ${$.totalLevels||"?"}`:void 0,department:$.department,currentLevelSLA:$.currentLevelSLA,templateType:$.templateType||$.template_type}});a(F)}finally{n(!1),l(!1)}},[h,u]);x.current=v;const w=p.useCallback(()=>{l(!0),v(u.currentPage,y(!0))},[u.currentPage,v]),C=p.useCallback(A=>{A>=1&&A<=o&&(u.setCurrentPage(A),v(A,y(!0)))},[o,u,v]),k=()=>{const A=[];let P=Math.max(1,u.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++)A.push(O);return A},S=p.useRef(!1);p.useEffect(()=>{if(!S.current){S.current=!0;const A=u.currentPage||1;v(A,y(!0))}},[]);const _=p.useRef({searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:f});p.useEffect(()=>{if(!S.current)return;const A=_.current;if(!(A.searchTerm!==u.searchTerm||A.statusFilter!==u.statusFilter||A.priorityFilter!==u.priorityFilter||A.templateTypeFilter!==u.templateTypeFilter||A.sortBy!==u.sortBy||A.sortOrder!==u.sortOrder||A.isDealer!==f))return;const P=setTimeout(()=>{u.setCurrentPage(1),v(1,y(!0)),_.current={searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:f}},u.searchTerm?500:0);return()=>clearTimeout(P)},[u.searchTerm,u.statusFilter,u.priorityFilter,u.templateTypeFilter,u.sortBy,u.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(Re,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900",children:"My Open Requests"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:"Manage and track your active approval requests"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsxs(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…":`${d||s.length} open`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:w,disabled:i,children:[e.jsx($t,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:i?"Refreshing...":"Refresh"})]})]})]}),e.jsx(b,{searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,onSearchChange:u.setSearchTerm,onStatusFilterChange:u.setStatusFilter,onPriorityFilterChange:u.setPriorityFilter,onTemplateTypeFilterChange:u.setTemplateTypeFilter,onSortByChange:u.setSortBy,onSortOrderChange:u.setSortOrder,onClearFilters:u.clearFilters,activeFiltersCount:u.activeFiltersCount}),e.jsx("div",{className:"space-y-3",children:D.map(A=>{const N=jT(A.priority),P=NT(A.status);return e.jsx(ee,{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(A.id,A.title),children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${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:A.displayId||A.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||A.status]}),A.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:A.department}),e.jsx(ne,{variant:"outline",className:`${N.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:A.priority}),(()=>{const R=(A==null?void 0:A.templateType)||(A==null?void 0:A.template_type)||"",O=(R==null?void 0:R.toUpperCase())||"";let F="Non-Templatized",$="bg-purple-100 !text-purple-600 border-purple-200";return O==="DEALER CLAIM"?(F="Dealer Claim",$="bg-blue-100 !text-blue-700 border-blue-200"):O==="TEMPLATE"&&(F="Template"),e.jsx(ne,{variant:"outline",className:`${$} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:F})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:A.title}),A.currentLevelSLA&&(()=>{var V;const R=!!(A.isPaused||(V=A.pauseInfo)!=null&&V.isPaused||A.status==="paused"),O=A.currentLevelSLA.percentageUsed||0,$=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 ${$.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(pn,{className:`w-3.5 h-3.5 ${$.icon}`}):e.jsx(st,{className:`w-3.5 h-3.5 ${$.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:A.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${$.text}`,children:[A.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(na,{value:O,className:"h-1.5",indicatorClassName:$.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(Zt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:A.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:A.initiator.name})]}),A.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Zt,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(Jt,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:A.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:A.currentApprover.name})]}),A.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ze,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:A.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ot,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",A.createdAt!=="—"?xa(A.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(ss,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},A.id)})}),D.length===0&&e.jsx(ee,{className:"shadow-lg border-0",children:e.jsxs(se,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Re,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:u.searchTerm||u.activeFiltersCount>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),u.activeFiltersCount>0&&e.jsx(E,{variant:"outline",className:"mt-4",onClick:u.clearFilters,children:"Clear all filters"})]})}),o>1&&!r&&e.jsx(ee,{className:"shadow-md",children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(u.currentPage-1)*h+1," to ",Math.min(u.currentPage*h,d)," of ",d," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>C(u.currentPage-1),disabled:u.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(ss,{className:"h-4 w-4 rotate-180"})}),u.currentPage>3&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>C(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),k().map(A=>e.jsx(E,{variant:A===u.currentPage?"default":"outline",size:"sm",onClick:()=>C(A),className:`h-8 w-8 p-0 ${A===u.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:A},A)),u.currentPage<o-2&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>C(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>C(u.currentPage+1),disabled:u.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(ss,{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(Re,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900",children:"My Closed Requests"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:"Review your completed and archived requests"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsxs(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(E,{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($t,{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 ST(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ha,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ot,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ot,iconColor:"text-gray-600"}}}function AT(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:wt,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ze,iconColor:"text-gray-600",label:t,description:""}}}function TT({request:t,onViewRequest:s}){const a=ST(t.priority),r=AT(t.status),n=a.icon,i=r.icon;return e.jsx(ee,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>s==null?void 0:s(t.id,t.title),"data-testid":`closed-request-card-${t.id}`,children:e.jsx(se,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-5",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${a.color} border shadow-sm`,children:e.jsx(n,{className:`w-5 h-5 ${a.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:t.displayId||t.id}),e.jsxs(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 c="Non-Templatized",d="bg-purple-100 !text-purple-600 border-purple-200";return o==="DEALER CLAIM"?(c="Dealer Claim",d="bg-blue-100 !text-blue-700 border-blue-200"):o==="TEMPLATE"&&(c="Template"),e.jsx(ne,{variant:"outline",className:`${d} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:c})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Zt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:t.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:t.initiator.name})]}),(t.totalLevels??0)>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(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(ot,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?xa(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: ",xa(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(ss,{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(ee,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(se,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Re,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:t||s>0?"Try adjusting your filters or search terms to see more results.":"No closed requests available at the moment."}),s>0&&e.jsx(E,{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(ee,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(a-1)*i+1," to ",Math.min(a*i,n)," of ",n," closed requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{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(ss,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{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(E,{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(E,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(E,{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(ss,{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]=p.useState([]),[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=p.useCallback(async(h=1,x)=>{try{h===1&&(n(!0),a([]));const u=await ks.listClosedByMe({page:h,limit:t,search:x==null?void 0:x.search,status:x!=null&&x.status&&x.status!=="all"?x.status:void 0,priority:x==null?void 0:x.priority,templateType:x==null?void 0:x.templateType,sortBy:x==null?void 0:x.sortBy,sortOrder:x==null?void 0:x.sortOrder}),g=Array.isArray(u==null?void 0:u.data)?u.data:[],b=ET(g);a(b);const f=u==null?void 0:u.pagination;f&&c({currentPage:f.page||1,totalPages:f.totalPages||1,totalRecords:f.total||0,itemsPerPage:t})}catch(u){console.error("[ClosedRequests] Error fetching requests:",u),a([])}finally{n(!1),l(!1)}},[t]),m=p.useCallback(h=>{l(!0),d(o.currentPage,h)},[d,o.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:o,fetchRequests:d,handleRefresh:m}}const _T={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},Jp=Br({name:"closedRequests",initialState:_T,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:LT,setStatusFilter:MT,setPriorityFilter:$T,setTemplateTypeFilter:OT,setSortBy:UT,setSortOrder:BT,setCurrentPage:VT,clearFilters:zT}=Jp.actions;function HT({onFiltersChange:t,debounceMs:s=500}={}){const a=Sn(),r=p.useRef(null),n=p.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,sortBy:d,sortOrder:m,currentPage:h}=zr(S=>S.closedRequests),x=p.useCallback(S=>a(LT(S)),[a]),u=p.useCallback(S=>a(MT(S)),[a]),g=p.useCallback(S=>a($T(S)),[a]),b=p.useCallback(S=>a(OT(S)),[a]),f=p.useCallback(S=>a(UT(S)),[a]),y=p.useCallback(S=>a(BT(S)),[a]),v=p.useCallback(S=>a(VT(S)),[a]),w=p.useCallback(()=>({search:i,status:l,priority:o,templateType:c!=="all"?c:void 0,sortBy:d,sortOrder:m}),[i,l,o,c,d,m]);p.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const S=setTimeout(()=>{t&&t(w())},i?s:0);return r.current=S,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,t,w,s]);const C=p.useCallback(()=>{a(zT())},[a]),k=[i,o!=="all"?o:null,l!=="all"?l:null,c!=="all"?c:null].filter(Boolean).length;return{searchTerm:i,priorityFilter:o,statusFilter:l,templateTypeFilter:c,sortBy:d,sortOrder:m,currentPage:h,setSearchTerm:x,setPriorityFilter:g,setStatusFilter:u,setTemplateTypeFilter:b,setSortBy:f,setSortOrder:y,setCurrentPage:v,clearFilters:C,activeFiltersCount:k,getFilters:w}}function WT({onViewRequest:t}){const s=FT({itemsPerPage:10}),a=p.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=HT(),n=p.useMemo(()=>{try{const h=tt.getUserData();return Eo(h)}catch(h){return console.error("[ClosedRequests] Error getting user filter type:",h),"STANDARD"}},[]),i=p.useMemo(()=>yT(n),[n]),l=n==="DEALER",o=p.useRef({searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}),c=p.useRef(!1);p.useEffect(()=>{const h=r.currentPage||1;a.current(h,{search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:!l&&r.priorityFilter!=="all"?r.priorityFilter:void 0,templateType:!l&&r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}),c.current=!0},[l]),p.useEffect(()=>{if(!c.current)return;const h=o.current;if(!(h.searchTerm!==r.searchTerm||h.statusFilter!==r.statusFilter||h.priorityFilter!==r.priorityFilter||h.templateTypeFilter!==r.templateTypeFilter||h.sortBy!==r.sortBy||h.sortOrder!==r.sortOrder))return;const u=setTimeout(()=>{r.setCurrentPage(1),a.current(1,{search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:r.priorityFilter!=="all"?r.priorityFilter:void 0,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}),o.current={searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}},r.searchTerm!==h.searchTerm?500:0);return()=>clearTimeout(u)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.templateTypeFilter,r.sortBy,r.sortOrder,l]);const d=p.useCallback(h=>{h>=1&&h<=s.pagination.totalPages&&(r.setCurrentPage(h),s.fetchRequests(h,{search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:r.priorityFilter!=="all"?r.priorityFilter:void 0,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}))},[s,r]),m=p.useCallback(()=>{s.handleRefresh({search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:r.priorityFilter!=="all"?r.priorityFilter:void 0,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder})},[s,r]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"closed-requests-page",children:[e.jsx(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:d})]})}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 YT(t){return GT(t)?"DEALER_CLAIM":"CUSTOM"}function KT(t,s){return`/request/${t}`}class XT extends p.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("RequestDetail Router Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(as,{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(E,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(E,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function ZT({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=Ea().requestId||t||"",{user:i}=Kt(),{apiRequest:l,loading:o}=hc(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($t,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading request details..."})]})});const c=YT(l),d=fT(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function JT(t){return e.jsx(XT,{children:e.jsx(ZT,{...t})})}function QT({onViewSummary:t}){const s=Ks(),[a,r]=p.useState([]),[n,i]=p.useState(!0),[l,o]=p.useState(""),[c,d]=p.useState(1),[m,h]=p.useState(1),[x,u]=p.useState(0),g=10,b=p.useCallback(async(w=1)=>{try{i(!0);const C=await aA({page:w,limit:g});r(C.data||[]),h(C.pagination.totalPages||1),u(C.pagination.total||0),d(C.pagination.page||1)}catch(C){console.error("Failed to fetch shared summaries:",C),K.error("Failed to load shared summaries")}finally{i(!1)}},[]);p.useEffect(()=>{b(1)},[b]);const f=async w=>{try{await Up(w),r(C=>C.map(k=>k.sharedSummaryId===w?{...k,isRead:!0,viewedAt:new Date().toISOString()}:k)),t?t(w):s(`/shared-summaries/${w}`)}catch(C){console.error("Failed to mark as viewed:",C),t?t(w):s(`/shared-summaries/${w}`)}},y=w=>{w>=1&&w<=m&&b(w)},v=a.filter(w=>{var k,S,_,D;if(!l)return!0;const C=l.toLowerCase();return((k=w.title)==null?void 0:k.toLowerCase().includes(C))||((S=w.requestNumber)==null?void 0:S.toLowerCase().includes(C))||((_=w.initiatorName)==null?void 0:_.toLowerCase().includes(C))||((D=w.sharedByName)==null?void 0:D.toLowerCase().includes(C))});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(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Oe,{placeholder:"Search by title, request number, or user...",value:l,onChange:w=>o(w.target.value),className:"pl-10 text-sm sm:text-base"})]})}),n&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(lt,{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(Re,{className:"h-8 w-8 sm:h-12 sm:w-12 text-gray-400 mx-auto mb-3 sm:mb-4"}),e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-1 sm:mb-2",children:"No shared summaries"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:l?"No summaries match your search.":"You haven't received any shared summaries yet."})]}),!n&&v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-3 sm:gap-4 mb-4 sm:mb-6",children:v.map(w=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${w.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>f(w.sharedSummaryId),children:e.jsx("div",{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[w.isRead?e.jsx(h0,{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:w.title}),!w.isRead&&e.jsx("span",{className:"px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded-full flex-shrink-0",children:"New"})]}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 break-words",children:["Request: ",e.jsx("span",{className:"font-medium",children:w.requestNumber})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap items-start sm:items-center gap-2 sm:gap-3 md:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Vt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Initiator: ",e.jsx("span",{className:"font-medium",children:w.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Vt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared by: ",e.jsx("span",{className:"font-medium",children:w.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(ot,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",He(new Date(w.sharedAt),"MMM dd, yyyy HH:mm")]})]}),w.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: ",He(new Date(w.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(E,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:C=>{C.stopPropagation(),f(w.sharedSummaryId)},children:"View"})]})})},w.sharedSummaryId))}),m>1&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 sm:gap-4 bg-white rounded-lg shadow-sm border border-gray-200 p-3 sm:p-4",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-gray-600 text-center sm:text-left",children:["Showing ",(c-1)*g+1," to ",Math.min(c*g,x)," of ",x," summaries"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>y(c-1),disabled:c===1,className:"text-xs sm:text-sm",children:"Previous"}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 whitespace-nowrap",children:["Page ",c," of ",m]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>y(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function qT(){const{sharedSummaryId:t}=Ea(),s=Ks(),[a,r]=p.useState(null),[n,i]=p.useState(!0);p.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,h;try{i(!0);try{await Up(t)}catch(u){console.warn("Failed to mark as viewed:",u)}const x=await pc(t);r(x)}catch(x){console.error("Failed to fetch summary details:",x),K.error(((h=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:h.message)||"Failed to load summary"),s("/shared-summaries")}finally{i(!1)}})()},[t,s]);const l=d=>{const m=d.toLowerCase();return m==="approved"?e.jsx(De,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(wt,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(st,{className:"h-4 w-4 text-orange-600"}):e.jsx(Re,{className:"h-4 w-4 text-gray-600"})},o=d=>{const m=d.toLowerCase();return m==="approved"?"bg-green-100 text-green-700 border-green-300":m==="rejected"?"bg-red-100 text-red-700 border-red-300":m==="pending"||m==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},c=(d,m)=>d&&d.trim()&&d.trim().toUpperCase()!=="N/A"?d:m&&m.trim()&&m.trim().toUpperCase()!=="N/A"?m:"N/A";return n?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(lt,{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(E,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(Ns,{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(sa,{content:a.description,className:"text-gray-700"})})]}),e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Initiator"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:He(new Date(a.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),a.approvers&&a.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),a.approvers.map((d,m)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsxs("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:["Approver ",d.levelNumber]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:d.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(d.designation,d.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[l(d.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:d.status})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:He(new Date(d.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:d.remarks})]})]},m))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),a.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(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(sa,{content:a.closingRemarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]})]})]})]})}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Re,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Summary Not Found"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"The summary you're looking for doesn't exist."}),e.jsx(E,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function e5(){const{requestId:t}=Ea(),s=Ks(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(ys,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(Op,{requestId:t||""})})})}function Qp({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 Bs({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:l,testId:o="stats-card",onClick:c}){return e.jsx(ee,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":o,onClick:c,children:e.jsx(se,{className:"p-3 sm:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:`text-xs sm:text-sm font-medium ${i}`,"data-testid":`${o}-label`,children:t}),e.jsx("p",{className:`text-xl sm:text-2xl font-bold ${l}`,"data-testid":`${o}-value`,children:s})]}),e.jsx(a,{className:`w-6 h-6 sm:w-8 sm:h-8 ${r}`,"data-testid":`${o}-icon`})]})})})}function 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(Bs,{label:"Total",value:t.total,icon:Re,iconColor:"text-blue-600",gradient:"bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200",textColor:"text-blue-700",valueColor:"text-blue-900",testId:"stat-total",onClick:s?()=>a("all"):void 0}),e.jsx(Bs,{label:"Pending",value:t.pending,icon:st,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(Bs,{label:"Paused",value:t.paused,icon:za,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(Bs,{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(Bs,{label:"Rejected",value:t.rejected,icon:wt,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(Bs,{label:"Draft",value:t.draft,icon:go,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(Bs,{label:"Closed",value:t.closed,icon:fo,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(ee,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(se,{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-3 sm:gap-4 items-start md:items-center",children:[e.jsxs("div",{className:"flex-1 relative w-full",children:[e.jsx(Rs,{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(Oe,{placeholder:"Search requests by title, description, or ID...",value:t,onChange:c=>n(c.target.value),className:"pl-9 text-sm sm:text-base bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"search-input"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 w-full md:w-auto",children:[e.jsxs(We,{value:s,onValueChange:i,children:[e.jsx(Ye,{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(Ge,{placeholder:"Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"draft",children:"Draft"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"paused",children:"Paused"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(We,{value:a,onValueChange:l,children:[e.jsx(Ye,{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(Ge,{placeholder:"Priority"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(We,{value:r,onValueChange:o,children:[e.jsx(Ye,{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(Ge,{placeholder:"Template Type"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]})]})]})})})}function a5(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ha,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ot,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ot,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:wt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,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:go,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ze,iconColor:"text-gray-600"}}}const n5=t=>{if(!t)return"";let s=t.replace(/<(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|tfoot|ul|video)[^>]*>/gi," ");return s=s.replace(/<br\s*\/?>/gi," "),s=s.replace(/<[^>]*>/g,""),s=s.replace(/\s+/g," ").trim(),s=s.replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"),s};function 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(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(ee,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(se,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(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(za,{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 c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Non-Templatized",h="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",h="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(ne,{variant:"outline",className:`${h} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})()]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2 leading-relaxed","data-testid":"request-description",children: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:"})," ",xa(t.submittedDate)]})]})]}),e.jsx(ss,{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(Vt,{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(ta,{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(st,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",xa(t.submittedDate)]})]})]})]})})})})}function l5({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(ee,{"data-testid":"loading-state",children:e.jsx(se,{className:"p-6 text-sm text-gray-600",children:"Loading your requests…"})});if(t.length===0){const l=a||r!=="all"||n!=="all";return e.jsx(ee,{"data-testid":"empty-state",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(Re,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600",children: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 qp(t){return Array.isArray(t)?t.map(o5):[]}function c5({itemsPerPage:t=10}={}){const[s,a]=p.useState([]),[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=p.useCallback(async(m=1,h)=>{try{m===1&&(n(!0),a([]));const x=await ks.listMyInitiatedWorkflows({page:m,limit:t,search:h==null?void 0:h.search,status:h==null?void 0:h.status,priority:h==null?void 0:h.priority,templateType:h==null?void 0:h.templateType}),u=Array.isArray(x==null?void 0:x.data)?x.data:[],g=qp(u);a(g),l(!0);const b=x==null?void 0:x.pagination;b&&c({currentPage:b.page||1,totalPages:b.totalPages||1,totalRecords:b.total||0,itemsPerPage:t})}catch(x){console.error("[MyRequests] Error fetching requests:",x),a([]),l(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:o,fetchMyRequests:d}}const d5={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},eg=Br({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}=eg.actions;function f5({onFiltersChange:t,debounceMs:s=500}={}){const a=Sn(),r=p.useRef(null),n=p.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d}=zr(y=>y.myRequests),m=p.useCallback(y=>a(m5(y)),[a]),h=p.useCallback(y=>a(u5(y)),[a]),x=p.useCallback(y=>a(x5(y)),[a]),u=p.useCallback(y=>a(h5(y)),[a]),g=p.useCallback(y=>a(p5(y)),[a]),b=p.useCallback(()=>({search:i,status:l,priority:o,templateType:c}),[i,l,o,c]);p.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const y=setTimeout(()=>{t&&t(b())},i?s:0);return r.current=y,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,t,b,s]);const f=p.useCallback(()=>{a(g5())},[a]);return{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d,setSearchTerm:m,setStatusFilter:h,setPriorityFilter:x,setTemplateTypeFilter:u,setCurrentPage:g,getFilters:b,resetFilters:f}}function b5({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=Kt(),r=c5({itemsPerPage:10}),n=p.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=f5(),l=p.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}),o=p.useRef(!1);p.useEffect(()=>{const y=i.currentPage||1;n.current(y,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),o.current=!0},[]),p.useEffect(()=>{if(!o.current)return;const y=l.current;if(!(y.searchTerm!==i.searchTerm||y.statusFilter!==i.statusFilter||y.priorityFilter!==i.priorityFilter||y.templateTypeFilter!==i.templateTypeFilter))return;const w=setTimeout(()=>{i.setCurrentPage(1),n.current(1,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),l.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}},i.searchTerm!==y.searchTerm?500:0);return()=>clearTimeout(w)},[i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter]);const[c,d]=p.useState(null),[m,h]=p.useState(!1),x=p.useCallback(async()=>{if(a!=null&&a.userId)try{h(!0);const y=await At.getRequestStats("all",void 0,void 0,void 0,i.priorityFilter!=="all"?i.priorityFilter:void 0,i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0,void 0,a.userId,void 0,void 0,i.searchTerm||void 0,void 0,!0);d({total:y.totalRequests||0,pending:y.openRequests||0,paused:y.pausedRequests||0,approved:y.approvedRequests||0,rejected:y.rejectedRequests||0,draft:y.draftRequests||0,closed:y.closedRequests||0})}catch(y){console.error("Failed to fetch backend stats:",y),d(null)}finally{h(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter,i.templateTypeFilter]);p.useEffect(()=>{const y=setTimeout(()=>{x()},i.searchTerm?500:0);return()=>clearTimeout(y)},[i.searchTerm,i.priorityFilter,i.templateTypeFilter,x]);const u=qp(s),g=r.hasFetchedFromApi?r.requests:u,b=p.useMemo(()=>c?{total:c.total||0,pending:c.pending||0,paused:c.paused||0,approved:c.approved||0,rejected:c.rejected||0,draft:c.draft||0,closed:c.closed||0}:{total:0,pending:0,paused:0,approved:0,rejected:0,draft:0,closed:0},[c]),f=p.useCallback(y=>{y>=1&&y<=r.pagination.totalPages&&(i.setCurrentPage(y),r.fetchMyRequests(y,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}))},[r,i]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"my-requests-page",children:[e.jsx(Qp,{icon:Re,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${b.total} total`,label:"requests",loading:r.loading||m},testId:"my-requests-header"}),e.jsx(t5,{stats:b,onStatusFilter:y=>{i.setStatusFilter(y)}}),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(vr,{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 tg({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(Qp,{icon:Re,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(E,{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($t,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function sg({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(Bs,{label:"Total",value:t.total,icon:Re,iconColor:"text-blue-600",gradient:"bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200",textColor:"text-blue-700",valueColor:"text-blue-900",testId:"stat-total",onClick:s?()=>a("all"):void 0}),e.jsx(Bs,{label:"Pending",value:t.pending,icon:st,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(Bs,{label:"Paused",value:t.paused,icon:za,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(Bs,{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(Bs,{label:"Rejected",value:t.rejected,icon:wt,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(Bs,{label:"Closed",value:t.closed,icon:fo,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 y5=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ha,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ot,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ot,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:wt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,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:go,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ze,iconColor:"text-gray-600"}}},j5=t=>{if(!t)return"";let s=t.replace(/<(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|tfoot|ul|video)[^>]*>/gi," ");return s=s.replace(/<br\s*\/?>/gi," "),s=s.replace(/<[^>]*>/g,""),s=s.replace(/\s+/g," ").trim(),s=s.replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"),s};function N5({request:t,index:s,onViewRequest:a}){var o;const r=v5(t.status),n=y5(t.priority),i=r.icon,l=n.icon;return e.jsx(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(ee,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(se,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(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(za,{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 c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Non-Templatized",h="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",h="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(ne,{variant:"outline",className:`${h} 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:"})," ",xa(t.submittedDate)]})]})]}),e.jsx(ss,{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(Vt,{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(ta,{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(st,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",xa(t.submittedDate)]})]})]})]})})})})}function ag({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(ee,{"data-testid":"loading-state",children:e.jsx(se,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(ee,{"data-testid":"empty-state",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(Re,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600",children:a?"Try adjusting your search or filters":"No requests match the current criteria"})]})}):e.jsx("div",{className:"space-y-4","data-testid":"requests-list",children:t.map((n,i)=>e.jsx(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},rg=Br({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:S5,setPriorityFilter:A5,setTemplateTypeFilter:T5,setSlaComplianceFilter:k5,setDepartmentFilter:R5,setInitiatorFilter:D5,setApproverFilter:P5,setApproverFilterType:I5,setDateRange:Cu,setCustomStartDate:Cl,setCustomEndDate:Sl,setShowCustomDatePicker:Vn,setCurrentPage:E5,clearFilters:F5}=rg.actions;function ng(){const t=Sn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:c,approverFilterType:d,dateRange:m,customStartDate:h,customEndDate:x,showCustomDatePicker:u,currentPage:g}=zr(j=>j.requests),b=p.useCallback(j=>t(C5(j)),[t]),f=p.useCallback(j=>t(S5(j)),[t]),y=p.useCallback(j=>t(A5(j)),[t]),v=p.useCallback(j=>t(T5(j)),[t]),w=p.useCallback(j=>t(k5(j)),[t]),C=p.useCallback(j=>t(R5(j)),[t]),k=p.useCallback(j=>t(D5(j)),[t]),S=p.useCallback(j=>t(P5(j)),[t]),_=p.useCallback(j=>t(I5(j)),[t]),D=p.useCallback(j=>t(Cu(j)),[t]),A=p.useCallback(j=>t(Cl(j)),[t]),N=p.useCallback(j=>t(Sl(j)),[t]),P=p.useCallback(j=>t(Vn(j)),[t]),R=p.useCallback(j=>t(E5(j)),[t]),O=p.useCallback(()=>({search:s||void 0,status:a!=="all"?a:void 0,priority:r!=="all"?r:void 0,templateType:n!=="all"?n:void 0,slaCompliance:i!=="all"?i:void 0,department:l!=="all"?l:void 0,initiator:o!=="all"?o:void 0,approver:c!=="all"?c:void 0,approverType:c!=="all"?d:void 0,dateRange:m,startDate:h,endDate:x}),[s,a,r,n,i,l,o,c,d,m,h,x]),F=p.useCallback(()=>{t(F5())},[t]),$=p.useCallback(j=>{const U=j;t(Cu(U)),U!=="custom"?(t(Cl(void 0)),t(Sl(void 0)),t(Vn(!1))):t(Vn(!0))},[t]),V=p.useCallback(()=>{h&&x&&(h>x&&(t(Cl(x)),t(Sl(h))),t(Vn(!1)))},[h,x,t]);return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:c,approverFilterType:d,dateRange:m,customStartDate:h,customEndDate:x,showCustomDatePicker:u,currentPage:g,hasActiveFilters:!!(s||a!=="all"||r!=="all"||n!=="all"||i!=="all"||l!=="all"||o!=="all"||c!=="all"||m!=="all"||h||x),setSearchTerm:b,setStatusFilter:f,setPriorityFilter:y,setTemplateTypeFilter:v,setSlaComplianceFilter:w,setDepartmentFilter:C,setInitiatorFilter:k,setApproverFilter:S,setApproverFilterType:_,setDateRange:D,setCustomStartDate:A,setCustomEndDate:N,setShowCustomDatePicker:P,setCurrentPage:R,getFilters:O,clearFilters:F,handleDateRangeChange:$,handleApplyCustomDate:V}}function hi({filterValue:t,onFilterChange:s,source:a="default"}){const[r,n]=p.useState(""),[i,l]=p.useState([]),[o,c]=p.useState(!1),[d,m]=p.useState(null),[h,x]=p.useState(!1),u=p.useRef(null);p.useEffect(()=>{async function y(){if(t!=="all"&&!d)try{const v=await dr.getUserById(t);v&&(m(v),n(v.displayName||v.email))}catch(v){console.error("Failed to fetch user detail for search:",v)}else t==="all"&&(m(null),n(""))}y()},[t]),p.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const g=p.useCallback(y=>{if(n(y),u.current&&clearTimeout(u.current),!y||y.trim().length<2){l([]),c(!1);return}u.current=setTimeout(async()=>{var v;x(!0);try{const C=((v=(await dr.searchUsers(y.trim(),10,a)).data)==null?void 0:v.data)||[];l(C),c(C.length>0)}catch(w){console.error("Search API failed:",w),l([]),c(!1)}finally{x(!1)}},400)},[a]),b=p.useCallback(y=>{m(y),s(y.userId),n(y.displayName||y.email),c(!1),l([])},[s]),f=p.useCallback(()=>{m(null),s("all"),n(""),c(!1),l([])},[s]);return{searchQuery:r,searchResults:i,showResults:o,selectedUser:d,searching:h,handleSearch:g,handleSelect:b,handleClear:f,setShowResults:c}}function _5(t){var d,m,h,x,u,g,b;const s=t.submittedAt||t.submitted_at||t.createdAt||t.created_at,a=(t.priority||"").toString().toLowerCase(),r=(t.status||"").toString().toUpperCase();let n="—",i="—";const l=t.currentApprover||t.current_approver||t.currentApproverData;if(l)n=l.name||l.approverName||l.displayName||l.email||l.approverEmail||"—";else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const f=t.approvals.find(y=>{const v=(y.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(f)n=f.approverName||((d=f.approver)==null?void 0:d.name)||((m=f.approver)==null?void 0:m.displayName)||f.approverEmail||((h=f.approver)==null?void 0:h.email)||"—";else{const v=[...t.approvals].sort((w,C)=>{const k=w.levelNumber||w.level_number||0;return(C.levelNumber||C.level_number||0)-k})[0];v&&(n=v.approverName||((x=v.approver)==null?void 0:x.name)||((u=v.approver)==null?void 0:u.displayName)||v.approverEmail||((g=v.approver)==null?void 0:g.email)||"—")}}const o=t.currentLevel||t.current_level||t.currentLevelNumber||t.current_level_number,c=t.totalLevels||t.total_levels||t.totalLevelsCount||t.total_levels_count;if(o&&c)i=`${o} of ${c}`;else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const f=t.approvals.find(y=>{const v=(y.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(f){const y=f.levelNumber||f.level_number||0,v=c||t.approvals.length;i=`${y} of ${v}`}else c&&(i=`${c} of ${c}`)}else t.currentStep&&t.totalSteps&&(i=`${t.currentStep} of ${t.totalSteps}`);return{id:t.requestNumber||t.request_number||t.requestId||t.id||t.request_id,requestId:t.requestId||t.id||t.request_id,displayId:t.requestNumber||t.request_number||t.id,title:t.title,description:t.description,status:r.toLowerCase().replace("_","-"),priority:a,department:t.department||((b=t.initiator)==null?void 0:b.department),submittedDate:t.submittedAt||(t.createdAt?new Date(t.createdAt).toISOString().split("T")[0]:void 0),createdAt:s,currentApprover:n,approverLevel:i,templateType:t.templateType||t.template_type,workflowType:t.workflowType||t.workflow_type,templateName:t.templateName||t.template_name}}function ig(t){return Array.isArray(t)?t.map(_5):[]}function L5(t,s,a,r,n,i){if(t.length>0){const l=t.length,o=t.filter(u=>{const g=(u.status||"").toString().toUpperCase();return g==="PENDING"||g==="IN_PROGRESS"}).length,c=t.filter(u=>(u.status||"").toString().toUpperCase()==="APPROVED").length,d=t.filter(u=>(u.status||"").toString().toUpperCase()==="REJECTED").length,m=t.filter(u=>(u.status||"").toString().toUpperCase()==="DRAFT").length,h=t.filter(u=>(u.status||"").toString().toUpperCase()==="CLOSED").length,x=t.filter(u=>(u.status||"").toString().toUpperCase()==="PAUSED").length;return{total:l,pending:o,paused:x,approved:c,rejected:d,draft:m,closed:h}}else return s&&a?{total:a.total,pending:a.pending,paused:a.paused||0,approved:a.approved,rejected:a.rejected,draft:a.draft,closed:a.closed}:{total:n||i.length,pending:i.filter(o=>o.status==="pending"||o.status==="in-progress").length,paused:i.filter(o=>o.status==="paused").length,approved:i.filter(o=>o.status==="approved").length,rejected:i.filter(o=>o.status==="rejected").length,draft:i.filter(o=>o.status==="draft").length,closed:i.filter(o=>o.status==="closed").length}}var lg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(fi,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(lg);var M5=lg.exports;const og=bi(M5);var cg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(fi,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(cg);var $5=cg.exports;const dg=bi($5);Bt.extend(dg);Bt.extend(og);function O5(t,s){let a=[...t];if(s.search){const r=s.search.toLowerCase();a=a.filter(n=>{var i,l,o,c;return((i=n.title)==null?void 0:i.toLowerCase().includes(r))||((l=n.description)==null?void 0:l.toLowerCase().includes(r))||((o=n.requestNumber)==null?void 0:o.toLowerCase().includes(r))||((c=n.request_number)==null?void 0:c.toLowerCase().includes(r))})}if(s.status&&s.status!=="all")if(s.status.toLowerCase()==="pending")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return(n==="PENDING"||n==="IN_PROGRESS")&&!i});else if(s.status.toLowerCase()==="paused")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return n==="PAUSED"||i});else{const r=s.status.toUpperCase().replace("-","_");a=a.filter(n=>{var o;const i=(n.status||"").toString().toUpperCase(),l=((o=n.pauseInfo)==null?void 0:o.isPaused)||n.isPaused||!1;return r==="IN_PROGRESS"||r==="IN-PROGRESS"?i==="IN_PROGRESS"&&!l:i===r&&!l})}if(s.priority&&s.priority!=="all"&&(a=a.filter(r=>{var n;return(r.priority||"").toString().toLowerCase()===((n=s.priority)==null?void 0:n.toLowerCase())})),s.department&&s.department!=="all"&&(a=a.filter(r=>{var i;return(r.department||((i=r.initiator)==null?void 0:i.department)||"")===s.department})),s.initiator&&s.initiator!=="all"&&(a=a.filter(r=>{var i,l;return(r.initiatorId||r.initiator_id||((i=r.initiator)==null?void 0:i.userId)||((l=r.initiator)==null?void 0:l.user_id)||(r.initiator&&typeof r.initiator=="object"&&"userId"in r.initiator?r.initiator.userId:null))===s.initiator})),s.approver&&s.approver!=="all"&&((s.approverType||"current")==="current"?a=a.filter(n=>{var l,o,c,d,m,h;return(((l=n.currentApprover)==null?void 0:l.userId)||((o=n.currentApprover)==null?void 0:o.user_id)||((d=(c=n.approvals)==null?void 0:c.find(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:d.approverId)||((h=(m=n.approvals)==null?void 0:m.find(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:h.approver_id)||n.currentApproverId||n.current_approver_id)===s.approver}):a=a.filter(n=>{var l,o;const i=[];return(l=n.currentApprover)!=null&&l.userId&&i.push(n.currentApprover.userId),(o=n.currentApprover)!=null&&o.user_id&&i.push(n.currentApprover.user_id),Array.isArray(n.approvals)&&n.approvals.forEach(c=>{c.approverId&&i.push(c.approverId),c.approver_id&&i.push(c.approver_id)}),i.includes(s.approver||"")})),s.slaCompliance&&s.slaCompliance!=="all"&&(a=a.filter(r=>{var c,d,m,h,x,u,g,b,f,y,v,w;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const C=(r.status||"").toString().toUpperCase();if(!(C==="APPROVED"||C==="REJECTED"||C==="CLOSED"))return!1;const S=((c=r.currentLevelSLA)==null?void 0:c.status)||((m=(d=r.currentApprover)==null?void 0:d.sla)==null?void 0:m.status)||((h=r.sla)==null?void 0:h.status)||((u=(x=r.summary)==null?void 0:x.sla)==null?void 0:u.status);return S?S!=="breached"&&S.toLowerCase()!=="breached":!0}const i=((g=r.currentLevelSLA)==null?void 0:g.status)||((f=(b=r.currentApprover)==null?void 0:b.sla)==null?void 0:f.status)||((y=r.sla)==null?void 0:y.status)||((w=(v=r.summary)==null?void 0:v.sla)==null?void 0:w.status);if(!i)return n==="on-track"||n==="on_track";const o={"on-track":"on_track",on_track:"on_track",approaching:"approaching",critical:"critical",breached:"breached"}[n.toLowerCase()]||n.toLowerCase();return i===o||i.toLowerCase()===o})),s.dateRange){let r=null,n=null;if(s.dateRange==="custom"&&s.startDate&&s.endDate)r=Bt(s.startDate).startOf("day").toDate(),n=Bt(s.endDate).endOf("day").toDate();else{const i=Bt();switch(s.dateRange){case"today":r=i.startOf("day").toDate(),n=i.endOf("day").toDate();break;case"week":r=i.startOf("week").toDate(),n=i.endOf("week").toDate();break;case"month":r=i.startOf("month").toDate(),n=i.endOf("month").toDate();break}}r&&n&&(a=a.filter(i=>{const l=i.submittedAt||i.submission_date||i.submitted_at;if(!l){const m=i.createdAt||i.created_at||i.created_date;if(!m)return!1;const h=Bt(m).startOf("day").toDate(),x=Bt(r).startOf("day").toDate(),u=Bt(n).endOf("day").toDate();return h>=x&&h<=u}const o=Bt(l).startOf("day").toDate(),c=Bt(r).startOf("day").toDate(),d=Bt(n).endOf("day").toDate();return o>=c&&o<=d}))}return a}Bt.extend(og);Bt.extend(dg);function U5(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return He(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function mg(t,s){const a=O5(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var v,w,C,k,S;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),h=((v=c.initiator)==null?void 0:v.displayName)||((w=c.initiator)==null?void 0:w.email)||c.initiatorName||"N/A",x=c.department||((C=c.initiator)==null?void 0:C.department)||"N/A",u=((k=c.currentApprover)==null?void 0:k.displayName)||((S=c.currentApprover)==null?void 0:S.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",b=U5(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),f=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),y=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${h.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,`"${u.replace(/"/g,'""')}"`,g,b,`"${f}"`];r.push(y.join(","))});const n=r.join(`
`),i=new Blob([n],{type:"text/csv;charset=utf-8;"}),l=document.createElement("a"),o=URL.createObjectURL(i);l.setAttribute("href",o),l.setAttribute("download",`requests-export-${new Date().toISOString().split("T")[0]}.csv`),l.style.visibility="hidden",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o)}async function B5({page:t,itemsPerPage:s,filters:a,isOrgLevel:r}){var n,i,l,o;if(r){const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.approver&&a.approver!=="all"&&(c.approver=a.approver,c.approverType=a.approverType||"current"),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(n=a.startDate)==null?void 0:n.toISOString()),a!=null&&a.endDate&&(c.endDate=(i=a.endDate)==null?void 0:i.toISOString());const d=await ks.listWorkflows({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const h=m.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:h.length,totalPages:1};return{data:h,allData:[],filteredData:h,pagination:{page:x.page,limit:x.limit||s,total:x.total||h.length,totalPages:x.totalPages||1}}}else{const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(l=a.startDate)==null?void 0:l.toISOString()),a!=null&&a.endDate&&(c.endDate=(o=a.endDate)==null?void 0:o.toISOString());const d=await ks.listParticipantRequests({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const h=m.filter(u=>(u.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:h.length,totalPages:1};return{data:h,allData:[],filteredData:h,pagination:x}}}async function V5(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const l=t?await ks.listWorkflows({page:r,limit:100}):await ks.listParticipantRequests({page:r,limit:100});let o=[];if(Array.isArray(l==null?void 0:l.data)?o=l.data:Array.isArray(l)&&(o=l),o.length>0){const c=o.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");a.push(...c),r++,l!=null&&l.pagination?n=r<=l.pagination.totalPages:n=o.length===100}else n=!1}return a}function z5({onViewRequest:t}){const{user:s}=Kt(),a=zr(I=>I.dashboard.viewAsUser),r=p.useMemo(()=>ki(s),[s]),n=p.useMemo(()=>r&&!a,[r,a]),i=ng(),[l,o]=p.useState([]),[c,d]=p.useState(!1),[m,h]=p.useState(!1),[x,u]=p.useState(null),[g,b]=p.useState([]),[f,y]=p.useState(!1),[v,w]=p.useState(1),[C,k]=p.useState(0),[S]=p.useState(10),_=hi({filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter,source:"local"}),D=hi({filterValue:i.approverFilter,onFilterChange:i.setApproverFilter,source:"local"}),A=p.useCallback(async(I,M,W,G)=>{try{const ce=G==null?void 0:G.slaCompliance;if(ce&&ce!=="all"&&ce!=="breached"&&ce!=="compliant"){const L={};G!=null&&G.search&&(L.search=G.search),G!=null&&G.priority&&G.priority!=="all"&&(L.priority=G.priority),G!=null&&G.department&&G.department!=="all"&&(L.department=G.department),G!=null&&G.initiator&&G.initiator!=="all"&&(L.initiator=G.initiator),G!=null&&G.approver&&G.approver!=="all"&&(L.approver=G.approver,L.approverType=G.approverType||"current"),L.slaCompliance=ce,I&&(L.dateRange=I),M&&(L.startDate=M.toISOString()),W&&(L.endDate=W.toISOString());const z=n?await ks.listWorkflows({page:1,limit:1e3,...L}):await ks.listParticipantRequests({page:1,limit:1e3,...L}),H=Array.isArray(z==null?void 0:z.data)?z.data:[],ye=H.length,ae=H.filter(Ce=>{const Ee=(Ce.status||"").toString().toUpperCase();return Ee==="PENDING"||Ee==="IN_PROGRESS"}).length,me=H.filter(Ce=>(Ce.status||"").toString().toUpperCase()==="APPROVED").length,Q=H.filter(Ce=>(Ce.status||"").toString().toUpperCase()==="REJECTED").length,oe=H.filter(Ce=>(Ce.status||"").toString().toUpperCase()==="CLOSED").length;u({total:ye,pending:ae,paused:0,approved:me,rejected:Q,draft:0,closed:oe})}else{const L=await At.getRequestStats(I,M?M.toISOString():void 0,W?W.toISOString():void 0,void 0,G==null?void 0:G.priority,G==null?void 0:G.templateType,G==null?void 0:G.department,G==null?void 0:G.initiator,G==null?void 0:G.approver,G==null?void 0:G.approverType,G==null?void 0:G.search,G==null?void 0:G.slaCompliance,!n);u({total:L.totalRequests||0,pending:L.openRequests||0,paused:L.pausedRequests||0,approved:L.approvedRequests||0,rejected:L.rejectedRequests||0,draft:L.draftRequests||0,closed:L.closedRequests||0})}}catch(ce){console.error("Failed to fetch backend stats:",ce)}finally{}},[n]),N=p.useCallback(async()=>{try{y(!0);const I=await At.getDepartments();b(I)}catch{}finally{y(!1)}},[]),P=p.useRef(i),R=p.useRef(A);p.useEffect(()=>{P.current=i,R.current=A},[i,A]),p.useEffect(()=>{const I=new URLSearchParams(window.location.search),M=I.get("approver"),W=I.get("approverType"),G=I.get("slaCompliance"),ce=I.get("dateRange"),te=I.get("startDate"),L=I.get("endDate");M&&i.setApproverFilter(M),(W==="current"||W==="any")&&i.setApproverFilterType(W),G&&i.setSlaComplianceFilter(G),ce&&i.setDateRange(ce),te&&i.setCustomStartDate(new Date(te)),L&&i.setCustomEndDate(new Date(L))},[]);const O=p.useCallback(async(I=1)=>{try{I===1&&(d(!0),o([]));const M=P.current.getFilters(),W=await B5({page:I,itemsPerPage:S,filters:M,isOrgLevel:n});o(W.data),i.setCurrentPage(W.pagination.page),w(W.pagination.totalPages),k(W.pagination.total)}catch{o([])}finally{d(!1)}},[S,n]),F=p.useCallback(async()=>{try{h(!0);const I=await V5(n);await mg(I,i.getFilters())}catch(I){console.error("Failed to export requests:",I),alert("Failed to export requests. Please try again.")}finally{h(!1)}},[n,i]);p.useEffect(()=>{N()},[N]),p.useEffect(()=>{const I=setTimeout(()=>{const M={priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0,department:i.departmentFilter!=="all"?i.departmentFilter:void 0,initiator:i.initiatorFilter!=="all"?i.initiatorFilter:void 0,approver:i.approverFilter!=="all"?i.approverFilter:void 0,approverType:i.approverFilter!=="all"?i.approverFilterType:void 0,search:i.searchTerm||void 0,slaCompliance:i.slaComplianceFilter!=="all"?i.slaComplianceFilter:void 0},W=i.dateRange||"all";R.current(W,i.customStartDate,i.customEndDate,M)},i.searchTerm?500:0);return()=>clearTimeout(I)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.templateTypeFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const $=p.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,slaComplianceFilter:i.slaComplianceFilter,departmentFilter:i.departmentFilter,initiatorFilter:i.initiatorFilter,approverFilter:i.approverFilter,approverFilterType:i.approverFilterType,dateRange:i.dateRange,customStartDate:i.customStartDate,customEndDate:i.customEndDate,isOrgLevel:n}),V=p.useRef(!1);p.useEffect(()=>{const I=i.currentPage||1;O(I),V.current=!0},[]),p.useEffect(()=>{if(!V.current)return;const I=$.current;if(!(I.searchTerm!==i.searchTerm||I.statusFilter!==i.statusFilter||I.priorityFilter!==i.priorityFilter||I.templateTypeFilter!==i.templateTypeFilter||I.slaComplianceFilter!==i.slaComplianceFilter||I.departmentFilter!==i.departmentFilter||I.initiatorFilter!==i.initiatorFilter||I.approverFilter!==i.approverFilter||I.approverFilterType!==i.approverFilterType||I.dateRange!==i.dateRange||I.customStartDate!==i.customStartDate||I.customEndDate!==i.customEndDate||I.isOrgLevel!==n))return;const W=setTimeout(()=>{i.setCurrentPage(1),O(1),$.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,slaComplianceFilter:i.slaComplianceFilter,departmentFilter:i.departmentFilter,initiatorFilter:i.initiatorFilter,approverFilter:i.approverFilter,approverFilterType:i.approverFilterType,dateRange:i.dateRange,customStartDate:i.customStartDate,customEndDate:i.customEndDate,isOrgLevel:n}},i.searchTerm!==I.searchTerm?500:0);return()=>clearTimeout(W)},[n,i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter,i.slaComplianceFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.dateRange,i.customStartDate,i.customEndDate]);const T=p.useCallback(I=>{I>=1&&I<=v&&(i.setCurrentPage(I),O(I))},[v,O,i]),j=p.useMemo(()=>ig(l),[l]),U=p.useMemo(()=>x?{total:x.total||0,pending:x.pending||0,paused:x.paused||0,approved:x.approved||0,rejected:x.rejected||0,draft:x.draft||0,closed:x.closed||0}:L5([],n,x,!1,C,j),[n,x,C,j]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(tg,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:F}),e.jsx(sg,{stats:U,onStatusFilter:I=>{i.setStatusFilter(I)}}),e.jsx(ee,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(se,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(E,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx($t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Ts,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search requests...",value:i.searchTerm,onChange:I=>i.setSearchTerm(I.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(We,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"paused",children:"Paused"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(We,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"All Priority"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(We,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs(We,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:f||g.length===0,children:[e.jsx(Ye,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ge,{placeholder:f?"Loading...":"All Departments"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Departments"}),g.map(I=>e.jsx(Y,{value:I,children:I},I))]})]}),e.jsxs(We,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"All SLA Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All SLA Status"}),e.jsx(Y,{value:"compliant",children:"Compliant"}),e.jsx(Y,{value:"on-track",children:"On Track"}),e.jsx(Y,{value:"approaching",children:"Approaching"}),e.jsx(Y,{value:"critical",children:"Critical"}),e.jsx(Y,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:_.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:_.selectedUser.displayName||_.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:_.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{placeholder:"Search initiator...",value:_.searchQuery,onChange:I=>_.handleSearch(I.target.value),onFocus:()=>{_.searchResults.length>0&&_.setShowResults(!0)},onBlur:()=>setTimeout(()=>_.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),_.showResults&&_.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:_.searchResults.map(I=>e.jsx("button",{type:"button",onClick:()=>_.handleSelect(I),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:I.displayName||I.email}),I.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:I.email})]})},I.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(We,{value:i.approverFilterType,onValueChange:I=>i.setApproverFilterType(I),children:[e.jsx(Ye,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"current",children:"Current Only"}),e.jsx(Y,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:D.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:D.selectedUser.displayName||D.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:D.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{placeholder:"Search approver...",value:D.searchQuery,onChange:I=>D.handleSearch(I.target.value),onFocus:()=>{D.searchResults.length>0&&D.setShowResults(!0)},onBlur:()=>setTimeout(()=>D.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),D.showResults&&D.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:D.searchResults.map(I=>e.jsx("button",{type:"button",onClick:()=>D.handleSelect(I),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:I.displayName||I.email}),I.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:I.email})]})},I.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Ye,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(Hs,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ot,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${He(i.customStartDate,"MMM d, yyyy")} - ${He(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Ms,{value:i.customStartDate||null,onChange:I=>{const M=I?new Date(I):void 0;M?(i.setCustomStartDate(M),i.customEndDate&&M>i.customEndDate&&i.setCustomEndDate(M)):i.setCustomStartDate(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",children:"End Date"}),e.jsx(Ms,{value:i.customEndDate||null,onChange:I=>{const M=I?new Date(I):void 0;M?(i.setCustomEndDate(M),i.customStartDate&&M<i.customStartDate&&i.setCustomStartDate(M)):i.setCustomEndDate(void 0)},minDate:i.customStartDate||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsx(E,{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(E,{size:"sm",variant:"outline",onClick:()=>{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})})]})})]})]})]})})}),e.jsx(ag,{requests:j,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(vr,{currentPage:i.currentPage||1,totalPages:v,totalRecords:C,itemsPerPage:S,onPageChange:T,loading:c,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 ks.listParticipantRequests({page:t,limit:s,...r});let i=[];Array.isArray(n==null?void 0:n.data)?i=n.data:Array.isArray(n)&&(i=n);const l=i.filter(c=>(c.status||"").toString().toUpperCase()!=="DRAFT"),o=(n==null?void 0:n.pagination)||{page:t,limit:s,total:l.length,totalPages:1};return{data:l,allData:[],filteredData:l,pagination:{page:o.page,limit:o.limit||s,total:o.total||l.length,totalPages:o.totalPages||1}}}const Su=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 ks.listParticipantRequests({page:r,limit:Su,...i});let o=[];if(Array.isArray(l==null?void 0:l.data)?o=l.data:Array.isArray(l)&&(o=l),o.length===0)a=!1;else{const c=o.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");s.push(...c),r++,l!=null&&l.pagination?a=r<=l.pagination.totalPages:a=o.length===Su}}return s}function G5({onViewRequest:t}){const s=ng(),a=p.useMemo(()=>{try{const W=tt.getUserData();return Eo(W)}catch(W){return console.error("[UserAllRequests] Error getting user filter type:",W),"STANDARD"}},[]),r=p.useMemo(()=>vT(a),[a]),n=a==="DEALER",i=p.useCallback(()=>{const W=s.getFilters();if(n){const{priority:G,templateType:ce,department:te,slaCompliance:L,...z}=W;return z}return W},[s,n]),l=p.useCallback(()=>n?!!(s.searchTerm||s.statusFilter!=="all"||s.initiatorFilter!=="all"||s.approverFilter!=="all"||s.dateRange!=="all"||s.customStartDate||s.customEndDate):s.hasActiveFilters,[n,s]),[o,c]=p.useState([]),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(null),[b,f]=p.useState([]),[y,v]=p.useState(!1),[w,C]=p.useState(1),[k,S]=p.useState(0),[_]=p.useState(10),D=hi({filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter,source:"local"}),A=hi({filterValue:s.approverFilter,onFilterChange:s.setApproverFilter,source:"local"}),N=p.useCallback(async(W,G,ce,te)=>{try{const L=await At.getRequestStats(W,G?G.toISOString():void 0,ce?ce.toISOString():void 0,void 0,te==null?void 0:te.priority,te==null?void 0:te.templateType,te==null?void 0:te.department,te==null?void 0:te.initiator,te==null?void 0:te.approver,te==null?void 0:te.approverType,te==null?void 0:te.search,te==null?void 0:te.slaCompliance,!0);g({total:L.totalRequests||0,pending:L.openRequests||0,paused:L.pausedRequests||0,approved:L.approvedRequests||0,rejected:L.rejectedRequests||0,draft:L.draftRequests||0,closed:L.closedRequests||0})}catch(L){console.error("Failed to fetch backend stats:",L)}},[]),P=p.useCallback(async()=>{try{v(!0);const W=await At.getDepartments();f(W)}catch{}finally{v(!1)}},[]),R=p.useRef(s),O=p.useRef(N),F=p.useRef(i);p.useEffect(()=>{R.current=s,O.current=N,F.current=i},[s,N,i]);const $=p.useCallback(async(W=1)=>{try{W===1&&(m(!0),c([]));const G=F.current(),ce=await H5({page:W,itemsPerPage:_,filters:G});c(ce.data),s.setCurrentPage(ce.pagination.page),C(ce.pagination.totalPages),S(ce.pagination.total)}catch{c([])}finally{m(!1)}},[_,s]),V=p.useCallback(async()=>{try{x(!0);const W=i(),G=await W5(W);await mg(G,W)}catch(W){console.error("Failed to export requests:",W),alert("Failed to export requests. Please try again.")}finally{x(!1)}},[i]);p.useEffect(()=>{P()},[P]),p.useEffect(()=>{const W=setTimeout(()=>{const G={initiator:s.initiatorFilter!=="all"?s.initiatorFilter:void 0,approver:s.approverFilter!=="all"?s.approverFilter:void 0,approverType:s.approverFilter!=="all"?s.approverFilterType:void 0,search:s.searchTerm||void 0};n||(s.priorityFilter!=="all"&&(G.priority=s.priorityFilter),s.templateTypeFilter!=="all"&&(G.templateType=s.templateTypeFilter),s.departmentFilter!=="all"&&(G.department=s.departmentFilter),s.slaComplianceFilter!=="all"&&(G.slaCompliance=s.slaComplianceFilter));const ce=s.dateRange==="all"?"all":s.dateRange||"month";O.current(ce,s.customStartDate,s.customEndDate,G)},s.searchTerm?500:0);return()=>clearTimeout(W)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter,n]);const T=p.useRef({searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}),j=p.useRef(!1);p.useEffect(()=>{const W=s.currentPage||1;$(W),j.current=!0},[]),p.useEffect(()=>{if(!j.current)return;const W=T.current;if(!(W.searchTerm!==s.searchTerm||W.statusFilter!==s.statusFilter||W.priorityFilter!==s.priorityFilter||W.templateTypeFilter!==s.templateTypeFilter||W.slaComplianceFilter!==s.slaComplianceFilter||W.departmentFilter!==s.departmentFilter||W.initiatorFilter!==s.initiatorFilter||W.approverFilter!==s.approverFilter||W.approverFilterType!==s.approverFilterType||W.dateRange!==s.dateRange||W.customStartDate!==s.customStartDate||W.customEndDate!==s.customEndDate))return;const ce=setTimeout(()=>{s.setCurrentPage(1),$(1),T.current={searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}},s.searchTerm!==W.searchTerm?500:0);return()=>clearTimeout(ce)},[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 U=p.useCallback(W=>{W>=1&&W<=w&&(s.setCurrentPage(W),$(W))},[w,$,s]),I=p.useMemo(()=>ig(o),[o]),M=p.useMemo(()=>{if(u)return{total:u.total||0,pending:u.pending||0,paused:u.paused||0,approved:u.approved||0,rejected:u.rejected||0,draft:u.draft||0,closed:u.closed||0};const W=I.filter(z=>{const H=(z.status||"").toString().toLowerCase();return H==="pending"||H==="in-progress"}).length,G=I.filter(z=>(z.status||"").toString().toLowerCase()==="paused").length,ce=I.filter(z=>(z.status||"").toString().toLowerCase()==="approved").length,te=I.filter(z=>(z.status||"").toString().toLowerCase()==="rejected").length,L=I.filter(z=>(z.status||"").toString().toLowerCase()==="closed").length;return{total:k>0?k:I.length,pending:W,paused:G,approved:ce,rejected:te,draft:0,closed:L}},[u,k,I]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"user-all-requests-page",children:[e.jsx(tg,{isOrgLevel:!1,isAdmin:!1,loading:d,exporting:h,onExport:V}),e.jsx(sg,{stats:M,onStatusFilter:W=>{s.setStatusFilter(W)}}),e.jsx(r,{searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,departmentFilter:s.departmentFilter,slaComplianceFilter:s.slaComplianceFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate,showCustomDatePicker:s.showCustomDatePicker,departments:b,loadingDepartments:y,initiatorSearch:D,approverSearch:A,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(ag,{requests:I,loading:d,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(vr,{currentPage:s.currentPage||1,totalPages:w,totalRecords:k,itemsPerPage:_,onPageChange:U,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function Y5(){const t=Ks();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(ee,{children:e.jsxs(se,{className:"p-8 text-center",children:[e.jsx(ze,{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(E,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(Ns,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function K5({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(cs,{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(E,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx($t,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function X5({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(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[s,"%"]}),e.jsx("div",{className:`p-2 rounded-lg ${s>=95?"bg-green-100":s>=90?"bg-blue-100":s>=85?"bg-orange-100":"bg-red-100"}`,children:e.jsx(Ot,{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(na,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.totalApproved}),e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(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(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[t.avgResponseHours.toFixed(1),"h"]}),e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(bo,{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(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.pendingCount}),e.jsx("div",{className:"p-2 bg-orange-100 rounded-lg",children:e.jsx(st,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function Z5({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(ee,{"data-testid":"approver-actions-stats",children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Approver's Actions"}),e.jsxs($e,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?Cj(a,r,n,""):"(all time)"]})]}),e.jsxs(se,{children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2",children:[e.jsx(cs,{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(wt,{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(st,{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(fo,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"text-2xl font-bold text-gray-700",children:(s==null?void 0:s.closedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Closed Requests"})]}),e.jsxs("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Re,{className:"w-5 h-5 text-blue-600"})}),e.jsx("div",{className:"text-2xl font-bold text-blue-700",children:(s==null?void 0:s.totalApproved)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Total Requests"})]})]})]}),e.jsxs("div",{className:"mb-6 pt-4 border-t",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2",children:[e.jsx(Ot,{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(p0,{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(ze,{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(Il,{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 J5({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:l,showCustomDatePicker:o,tempCustomStartDate:c,tempCustomEndDate:d,onSearchChange:m,onStatusChange:h,onPriorityChange:x,onSlaComplianceChange:u,onDateRangeChange:g,onShowCustomDatePickerChange:b,onTempStartDateChange:f,onTempEndDateChange:y,onApplyCustomDate:v,onClearFilters:w}){return e.jsxs(ee,{"data-testid":"approver-performance-filters",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{children:"Filters"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:w,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(se,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Oe,{placeholder:"Search requests...",value:t,onChange:C=>m(C.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(We,{value:s,onValueChange:h,children:[e.jsx(Ye,{"data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(We,{value:a,onValueChange:x,children:[e.jsx(Ye,{"data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"Priority"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(We,{value:r,onValueChange:u,children:[e.jsx(Ye,{"data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"SLA Compliance"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All SLA"}),e.jsx(Y,{value:"compliant",children:"Compliant"}),e.jsx(Y,{value:"on-track",children:"On Track"}),e.jsx(Y,{value:"approaching",children:"Approaching"}),e.jsx(Y,{value:"critical",children:"Critical"}),e.jsx(Y,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:n,onValueChange:g,children:[e.jsx(Ye,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(Hs,{open:o,onOpenChange:b,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(ot,{className:"w-4 h-4"}),c&&d?`${He(c,"MMM d")} - ${He(d,"MMM d")}`:"Select dates"]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Oe,{id:"start-date",type:"date",value:c?He(c,"yyyy-MM-dd"):"",onChange:C=>{const k=C.target.value?new Date(C.target.value):void 0;k?(f(k),d&&k>d&&y(k)):f(void 0)},max:He(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Oe,{id:"end-date",type:"date",value:d?He(d,"yyyy-MM-dd"):"",onChange:C=>{const k=C.target.value?new Date(C.target.value):void 0;k?(y(k),c&&k<c&&f(k)):y(void 0)},min:c?He(c,"yyyy-MM-dd"):void 0,max:He(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{size:"sm",onClick:v,disabled:!c||!d,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-date-button",children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>{b(!1),f(i),y(l),(!i||!l)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const Q5=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ta,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ot,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ot,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:wt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:st,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:Re,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 He(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function sk(t){if(!t)return"N/A";try{return He(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function pi(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=KT(s);n(l)}function ak({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const c=Ks();return e.jsxs(ee,{"data-testid":"approver-performance-request-list",children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Request Details"}),e.jsxs($e,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(se,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx($t,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading requests..."})]}):t.length===0?e.jsxs("div",{className:"text-center py-12 text-gray-500","data-testid":"empty-state",children:[e.jsx(Re,{className:"w-12 h-12 mx-auto mb-4 text-gray-400"}),e.jsx("p",{className:"text-sm",children:"No requests found for this approver"})]}):e.jsx("div",{className:"space-y-4",children:t.map(d=>{const m=Q5(d.priority),h=q5(d.status),x=ek(d.slaStatus||""),u=m.icon,g=h.icon;return e.jsx(ee,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{pi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm text-blue-600 hover:underline","data-testid":"request-number",children:d.requestNumber}),e.jsxs(ne,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(u,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(ne,{className:h.color,"data-testid":"status-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${h.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(ne,{className:d.approvalStatus==="approved"||d.approvalStatus==="APPROVED"?"bg-green-100 text-green-800 border-green-200":d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?"bg-red-100 text-red-800 border-red-200":"bg-yellow-100 text-yellow-800 border-yellow-200","data-testid":"approval-status-badge",children:d.approvalStatus==="approved"||d.approvalStatus==="APPROVED"?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(st,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.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:d.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-500 mt-2",children:[e.jsxs("span",{className:"flex items-center gap-1","data-testid":"initiator-info",children:[e.jsx(Vt,{className:"w-3 h-3"}),d.initiatorName,d.initiatorDepartment&&e.jsxs("span",{className:"ml-1",children:["(",d.initiatorDepartment,")"]})]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"submission-date",children:[e.jsx(st,{className:"w-3 h-3"}),"Submitted: ",tk(d.submissionDate)]}),d.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(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(Ot,{className:"w-3 h-3"}),"Level ",d.levelNumber," of ",d.totalLevels]}),d.levelElapsedHours&&d.levelElapsedHours>0&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"tat-info",children:[e.jsx(bo,{className:"w-3 h-3"}),Ft(d.levelElapsedHours)," / ",Ft(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:b=>{b.stopPropagation(),pi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(ss,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(vr,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function rk(){const[t]=cx(),[s,a]=p.useState(""),[r,n]=p.useState(t.get("status")||"all"),[i,l]=p.useState(t.get("priority")||"all"),[o,c]=p.useState(t.get("slaCompliance")||"all"),[d,m]=p.useState(t.get("dateRange")||"all"),[h,x]=p.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[u,g]=p.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[b,f]=p.useState(!1),[y,v]=p.useState(void 0),[w,C]=p.useState(void 0),k=p.useCallback(()=>{a(""),n("all"),l("all"),c("all"),m("all"),x(void 0),g(void 0),v(void 0),C(void 0),f(!1)},[]),S=p.useCallback(D=>{const A=D;m(A),A!=="custom"?(x(void 0),g(void 0),v(void 0),C(void 0),f(!1)):(v(h),C(u),f(!0))},[h,u]),_=p.useCallback(()=>{if(y&&w){if(y>w){const D=y;x(w),g(D),v(w),C(D)}else x(y),g(w);f(!1)}},[y,w]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:d,customStartDate:h,customEndDate:u,showCustomDatePicker:b,tempCustomStartDate:y,tempCustomEndDate:w,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:x,setCustomEndDate:g,setShowCustomDatePicker:f,setTempCustomStartDate:v,setTempCustomEndDate:C,clearFilters:k,handleDateRangeChange:S,handleApplyCustomDate:_}}function nk({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:l,searchTerm:o,itemsPerPage:c}){const[d,m]=p.useState([]),[h,x]=p.useState(null),[u,g]=p.useState([]),[b,f]=p.useState(!0),[y,v]=p.useState(!1),[w,C]=p.useState(1),[k,S]=p.useState(1),[_,D]=p.useState(0),A=p.useRef(!0),N=p.useCallback(async()=>{if(t)try{const F=s==="all"?void 0:s,$=await At.getSingleApproverStats(t,F,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);x($)}catch(F){console.error("[ApproverPerformance] Failed to fetch approver stats:",F),x(null)}},[t,s,a,r,i,l]),P=p.useCallback(async(F=1)=>{if(!t){f(!1);return}try{f(!0);const $=await At.getRequestsByApprover(t,F,c,s==="all"?void 0:s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,l!=="all"?l:void 0,o||void 0);m($.requests),D($.pagination.totalRecords),S($.pagination.totalPages),C($.pagination.currentPage),g($.requests)}catch($){console.error("Failed to fetch requests:",$)}finally{f(!1),v(!1)}},[t,s,a,r,n,i,l,o,c]);p.useEffect(()=>{A.current&&(A.current=!1,N(),P(1))},[]),p.useEffect(()=>{A.current||N()},[s,a,r,i,l]),p.useEffect(()=>{A.current||P(1)},[s,a,r,n,i,l,o]);const R=p.useCallback(()=>{v(!0),N(),P(1)},[N,P]),O=p.useCallback(F=>{P(F)},[P]);return{requests:d,approverStats:h,allFilteredRequests:u,loading:b,refreshing:y,currentPage:w,totalPages:k,totalRecords:_,handleRefresh:R,handlePageChange:O}}const Au=10;function ik(){const[t]=cx(),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:Au});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(K5,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(X5,{approverStats:n.approverStats}),n.approverStats&&e.jsx(Z5,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(J5,{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:Au,onPageChange:n.handlePageChange})]}):e.jsx(Y5,{})}function lk(){const{user:t}=Kt(),s=()=>{var a,r;if(t!=null&&t.displayName){const n=t.displayName.split(" ").filter(Boolean);return n.length>=2?`${((a=n[0])==null?void 0:a[0])||""}${((r=n[n.length-1])==null?void 0:r[0])||""}`.toUpperCase():t.displayName.substring(0,2).toUpperCase()}return t!=null&&t.email?t.email.substring(0,2).toUpperCase():"U"};return e.jsxs("div",{className:"space-y-6 max-w-7xl mx-auto",children:[e.jsxs(ee,{className:"relative overflow-hidden shadow-xl border-0",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(se,{className:"relative z-10 p-8 lg:p-12",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-start md:items-center gap-6",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Zt,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Di,{src:(t==null?void 0:t.picture)||""}),e.jsx(Jt,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),lr(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(hs,{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:[lr(t)&&e.jsxs(ne,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(hs,{className:"w-3 h-3 mr-1"}),"Administrator"]}),Jr(t)&&e.jsxs(ne,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(cs,{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(ee,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Vt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx($e,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(se,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Ra,{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(Vt,{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(Vt,{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(Vt,{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(ji,{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(ee,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-emerald-100 rounded-lg",children:e.jsx(Pd,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx($e,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(se,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[(t==null?void 0:t.employeeId)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Vt,{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(mo,{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(Pd,{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(hs,{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:lr(t)||Jr(t)?"default":"secondary",className:lr(t)?"bg-yellow-400 text-slate-900":Jr(t)?"bg-blue-400 text-slate-900":"",children:lr(t)?"Administrator":Jr(t)?"Management":"User"}),(lr(t)||Jr(t))&&e.jsx(De,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(ot,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx($e,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-green-50 rounded-lg border border-green-200",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-green-500 rounded-full",children:e.jsx(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 zn="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",ok="https://reflow-uat.royalenfield.com";function Al(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(zn.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:Al(zn)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Al(zn)})}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:Al(zn)})}catch(o){const c=(l==null?void 0:l.message)||(o==null?void 0:o.message)||"Unknown error";throw c.includes("push service error")||c.includes("Registration failed")?new Error("Push service error: The browser's push service rejected the subscription. This may be due to an invalid VAPID key, network issues, or browser push service problems. Please verify your VAPID key configuration and try again."):new Error(`Failed to subscribe to push notifications: ${c}`)}}}catch(i){const l=(i==null?void 0:i.message)||"Unknown error";throw l.includes("push service error")||l.includes("Registration failed")?new Error("Push service error: The browser's push service rejected the subscription. Please verify your VAPID key is correct and matches the backend configuration. If the problem persists, try clearing your browser cache and service workers."):l.includes("Invalid key")?new Error("Invalid VAPID key format. Please verify that VITE_PUBLIC_VAPID_KEY is correctly set and matches the backend VAPID_PUBLIC_KEY."):new Error(`Failed to subscribe to push notifications: ${l}`)}const a=s.toJSON(),r=!0,n=null;try{const i={"Content-Type":"application/json"},l=await fetch(`${ok}/api/v1/workflows/notifications/subscribe`,{method:"POST",headers:i,credentials:"include",body:JSON.stringify(a)});if(!l.ok){const c=await l.json().catch(()=>({error:"Unknown error"}));throw new Error((c==null?void 0:c.error)||(c==null?void 0:c.message)||`Server error: ${l.status}`)}const o=await l.json();if(!o.success)throw new Error(o.error||"Failed to save subscription")}catch(i){throw i instanceof Error&&i.message.includes("Failed")?i:new Error(`Failed to save subscription to server: ${(i==null?void 0:i.message)||"Network error"}`)}return s}async function 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 uk({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const l=p.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(jf,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:ke("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:ke("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:ke("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,c)=>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"},c))]})}function xk({onConfigUpdate:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!0),[i,l]=p.useState(null),[o,c]=p.useState(null),[d,m]=p.useState({}),[h,x]=p.useState(null);p.useEffect(()=>{u()},[]);const u=async()=>{var N,P;try{n(!0),c(null);const R=await X2();a(R)}catch(R){c(((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),c(null);const O=d[N.configKey]??N.configValue;if(N.validationRules){const F=parseFloat(O);if(N.valueType==="NUMBER"){if(N.validationRules.min!==void 0&&F<N.validationRules.min)throw new Error(`Value must be at least ${N.validationRules.min}`);if(N.validationRules.max!==void 0&&F>N.validationRules.max)throw new Error(`Value must be at most ${N.validationRules.max}`)}}await Z2(N.configKey,O),a(F=>F.map($=>$.configKey===N.configKey?{...$,configValue:O}:$)),m(F=>{const $={...F};return delete $[N.configKey],$}),x(`${N.displayName} updated successfully`),setTimeout(()=>x(null),3e3),t&&t()}catch(O){c(O.message||((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to save configuration")}finally{l(null)}},b=async N=>{var P,R;if(confirm(`Reset "${N.displayName}" to default value?`))try{l(N.configKey),c(null),await J2(N.configKey),a(O=>O.map(F=>F.configKey===N.configKey?{...F,configValue:F.defaultValue||""}:F)),m(O=>{const F={...O};return delete F[N.configKey],F}),x(`${N.displayName} reset to default`),setTimeout(()=>x(null),3e3)}catch(O){c(((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}))},y=N=>d[N.configKey]??N.configValue,v=N=>d[N.configKey]!==void 0&&d[N.configKey]!==N.configValue,w=N=>{var O,F,$,V;const P=y(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(ze,{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(on,{checked:P==="true",onCheckedChange:I=>f(N.configKey,I?"true":"false"),disabled:R})]});case"slider":const T=parseInt(P)||0,j=((O=N.validationRules)==null?void 0:O.min)||0,U=((F=N.validationRules)==null?void 0:F.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:[T,"%"]}),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(uk,{value:[T],min:j,max:U,step:1,onValueChange:([I])=>{I!==void 0&&f(N.configKey,I.toString())},disabled:R,className:"w-full"})]});case"number":return e.jsx(Oe,{type:"number",value:P,onChange:I=>f(N.configKey,I.target.value),disabled:R,min:($=N.validationRules)==null?void 0:$.min,max:(V=N.validationRules)==null?void 0:V.max,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"});case"text":case"input":default:return e.jsx(Oe,{type:"text",value:P,onChange:I=>f(N.configKey,I.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"})}},C=N=>{switch(N){case"TAT_SETTINGS":return e.jsx(st,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Re,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(qs,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(qu,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(wn,{className:"w-5 h-5"});default:return e.jsx(Va,{className:"w-5 h-5"})}},k=["DASHBOARD_LAYOUT"],S=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],_=s.filter(N=>!k.includes(N.configCategory)&&!S.includes(N.configKey)),D=_.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(lt,{className:"w-8 h-8 animate-spin text-gray-400"})});if(_.length===0)return e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(Va,{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 A=Object.keys(D);return e.jsxs("div",{className:"space-y-6",children:[h&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(De,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:h})]}),o&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:o}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs($i,{defaultValue:A[0],className:"w-full",children:[e.jsx(Oi,{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:A.map(N=>e.jsx(qt,{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))}),A.map(N=>{var P,R,O;return e.jsx(es,{value:N,className:"space-y-4 mt-6",children:e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{className:"pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx("div",{className:"text-white",children:C(N)})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-slate-900",children:N.replace(/_/g," ")}),e.jsxs($e,{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(se,{className:"space-y-6",children:(O=D[N])==null?void 0:O.map(F=>e.jsxs("div",{className:"space-y-3 pb-6 border-b border-slate-100 last:border-b-0 last:pb-0 hover:bg-slate-50/50 -mx-6 px-6 py-4 rounded-md transition-colors",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[e.jsx(re,{className:"text-sm font-semibold text-slate-900",children:F.displayName}),v(F)&&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"}),F.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"})]}),F.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:F.description}),F.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:F.defaultValue})]})]})}),w(F),F.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(E,{size:"sm",onClick:()=>g(F),disabled:!v(F)||i===F.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===F.configKey?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ox,{className:"w-4 h-4"}),"Save Changes"]})}),F.defaultValue&&e.jsxs(E,{size:"sm",variant:"outline",onClick:()=>b(F),disabled:i===F.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(g0,{className:"w-4 h-4"}),"Reset to Default"]})]})]},F.configKey))})]})},N)})]})]})}function hk(){const[t,s]=p.useState([]),[a,r]=p.useState(!0),[n,i]=p.useState(new Date().getFullYear()),[l,o]=p.useState(!1),[c,d]=p.useState(null),[m,h]=p.useState(null),[x,u]=p.useState(null),[g,b]=p.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});p.useEffect(()=>{f()},[n]);const f=async()=>{var N,P;try{r(!0),h(null);const R=await Q2(n);s(R)}catch(R){h(((P=(N=R.response)==null?void 0:N.data)==null?void 0:P.error)||"Failed to load holidays")}finally{r(!1)}},y=()=>{b({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),o(!0)},v=N=>{b({holidayDate:N.holidayDate,holidayName:N.holidayName,description:N.description||"",holidayType:N.holidayType,isRecurring:N.isRecurring}),d(N),o(!0)},w=()=>{if(c)return;const N=new Date;return N.setDate(N.getDate()+1),N.toISOString().split("T")[0]},C=async()=>{var N,P;try{if(h(null),!g.holidayDate||!g.holidayName){h("Holiday date and name are required");return}c?(await eS(c.holidayId,g),u("Holiday updated successfully")):(await q2(g),u("Holiday created successfully")),await f(),o(!1),setTimeout(()=>u(null),3e3)}catch(R){h(((P=(N=R.response)==null?void 0:N.data)==null?void 0:P.error)||"Failed to save holiday")}},k=async N=>{var P,R;if(confirm(`Delete "${N.holidayName}"?`))try{h(null),await tS(N.holidayId),u("Holiday deleted successfully"),await f(),setTimeout(()=>u(null),3e3)}catch(O){h(((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to delete holiday")}},S=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"}},_=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},{}),A=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(ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:m}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>h(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ge,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(ot,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx($e,{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(We,{value:n.toString(),onValueChange:N=>i(parseInt(N)),children:[e.jsx(Ye,{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(Ge,{})}),e.jsx(Ke,{className:"rounded-md",children:_.map(N=>e.jsx(Y,{value:N.toString(),children:N},N))})]}),e.jsxs(E,{onClick:y,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(gs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Add Holiday"}),e.jsx("span",{className:"xs:hidden",children:"Add"})]})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(lt,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(ot,{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(E,{onClick:y,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:A.map(N=>{var P,R,O;return e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[N," ",n]}),e.jsxs($e,{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(ot,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:(O=D[N])==null?void 0:O.map(F=>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:F.holidayName}),e.jsx(ne,{variant:"outline",className:`${S(F.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:F.holidayType}),F.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:Yx(F.holidayDate)}),F.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:F.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>v(F),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>k(F),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(yo,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},F.holidayId))})]},N)})}),e.jsx(pt,{open:l,onOpenChange:o,children:e.jsxs(dt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(gt,{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(ot,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(Dt,{className:"text-sm text-slate-600 mt-1",children:c?"Update holiday information":"Add a new holiday to the calendar for TAT calculations"})]})]})}),e.jsxs("div",{className:"space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"date",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Oe,{id:"date",type:"date",value:g.holidayDate,onChange:N=>b({...g,holidayDate:N.target.value}),min:w(),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:c?"Select the holiday date":"Select the holiday date (minimum: tomorrow)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"name",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Holiday Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Oe,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:N=>b({...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(re,{htmlFor:"description",className:"text-sm font-semibold text-slate-900",children:["Description ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Oe,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:N=>b({...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(re,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(We,{value:g.holidayType,onValueChange:N=>b({...g,holidayType:N}),children:[e.jsx(Ye,{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(Ge,{})}),e.jsxs(Ke,{className:"rounded-lg",children:[e.jsx(Y,{value:"NATIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-red-500"}),e.jsx("span",{children:"National"})]})}),e.jsx(Y,{value:"REGIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-500"}),e.jsx("span",{children:"Regional"})]})}),e.jsx(Y,{value:"ORGANIZATIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-purple-500"}),e.jsx("span",{children:"Organizational"})]})}),e.jsx(Y,{value:"OPTIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-500"}),e.jsx("span",{children:"Optional"})]})})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select the category of this holiday"})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gradient-to-br from-slate-50 to-slate-100/50 border-2 border-slate-200 rounded-lg hover:border-slate-300 hover:bg-slate-100 transition-all cursor-pointer group",onClick:()=>b({...g,isRecurring:!g.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:g.isRecurring,onChange:N=>b({...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(re,{htmlFor:"recurring",className:"font-semibold cursor-pointer text-sm text-slate-900 block mb-1",children:"Recurring Holiday"}),e.jsx("p",{className:"text-xs text-slate-600",children:"This holiday will automatically repeat every year on the same date"})]})]})]}),e.jsxs(Tt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(E,{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(E,{onClick:C,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(ot,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function pk(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function gk(){const[t,s]=p.useState(""),[a,r]=p.useState([]),[n,i]=p.useState(!1),[l,o]=p.useState(null),[c,d]=p.useState("USER"),[m,h]=p.useState(!1),[x,u]=p.useState(null),[g,b]=p.useState([]),[f,y]=p.useState(!1),[v,w]=p.useState({admins:0,management:0,users:0}),[C,k]=p.useState("ELEVATED"),[S,_]=p.useState(1),[D,A]=p.useState(1),[N,P]=p.useState(0),R=10,O=p.useRef(null),F=p.useRef(null),$=p.useCallback(pk(async L=>{var z,H,ye;if(!L||!L.startsWith("@")||L.length<2){r([]),i(!1);return}i(!0);try{const ae=L.slice(1),Q=((z=(await dr.searchUsers(ae,20)).data)==null?void 0:z.data)||[];r(Q)}catch(ae){console.error("Search failed:",ae),u({type:"error",text:((ye=(H=ae.response)==null?void 0:H.data)==null?void 0:ye.message)||"Failed to search users"})}finally{i(!1)}},300),[]),V=L=>{const z=L.target.value;s(z),$(z)},T=async L=>{o(L),s(L.email),r([]);const z=g.find(H=>H.email.toLowerCase()===L.email.toLowerCase()||H.userId===L.userId);if(z&&z.role)d(z.role);else try{const ye=(await dr.getAllUsers()).find(ae=>ae.email&&ae.email.toLowerCase()===L.email.toLowerCase()||ae.userId&&ae.userId===L.userId);ye&&ye.role?d(ye.role):d("USER")}catch(H){console.error("Failed to check user role:",H),d("USER")}},j=async()=>{var L,z;if(!l||!c){u({type:"error",text:"Please select a user and role"});return}h(!0),u(null);try{await dr.assignRole(l.email,c),u({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await U(),await I()}catch(H){console.error("Role assignment failed:",H),u({type:"error",text:((z=(L=H.response)==null?void 0:L.data)==null?void 0:z.error)||"Failed to assign role"})}finally{h(!1)}},U=async(L=S)=>{var z,H,ye,ae,me,Q;y(!0);try{const oe=await dr.getUsersByRole(C,L,R),Ce=((H=(z=oe.data)==null?void 0:z.data)==null?void 0:H.users)||[],Ee=(ae=(ye=oe.data)==null?void 0:ye.data)==null?void 0:ae.pagination,be=(Q=(me=oe.data)==null?void 0:me.data)==null?void 0:Q.summary;b(Ce),Ee&&(_(Ee.currentPage),A(Ee.totalPages),P(Ee.totalUsers)),be&&w({admins:be.ADMIN||0,management:be.MANAGEMENT||0,users:be.USER||0})}catch(oe){console.error("Failed to fetch users:",oe)}finally{y(!1)}},I=async()=>{var L,z,H,ye,ae,me;try{const Q=await dr.getRoleStatistics(),oe=((z=(L=Q.data)==null?void 0:L.data)==null?void 0:z.statistics)||((H=Q.data)==null?void 0:H.statistics)||[];w({admins:parseInt(((ye=oe.find(Ce=>Ce.role==="ADMIN"))==null?void 0:ye.count)||"0"),management:parseInt(((ae=oe.find(Ce=>Ce.role==="MANAGEMENT"))==null?void 0:ae.count)||"0"),users:parseInt(((me=oe.find(Ce=>Ce.role==="USER"))==null?void 0:me.count)||"0")})}catch(Q){console.error("Failed to fetch statistics:",Q)}};p.useEffect(()=>{U(1),I()},[C]);const M=L=>{k(L),_(1)},W=L=>{U(L)},G=L=>{k(L),_(1),requestAnimationFrame(()=>{const z=F.current;z&&z.scrollIntoView({behavior:"smooth",block:"start"})})};p.useEffect(()=>{const L=z=>{O.current&&!O.current.contains(z.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L)}},[a]);const ce=L=>{switch(L){case"ADMIN":return"bg-yellow-400 text-slate-800";case"MANAGEMENT":return"bg-blue-400 text-slate-800";default:return"bg-gray-400 text-slate-800"}},te=L=>{switch(L){case"ADMIN":return e.jsx(Ln,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(cs,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(Vt,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(f0,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx($e,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6",children:[e.jsx(ee,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${C==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>G("ADMIN"),children:e.jsx(se,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Administrators"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"admin-count",children:v.admins}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1 font-semibold",children:C==="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(Ln,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(ee,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${C==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>G("MANAGEMENT"),children:e.jsx(se,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Management"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"management-count",children:v.management}),e.jsx("p",{className:"text-xs text-blue-700 mt-1 font-semibold",children:C==="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(cs,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(ee,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${C==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>G("USER"),children:e.jsx(se,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Regular Users"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"user-count",children:v.users}),e.jsx("p",{className:"text-xs text-gray-700 mt-1 font-semibold",children:C==="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(Vt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(Ts,{}),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(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(Oe,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:V,className:"pl-10 pr-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"user-search-input"}),n&&e.jsx(lt,{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(L=>e.jsxs("button",{onClick:()=>T(L),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${L.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:L.displayName||L.email}),e.jsx("p",{className:"text-xs text-gray-600",children:L.email}),L.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[L.department,L.designation?` • ${L.designation}`:""]})]},L.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(E,{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(We,{value:c,onValueChange:L=>d(L),children:[e.jsx(Ye,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Ge,{placeholder:"Select role"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(Y,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(Y,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ln,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(E,{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(lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hs,{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(ze,{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(Ts,{}),e.jsxs("div",{ref:F,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," ",C!=="ALL"&&C!=="ELEVATED"?C.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(We,{value:C,onValueChange:M,children:[e.jsx(Ye,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Ge,{placeholder:"Filter by role"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",v.admins+v.management,")"]})]})}),e.jsx(Y,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ln,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",v.admins,")"]})]})}),e.jsx(Y,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",v.management,")"]})]})}),e.jsx(Y,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",v.users,")"]})]})}),e.jsx(Y,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{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(lt,{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(cs,{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:C==="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(L=>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-${L.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(L.role)} flex items-center justify-center shadow-sm`,children:te(L.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:L.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:L.email}),L.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[L.department,L.designation?` • ${L.designation}`:""]})]})]}),e.jsx(ne,{className:`${ce(L.role)} shrink-0`,"data-testid":`role-badge-${L.role}`,children:L.role})]})},L.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 ",(S-1)*R+1," to ",Math.min(S*R,N)," of ",N," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>W(S-1),disabled:S===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,D)},(L,z)=>{let H;return D<=5||S<=3?H=z+1:S>=D-2?H=D-4+z:H=S-2+z,e.jsx(E,{variant:S===H?"default":"outline",size:"sm",onClick:()=>W(H),className:`w-9 h-9 p-0 ${S===H?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${H}-button`,children:H},H)})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>W(S+1),disabled:S===D,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function fk(){const[t,s]=p.useState([]),[a,r]=p.useState(!0),[n,i]=p.useState(!1),[l,o]=p.useState(null),[c,d]=p.useState(null),[m,h]=p.useState(null),[x,u]=p.useState({title:"",itemCode:"",taxationType:"",sapRefNo:""});p.useEffect(()=>{g()},[]);const g=async()=>{var k,S;try{r(!0),d(null);const _=await aS(!1);s(_)}catch(_){const D=((S=(k=_.response)==null?void 0:k.data)==null?void 0:S.error)||"Failed to load activity types";d(D),K.error(D)}finally{r(!1)}},b=()=>{u({title:"",itemCode:"",taxationType:"",sapRefNo:""}),o(null),i(!0)},f=k=>{u({title:k.title,itemCode:k.itemCode||"",taxationType:k.taxationType||"",sapRefNo:k.sapRefNo||""}),o(k),i(!0)},y=async()=>{var k,S;try{if(d(null),!x.title.trim()){d("Activity type title is required");return}const _={title:x.title.trim(),itemCode:x.itemCode.trim()||null,taxationType:x.taxationType.trim()||null,sapRefNo:x.sapRefNo.trim()||null};l?(await nS(l.activityTypeId,_),h("Activity type updated successfully"),K.success("Activity type updated successfully")):(await rS(_),h("Activity type created successfully"),K.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>h(null),3e3)}catch(_){const D=((S=(k=_.response)==null?void 0:k.data)==null?void 0:S.error)||"Failed to save activity type";d(D),K.error(D)}},v=async k=>{var S,_;if(confirm(`Delete "${k.title}"? This will deactivate the activity type.`))try{d(null),await iS(k.activityTypeId),h("Activity type deleted successfully"),K.success("Activity type deleted successfully"),await g(),setTimeout(()=>h(null),3e3)}catch(D){const A=((_=(S=D.response)==null?void 0:S.data)==null?void 0:_.error)||"Failed to delete activity type";d(A),K.error(A)}},w=t.filter(k=>k.isActive!==!1&&k.isActive!==void 0),C=t.filter(k=>k.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})]}),c&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:c}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>d(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ge,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Re,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Activity Types"}),e.jsx($e,{className:"text-sm",children:"Manage dealer claim activity types"})]})]}),e.jsxs(E,{onClick:b,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Add Activity Type"}),e.jsx("span",{className:"xs:hidden",children:"Add"})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(lt,{className:"w-8 h-8 animate-spin text-gray-400"})}):w.length===0?e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(Re,{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(E,{onClick:b,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),"Add First Activity Type"]})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Active Activity Types"}),e.jsxs($e,{className:"text-xs sm:text-sm",children:[w.length," active type",w.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(se,{className:"space-y-3 pt-4",children:w.map(k=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 hover:border-slate-300 transition-all shadow-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-900 text-sm sm:text-base",children:k.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:[k.itemCode&&e.jsxs("span",{className:"font-medium",children:["Item Code: ",e.jsx("span",{className:"text-slate-900",children:k.itemCode})]}),k.taxationType&&e.jsxs("span",{className:"font-medium",children:["Taxation: ",e.jsx("span",{className:"text-slate-900",children:k.taxationType})]}),k.sapRefNo&&e.jsxs("span",{className:"font-medium",children:["SAP Ref: ",e.jsx("span",{className:"text-slate-900",children:k.sapRefNo})]}),!k.itemCode&&!k.taxationType&&!k.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(E,{size:"sm",variant:"ghost",onClick:()=>f(k),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>v(k),className:"gap-1.5 text-red-600 hover:text-red-700 hover:bg-red-50 border border-transparent hover:border-red-200 text-xs sm:text-sm",children:[e.jsx(yo,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},k.activityTypeId))})]}),C.length>0&&e.jsxs(ee,{className:"shadow-lg border-0 rounded-md border-amber-200",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Inactive Activity Types"}),e.jsxs($e,{className:"text-xs sm:text-sm",children:[C.length," inactive type",C.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-amber-50 rounded-md",children:e.jsx(ze,{className:"w-4 h-4 text-amber-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:C.map(k=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-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:k.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(E,{size:"sm",variant:"ghost",onClick:()=>f(k),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]})})]},k.activityTypeId))})]})]}),e.jsx(pt,{open:n,onOpenChange:i,children:e.jsxs(dt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(gt,{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(Re,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl font-semibold text-slate-900",children:l?"Edit Activity Type":"Add New Activity Type"}),e.jsx(Dt,{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(re,{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(Oe,{id:"title",placeholder:"e.g., Riders Mania Claims, Legal Claims Reimbursement",value:x.title,onChange:k=>u({...x,title:k.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(re,{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(Oe,{id:"itemCode",placeholder:"e.g., 1, 2, 3",value:x.itemCode,onChange:k=>u({...x,itemCode:k.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(re,{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(Oe,{id:"taxationType",placeholder:"e.g., GST, VAT, Exempt",value:x.taxationType,onChange:k=>u({...x,taxationType:k.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(re,{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(Oe,{id:"sapRefNo",placeholder:"e.g., SAP-12345",value:x.sapRefNo,onChange:k=>u({...x,sapRefNo:k.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(E,{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(E,{onClick:y,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(Re,{className:"w-4 h-4 mr-2"}),l?"Update Activity Type":"Add Activity Type"]})]})]})})]})}function bk({open:t,onClose:s,success:a,message:r}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(qs,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(Dt,{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(wt,{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(E,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const yk=async()=>(await je.get("/user/preferences/notifications")).data.data,vk=async t=>(await je.put("/user/preferences/notifications",t)).data.data;function jk({open:t,onClose:s}){const[a,r]=p.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=p.useState(!0),[l,o]=p.useState(null),[c,d]=p.useState(null),[m,h]=p.useState(null);p.useEffect(()=>{t&&x()},[t]);const x=async()=>{var g,b;try{i(!0),h(null);const f=await yk();r(f)}catch(f){console.error("[NotificationPreferences] Failed to load preferences:",f),h(((b=(g=f.response)==null?void 0:g.data)==null?void 0:b.message)||"Failed to load notification preferences")}finally{i(!1)}},u=async(g,b)=>{var f,y;try{o(g),h(null),d(null);const v={[g]:b},w=await vk(v);r(w),d(`${g==="emailNotificationsEnabled"?"Email":g==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${b?"enabled":"disabled"}`),setTimeout(()=>d(null),3e3)}catch(v){console.error("[NotificationPreferences] Failed to update preference:",v),h(((y=(f=v.response)==null?void 0:f.data)==null?void 0:y.message)||"Failed to update notification preference"),x()}finally{o(null)}};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(gt,{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(Va,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(mt,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(Dt,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(Ts,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(lt,{className:"w-8 h-8 animate-spin text-gray-400"})}):e.jsxs("div",{className:"space-y-6",children:[c&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-50 border border-green-200 rounded-md animate-in fade-in slide-in-from-top-2",children:[e.jsx(De,{className:"w-4 h-4 text-green-600 shrink-0"}),e.jsx("p",{className:"text-sm text-green-800 font-medium",children:c})]}),m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-md animate-in fade-in slide-in-from-top-2",children:[e.jsx(ze,{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(Ra,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Receive important updates and alerts via email"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="emailNotificationsEnabled"&&e.jsx(lt,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(on,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:g=>u("emailNotificationsEnabled",g),disabled:l==="emailNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(qs,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"push-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Push Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Get instant browser notifications for real-time updates"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="pushNotificationsEnabled"&&e.jsx(lt,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(on,{id:"push-notifications-modal",checked:a.pushNotificationsEnabled,onCheckedChange:g=>u("pushNotificationsEnabled",g),disabled:l==="pushNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(As,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"inapp-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"View notifications in the notification center"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="inAppNotificationsEnabled"&&e.jsx(lt,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(on,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>u("inAppNotificationsEnabled",g),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx(Ts,{}),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 Nk(){const{user:t}=Kt(),s=lr(t),[a,r]=p.useState(!1),[n,i]=p.useState(!1),[l,o]=p.useState(),[c,d]=p.useState(!1),[m,h]=p.useState(!1),[x,u]=p.useState(!1),[g,b]=p.useState(!0),[f,y]=p.useState(!1);p.useEffect(()=>{v()},[]);const v=async()=>{try{b(!0);const C=await ry();u(C.length>0)}catch(C){console.error("Failed to check subscription status:",C),u(!1)}finally{b(!1)}},w=async()=>{d(!0),r(!1);try{if(!("Notification"in window)){i(!1),o("Notifications are not supported in this browser. Please use a modern browser like Chrome, Firefox, or Edge."),r(!0),d(!1);return}let C=Notification.permission;if(C==="denied"){i(!1),o(`Notification permission was previously denied. To enable notifications:
1. Click the lock icon (🔒) or info icon () in your browser's address bar
2. Find "Notifications" in the permissions list
3. Change it from "Block" to "Allow"
4. Refresh this page and try again
Alternatively, you can enable notifications in your browser's site settings.`),r(!0),d(!1);return}if(C==="default"&&(C=await Notification.requestPermission(),C==="denied")){i(!1),o(`Notification permission was denied. To enable notifications:
1. Click the lock icon (🔒) or info icon () in your browser's address bar
2. Find "Notifications" in the permissions list
3. Change it from "Block" to "Allow"
4. Refresh this page and try again`),r(!0),d(!1);return}if(C!=="granted"){i(!1),o("Notification permission is required to enable push notifications. Please grant permission and try again."),r(!0),d(!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(C){console.error("[Settings] Error enabling notifications:",C),i(!1);const k=(C==null?void 0:C.message)||"Unknown error occurred";o(k.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":k.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":k.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${k}`),r(!0)}finally{d(!1)}};return e.jsxs("div",{className:"min-h-screen pb-8",children:[e.jsxs("div",{className:"max-w-7xl mx-auto space-y-6",children:[e.jsxs(ee,{className:"relative overflow-hidden shadow-2xl border-0 rounded-2xl",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,_var(--tw-gradient-stops))] from-yellow-400/20 via-transparent to-transparent"}),e.jsx(se,{className:"relative z-10 p-6 sm:p-8 lg:p-12",children:e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[e.jsx("div",{className:"w-14 h-14 sm:w-16 sm:h-16 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-2xl flex items-center justify-center shadow-xl transform hover:scale-105 transition-transform",children:e.jsx(Va,{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($i,{defaultValue:"user",className:"w-full",children:[e.jsxs(Oi,{className:"grid w-full grid-cols-2 lg:grid-cols-4 mb-8 bg-slate-100 p-1 rounded-xl h-auto gap-1",children:[e.jsxs(qt,{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(Va,{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(qt,{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(hs,{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(qt,{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(b0,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(qt,{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(ot,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Holidays"}),e.jsx("span",{className:"sm:hidden",children:"Holidays"})]}),e.jsxs(qt,{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(Re,{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(es,{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(ee,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(qs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx($e,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-4",children:[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(E,{onClick:w,disabled:c||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(qs,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":x?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(pn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx($e,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Security settings will be available soon"})})})})]}),e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Id,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx($e,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Appearance settings will be available soon"})})})})]}),e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(hs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx($e,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(se,{children:e.jsxs(E,{onClick:()=>h(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(hs,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(es,{value:"roles",className:"mt-0",children:e.jsx(gk,{})}),e.jsx(es,{value:"system",className:"mt-0",children:e.jsx(xk,{})}),e.jsx(es,{value:"holidays",className:"mt-0",children:e.jsx(hk,{})}),e.jsx(es,{value:"templates",className:"mt-0",children:f?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ge,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(E,{variant:"ghost",size:"sm",onClick:()=>y(!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(Re,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Dealer Claim Activity Settings"}),e.jsx($e,{className:"text-sm",children:"Manage activity types for dealer claim workflows"})]})]})})})}),e.jsx(fk,{})]}):e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Re,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Template Settings"}),e.jsx($e,{className:"text-sm",children:"Manage templates and activity types for workflows"})]})]})}),e.jsx(se,{className:"pt-6",children:e.jsx("div",{className:"space-y-4",children:e.jsx(ee,{className:"shadow-md hover:shadow-lg transition-all duration-300 border border-slate-200 rounded-lg cursor-pointer group",onClick:()=>y(!0),children:e.jsx(se,{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(Re,{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(ee,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(qs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx($e,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-4",children:[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(E,{onClick:w,disabled:c||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(qs,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":x?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(pn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx($e,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Security settings will be available soon"})})})})]}),e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Id,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx($e,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Appearance settings will be available soon"})})})})]}),e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(hs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx($e,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(se,{children:e.jsxs(E,{onClick:()=>h(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(hs,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(bk,{open:a,onClose:()=>r(!1),success:n,message:l}),e.jsx(jk,{open:m,onClose:()=>h(!1)})]})}function wk({onNavigate:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!0),[i,l]=p.useState(1),[o,c]=p.useState(1),[d,m]=p.useState(0),[h,x]=p.useState("all"),[u,g]=p.useState(!1),b=20,f=async(A=i,N=h==="unread")=>{var P,R;try{n(A===1);const O=await Ba.list({page:A,limit:b,unreadOnly:N}),F=((P=O.data)==null?void 0:P.notifications)||[],$=((R=O.data)==null?void 0:R.pagination)||{},V=$.total||0,T=$.totalPages||1;a(F),m(V),c(T),l(A)}catch(O){console.error("[Notifications] Failed to fetch:",O)}finally{n(!1),g(!1)}};p.useEffect(()=>{l(1),f(1,h==="unread")},[h]);const y=async A=>{var N;try{if(A.isRead||(await Ba.markAsRead(A.notificationId),a(P=>P.map(R=>R.notificationId===A.notificationId?{...R,isRead:!0}:R))),A.actionUrl&&t){const P=(N=A.metadata)==null?void 0:N.requestNumber;if(P){let R=`request/${P}`;(A.notificationType==="mention"||A.notificationType==="comment"||A.notificationType==="worknote")&&(R+="?tab=worknotes"),A.notificationType==="document_added"&&(R+="?tab=documents"),t(R)}}}catch(P){console.error("[Notifications] Error handling notification click:",P)}},v=async()=>{try{g(!0),await Ba.markAllAsRead(),await f(i,h==="unread")}catch(A){console.error("[Notifications] Error marking all as read:",A),g(!1)}},w=async A=>{try{await Ba.delete(A),a(N=>N.filter(P=>P.notificationId!==A)),m(N=>N-1)}catch(N){console.error("[Notifications] Error deleting notification:",N)}},C=()=>{g(!0),f(i,h==="unread")},k=A=>{A<1||A>o||(l(A),f(A,h==="unread"))},S=A=>{const N="w-6 h-6";switch(A){case"mention":case"comment":return e.jsx(As,{className:`${N} text-blue-600`});case"worknote":return e.jsx(Re,{className:`${N} text-purple-600`});case"document_added":return e.jsx(Re,{className:`${N} text-teal-600`});case"assignment":return e.jsx(wi,{className:`${N} text-indigo-600`});case"approval":return e.jsx(De,{className:`${N} text-green-600`});case"rejection":return e.jsx(wt,{className:`${N} text-red-600`});case"tat_alert":return e.jsx(st,{className:`${N} text-orange-600`});case"tat_breach":return e.jsx(ze,{className:`${N} text-red-600`});case"tat_breach_initiator":return e.jsx(as,{className:`${N} text-amber-600`});default:return e.jsx(qs,{className:`${N} text-gray-600`})}},_=A=>{switch(A==null?void 0:A.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(A=>!A.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(qs,{className:"w-8 h-8 text-blue-600"}),"Notifications"]}),e.jsxs("p",{className:"text-gray-600 mt-1",children:[d," total notification",d!==1?"s":"",D>0&&` • ${D} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:C,disabled:u,className:"gap-2",children:[e.jsx($t,{className:`w-4 h-4 ${u?"animate-spin":""}`}),"Refresh"]}),D>0&&e.jsxs(E,{variant:"outline",size:"sm",onClick:v,disabled:u,className:"gap-2",children:[e.jsx(y0,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{variant:h==="all"?"default":"outline",size:"sm",onClick:()=>{x("all"),l(1)},children:"All Notifications"}),e.jsxs(E,{variant:h==="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(ee,{children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Recent Activity"}),e.jsx($e,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(se,{children:r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"})}):s.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(qs,{className:"w-16 h-16 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-lg font-medium text-gray-900 mb-2",children:"No notifications"}),e.jsx("p",{className:"text-sm text-gray-500",children:h==="unread"?"You're all caught up! No unread notifications.":"You don't have any notifications yet."})]}):e.jsx("div",{className:"space-y-2",children:s.map(A=>{var N;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${A.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>y(A),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:S(A.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 ${A.isRead?"font-semibold":"font-bold"} text-gray-900`,children:A.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[A.priority&&A.priority!=="LOW"&&e.jsx(ne,{variant:"outline",className:`text-xs ${_(A.priority)}`,children:A.priority}),!A.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:A.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[zu(new Date(A.createdAt),{addSuffix:!0}),((N=A.metadata)==null?void 0:N.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",A.metadata.requestNumber]})]}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:P=>{P.stopPropagation(),w(A.notificationId)},children:e.jsx(yo,{className:"w-3.5 h-3.5"})})]})]})]})},A.notificationId)})})})]}),!r&&o>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing ",(i-1)*b+1," to ",Math.min(i*b,d)," of ",d," notifications"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>k(i-1),disabled:i===1,children:[e.jsx(Zu,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,o)},(A,N)=>{let P;return o<=5||i<=3?P=N+1:i>=o-2?P=o-4+N:P=i-2+N,e.jsx(E,{variant:i===P?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>k(P),children:P},P)})}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>k(i+1),disabled:i===o,children:["Next",e.jsx(yi,{className:"w-4 h-4"})]})]})]})]})}function Ck({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(E,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(Ns,{className:"w-4 h-4 mr-2"}),"Back to Dashboard"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(Re,{className:"h-6 w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Detailed Reports"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Comprehensive workflow and activity reports"})]})]})]})})}function fc({dateRange:t,customStartDate:s,customEndDate:a,showCustomDatePicker:r,tempCustomStartDate:n,tempCustomEndDate:i,onDateRangeChange:l,onShowCustomDatePickerChange:o,onStartDateChange:c,onEndDateChange:d,onApply:m,onCancel:h,testIdPrefix:x="date-filter"}){const u=s&&a?`${He(s,"d MMM yyyy")} - ${He(a,"d MMM yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${x}-container`,children:[e.jsx(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:t,onValueChange:l,"data-testid":`${x}-select`,children:[e.jsx(Ye,{className:"w-[160px]",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(Hs,{open:r,onOpenChange:o,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${x}-custom-trigger`,children:[e.jsx(ot,{className:"w-4 h-4"}),u]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:`${x}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(Ms,{value:n||null,onChange:g=>{const b=g?new Date(g):void 0;c(b)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full",id:`${x}-start-date`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:`${x}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(Ms,{value:i||null,onChange:g=>{const b=g?new Date(g):void 0;d(b)},minDate:n||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full",id:`${x}-end-date`})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{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(E,{size:"sm",variant:"outline",onClick:h,"data-testid":`${x}-cancel-button`,children:"Cancel"})]})]})})]})]})}function Sk(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 ug(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 xg(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 Tk({lifecycleRequests:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,exporting:h,onDateRangeChange:x,onShowCustomDatePickerChange:u,onStartDateChange:g,onEndDateChange:b,onApplyCustomDate:f,onCancelCustomDate:y,onPageChange:v,onExport:w,onViewRequest:C}){return e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(ge,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(kt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx($e,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",onClick:w,disabled:h,"data-testid":"export-lifecycle-button",children:[e.jsx(Ct,{className:"w-4 h-4"}),h?"Exporting...":"Download CSV"]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(fc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:x,onShowCustomDatePickerChange:u,onStartDateChange:g,onEndDateChange:b,onApply:f,onCancel:y,testIdPrefix:"lifecycle"})})]}),e.jsxs(se,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(lt,{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(ze,{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(k=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${k.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:()=>C(k.requestId||k.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("button",{onClick:S=>{S.stopPropagation(),C(k.requestId||k.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${k.id}`,children:k.id}),e.jsx(ne,{className:ug(k.priority),"data-testid":`lifecycle-priority-${k.id}`,children:k.priority}),e.jsx(ne,{className:xg(k.status),"data-testid":`lifecycle-status-${k.id}`,children:k.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:k.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:k.initiator})," on ",k.initDate]}),k.currentStage&&!k.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",k.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:k.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",k.currentLevel,"/",k.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:k.overallTAT}),k.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[k.breachCount," breach",k.breachCount>1?"es":""]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>C(k.requestId||k.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${k.id}`,children:e.jsx(yi,{className:"w-4 h-4"})})]})]})})},k.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(lt,{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(E,{variant:"outline",size:"sm",onClick:()=>v(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>v(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function hg({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:ke("w-full caption-bottom text-sm",t),...s})})}function pg({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:ke("[&_tr]:border-b",t),...s})}function gg({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:ke("[&_tr:last-child]:border-0",t),...s})}function gi({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:ke("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function ws({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:ke("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 Cs({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:ke("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function kk({activityLog:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,filterCategory:h,filterSeverity:x,exporting:u,onDateRangeChange:g,onShowCustomDatePickerChange:b,onStartDateChange:f,onEndDateChange:y,onApplyCustomDate:v,onCancelCustomDate:w,onCategoryChange:C,onSeverityChange:k,onClearFilters:S,onPageChange:_,onExport:D,onViewRequest:A}){const N=h!=="all"||x!=="all"||i!=="month"||l||o;return e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(ge,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-indigo-100 rounded-lg",children:e.jsx(lx,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx($e,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",onClick:D,disabled:u,"data-testid":"export-activity-button",children:[e.jsx(Ct,{className:"w-4 h-4"}),u?"Exporting...":"Download CSV"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(fc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:g,onShowCustomDatePickerChange:b,onStartDateChange:f,onEndDateChange:y,onApply:v,onCancel:w,testIdPrefix:"activity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Category:"}),e.jsxs(We,{value:h,onValueChange:C,"data-testid":"activity-category-filter",children:[e.jsx(Ye,{className:"w-40",children:e.jsx(Ge,{placeholder:"All Categories"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Categories"}),e.jsx(Y,{value:"WORKFLOW",children:"Workflow"}),e.jsx(Y,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(Y,{value:"DOCUMENT",children:"Document"}),e.jsx(Y,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(Y,{value:"SYSTEM",children:"System"}),e.jsx(Y,{value:"OTHER",children:"Other"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Severity:"}),e.jsxs(We,{value:x,onValueChange:k,"data-testid":"activity-severity-filter",children:[e.jsx(Ye,{className:"w-40",children:e.jsx(Ge,{placeholder:"All Severities"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Severities"}),e.jsx(Y,{value:"INFO",children:"Info"}),e.jsx(Y,{value:"WARNING",children:"Warning"}),e.jsx(Y,{value:"ERROR",children:"Error"}),e.jsx(Y,{value:"CRITICAL",children:"Critical"})]})]})]}),N&&e.jsx(E,{variant:"ghost",size:"sm",onClick:S,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(se,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(lt,{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(ze,{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(hg,{children:[e.jsx(pg,{children:e.jsxs(gi,{className:"bg-gray-50",children:[e.jsx(ws,{className:"font-semibold",children:"Timestamp"}),e.jsx(ws,{className:"font-semibold",children:"User"}),e.jsx(ws,{className:"font-semibold",children:"Action"}),e.jsx(ws,{className:"font-semibold",children:"Details"}),e.jsx(ws,{className:"font-semibold",children:"IP Address"}),e.jsx(ws,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(gg,{children:t.map((P,R)=>e.jsxs(gi,{className:"hover:bg-gray-50","data-testid":`activity-row-${R}`,children:[e.jsx(Cs,{className:"text-xs font-medium",children:P.timestamp}),e.jsx(Cs,{className:"text-sm",children:P.user}),e.jsx(Cs,{children:e.jsx(ne,{className:Sk(P.action),"data-testid":`activity-action-${R}`,children:P.action})}),e.jsx(Cs,{className:"text-sm text-gray-600",children:P.details}),e.jsx(Cs,{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(Cs,{children:P.requestId!=="-"&&P.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const O=P.requestId;O&&A(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(lt,{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(E,{variant:"outline",size:"sm",onClick:()=>_(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>_(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function Rk({agingWorkflows:t,loading:s,loadingPage:a,error:r,pagination:n,threshold:i,thresholdError:l,dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:h,tempCustomEndDate:x,searchQuery:u,exporting:g,onThresholdChange:b,onThresholdBlur:f,onDateRangeChange:y,onShowCustomDatePickerChange:v,onStartDateChange:w,onEndDateChange:C,onApplyCustomDate:k,onCancelCustomDate:S,onSearchChange:_,onPageChange:D,onExport:A,onViewRequest:N}){return e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(ge,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-amber-100 rounded-lg",children:e.jsx(bo,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx($e,{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(Oe,{type:"number",min:"1",value:i,onChange:P=>b(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(E,{variant:"outline",size:"sm",className:"gap-2",onClick:A,disabled:g,"data-testid":"export-aging-button",children:[e.jsx(Ct,{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(fc,{dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:h,tempCustomEndDate:x,onDateRangeChange:y,onShowCustomDatePickerChange:v,onStartDateChange:w,onEndDateChange:C,onApply:k,onCancel:S,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Oe,{placeholder:"Search by Request ID, Title, or Initiator...",value:u,onChange:P=>_(P.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(se,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(lt,{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(ze,{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(hg,{children:[e.jsx(pg,{children:e.jsxs(gi,{className:"bg-gray-50",children:[e.jsx(ws,{className:"font-semibold",children:"Request ID"}),e.jsx(ws,{className:"font-semibold",children:"Title"}),e.jsx(ws,{className:"font-semibold",children:"Initiator"}),e.jsx(ws,{className:"font-semibold",children:"Start Date"}),e.jsx(ws,{className:"font-semibold",children:"Days Open"}),e.jsx(ws,{className:"font-semibold",children:"Current Stage"}),e.jsx(ws,{className:"font-semibold",children:"Assigned To"}),e.jsx(ws,{className:"font-semibold",children:"Priority"}),e.jsx(ws,{className:"font-semibold",children:"Status"})]})}),e.jsx(gg,{children:t.map(P=>e.jsxs(gi,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${P.id}`,children:[e.jsx(Cs,{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(Cs,{className:"text-sm",children:P.title}),e.jsx(Cs,{className:"text-sm",children:P.initiator}),e.jsx(Cs,{className:"text-sm text-gray-600",children:P.startDate}),e.jsx(Cs,{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(Cs,{className:"text-sm",children:P.currentStage}),e.jsx(Cs,{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(Cs,{children:e.jsx(ne,{className:ug(P.priority),"data-testid":`aging-priority-${P.id}`,children:P.priority})}),e.jsx(Cs,{children:e.jsx(ne,{className:xg(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(lt,{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(E,{variant:"outline",size:"sm",onClick:()=>D(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>D(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function Tl(t="month"){const[s,a]=p.useState(t),[r,n]=p.useState(void 0),[i,l]=p.useState(void 0),[o,c]=p.useState(!1),[d,m]=p.useState(void 0),[h,x]=p.useState(void 0),u=p.useCallback(C=>{const k=C;a(k),k!=="custom"?(n(void 0),l(void 0),m(void 0),x(void 0),c(!1)):(m(r),x(i),c(!0))},[r,i]),g=p.useCallback(()=>{if(d&&h){if(d>h){const C=d;n(h),l(C),m(h),x(C)}else n(d),l(h);c(!1)}},[d,h]),b=p.useCallback(()=>{c(!1),m(r),x(i),(!r||!i)&&(n(void 0),l(void 0),a("month"))},[r,i]),f=p.useCallback(C=>{C?(m(C),h&&C>h&&x(C)):m(void 0)},[h]),y=p.useCallback(C=>{C?(x(C),d&&C<d&&m(C)):x(void 0)},[d]),v=p.useCallback(()=>r&&i?`${He(r,"MMM d, yyyy")} - ${He(i,"MMM d, yyyy")}`:"Select dates",[r,i]),w=p.useCallback(()=>{a("month"),n(void 0),l(void 0),c(!1),m(void 0),x(void 0)},[]);return{dateRange:s,customStartDate:r,customEndDate:i,showCustomDatePicker:o,tempCustomStartDate:d,tempCustomEndDate:h,setShowCustomDatePicker:c,handleDateRangeChange:u,handleApplyCustomDate:g,handleCancelCustomDate:b,handleStartDateChange:f,handleEndDateChange:y,getDisplayDateRange:v,reset:w}}function Dk(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return Ft(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${Ft(r)}`:`${a}d`}function fg(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 mr(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 Pk=10;function Ik({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=p.useState([]),[i,l]=p.useState(!0),[o,c]=p.useState(!1),[d,m]=p.useState(null),[h,x]=p.useState({page:1,totalPages:1,totalRecords:0}),u=p.useRef(!0),g=p.useCallback(async(b=1)=>{const f=b===1&&u.current;try{f?l(!0):c(!0),m(null);const y=await At.getLifecycleReport(b,Pk,t,s,a),v=y.lifecycleData.map(w=>{const C=Dk(w.overallTATHours);return{id:w.requestNumber,requestId:w.requestId,title:w.title,priority:w.priority||"medium",status:w.status,initiator:w.initiatorName||"Unknown",initDate:fg(w.submissionDate),currentStage:w.currentStageName||`Level ${w.currentLevel}`,overallTAT:C,currentLevel:w.currentLevel,totalLevels:w.totalLevels,breachCount:w.breachCount||0}});n(v),x({page:y.pagination.currentPage,totalPages:y.pagination.totalPages,totalRecords:y.pagination.totalRecords})}catch(y){console.error("Failed to fetch lifecycle data:",y),m((y==null?void 0:y.message)||"Failed to load lifecycle data")}finally{f?l(!1):c(!1)}f&&(u.current=!1)},[t,s,a]);return p.useEffect(()=>{t==="custom"&&(!s||!a)||g(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:o,error:d,pagination:h,fetchData:g}}const Ek=20;function Fk({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,l]=p.useState([]),[o,c]=p.useState(!0),[d,m]=p.useState(!1),[h,x]=p.useState(null),[u,g]=p.useState({page:1,totalPages:1,totalRecords:0}),b=p.useRef(!0),f=p.useCallback(async(y=1)=>{const v=y===1&&b.current;try{v?c(!0):m(!0),x(null);const w=await At.getActivityLogReport(y,Ek,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),C=w.activities.map(k=>{const S=bg(k.type||"",k.details),_=(k.type||"").toLowerCase()==="login"||k.requestId==="00000000-0000-0000-0000-000000000001"||k.requestId==="SYSTEM_LOGIN",D=_?k.details||"User login":k.requestTitle||k.requestNumber||k.details||"N/A";return{timestamp:k.timestamp?fg(k.timestamp):"N/A",user:k.userName||"Unknown",action:S,details:D,ip:k.ipAddress||"N/A",userAgent:k.userAgent||null,requestId:_?"System Login":k.requestNumber||k.requestId||"-",userId:k.userId}});l(C),g({page:w.pagination.currentPage,totalPages:w.pagination.totalPages,totalRecords:w.pagination.totalRecords})}catch(w){console.error("Failed to fetch activity data:",w),x((w==null?void 0:w.message)||"Failed to load activity data")}finally{v?c(!1):m(!1)}v&&(b.current=!1)},[r,n,t,s,a]);return p.useEffect(()=>{t==="custom"&&(!s||!a)||f(1)},[r,n,t,s,a]),{activityLog:i,loading:o,loadingPage:d,error:h,pagination:u,fetchData:f}}const _k=20;function Lk({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,l]=p.useState([]),[o,c]=p.useState(!0),[d,m]=p.useState(!1),[h,x]=p.useState(null),[u,g]=p.useState({page:1,totalPages:1,totalRecords:0}),b=p.useRef(!0),f=p.useCallback(async(v=1)=>{const w=v===1&&b.current;try{w?c(!0):m(!0),x(null);const C=parseInt(t,10);if(isNaN(C)||C<1){x("Please enter a valid threshold (minimum 1 day)");return}const k=await At.getWorkflowAgingReport(C,v,_k,s,a,r),S=k.agingData.map(_=>({id:_.requestNumber||_.requestId,requestId:_.requestId,title:_.title,initiator:_.initiatorName||"Unknown",startDate:_.submissionDate?new Date(_.submissionDate).toLocaleDateString():"N/A",daysOpen:_.daysOpen,currentStage:_.currentStageName||`Level ${_.currentLevel}`,assignedTo:_.currentApproverName||"N/A",priority:_.priority||"medium",status:_.status||"pending"}));l(S),g({page:k.pagination.currentPage,totalPages:k.pagination.totalPages,totalRecords:k.pagination.totalRecords})}catch(C){console.error("Failed to fetch aging data:",C),x((C==null?void 0:C.message)||"Failed to load aging data")}finally{w?c(!1):m(!1)}w&&(b.current=!1)},[t,s,a,r]),y=p.useMemo(()=>i.filter(v=>{var C,k,S;if(!n)return!0;const w=n.toLowerCase();return((C=v.id)==null?void 0:C.toLowerCase().includes(w))||((k=v.title)==null?void 0:k.toLowerCase().includes(w))||((S=v.initiator)==null?void 0:S.toLowerCase().includes(w))}),[i,n]);return p.useEffect(()=>{s==="custom"&&(!a||!r)||f(1)},[t,s,a,r]),{agingWorkflows:y,loading:o,loadingPage:d,error:h,pagination:u,fetchData:f}}function Mk(t="7"){const[s,a]=p.useState(t),[r,n]=p.useState(null),i=p.useCallback(o=>{if(o===""){a(""),n(null);return}const c=parseInt(o,10);isNaN(c)||c<1?(n("Minimum threshold is 1 day"),a(o)):(n(null),a(o))},[]),l=p.useCallback(()=>{(s===""||isNaN(parseInt(s,10))||parseInt(s,10)<1)&&(a("1"),n(null))},[s]);return{threshold:s,thresholdError:r,setThreshold:a,handleThresholdChange:i,handleThresholdBlur:l}}async function $k(t,s,a){const r=await At.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 vs(i.requestId||i.requestNumber),o=i.submissionDate?mr(i.submissionDate):"N/A",c=i.closureDate?mr(i.closureDate):"N/A",d=i.overallTATHours||0,m=d>0?(d/8).toFixed(2):"0",h=i.totalLevels||1,x=Math.min(Math.max(1,i.currentLevel||1),h),u=(l==null?void 0:l.approvals)||[];if(u.length===0){const g=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,c,h.toString(),x.toString(),d.toString(),m,(i.breachCount||0).toString(),"N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(g.join(","))}else u.forEach(g=>{const b=g.levelStartTime?mr(g.levelStartTime):"N/A",f=g.levelEndTime||g.completedAt?mr(g.levelEndTime||g.completedAt):"N/A",y=g.tatHours||0,v=g.tatDays||(y>0?(y/8).toFixed(2):"0");let w="N/A",C="N/A",k="N/A",S="N/A";if(g.levelStartTime){const D=new Date(g.levelStartTime);if(C=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-D.getTime())/(1e3*60*60)).toFixed(2),y>0){const P=parseFloat(C);k=Math.max(0,y-P).toFixed(2),S=(P/y*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?w=P<=y?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?w=P<=y?"On Track":"At Risk":w="N/A"}}const _=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,c,(i.totalLevels||0).toString(),(i.currentLevel||0).toString(),d.toString(),m,(i.breachCount||0).toString(),(g.levelNumber||"").toString(),`"${(g.levelName||`Level ${g.levelNumber}`).replace(/"/g,'""')}"`,`"${(g.approverName||"N/A").replace(/"/g,'""')}"`,`"${(g.approverEmail||"N/A").replace(/"/g,'""')}"`,g.status||"PENDING",b,f,y.toString(),v.toString(),w,C,k,S];n.push(_.join(","))})}catch(l){console.error(`Failed to fetch details for request ${i.requestNumber}:`,l);const o=i.submissionDate?mr(i.submissionDate):"N/A",c=i.overallTATHours||0,d=c>0?(c/8).toFixed(2):"0",m=i.totalLevels||1,h=Math.min(Math.max(1,i.currentLevel||1),m),x=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,"N/A",m.toString(),h.toString(),c.toString(),d,(i.breachCount||0).toString(),"Error","Error fetching details","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(x.join(","))}bc(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function Ok(t,s,a,r,n){const i=await At.getActivityLogReport(1,1e4,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),l=[["Timestamp","User","Action","Details","IP Address","User Agent","Request ID"].join(",")];i.activities.forEach(o=>{const c=bg(o.type||"",o.details),m=[o.timestamp?mr(o.timestamp):"N/A",`"${(o.userName||"Unknown").replace(/"/g,'""')}"`,`"${c.replace(/"/g,'""')}"`,`"${(o.requestTitle||o.requestNumber||o.details||"N/A").replace(/"/g,'""')}"`,o.ipAddress||"N/A",`"${(o.userAgent||"").replace(/"/g,'""')}"`,o.requestNumber||o.requestId||"-"];l.push(m.join(","))}),bc(l,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function Uk(t,s,a,r){const n=await At.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?mr(l.submissionDate):"N/A",c=[l.requestNumber||l.requestId||"",`"${(l.title||"").replace(/"/g,'""')}"`,`"${(l.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,(l.daysOpen||0).toString(),`"${(l.currentStageName||`Level ${l.currentLevel}`).replace(/"/g,'""')}"`,`"${(l.currentApproverName||"N/A").replace(/"/g,'""')}"`,l.priority||"medium",l.status||"pending"];i.push(c.join(","))}),bc(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function bc(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 Bk(){const[t,s]=p.useState(!1),[a,r]=p.useState(!1),[n,i]=p.useState(!1),l=p.useCallback(async(d,m,h)=>{try{s(!0),await $k(d,m,h)}catch(x){console.error("Failed to export lifecycle data:",x),alert("Failed to export lifecycle data. Please try again.")}finally{s(!1)}},[]),o=p.useCallback(async(d,m,h,x,u)=>{try{r(!0),await Ok(d,m,h,x,u)}catch(g){console.error("Failed to export activity data:",g),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),c=p.useCallback(async(d,m,h,x)=>{try{i(!0),await Uk(d,m,h,x)}catch(u){console.error("Failed to export aging data:",u),alert("Failed to export aging data. Please try again.")}finally{i(!1)}},[]);return{exportingLifecycle:t,exportingActivity:a,exportingAging:n,handleExportLifecycle:l,handleExportActivity:o,handleExportAging:c}}function Vk({onBack:t}){const s=Ks(),[a,r]=p.useState(""),[n,i]=p.useState("all"),[l,o]=p.useState("all"),c=Tl("month"),d=Tl("month"),m=Tl("month"),h=Mk("7"),x=Ik({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),u=Fk({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:l}),g=Lk({threshold:h.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),b=Bk(),f=p.useCallback(()=>{t?t():s("/dashboard")},[t,s]),y=p.useCallback(S=>{pi({requestId:S,navigate:s})},[s]),v=p.useCallback(()=>{b.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[b,c]),w=p.useCallback(()=>{b.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,l)},[b,d,n,l]),C=p.useCallback(()=>{const S=parseInt(h.threshold,10);!isNaN(S)&&S>=1&&b.handleExportAging(S,m.dateRange,m.customStartDate,m.customEndDate)},[b,h.threshold,m]),k=p.useCallback(()=>{i("all"),o("all"),d.reset()},[d]);return e.jsx("div",{className:"flex-1 p-3 lg:p-6 overflow-auto min-w-0","data-testid":"detailed-reports",children:e.jsxs("div",{className:"space-y-6 max-w-7xl mx-auto p-4",children:[e.jsx(Ck,{onBack:f}),e.jsx(Tk,{lifecycleRequests:x.lifecycleRequests,loading:x.loading,loadingPage:x.loadingPage,error:x.error,pagination:x.pagination,dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate,showCustomDatePicker:c.showCustomDatePicker,tempCustomStartDate:c.tempCustomStartDate,tempCustomEndDate:c.tempCustomEndDate,exporting:b.exportingLifecycle,onDateRangeChange:c.handleDateRangeChange,onShowCustomDatePickerChange:c.setShowCustomDatePicker,onStartDateChange:c.handleStartDateChange,onEndDateChange:c.handleEndDateChange,onApplyCustomDate:c.handleApplyCustomDate,onCancelCustomDate:c.handleCancelCustomDate,onPageChange:x.fetchData,onExport:v,onViewRequest:y}),e.jsx(kk,{activityLog:u.activityLog,loading:u.loading,loadingPage:u.loadingPage,error:u.error,pagination:u.pagination,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,showCustomDatePicker:d.showCustomDatePicker,tempCustomStartDate:d.tempCustomStartDate,tempCustomEndDate:d.tempCustomEndDate,filterCategory:n,filterSeverity:l,exporting:b.exportingActivity,onDateRangeChange:d.handleDateRangeChange,onShowCustomDatePickerChange:d.setShowCustomDatePicker,onStartDateChange:d.handleStartDateChange,onEndDateChange:d.handleEndDateChange,onApplyCustomDate:d.handleApplyCustomDate,onCancelCustomDate:d.handleCancelCustomDate,onCategoryChange:i,onSeverityChange:o,onClearFilters:k,onPageChange:u.fetchData,onExport:w,onViewRequest:y}),e.jsx(Rk,{agingWorkflows:g.agingWorkflows,loading:g.loading,loadingPage:g.loadingPage,error:g.error,pagination:g.pagination,threshold:h.threshold,thresholdError:h.thresholdError,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,showCustomDatePicker:m.showCustomDatePicker,tempCustomStartDate:m.tempCustomStartDate,tempCustomEndDate:m.tempCustomEndDate,searchQuery:a,exporting:b.exportingAging,onThresholdChange:h.handleThresholdChange,onThresholdBlur:h.handleThresholdBlur,onDateRangeChange:m.handleDateRangeChange,onShowCustomDatePickerChange:m.setShowCustomDatePicker,onStartDateChange:m.handleStartDateChange,onEndDateChange:m.handleEndDateChange,onApplyCustomDate:m.handleApplyCustomDate,onCancelCustomDate:m.handleCancelCustomDate,onSearchChange:r,onPageChange:g.fetchData,onExport:C,onViewRequest:y})]})})}function Hn({className:t,...s}){return e.jsx("div",{"data-slot":"skeleton",className:ke("bg-accent animate-pulse rounded-md",t),...s})}function zk(){const t=Ks(),[s,a]=p.useState(()=>bu()||[]),[r,n]=p.useState(()=>!bu()),[i,l]=p.useState(""),o=async()=>{try{s.length===0&&n(!0);const m=await Mi();a(m||[])}catch(m){console.error("Failed to fetch templates:",m),K.error("Failed to load templates")}finally{n(!1)}};p.useEffect(()=>{o()},[]);const c=s.filter(m=>m.name.toLowerCase().includes(i.toLowerCase())||m.category.toLowerCase().includes(i.toLowerCase())),d=m=>{switch(m.toLowerCase()){case"high":return"bg-red-100 text-red-700 border-red-200";case"medium":return"bg-orange-100 text-orange-700 border-orange-200";case"low":return"bg-green-100 text-green-700 border-green-200";default:return"bg-gray-100 text-gray-700 border-gray-200"}};return e.jsxs("div",{className:"max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:"Admin Templates"}),e.jsx("p",{className:"text-gray-500",children:"Manage workflow templates for your organization"})]}),e.jsxs(E,{onClick:()=>t("/admin/create-template"),className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Create New Template"]})]}),e.jsx("div",{className:"flex items-center gap-4 bg-white p-4 rounded-lg border border-gray-200 shadow-sm",children:e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search templates...",className:"pl-10 border-gray-200",value:i,onChange:m=>l(m.target.value)})]})}),r?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(m=>e.jsxs(ee,{className:"h-48",children:[e.jsxs(ge,{children:[e.jsx(Hn,{className:"h-6 w-3/4 mb-2"}),e.jsx(Hn,{className:"h-4 w-1/2"})]}),e.jsxs(se,{children:[e.jsx(Hn,{className:"h-4 w-full mb-2"}),e.jsx(Hn,{className:"h-4 w-2/3"})]})]},m))}):c.length===0?e.jsxs("div",{className:"text-center py-16 bg-white rounded-lg border border-dashed border-gray-300",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Re,{className:"w-8 h-8 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No templates found"}),e.jsx("p",{className:"text-gray-500 max-w-sm mx-auto mb-6",children:i?"Try adjusting your search terms":"Get started by creating your first workflow template"}),!i&&e.jsx(E,{onClick:()=>t("/admin/create-template"),variant:"outline",children:"Create Template"})]}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:c.map(m=>{var h;return e.jsxs(ee,{className:"hover:shadow-md transition-shadow duration-200 group",children:[e.jsxs(ge,{className:"pb-3",children:[e.jsxs("div",{className:"flex justify-between items-start gap-2",children:[e.jsx("div",{className:"p-2 bg-blue-50 rounded-lg text-blue-600 mb-2 w-fit",children:e.jsx(Re,{className:"w-5 h-5"})}),e.jsx(ne,{variant:"outline",className:d(m.priority),children:m.priority})]}),e.jsx(fe,{className:"line-clamp-1 text-lg",children:m.name}),e.jsx($e,{className:"line-clamp-3 min-h-[4.5rem]",children:m.description})]}),e.jsxs(se,{children:[e.jsxs("div",{className:"text-sm text-gray-500 mb-4 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Category:"}),e.jsx("span",{className:"font-medium text-gray-900",children:m.category})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"SLA:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[m.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Approvers:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[((h=m.approvers)==null?void 0:h.length)||0," levels"]})]})]}),e.jsx("div",{className:"flex gap-2 pt-2 border-t mt-2",children:e.jsxs(E,{variant:"outline",className:"flex-1 text-blue-600 hover:text-blue-700 hover:bg-blue-50 border-blue-100",onClick:()=>t(`/admin/edit-template/${m.id}`),children:[e.jsx(v0,{className:"w-4 h-4 mr-2"}),"Edit"]})})]})]},m.id)})})]})}function Tu(){const t=Ks(),{templateId:s}=Ea(),a=!!s,[r,n]=p.useState(!1),[i,l]=p.useState(!1),{searchResults:o,searchLoading:c,searchUsersDebounced:d,clearSearch:m}=Dp(),[h,x]=p.useState(""),[u,g]=p.useState({name:"",description:"",category:"General",priority:"medium",estimatedTime:"2 days",suggestedSLA:24,approvers:[]});p.useEffect(()=>{a&&s&&(async()=>{try{l(!0);const D=(await Mi()).find(A=>A.id===s);D?g({name:D.name,description:D.description,category:D.category,priority:D.priority,estimatedTime:D.estimatedTime,suggestedSLA:D.suggestedSLA,approvers:D.approvers||[]}):(K.error("Template not found"),t("/admin/templates"))}catch(_){console.error("Failed to load template:",_),K.error("Failed to load template details")}finally{l(!1)}})()},[a,s,t]);const b=S=>{const{name:_,value:D}=S.target;g(A=>({...A,[_]:D}))},f=(S,_)=>{g(D=>({...D,[S]:_}))},y=S=>{if(x(S),S.startsWith("@")&&S.slice(1).length>=1){d(S,5);return}m()},v=S=>{if(u.approvers.some(_=>_.userId===S.userId)){K.error("Approver already added");return}g(_=>({..._,approvers:[..._.approvers,{userId:S.userId,name:S.displayName||S.email,email:S.email,level:_.approvers.length+1,tat:24,tatType:"hours"}]})),x(""),m()},w=S=>{const _=[...u.approvers];_.splice(S,1),_.forEach((D,A)=>D.level=A+1),g(D=>({...D,approvers:_}))},C=async S=>{if(S.preventDefault(),!u.name||!u.description){K.error("Please fill in required fields");return}if(u.approvers.length===0){K.error("Please add at least one approver");return}const _={...u,approvers:u.approvers.map(D=>({...D,tat:D.tatType==="days"?parseInt(D.tat)*24:parseInt(D.tat)}))};try{n(!0),a&&s?(await AS(s,_),K.success("Template updated successfully")):(await SS(_),K.success("Template created successfully")),t("/admin/templates")}catch(D){K.error(a?"Failed to update template":"Failed to create template"),console.error(D)}finally{n(!1)}};if(i)return e.jsx("div",{className:"flex h-96 items-center justify-center",children:e.jsx(lt,{className:"h-8 w-8 animate-spin text-gray-400"})});const k=u.name&&u.description&&u.approvers.length>0&&u.approvers.every(S=>{const _=parseInt(String(S.tat))||0,D=S.tatType==="days"?7:24;return _>=1&&_<=D});return e.jsxs("div",{className:"max-w-4xl mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>t("/admin/templates"),children:e.jsx(Ns,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:a?"Edit Workflow Template":"Create Workflow Template"}),e.jsx("p",{className:"text-gray-500",children:a?"Update existing workflow configuration":"Define a new standardized request workflow"})]})]}),e.jsxs("form",{onSubmit:C,className:"space-y-6",children:[e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Basic Information"}),e.jsx($e,{children:"General details about the template"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Template Name *"}),e.jsx(Oe,{id:"name",name:"name",placeholder:"e.g., Office Stationery Request",value:u.name,onChange:b,className:"border-gray-200",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"category",children:"Category"}),e.jsx("div",{className:"relative",children:e.jsx(Oe,{id:"category",name:"category",placeholder:"e.g., Admin, HR, Finance",value:u.category,onChange:b,className:"border-gray-200"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description *"}),e.jsx(Ds,{id:"description",name:"description",placeholder:"Describe what this request is for...",value:u.description,onChange:b,className:"border-gray-200",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"priority",children:"Default Priority"}),e.jsxs(We,{name:"priority",value:u.priority,onValueChange:S=>f("priority",S),children:[e.jsx(Ye,{children:e.jsx(Ge,{placeholder:"Select priority"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"low",children:"Low"}),e.jsx(Y,{value:"medium",children:"Medium"}),e.jsx(Y,{value:"high",children:"High"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"estimatedTime",children:"Estimated Time"}),e.jsx(Oe,{id:"estimatedTime",name:"estimatedTime",placeholder:"e.g., 2 days",value:u.estimatedTime,onChange:b,className:"border-gray-200"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"suggestedSLA",children:"SLA (Hours)"}),e.jsx(Oe,{id:"suggestedSLA",name:"suggestedSLA",type:"number",placeholder:"24",value:u.suggestedSLA,onChange:b,className:"border-gray-200"})]})]})]})]}),e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Approver Workflow"}),e.jsx($e,{children:"Define static approvers for this template"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[u.approvers.map((S,_)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsxs(ne,{variant:"outline",className:"bg-white",children:["Level ",S.level]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:S.name}),e.jsx("div",{className:"text-sm text-gray-500",children:S.email})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(re,{htmlFor:`tat-${_}`,className:"text-xs whitespace-nowrap",children:"TAT"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Oe,{id:`tat-${_}`,type:"number",className:"h-8 w-16 border-gray-200",value:S.tat||"",min:1,max:S.tatType==="days"?7:24,placeholder:S.tatType==="days"?"1":"24",onChange:D=>{if((parseInt(D.target.value)||0)<0)return;const N=[...u.approvers];N[_].tat=D.target.value,g(P=>({...P,approvers:N}))}}),e.jsxs(We,{value:S.tatType||"hours",onValueChange:D=>{const A=[...u.approvers];A[_].tatType=D,A[_].tat=1,g(N=>({...N,approvers:A}))},children:[e.jsx(Ye,{className:"h-8 w-20 text-xs px-2",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>w(_),children:e.jsx(ft,{className:"w-4 h-4 text-gray-500 hover:text-red-600"})})]},_)),u.approvers.length===0&&e.jsx("div",{className:"text-center p-8 border-2 border-dashed rounded-lg text-gray-500 text-sm",children:"No approvers defined. Requests will be auto-approved or require manual assignment."})]}),e.jsxs("div",{className:"space-y-2 relative",children:[e.jsx(re,{children:"Add Approver"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Oe,{placeholder:"Type '@' to search user by name or email...",value:h,onChange:S=>y(S.target.value),className:"border-gray-200"})}),(c||o.length>0)&&e.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-white border rounded-lg shadow-lg z-10 max-h-60 overflow-y-auto",children:[c&&e.jsx("div",{className:"p-2 text-sm text-gray-500",children:"Searching..."}),o.map(S=>e.jsxs("div",{className:"p-2 hover:bg-gray-50 cursor-pointer flex items-center gap-3",onClick:()=>v(S),children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{children:(S.displayName||"U").substring(0,2)})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:S.displayName}),e.jsx("div",{className:"text-xs text-gray-500",children:S.email})]})]},S.userId))]})]}),u.approvers.length>0&&e.jsx("div",{className:"mt-6 p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(st,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{const S=u.approvers.reduce((D,A)=>{const N=Number(A.tat||0);return(A.tatType||"hours")==="days"?D+N:D+N/24},0)||0,_=Math.ceil(S);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[_," ",_===1?"Day":"Days"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Duration"})]})})()})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:u.approvers.map((S,_)=>{const D=Number(S.tat||0),N=(S.tatType||"hours")==="days"?D*24:D;return D?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",_+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[N," ",N===1?"hour":"hours"]})]})},_):null})}),(()=>{const S=u.approvers.reduce((D,A)=>{const N=Number(A.tat||0);return(A.tatType||"hours")==="days"?D+N*24:D+N},0)||0,_=Math.ceil(S/8);return S===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:[S,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children:_}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Working Days*"})]})]}),e.jsx("p",{className:"text-xs text-emerald-600 mt-2 text-center",children:"*Based on 8-hour working days"})]})})()]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[e.jsx(E,{type:"button",variant:"outline",onClick:()=>t("/admin/templates"),children:"Cancel"}),e.jsx(E,{type:"submit",disabled:r||!k,className:"bg-re-green hover:bg-re-green/90",children:r?"Saving...":e.jsxs(e.Fragment,{children:[e.jsx(ox,{className:"w-4 h-4 mr-2"}),a?"Update Template":"Create Template"]})})]})]})]})}function Hk({template:t,formData:s,setFormData:a,documents:r,setDocuments:n}){const i=p.useRef(null),[l,o]=p.useState(null),c=u=>{u.target.files&&u.target.files.length>0&&n([...r,...Array.from(u.target.files)])},d=u=>{const g=[...r];g.splice(u,1),n(g)},m=u=>{const g=URL.createObjectURL(u);o({file:u,url:g})},h=()=>{l!=null&&l.url&&URL.revokeObjectURL(l.url),o(null)},x=u=>u.type.includes("image")||u.type.includes("pdf");return e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(ee,{className:"shadow-sm",children:e.jsxs(se,{className:"pt-6",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-xl font-bold text-gray-800",children:t.name}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.description})]}),e.jsxs("div",{className:"flex gap-4 text-sm text-gray-600 bg-gray-50 p-3 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-semibold",children:"Category:"})," ",t.category]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-semibold",children:"Priority:"}),e.jsx("span",{className:"capitalize",children:t.priority})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-semibold",children:"SLA:"})," ",t.suggestedSLA," Hours"]})]})]})}),e.jsx(ee,{children:e.jsxs(se,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"requestTitle",children:"Request Title *"}),e.jsx(Oe,{id:"requestTitle",value:s.title,onChange:u=>a({...s,title:u.target.value}),placeholder:`Request for ${t.name}`,className:"border-gray-200"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"justification",className:"text-base font-semibold",children:"Request Detail *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Explain what you need approval for, why it's needed, and any relevant details."}),e.jsx(Rn,{value:s.description||"",onChange:u=>a({...s,description:u}),placeholder:"Provide comprehensive details about your request...",className:"min-h-[120px] text-base border-gray-200 bg-white shadow-sm",minHeight:"120px"})]})]})}),e.jsx(ee,{children:e.jsxs(se,{className:"pt-6 space-y-4",children:[e.jsx(re,{children:"Supporting Documents"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>{var u;return(u=i.current)==null?void 0:u.click()},children:[e.jsx(zs,{className:"w-10 h-10 text-gray-400 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium text-gray-700",children:"Click to upload files"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"PDF, Excel, Images (Max 10MB)"}),e.jsx("input",{ref:i,type:"file",multiple:!0,className:"hidden",onChange:c})]}),r.length>0&&e.jsx("div",{className:"grid grid-cols-1 gap-2 mt-4",children:r.map((u,g)=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-white border rounded-lg shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center",children:e.jsx(Re,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-800 truncate max-w-[200px]",children:u.name}),e.jsxs("p",{className:"text-xs text-gray-500",children:[(u.size/1024/1024).toFixed(2)," MB"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[x(u)&&e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>m(u),children:e.jsx(ht,{className:"w-4 h-4 text-gray-500 hover:text-blue-600"})}),e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>d(g),children:e.jsx(ft,{className:"w-4 h-4 text-gray-500 hover:text-red-500"})})]})]},g))})]})}),l&&e.jsx(jr,{fileName:l.file.name,fileType:l.file.type,fileUrl:l.url,fileSize:l.file.size,open:!!l,onClose:h})]})}function Wk({template:t,formData:s,documents:a}){const r=t.workflowApprovers||[];return e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(ze,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900",children:"Ready to Submit?"}),e.jsx("p",{className:"text-sm text-blue-700 mt-1",children:"Please review the details below. This request will follow the standardized approval workflow defined by the administrator."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsxs(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-lg",children:"Request Overview"})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Title"}),e.jsx("p",{className:"text-base font-medium text-gray-900 mt-1",children:s.title})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Request Detail"}),e.jsx("div",{className:"text-sm text-gray-700 mt-1 prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:ba(s.description)}})]}),a.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider block mb-2",children:["Attachments (",a.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((n,i)=>e.jsxs(ne,{variant:"secondary",className:"pl-1 pr-2 py-1 flex items-center gap-1.5 h-auto",children:[e.jsx(Re,{className:"w-3 h-3 text-gray-500"}),e.jsx("span",{className:"truncate max-w-[150px]",children:n.name})]},i))})]})]})})]}),e.jsxs(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-lg",children:"Approval Workflow"})}),e.jsx(se,{children:e.jsx("div",{className:"relative pl-6 border-l-2 border-gray-100 space-y-8 py-2",children:r.map((n,i)=>e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute -left-[31px] top-1 w-4 h-4 rounded-full bg-white border-2 border-blue-500 flex items-center justify-center",children:e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-blue-500"})}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-3 border border-gray-100",children:[e.jsxs("div",{className:"flex justify-between items-start mb-1",children:[e.jsxs("div",{children:[e.jsx("h5",{className:"font-semibold text-gray-800 text-sm",children:n.name||n.email}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Level ",n.level," Approver"]})]}),e.jsxs(ne,{variant:"outline",className:"bg-white text-xs",children:[n.tat||24," Hours TAT"]})]}),e.jsx("p",{className:"text-xs text-gray-400",children:n.email})]})]},i))})})]})]}),e.jsx("div",{className:"space-y-6",children:e.jsxs(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm uppercase text-gray-500",children:"Properties"})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Template"}),e.jsx("span",{className:"text-sm font-medium text-right",children:t.name})]}),e.jsx(Ts,{}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Priority"}),e.jsx(ne,{className:t.priority==="high"?"bg-red-100 text-red-700 hover:bg-red-100":t.priority==="medium"?"bg-orange-100 text-orange-700 hover:bg-orange-100":"bg-green-100 text-green-700 hover:bg-green-100",children:t.priority.toUpperCase()})]}),e.jsx(Ts,{}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Est. Time"}),e.jsx("span",{className:"text-sm text-gray-900",children:t.estimatedTime})]})]})]})})]})]})}function Gk(){const{templateId:t}=Ea(),s=Ks(),{user:a}=Kt(),[r,n]=p.useState(!0),[i,l]=p.useState(!1),[o,c]=p.useState(null),[d,m]=p.useState(1),[h,x]=p.useState([]),[u,g]=p.useState({title:"",description:""}),b=["Request Details","Review & Submit"];p.useEffect(()=>{t&&(async()=>{try{n(!0);const w=(await Mi()).find(C=>C.id===t);if(w){const C={id:w.id,name:w.name,description:w.description,category:w.category,icon:Re,estimatedTime:w.estimatedTime,commonApprovers:w.approvers.map(k=>k.name),workflowApprovers:w.approvers,suggestedSLA:w.suggestedSLA,priority:w.priority,fields:w.fields||{}};c(C),g({title:C.name,description:C.description})}else K.error("Template not found")}catch(v){console.error("Error loading template:",v),K.error("Failed to load template details")}finally{n(!1)}})()},[t,s]);const f=async()=>{var y;if(o)try{l(!0);const v={templateId:o.id,templateType:"TEMPLATE",title:u.title,description:u.description,priorityUi:o.priority==="high"?"express":"standard",approverCount:((y=o.workflowApprovers)==null?void 0:y.length)||0,approvers:(o.workflowApprovers||[]).map(C=>({email:C.email,name:C.name,tat:C.tat,tatType:"hours"})),spectators:[],ccList:[]},w=await Io(v,h);w&&w.id&&await Wx(w.id),K.success("Request Submitted Successfully",{description:`Your request "${u.title}" has been created.`}),s("/my-requests")}catch(v){console.error("Submission failed:",v),K.error("Failed to submit request")}finally{l(!1)}};return r?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):o?e.jsxs("div",{className:"h-screen flex flex-col bg-gray-50 overflow-hidden",children:[e.jsxs("header",{className:"bg-white border-b flex-shrink-0 z-10",children:[e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>s("/new-request"),children:e.jsx(Ns,{className:"w-5 h-5 text-gray-500"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold text-gray-900",children:"New Request"}),e.jsx("p",{className:"text-sm text-gray-500",children:o.name})]})]}),e.jsx(E,{variant:"outline",onClick:()=>s("/dashboard"),children:"Cancel Request"})]}),e.jsx(Rp,{currentStep:d,totalSteps:2,stepNames:b})]}),e.jsx("main",{className:"flex-1 overflow-y-auto py-8 px-6 bg-gray-50/50",children:e.jsx("div",{className:"max-w-4xl mx-auto",children:d===1?e.jsx(Hk,{template:o,formData:u,setFormData:g,documents:h,setDocuments:x}):e.jsx(Wk,{template:o,formData:u,documents:h})})}),e.jsx("footer",{className:"bg-white border-t px-6 py-4 flex-shrink-0 z-10",children:e.jsxs("div",{className:"max-w-4xl mx-auto flex items-center justify-between",children:[e.jsx(E,{variant:"outline",onClick:()=>d===1?s("/new-request"):m(1),disabled:i,children:d===1?"Cancel":"Back to Details"}),e.jsx(E,{onClick:()=>d===1?m(2):f(),disabled:i,className:"bg-re-green hover:bg-re-green/90",children:d===1?e.jsxs(e.Fragment,{children:["Review Request ",e.jsx(yi,{className:"w-4 h-4 ml-1"})]}):e.jsxs(e.Fragment,{children:[i?"Submitting...":"Submit Request"," ",e.jsx(yr,{className:"w-4 h-4 ml-1"})]})})]})})]}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex flex-col items-center justify-center p-4",children:e.jsxs("div",{className:"bg-white p-8 rounded-lg shadow-md max-w-md w-full text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Re,{className:"w-8 h-8 text-red-600"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Template Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The requested template could not be loaded. It may have been deleted or you do not have permission to view it."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsx(E,{variant:"outline",onClick:()=>s("/dashboard"),children:"Go to Dashboard"}),e.jsx(E,{onClick:()=>s("/new-request"),children:"Browse Templates"})]})]})})}function Yk({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[l,o]=p.useState(""),[c,d]=p.useState(!1),m=async()=>{if(!(!l.trim()||l.length>500)){d(!0);try{await i(a,l.trim()),o(""),s()}catch(b){console.error("Error submitting approval action:",b)}finally{d(!1)}}},h=()=>{o(""),s()},u=a==="approve"?{title:"Approve Request",description:"Please provide your approval comments and remarks",icon: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:wt,iconColor:"text-red-600",buttonColor:"bg-red-600 hover:bg-red-700",badgeColor:"bg-red-100 text-red-800 border-red-200",placeholder:"Enter detailed reasons for rejection and any suggestions for improvement..."},g=u.icon;return e.jsx(pt,{open:t,onOpenChange:h,children:e.jsxs(dt,{className:"max-w-2xl bg-white",children:[e.jsxs(gt,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:`p-2 rounded-lg ${a==="approve"?"bg-green-100":"bg-red-100"}`,children:e.jsx(g,{className:`w-6 h-6 ${u.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl",children:u.title}),e.jsx(Dt,{className:"mt-1",children:u.description})]})]}),e.jsxs("div",{className:"space-y-3 p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Request ID:"}),e.jsx(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:u.badgeColor,variant:"outline",children:[e.jsx(g,{className:"w-3 h-3 mr-1"}),a==="approve"?"APPROVE":"REJECT"]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(Ds,{id:"comment",placeholder:u.placeholder,value:l,onChange:b=>o(b.target.value.slice(0,500)),className:"min-h-[120px] resize-none",rows:6}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(as,{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(as,{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(E,{variant:"outline",onClick:h,disabled:c,children:"Cancel"}),e.jsx(E,{onClick:m,disabled:!l.trim()||c||l.length>500,className:u.buttonColor,children:c?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(g,{className:"w-4 h-4 mr-2"}),a==="approve"?"Approve Request":"Reject Request"]})})]})]})})}var Kk=(t,s,a,r,n,i,l,o)=>{let c=document.documentElement,d=["light","dark"];function m(u){(Array.isArray(t)?t:[t]).forEach(g=>{let b=g==="class",f=b&&i?n.map(y=>i[y]||y):n;b?(c.classList.remove(...f),c.classList.add(i&&i[u]?i[u]:u)):c.setAttribute(g,u)}),h(u)}function h(u){o&&d.includes(u)&&(c.style.colorScheme=u)}function x(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let u=localStorage.getItem(s)||a,g=l&&u==="system"?x():u;m(g)}catch{}},Xk=p.createContext(void 0),Zk={setTheme:t=>{},themes:[]},Jk=()=>{var t;return(t=p.useContext(Xk))!=null?t:Zk};p.memo(({forcedTheme:t,storageKey:s,attribute:a,enableSystem:r,enableColorScheme:n,defaultTheme:i,value:l,themes:o,nonce:c,scriptProps:d})=>{let m=JSON.stringify([a,s,i,t,o,l,r,n]).slice(1,-1);return p.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${Kk.toString()})(${m})`}})});const Qk=({...t})=>{const{theme:s="system"}=Jk();return e.jsx(j0,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function qk({open:t,onClose:s,onSelect:a,managers:r=[],errorType:n,message:i,isLoading:l=!1}){const o=c=>{a(c)};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[600px]",children:[e.jsxs(gt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:n==="NO_MANAGER_FOUND"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-amber-500"}),"Manager Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ls,{className:"w-5 h-5 text-blue-500"}),"Select Your Manager"]})}),e.jsx(Dt,{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(ze,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-amber-900",children:"Unable to Proceed"}),e.jsx("p",{className:"text-sm text-amber-700 mt-1",children:"We couldn't find your reporting manager in the system. The claim request cannot be created without a valid manager assigned."})]})]})}):e.jsx("div",{className:"space-y-3 max-h-[400px] overflow-y-auto",children:r.map(c=>e.jsx("div",{className:"border rounded-lg p-4 hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>!l&&o(c.email),children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-1",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Vt,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsx("p",{className:"font-medium text-gray-900",children:c.displayName||`${c.firstName||""} ${c.lastName||""}`.trim()||"Unknown"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(Ra,{className:"w-4 h-4"}),e.jsx("span",{className:"truncate",children:c.email})]}),c.department&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(mo,{className:"w-4 h-4"}),e.jsx("span",{children:c.department})]})]})]})]}),e.jsx(E,{onClick:d=>{d.stopPropagation(),o(c.email)},disabled:l,className:"flex-shrink-0",size:"sm",children:"Select"})]})},c.userId))})}),e.jsx("div",{className:"flex justify-end gap-3 mt-6",children:n==="NO_MANAGER_FOUND"?e.jsx(E,{onClick:s,variant:"outline",children:"Close"}):e.jsx(e.Fragment,{children:e.jsx(E,{onClick:s,variant:"outline",disabled:l,children:"Cancel"})})})]})})}function e4({onViewRequest:t}){const{user:s}=Kt();return ki(s)?e.jsx(z5,{onViewRequest:t}):e.jsx(G5,{onViewRequest:t})}function ku({onNavigate:t,onNewRequest:s}){const[a,r]=p.useState(!1),[n,i]=p.useState(!0);return p.useEffect(()=>{try{const l=tt.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 t4({onLogout:t}){const s=Ks(),[a,r]=p.useState(null),[n,i]=p.useState([]),[l,o]=p.useState(""),[c,d]=p.useState(""),[m,h]=p.useState(!1),[x,u]=p.useState(null);p.useEffect(()=>{const S=localStorage.getItem("dynamicRequests");if(S)try{const _=JSON.parse(S);i(_)}catch(_){console.error("Error parsing dynamic requests:",_)}},[]),p.useEffect(()=>{n.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(n))},[n]);const g=S=>{if(S==="profile"){s("/profile");return}if(S==="settings"){s("/settings");return}S.startsWith("/")?s(S):s(`/${S}`)},b=(S,_,D,A)=>{o(S),d(_||"Unknown Request"),pi({requestId:S,status:D,request:A,navigate:s})},f=()=>{s(-1)},y=()=>{s("/new-request")},v=S=>{var A,N,P,R,O,F,$,V,T,j,U;if(S.templateType){S.templateType==="claim-management"&&s("/claim-management");return}if(S.backendId){s("/my-requests");return}const D={id:`RE-REQ-2024-${String(n.length+1).padStart(3,"0")}`,title:S.title,description:S.description||"",category:S.category||"General",subcategory:S.subcategory||"",status:"pending",priority:S.priority||"standard",amount:S.budget||"N/A",slaProgress:0,slaRemaining:"5 days",slaEndDate:new Date(Date.now()+5*24*60*60*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),currentStep:1,totalSteps:((A=S.approvers)==null?void 0:A.length)||1,currentApprover:((P=(N=S.approvers)==null?void 0:N[0])==null?void 0:P.name)||((F=(O=(R=S.approvers)==null?void 0:R[0])==null?void 0:O.email)==null?void 0:F.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${(($=S.approvers)==null?void 0:$.length)||1}`,template:"custom",initiator:{name:"Current User",role:S.initiatorRole||"Employee",department:S.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:S.department||"General",createdAt:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),updatedAt:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),dueDate:new Date(Date.now()+5*24*60*60*1e3).toISOString(),submittedDate:new Date().toISOString(),estimatedCompletion:new Date(Date.now()+5*24*60*60*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),conclusionRemark:"",approvalFlow:(S.approvers||[]).filter(I=>I).map((I,M)=>{var ce;const W=(I==null?void 0:I.name)||((ce=I==null?void 0:I.email)==null?void 0:ce.split("@")[0])||`Approver ${M+1}`,G=(I==null?void 0:I.email)||"";return{step:M+1,approver:`${W}${G?` (${G})`:""}`,role:(I==null?void 0:I.role)||`Level ${(I==null?void 0:I.level)||M+1} Approver`,status:M===0?"pending":"waiting",tatHours:I!=null&&I.tat?typeof I.tat=="string"?parseInt(I.tat):I.tat:48,elapsedHours:0,assignedAt:M===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(S.spectators||[]).filter(I=>I&&(I.name||I.email)).map(I=>{var W;const M=(I==null?void 0:I.name)||((W=I==null?void 0:I.email)==null?void 0:W.split("@")[0])||"Observer";return{name:M,role:(I==null?void 0:I.role)||(I==null?void 0:I.department)||"Observer",avatar:M.split(" ").map(G=>G[0]).join("").toUpperCase().slice(0,2)||"OB"}}),auditTrail:[{type:"created",action:"Request Created",details:`Custom request "${S.title}" created`,user:"Current User",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})},{type:"assignment",action:"Assigned to Approver",details:`Request assigned to ${((T=(V=S.approvers)==null?void 0:V[0])==null?void 0:T.name)||((U=(j=S.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:S.tags||["custom-request"]};i([...n,D]),s("/my-requests")},w=(S,_)=>new Promise(D=>{setTimeout(()=>{S==="approve"?K.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):K.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),r(null),D(!0)},1e3)}),C=()=>{r(null)},k=async(S,_)=>{var D,A,N,P,R,O,F;try{const $={activityName:S.activityName,activityType:S.activityType,dealerCode:S.dealerCode,dealerName:S.dealerName,dealerEmail:S.dealerEmail||void 0,dealerPhone:S.dealerPhone||void 0,dealerAddress:S.dealerAddress||void 0,activityDate:S.activityDate?new Date(S.activityDate).toISOString():void 0,location:S.location,requestDescription:S.requestDescription,periodStartDate:S.periodStartDate?new Date(S.periodStartDate).toISOString():void 0,periodEndDate:S.periodEndDate?new Date(S.periodEndDate).toISOString():void 0,estimatedBudget:S.estimatedBudget||void 0,approvers:S.approvers||[]},V=await OA($);if(!V||!V.request)throw new Error("Invalid response from server: Request object not found");const T=V.request;if(!T.requestNumber&&!T.requestId)throw new Error("Invalid response from server: Request identifier not found");h(!1),u(null),K.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),T.requestNumber?s(`/request/${T.requestNumber}`):T.requestId?s(`/request/${T.requestId}`):s("/my-requests")}catch($){console.error("[App] Error creating claim request:",$);const V=(D=$==null?void 0:$.response)==null?void 0:D.data,T=(V==null?void 0:V.code)||((A=V==null?void 0:V.error)==null?void 0:A.code);if(T==="NO_MANAGER_FOUND"){u({errorType:"NO_MANAGER_FOUND",message:(V==null?void 0:V.message)||((N=V==null?void 0:V.error)==null?void 0:N.message)||"No reporting manager found. Please ensure your manager is correctly configured in the system.",pendingClaimData:S}),h(!0);return}if(T==="MULTIPLE_MANAGERS_FOUND"){const U=(V==null?void 0:V.managers)||((P=V==null?void 0:V.error)==null?void 0:P.managers)||[];u({errorType:"MULTIPLE_MANAGERS_FOUND",managers:U,message:(V==null?void 0:V.message)||((R=V==null?void 0:V.error)==null?void 0:R.message)||"Multiple managers found. Please select one.",pendingClaimData:S}),h(!0);return}const j=((F=(O=$==null?void 0:$.response)==null?void 0:O.data)==null?void 0:F.message)||($==null?void 0:$.message)||"Failed to create claim request";K.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(Lt,{path:"/login/callback",element:e.jsx(wx,{})}),e.jsx(Lt,{path:"/",element:e.jsx(ys,{currentPage:"dashboard",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(ku,{onNavigate:g,onNewRequest:y})})}),e.jsx(Lt,{path:"/dashboard",element:e.jsx(ys,{currentPage:"dashboard",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(ku,{onNavigate:g,onNewRequest:y})})}),e.jsxs(Lt,{element:e.jsx(ys,{currentPage:"admin-templates",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(A0,{})}),children:[e.jsx(Lt,{path:"/admin/create-template",element:e.jsx(Tu,{})}),e.jsx(Lt,{path:"/admin/edit-template/:templateId",element:e.jsx(Tu,{})}),e.jsx(Lt,{path:"/admin/templates",element:e.jsx(zk,{})})]}),e.jsx(Lt,{path:"/create-admin-request/:templateId",element:e.jsx(Gk,{})}),e.jsx(Lt,{path:"/open-requests",element:e.jsx(ys,{currentPage:"open-requests",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(wT,{onViewRequest:b})})}),e.jsx(Lt,{path:"/closed-requests",element:e.jsx(ys,{currentPage:"closed-requests",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(WT,{onViewRequest:b})})}),e.jsx(Lt,{path:"/shared-summaries",element:e.jsx(ys,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(QT,{})})}),e.jsx(Lt,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(ys,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(qT,{})})}),e.jsx(Lt,{path:"/my-requests",element:e.jsx(ys,{currentPage:"my-requests",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(b5,{onViewRequest:b,dynamicRequests:n})})}),e.jsx(Lt,{path:"/requests",element:e.jsx(ys,{currentPage:"requests",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(e4,{onViewRequest:b})})}),e.jsx(Lt,{path:"/approver-performance",element:e.jsx(ys,{currentPage:"approver-performance",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(ik,{})})}),e.jsx(Lt,{path:"/request/:requestId",element:e.jsx(ys,{currentPage:"request-detail",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(JT,{requestId:"",onBack:f,dynamicRequests:n})})}),e.jsx(Lt,{path:"/work-notes/:requestId",element:e.jsx(e5,{})}),e.jsx(Lt,{path:"/new-request",element:e.jsx(ju,{onBack:f,onSubmit:v})}),e.jsx(Lt,{path:"/edit-request/:requestId",element:e.jsx(ju,{onBack:f,onSubmit:v,requestId:void 0,isEditMode:!0})}),e.jsx(Lt,{path:"/claim-management",element:e.jsx(sT,{onBack:f,onSubmit:k})}),e.jsx(Lt,{path:"/profile",element:e.jsx(ys,{currentPage:"profile",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(lk,{})})}),e.jsx(Lt,{path:"/settings",element:e.jsx(ys,{currentPage:"settings",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(Nk,{})})}),e.jsx(Lt,{path:"/notifications",element:e.jsx(ys,{currentPage:"notifications",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(wk,{onNavigate:g})})}),e.jsx(Lt,{path:"/detailed-reports",element:e.jsx(ys,{currentPage:"detailed-reports",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(Vk,{})})})]}),e.jsx(Qk,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),e.jsx(qk,{open:m,onClose:()=>{h(!1),u(null)},onSelect:async S=>{x!=null&&x.pendingClaimData&&await k(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(Yk,{isOpen:!!a,onClose:C,action:a,requestId:l,requestTitle:c,onSubmit:w})]})}function s4(t){const{onLogout:s}=t||{};return e.jsx(C0,{children:e.jsx(t4,{onLogout:s})})}function a4(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=Kt(),[i,l]=p.useState(!1),o=typeof window<"u"&&window.location.pathname==="/login/callback",c=async()=>{try{if(!n){console.error("🔵 ERROR: logout function is undefined!");return}await n()}catch(d){console.error("🔵 Logout error in handleLogout:",d);try{localStorage.clear(),sessionStorage.clear(),window.location.href="/"}catch(m){console.error("🔵 Error during emergency cleanup:",m)}}};if(p.useEffect(()=>{},[t,s,a,r]),o){const d=typeof window<"u"?new URLSearchParams(window.location.search):null,m=d==null?void 0:d.get("code"),h=d==null?void 0:d.get("error");if(!m&&!h){console.log("🚪 AuthenticatedApp: Logout redirect detected, redirecting to home");const u=new URLSearchParams;return u.set("tanflow_logged_out","true"),u.set("logout",Date.now().toString()),window.location.replace(`/?${u.toString()}`),e.jsx("div",{className:"flex items-center justify-center min-h-screen bg-gradient-to-br from-slate-50 to-slate-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-slate-900 border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Redirecting..."})]})})}return(typeof window<"u"?sessionStorage.getItem("auth_provider"):null)==="tanflow"?e.jsx(Yb,{}):e.jsx(wx,{})}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(s4,{onLogout:c}),i&&e.jsx(Xb,{isOpen:i,onClose:()=>l(!1)})]}):e.jsx(Gb,{})}const qn=()=>{try{return!0}catch{return!1}},r4=()=>{if(qn())return null;try{return localStorage.getItem("token")}catch{return null}},n4={user:null,token:r4(),isAuthenticated:!1,isLoading:!1,error:null},yg=Br({name:"auth",initialState:n4,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,!qn())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,!qn())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!qn())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:b4,loginSuccess:y4,loginFailure:v4,logout:j4,clearError:N4,updateUser:w4}=yg.actions,i4=w0({reducer:{auth:yg.reducer,dashboard:kx.reducer,requests:rg.reducer,myRequests:eg.reducer,openRequests:Ux.reducer,closedRequests:Jp.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});El.createRoot(document.getElementById("root")).render(e.jsx(Tf.StrictMode,{children:e.jsx(G0,{store:i4,children:e.jsx(xb,{children:e.jsx(a4,{})})})}));export{je as a};