Re_Backend/build/assets/index-D-8iFw5e.js

76 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-DFaefruY.js","assets/radix-vendor-DIkYAdWy.js","assets/charts-vendor-Bme4E5cb.js","assets/utils-vendor-DNMmNUQL.js","assets/ui-vendor-DbB0YGPu.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-B1UBYWWO.js"])))=>i.map(i=>d[i]);
var Ug=Object.defineProperty;var Bg=(t,s,a)=>s in t?Ug(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Ji=(t,s,a)=>Bg(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Hu,R as Wu,I as Gu,F as Ku,a as Vg,T as zg,P as Hg,C as Wg,b as Gg,O as Yu,c as Zu,d as Kg,e as Yg,f as Zg,D as Xg,g as Qg,A as Jg,h as qg,i as ef,k as tf,l as sf,m as af,n as rf,V as nf,o as lf,p as of,q as cf,r as df,s as mf,t as uf,u as xf,v as hf,w as pf,x as gf,y as ff,z as yf,B as bf,E as vf,G as jf,H as Nf,J as wf,K as Cf,L as Af,M as Sf,N as Tf,Q as Xu,U as Qu,W as kf,X as Ju,Y as qu,Z as Rf,_ as Df,$ as Pf,a0 as If,a1 as Ef,a2 as Ff,a3 as Mf,a4 as _f,a5 as Lf,a6 as Of,a7 as $f,a8 as Uf,a9 as Bf,aa as Vf,ab as zf}from"./radix-vendor-DIkYAdWy.js";import{a as Hf,r as p,c as ex,d as Mr,B as Ul,C as oi,X as ci,Y as di,T as _r,L as mi,e as va,P as tx,f as sx,g as ax,h as Wf,i as Od,j as Ai,k as Si,b as Gf}from"./charts-vendor-Bme4E5cb.js";import{a as fo,f as rx,s as Ks,e as yo,b as $d,c as Kf,d as Ca,g as bn,i as bo,h as nx,j as Us,k as Hs,l as qi,m as Pa,n as Yf,o as Bl,p as Zf,q as Ye,r as Vl,t as Xf,u as Qf,v as Jf,w as qf,x as el,y as Ud,z as e0,A as ix,B as lx,C as vo,D as jo,E as t0,F as s0,G as ox,H as Sr,I as tl,J as a0,K as r0,L as n0}from"./utils-vendor-DNMmNUQL.js";import{L as i0,C as Ve,a as Rs,b as Ze,X as gt,H as l0,c as cx,P as us,U as Lt,F as De,d as Pe,S as Hr,e as o0,f as c0,B as Ds,g as Ga,h as sl,i as No,j as wo,k as Nr,l as dx,m as Ti,n as mx,o as lt,p as Qa,R as zt,I as Wr,T as Ht,q as Xe,r as ga,s as d0,A as xs,t as ss,M as Is,u as ki,v as Pt,w as zl,D as wt,Z as Ri,x as Bt,y as m0,z as u0,E as x0,G as h0,J as p0,K as g0,N as f0,O as y0,Q as b0,V as ux,W as v0,Y as j0,_ as Ia,$ as Di,a0 as Ka,a1 as ui,a2 as Bd,a3 as Vn,a4 as xi,a5 as xx,a6 as Nt,a7 as N0,a8 as K,a9 as Ys,aa as Ss,ab as Pi,ac as ls,ad as hx,ae as xt,af as w0,ag as C0,ah as px,ai as Ii,aj as gx,ak as Vd,al as A0,am as Co,an as ds,ao as Es,ap as Ea,aq as Ei,ar as Fi,as as Ns,at as S0,au as T0,av as fx,aw as k0,ax as Jn,ay as vn,az as Ao,aA as Mi,aB as hi,aC as yx,aD as bx,aE as So,aF as _i,aG as Li,aH as R0,aI as qn,aJ as vx,aK as pi,aL as D0,aM as P0,aN as I0,aO as Oi,aP as $i,aQ as To,aR as E0,aS as zd,aT as _a,aU as F0,aV as kn,aW as M0,aX as Rr,aY as jx,aZ as Hd,a_ as _0,a$ as L0,b0 as Nx,b1 as O0,b2 as $0,b3 as U0,b4 as B0,b5 as V0}from"./ui-vendor-DbB0YGPu.js";import{l as z0}from"./socket-vendor-TjCxX7sJ.js";import{c as Gr,a as H0}from"./redux-vendor-tbZCm13o.js";import{u as qs,a as La,b as wx,B as W0,R as G0,c as Ct,O as Wd}from"./router-vendor-B1UBYWWO.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 Hl={},Gd=Hf;Hl.createRoot=Gd.createRoot,Hl.hydrateRoot=Gd.hydrateRoot;var Cx={exports:{}},Ax={};/**
* @license React
* use-sync-external-store-with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Rn=p;function K0(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var Y0=typeof Object.is=="function"?Object.is:K0,Z0=Rn.useSyncExternalStore,X0=Rn.useRef,Q0=Rn.useEffect,J0=Rn.useMemo,q0=Rn.useDebugValue;Ax.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=X0(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=J0(function(){function c(x){if(!d){if(d=!0,m=x,x=r(x),n!==void 0&&l.hasValue){var g=l.value;if(n(g,x))return u=g}return u=x}if(g=u,Y0(m,x))return g;var f=r(x);return n!==void 0&&n(g,f)?(m=x,g):(m=x,u=f)}var d=!1,m,u,h=a===void 0?null:a;return[function(){return c(s())},h===null?void 0:function(){return c(h())}]},[s,a,r,n]);var o=Z0(t,i[0],i[1]);return Q0(function(){l.hasValue=!0,l.value=o},[o]),q0(o),o};Cx.exports=Ax;var ey=Cx.exports;function ty(t){t()}function sy(){let t=null,s=null;return{clear(){t=null,s=null},notify(){ty(()=>{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 Kd={notify(){},get:()=>[]};function ay(t,s){let a,r=Kd,n=0,i=!1;function l(f){m();const y=r.subscribe(f);let b=!1;return()=>{b||(b=!0,y(),u())}}function o(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=sy())}function u(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Kd)}function h(){i||(i=!0,m())}function x(){i&&(i=!1,u())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:h,tryUnsubscribe:x,getListeners:()=>r};return g}var ry=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ny=ry(),iy=()=>typeof navigator<"u"&&navigator.product==="ReactNative",ly=iy(),oy=()=>ny||ly?p.useLayoutEffect:p.useEffect,cy=oy(),al=Symbol.for("react-redux-context"),rl=typeof globalThis<"u"?globalThis:{};function dy(){if(!p.createContext)return{};const t=rl[al]??(rl[al]=new Map);let s=t.get(p.createContext);return s||(s=p.createContext(null),t.set(p.createContext,s)),s}var Ya=dy();function my(t){const{children:s,context:a,serverState:r,store:n}=t,i=p.useMemo(()=>{const c=ay(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=p.useMemo(()=>n.getState(),[n]);cy(()=>{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||Ya;return p.createElement(o.Provider,{value:i},s)}var uy=my;function ko(t=Ya){return function(){return p.useContext(t)}}var Sx=ko();function Tx(t=Ya){const s=t===Ya?Sx:ko(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var xy=Tx();function hy(t=Ya){const s=t===Ya?xy:Tx(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var py=hy(),gy=(t,s)=>t===s;function fy(t=Ya){const s=t===Ya?Sx:ko(t),a=(r,n={})=>{const{equalityFn:i=gy}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;p.useRef(!0);const m=p.useCallback({[r.name](h){return r(h)}}[r.name],[r]),u=ey.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return p.useDebugValue(u),u};return Object.assign(a,{withTypes:()=>a}),a}var yy=fy(),Wl=function(t,s){return Wl=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])},Wl(t,s)};function by(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");Wl(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var gi=function(){return gi=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},gi.apply(this,arguments)};var xr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ro(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Do(t,s){return t(s={exports:{}},s.exports),s.exports}var dr=Do(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()}});Ro(dr);var vy=Ro(Do(function(t,s){var a=xr&&xr.__awaiter||function(m,u,h,x){return new(h||(h=Promise))(function(g,f){function y(A){try{v(x.next(A))}catch(w){f(w)}}function b(A){try{v(x.throw(A))}catch(w){f(w)}}function v(A){A.done?g(A.value):new h(function(w){w(A.value)}).then(y,b)}v((x=x.apply(m,u||[])).next())})},r=xr&&xr.__generator||function(m,u){var h,x,g,f,y={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return f={next:b(0),throw:b(1),return:b(2)},typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function b(v){return function(A){return function(w){if(h)throw new TypeError("Generator is already executing.");for(;y;)try{if(h=1,x&&(g=2&w[0]?x.return:w[0]?x.throw||((g=x.return)&&g.call(x),0):x.next)&&!(g=g.call(x,w[1])).done)return g;switch(x=0,g&&(w=[2&w[0],g.value]),w[0]){case 0:case 1:g=w;break;case 4:return y.label++,{value:w[1],done:!1};case 5:y.label++,x=w[1],w=[0];continue;case 7:w=y.ops.pop(),y.trys.pop();continue;default:if(g=y.trys,!((g=g.length>0&&g[g.length-1])||w[0]!==6&&w[0]!==2)){y=0;continue}if(w[0]===3&&(!g||w[1]>g[0]&&w[1]<g[3])){y.label=w[1];break}if(w[0]===6&&y.label<g[1]){y.label=g[1],g=w;break}if(g&&y.label<g[2]){y.label=g[2],y.ops.push(w);break}g[2]&&y.ops.pop(),y.trys.pop();continue}w=u.call(m,y)}catch(T){w=[6,T],x=0}finally{h=g=0}if(5&w[0])throw w[1];return{value:w[0]?w[1]:void 0,done:!0}}([v,A])}}},n=xr;Object.defineProperty(s,"__esModule",{value:!0});var i="browser-tabs-lock-key",l={key:function(m){return a(n,void 0,void 0,function(){return r(this,function(u){throw new Error("Unsupported")})})},getItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(u){throw new Error("Unsupported")})})},clear:function(){return a(n,void 0,void 0,function(){return r(this,function(m){return[2,window.localStorage.clear()]})})},removeItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(u){throw new Error("Unsupported")})})},setItem:function(m,u){return a(n,void 0,void 0,function(){return r(this,function(h){throw new Error("Unsupported")})})},keySync:function(m){return window.localStorage.key(m)},getItemSync:function(m){return window.localStorage.getItem(m)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(m){return window.localStorage.removeItem(m)},setItemSync:function(m,u){return window.localStorage.setItem(m,u)}};function o(m){return new Promise(function(u){return setTimeout(u,m)})}function c(m){for(var u="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",h="",x=0;x<m;x++)h+=u[Math.floor(Math.random()*u.length)];return h}var d=function(){function m(u){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+c(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=u,m.waiters===void 0&&(m.waiters=[])}return m.prototype.acquireLock=function(u,h){return h===void 0&&(h=5e3),a(this,void 0,void 0,function(){var x,g,f,y,b,v,A;return r(this,function(w){switch(w.label){case 0:x=Date.now()+c(4),g=Date.now()+h,f=i+"-"+u,y=this.storageHandler===void 0?l:this.storageHandler,w.label=1;case 1:return Date.now()<g?[4,o(30)]:[3,8];case 2:return w.sent(),y.getItemSync(f)!==null?[3,5]:(b=this.id+"-"+u+"-"+x,[4,o(Math.floor(25*Math.random()))]);case 3:return w.sent(),y.setItemSync(f,JSON.stringify({id:this.id,iat:x,timeoutKey:b,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,o(30)];case 4:return w.sent(),(v=y.getItemSync(f))!==null&&(A=JSON.parse(v)).id===this.id&&A.iat===x?(this.acquiredIatSet.add(x),this.refreshLockWhileAcquired(f,x),[2,!0]):[3,7];case 5:return m.lockCorrector(this.storageHandler===void 0?l:this.storageHandler),[4,this.waitForSomethingToChange(g)];case 6:w.sent(),w.label=7;case 7:return x=Date.now()+c(4),[3,1];case 8:return[2,!1]}})})},m.prototype.refreshLockWhileAcquired=function(u,h){return a(this,void 0,void 0,function(){var x=this;return r(this,function(g){return setTimeout(function(){return a(x,void 0,void 0,function(){var f,y,b;return r(this,function(v){switch(v.label){case 0:return[4,dr.default().lock(h)];case 1:return v.sent(),this.acquiredIatSet.has(h)?(f=this.storageHandler===void 0?l:this.storageHandler,(y=f.getItemSync(u))===null?(dr.default().unlock(h),[2]):((b=JSON.parse(y)).timeRefreshed=Date.now(),f.setItemSync(u,JSON.stringify(b)),dr.default().unlock(h),this.refreshLockWhileAcquired(u,h),[2])):(dr.default().unlock(h),[2])}})})},1e3),[2]})})},m.prototype.waitForSomethingToChange=function(u){return a(this,void 0,void 0,function(){return r(this,function(h){switch(h.label){case 0:return[4,new Promise(function(x){var g=!1,f=Date.now(),y=!1;function b(){if(y||(window.removeEventListener("storage",b),m.removeFromWaiting(b),clearTimeout(v),y=!0),!g){g=!0;var A=50-(Date.now()-f);A>0?setTimeout(x,A):x(null)}}window.addEventListener("storage",b),m.addToWaiting(b);var v=setTimeout(b,Math.max(0,u-Date.now()))})];case 1:return h.sent(),[2]}})})},m.addToWaiting=function(u){this.removeFromWaiting(u),m.waiters!==void 0&&m.waiters.push(u)},m.removeFromWaiting=function(u){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(h){return h!==u}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(u){return u()})},m.prototype.releaseLock=function(u){return a(this,void 0,void 0,function(){return r(this,function(h){switch(h.label){case 0:return[4,this.releaseLock__private__(u)];case 1:return[2,h.sent()]}})})},m.prototype.releaseLock__private__=function(u){return a(this,void 0,void 0,function(){var h,x,g,f;return r(this,function(y){switch(y.label){case 0:return h=this.storageHandler===void 0?l:this.storageHandler,x=i+"-"+u,(g=h.getItemSync(x))===null?[2]:(f=JSON.parse(g)).id!==this.id?[3,2]:[4,dr.default().lock(f.iat)];case 1:y.sent(),this.acquiredIatSet.delete(f.iat),h.removeItemSync(x),dr.default().unlock(f.iat),m.notifyWaiters(),y.label=2;case 2:return[2]}})})},m.lockCorrector=function(u){for(var h=Date.now()-5e3,x=u,g=[],f=0;;){var y=x.keySync(f);if(y===null)break;g.push(y),f++}for(var b=!1,v=0;v<g.length;v++){var A=g[v];if(A.includes(i)){var w=x.getItemSync(A);if(w!==null){var T=JSON.parse(w);(T.timeRefreshed===void 0&&T.timeAcquired<h||T.timeRefreshed!==void 0&&T.timeRefreshed<h)&&(x.removeItemSync(A),b=!0)}}}b&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var pr=Do(function(t,s){var a=xr&&xr.__assign||function(){return a=Object.assign||function(c){for(var d,m=1,u=arguments.length;m<u;m++)for(var h in d=arguments[m])Object.prototype.hasOwnProperty.call(d,h)&&(c[h]=d[h]);return c},a.apply(this,arguments)};function r(c,d){if(!d)return"";var m="; "+c;return d===!0?m:m+"="+d}function n(c,d,m){return encodeURIComponent(c).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(d).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(u){if(typeof u.expires=="number"){var h=new Date;h.setMilliseconds(h.getMilliseconds()+864e5*u.expires),u.expires=h}return r("Expires",u.expires?u.expires.toUTCString():"")+r("Domain",u.domain)+r("Path",u.path)+r("Secure",u.secure)+r("SameSite",u.sameSite)}(m)}function i(c){for(var d={},m=c?c.split("; "):[],u=/(%[\dA-F]{2})+/gi,h=0;h<m.length;h++){var x=m[h].split("="),g=x.slice(1).join("=");g.charAt(0)==='"'&&(g=g.slice(1,-1));try{d[x[0].replace(u,decodeURIComponent)]=g.replace(u,decodeURIComponent)}catch{}}return d}function l(){return i(document.cookie)}function o(c,d,m){document.cookie=n(c,d,a({path:"/"},m))}s.__esModule=!0,s.encode=n,s.parse=i,s.getAll=l,s.get=function(c){return l()[c]},s.set=o,s.remove=function(c,d){o(c,"",a(a({},d),{expires:-1}))}});Ro(pr),pr.encode,pr.parse,pr.getAll;pr.get;pr.set;pr.remove;var Yd;(function(t){t.Code="code",t.ConnectCode="connect_code"})(Yd||(Yd={}));var Zd;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(Zd||(Zd={}));new vy;var jy={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Os=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},Ny=gi(gi({},jy),{buildAuthorizeUrl:Os,buildLogoutUrl:Os,getAccessTokenSilently:Os,getAccessTokenWithPopup:Os,getIdTokenClaims:Os,loginWithRedirect:Os,loginWithPopup:Os,connectAccountWithRedirect:Os,logout:Os,handleRedirectCallback:Os,getDpopNonce:Os,setDpopNonce:Os,generateDpopProof:Os,createFetcher:Os}),wy=p.createContext(Ny);(function(t){by(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 Cy=function(t){return t===void 0&&(t=wy),p.useContext(t)};const nl="idToken",il="userData",Ay=()=>!0;class at{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(nl,s)}static getIdToken(){return sessionStorage.getItem(nl)}static setUserData(s){localStorage.setItem(il,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(il);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(il),sessionStorage.removeItem(nl)}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 Ay()}}function ll(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 kx="https://re-workflow-nt-dev.siplsolutions.com/api/v1",je=fo.create({baseURL:kx,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=at.getRefreshToken(),l=await fo.post(`${kx}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(l.data.data||l.data).accessToken;return je(s)}catch(i){return at.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function Sy(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&&at.setUserData(l.user),l.idToken&&at.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(at.setAccessToken(l.accessToken),at.setRefreshToken(l.refreshToken)),l}catch(n){throw console.error("❌ Token exchange failed:",{message:n.message,response:(a=n.response)==null?void 0:a.data,status:(r=n.response)==null?void 0:r.status,code:t?`${t.substring(0,10)}...`:"MISSING",redirectUri:s}),n}}async function Ty(){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 dn(){const s=(await je.get("/auth/me")).data;return s.data||s}async function ky(){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 Xd="https://ssodev.rebridge.co.in/realms/RE",Ry="REFLOW",Rx=`${window.location.origin}/login/callback`;async function Dy(t,s){var r,n,i;const a="https://re-workflow-nt-dev.siplsolutions.com/api/v1";try{const l=await fo.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:Rx,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),o=((r=l.data)==null?void 0:r.data)||l.data;return o.accessToken&&at.setAccessToken(o.accessToken),o.refreshToken&&at.setRefreshToken(o.refreshToken),o.idToken&&at.setIdToken(o.idToken),o.user&&at.setUserData(o.user),o}catch(l){throw console.error("❌ Tanflow token exchange failed:",{message:l.message,response:(n=l.response)==null?void 0:n.data,status:(i=l.response)==null?void 0:i.status}),l}}function Py(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=Rx,a=new URL(`${Xd}/protocol/openid-connect/logout`);a.searchParams.set("client_id",Ry),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:`${Xd}/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 Dx=p.createContext(void 0);function Iy({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__"),A=sessionStorage.getItem("__force_logout__");if(v==="true"||A==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),at.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(T){console.error("Error clearing storage:",T)}a(!1),l(null),n(!1),c(null);return}const w=new URLSearchParams(window.location.search);if(w.has("logout")||w.has("okta_logged_out")||w.has("tanflow_logged_out")){console.log("🚪 Logout parameter detected in URL, clearing all tokens"),at.clearAll(),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state"),sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),sessionStorage.removeItem("tanflow_logged_out"),localStorage.clear(),a(!1),l(null),n(!1);const T=new URLSearchParams;w.has("okta_logged_out")&&T.set("okta_logged_out","true"),w.has("tanflow_logged_out")&&T.set("tanflow_logged_out","true");const C=T.toString()?`/?${T.toString()}`:"/";window.history.replaceState({},document.title,C);return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(at.getUserData(),d?n(!1):h())},[d]),p.useEffect(()=>{if(!s)return;const v=async()=>{try{await y()}catch(T){console.error("Silent refresh failed:",T)}},A=10*60*1e3,w=setInterval(v,A);return()=>clearInterval(w)},[s]);const u=p.useRef(!1);p.useEffect(()=>{if(u.current||window.location.pathname!=="/login/callback")return;(async()=>{const A=new URLSearchParams(window.location.search);if((A.has("logout")||A.has("tanflow_logged_out")||A.has("okta_logged_out"))&&!A.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const _=new URLSearchParams;A.has("tanflow_logged_out")&&_.set("tanflow_logged_out","true"),A.has("okta_logged_out")&&_.set("okta_logged_out","true"),A.has("logout")&&_.set("logout",A.get("logout")||Date.now().toString());const D=_.toString()?`/?${_.toString()}`:"/?logout="+Date.now();window.location.replace(D);return}u.current=!0;const w=A.get("code"),T=A.get("error");if(window.history.replaceState({},document.title,"/login/callback"),sessionStorage.getItem("auth_provider")==="tanflow"){u.current=!1;return}if(T){c(new Error(`Authentication error: ${T}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!w){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),c(null);const _=`${window.location.origin}/login/callback`,D=await Sy(w,_);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"),u.current=!1}finally{n(!1)}})()},[]);const h=async()=>{var A;if(d){n(!1);return}const v=!0;try{if(n(!0),v){const C=at.getUserData();try{const _=await dn();l(_),at.setUserData(_),a(!0)}catch(_){if(((A=_==null?void 0:_.response)==null?void 0:A.status)===401)try{await y();const D=await dn();l(D),at.setUserData(D),a(!0)}catch{at.clearAll(),a(!1),l(null)}else _!=null&&_.isConnectionError?C?(l(C),a(!0)):(a(!1),l(null)):(at.clearAll(),a(!1),l(null))}return}const w=at.getAccessToken(),T=at.getUserData();if(!w){a(!1),l(null),n(!1);return}if(ll(w))try{await y();const C=at.getAccessToken();if(C&&!ll(C)){const _=at.getUserData();if(_)l(_),a(!0);else try{const D=await dn();l(D),at.setUserData(D),a(!0)}catch{at.clearAll(),a(!1),l(null)}}else at.clearAll(),a(!1),l(null)}catch{at.clearAll(),a(!1),l(null)}else if(T)l(T),a(!0);else try{const C=await dn();l(C),at.setUserData(C),a(!0)}catch{at.clearAll(),a(!1),l(null)}}catch(w){console.error("Error checking auth status:",w),c(w),at.clearAll(),a(!1),l(null)}finally{n(!1)}},x=async()=>{try{c(null);const v="https://royalenfield.okta.com",A="0oa18b98aari6I6eo2p8",w=`${window.location.origin}/login/callback`,T="code",C="openid profile email",_=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const D=new URLSearchParams(window.location.search),S=D.has("logout")||D.has("okta_logged_out")||D.has("tanflow_logged_out");let j=`${v}/oauth2/default/v1/authorize?client_id=${A}&redirect_uri=${encodeURIComponent(w)}&response_type=${T}&scope=${encodeURIComponent(C)}&state=${_}`;S&&(j+="&prompt=login"),window.location.href=j}catch(v){throw c(v),v}},g=async()=>{try{const v=at.getIdToken(),A=sessionStorage.getItem("auth_provider")||(v&&v.includes("tanflow")?"tanflow":null)||"okta";sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),l(null),c(null),n(!0);try{await ky(),console.log("🚪 Backend logout API called successfully")}catch(D){console.error("🚪 Logout API error:",D),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const w=sessionStorage.getItem("__logout_in_progress__"),T=sessionStorage.getItem("__force_logout__"),C=sessionStorage.getItem("auth_provider");if(at.clearAll(),w&&sessionStorage.setItem("__logout_in_progress__",w),T&&sessionStorage.setItem("__force_logout__",T),v&&at.setIdToken(v),C&&sessionStorage.setItem("auth_provider",C),await new Promise(D=>setTimeout(D,100)),A==="tanflow"&&v){console.log("🚪 Initiating Tanflow logout...");try{Py(v);return}catch(D){console.error("🚪 Tanflow logout error:",D)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),v&&at.clearAll();const _=`${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 A=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(A)}catch{window.location.replace("/?logout="+Date.now())}}},f=async()=>{{if(s)return"cookie-based-auth";try{return await y(),s?"cookie-based-auth":null}catch{return null}}const v=at.getAccessToken();if(v&&!ll(v))return v;try{return await y(),at.getAccessToken()}catch{return null}},y=async()=>{try{const A=await Ty();return}catch(A){throw at.clearAll(),a(!1),l(null),A}},b={isAuthenticated:s,isLoading:r,user:i,error:o,login:x,logout:g,getAccessTokenSilently:f,refreshTokenSilently:y};return e.jsx(Dx.Provider,{value:b,children:t})}function Ey({children:t}){return e.jsx(Iy,{children:t})}function Qt(){const t=p.useContext(Dx);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function mr(t){return(t==null?void 0:t.role)==="ADMIN"}function an(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function Ui(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Qd=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,Jd=ex,Px=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return Jd(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,l=Object.keys(n).map(d=>{const m=a==null?void 0:a[d],u=i==null?void 0:i[d];if(m===null)return null;const h=Qd(m)||Qd(u);return n[d][h]}),o=a&&Object.entries(a).reduce((d,m)=>{let[u,h]=m;return h===void 0||(d[u]=h),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:u,className:h,...x}=m;return Object.entries(x).every(g=>{let[f,y]=g;return Array.isArray(y)?y.includes({...i,...o}[f]):{...i,...o}[f]===y})?[...d,u,h]:d},[]);return Jd(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},Po="-",Fy=t=>{const s=_y(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(Po);return o[0]===""&&o.length!==1&&o.shift(),Ix(o,s)||My(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},Ix=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Ix(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Po);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},qd=/^\[(.+)\]$/,My=t=>{if(qd.test(t)){const s=qd.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},_y=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Oy(Object.entries(t.classGroups),a).forEach(([i,l])=>{Gl(l,r,i,s)}),r},Gl=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:em(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Ly(n)){Gl(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{Gl(l,em(s,i),a,r)})})},em=(t,s)=>{let a=t;return s.split(Po).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Ly=t=>t.isThemeGetter,Oy=(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,$y=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)}}},Ex="!",Uy=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,l=o=>{const c=[];let d=0,m=0,u;for(let y=0;y<o.length;y++){let b=o[y];if(d===0){if(b===n&&(r||o.slice(y,y+i)===s)){c.push(o.slice(m,y)),m=y+i;continue}if(b==="/"){u=y;continue}}b==="["?d++:b==="]"&&d--}const h=c.length===0?o:o.substring(m),x=h.startsWith(Ex),g=x?h.substring(1):h,f=u&&u>m?u-m:void 0;return{modifiers:c,hasImportantModifier:x,baseClassName:g,maybePostfixModifierPosition:f}};return a?o=>a({className:o,parseClassName:l}):l},By=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},Vy=t=>({cache:$y(t.cacheSize),parseClassName:Uy(t),...Fy(t)}),zy=/\s+/,Hy=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(zy);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:u,baseClassName:h,maybePostfixModifierPosition:x}=a(d);let g=!!x,f=r(g?h.substring(0,x):h);if(!f){if(!g){o=d+(o.length>0?" "+o:o);continue}if(f=r(h),!f){o=d+(o.length>0?" "+o:o);continue}g=!1}const y=By(m).join(":"),b=u?y+Ex:y,v=b+f;if(i.includes(v))continue;i.push(v);const A=n(f,g);for(let w=0;w<A.length;++w){const T=A[w];i.push(b+T)}o=d+(o.length>0?" "+o:o)}return o};function Wy(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=Fx(s))&&(r&&(r+=" "),r+=a);return r}const Fx=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=Fx(t[r]))&&(a&&(a+=" "),a+=s);return a};function Gy(t,...s){let a,r,n,i=l;function l(c){const d=s.reduce((m,u)=>u(m),t());return a=Vy(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=Hy(c,a);return n(c,m),m}return function(){return i(Wy.apply(null,arguments))}}const _t=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},Mx=/^\[(?:([a-z-]+):)?(.+)\]$/i,Ky=/^\d+\/\d+$/,Yy=new Set(["px","full","screen"]),Zy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Xy=/\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$/,Qy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Jy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,qy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ka=t=>Lr(t)||Yy.has(t)||Ky.test(t),Va=t=>Kr(t,"length",lb),Lr=t=>!!t&&!Number.isNaN(Number(t)),ol=t=>Kr(t,"number",Lr),rn=t=>!!t&&Number.isInteger(Number(t)),eb=t=>t.endsWith("%")&&Lr(t.slice(0,-1)),it=t=>Mx.test(t),za=t=>Zy.test(t),tb=new Set(["length","size","percentage"]),sb=t=>Kr(t,tb,_x),ab=t=>Kr(t,"position",_x),rb=new Set(["image","url"]),nb=t=>Kr(t,rb,cb),ib=t=>Kr(t,"",ob),nn=()=>!0,Kr=(t,s,a)=>{const r=Mx.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},lb=t=>Xy.test(t)&&!Qy.test(t),_x=()=>!1,ob=t=>Jy.test(t),cb=t=>qy.test(t),db=()=>{const t=_t("colors"),s=_t("spacing"),a=_t("blur"),r=_t("brightness"),n=_t("borderColor"),i=_t("borderRadius"),l=_t("borderSpacing"),o=_t("borderWidth"),c=_t("contrast"),d=_t("grayscale"),m=_t("hueRotate"),u=_t("invert"),h=_t("gap"),x=_t("gradientColorStops"),g=_t("gradientColorStopPositions"),f=_t("inset"),y=_t("margin"),b=_t("opacity"),v=_t("padding"),A=_t("saturate"),w=_t("scale"),T=_t("sepia"),C=_t("skew"),_=_t("space"),D=_t("translate"),S=()=>["auto","contain","none"],j=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto",it,s],R=()=>[it,s],O=()=>["",ka,Va],F=()=>["auto",Lr,it],M=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],B=()=>["solid","dashed","dotted","double","none"],k=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],N=()=>["start","end","center","between","around","evenly","stretch"],U=()=>["","0",it],$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>[Lr,it];return{cacheSize:500,separator:":",theme:{colors:[nn],spacing:[ka,Va],blur:["none","",za,it],brightness:L(),borderColor:[t],borderRadius:["none","","full",za,it],borderSpacing:R(),borderWidth:O(),contrast:L(),grayscale:U(),hueRotate:L(),invert:U(),gap:R(),gradientColorStops:[t],gradientColorStopPositions:[eb,Va],inset:P(),margin:P(),opacity:L(),padding:R(),saturate:L(),scale:L(),sepia:U(),skew:L(),space:R(),translate:R()},classGroups:{aspect:[{aspect:["auto","square","video",it]}],container:["container"],columns:[{columns:[za]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...M(),it]}],overflow:[{overflow:j()}],"overflow-x":[{"overflow-x":j()}],"overflow-y":[{"overflow-y":j()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[f]}],"inset-x":[{"inset-x":[f]}],"inset-y":[{"inset-y":[f]}],start:[{start:[f]}],end:[{end:[f]}],top:[{top:[f]}],right:[{right:[f]}],bottom:[{bottom:[f]}],left:[{left:[f]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",rn,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",rn,it]}],"grid-cols":[{"grid-cols":[nn]}],"col-start-end":[{col:["auto",{span:["full",rn,it]},it]}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":[nn]}],"row-start-end":[{row:["auto",{span:[rn,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:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...N()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...N(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...N(),"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:[y]}],mx:[{mx:[y]}],my:[{my:[y]}],ms:[{ms:[y]}],me:[{me:[y]}],mt:[{mt:[y]}],mr:[{mr:[y]}],mb:[{mb:[y]}],ml:[{ml:[y]}],"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:[za]},za]}],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",za,Va]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",ol]}],"font-family":[{font:[nn]}],"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",Lr,ol]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",ka,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":[b]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[b]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...B(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",ka,Va]}],"underline-offset":[{"underline-offset":["auto",ka,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":[b]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...M(),ab]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",sb]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},nb]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[x]}],"gradient-via":[{via:[x]}],"gradient-to":[{to:[x]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[b]}],"border-style":[{border:[...B(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[b]}],"divide-style":[{divide:B()}],"border-color":[{border:[n]}],"border-color-x":[{"border-x":[n]}],"border-color-y":[{"border-y":[n]}],"border-color-s":[{"border-s":[n]}],"border-color-e":[{"border-e":[n]}],"border-color-t":[{"border-t":[n]}],"border-color-r":[{"border-r":[n]}],"border-color-b":[{"border-b":[n]}],"border-color-l":[{"border-l":[n]}],"divide-color":[{divide:[n]}],"outline-style":[{outline:["",...B()]}],"outline-offset":[{"outline-offset":[ka,it]}],"outline-w":[{outline:[ka,Va]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:O()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[b]}],"ring-offset-w":[{"ring-offset":[ka,Va]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",za,ib]}],"shadow-color":[{shadow:[nn]}],opacity:[{opacity:[b]}],"mix-blend":[{"mix-blend":[...k(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":k()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",za,it]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[u]}],saturate:[{saturate:[A]}],sepia:[{sepia:[T]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[u]}],"backdrop-opacity":[{"backdrop-opacity":[b]}],"backdrop-saturate":[{"backdrop-saturate":[A]}],"backdrop-sepia":[{"backdrop-sepia":[T]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",it]}],duration:[{duration:L()}],ease:[{ease:["linear","in","out","in-out",it]}],delay:[{delay:L()}],animate:[{animate:["none","spin","ping","pulse","bounce",it]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[w]}],"scale-x":[{"scale-x":[w]}],"scale-y":[{"scale-y":[w]}],rotate:[{rotate:[rn,it]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"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:[ka,Va,ol]}],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"]}}},mb=Gy(db);function Re(...t){return mb(ex(t))}const jn=Px("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),I=p.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Hu:"button";return e.jsx(l,{"data-slot":"button",className:Re(jn({variant:s,size:a,className:t})),ref:i,...n})});I.displayName="Button";function J({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:Re("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function me({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:Re("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",t),...s})}function ue({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:Re("leading-none",t),...s})}function Te({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:Re("text-muted-foreground",t),...s})}function q({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:Re("px-6 [&:last-child]:pb-6",t),...s})}const Bi="/assets/Re_Logo-By51taPS.png",tm="/assets/landing_page_image-ClTD-4qZ.jpg";function ub(){const{login:t,isLoading:s,error:a}=Qt(),[r]=p.useState(!1),[n,i]=p.useState(!1);p.useEffect(()=>{const o=new Image;o.src=tm,o.onload=()=>{i(!0)},o.complete&&i(!0)},[]);const l=async()=>{localStorage.clear(),sessionStorage.clear();try{await t()}catch(o){console.error("========================================"),console.error("OKTA LOGIN ERROR"),console.error("Error details:",o),console.error("Error message:",o==null?void 0:o.message),console.error("Error stack:",o==null?void 0:o.stack),console.error("========================================")}};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:n?`url(${tm})`:"none",backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transition:"background-image 0.3s ease-in-out"},children:[!n&&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(J,{className:"w-full max-w-md shadow-xl relative z-10 bg-black backdrop-blur-sm border-gray-800",children:[e.jsx(me,{className:"space-y-1 text-center pb-6",children:e.jsxs("div",{className:"flex flex-col items-center justify-center mb-4",children:[e.jsx("img",{src:Bi,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(q,{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.jsx("div",{className:"space-y-3",children:e.jsx(I,{onClick:l,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(i0,{className:"mr-2 h-5 w-5"}),"RE Employee 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 Lx(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Qt(),[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:Bi,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(Ve,{className:"w-16 h-16 text-red-500"})}),e.jsx(Ve,{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(Rs,{className:"w-16 h-16 text-green-500"})}),e.jsx(Rs,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Ze,{className:"w-16 h-16 animate-spin text-re-red"}),e.jsx("div",{className:"absolute inset-0 border-4 rounded-full border-re-red/20"}),e.jsx("div",{className:"absolute inset-0 border-4 border-transparent border-t-re-red rounded-full animate-spin"})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-white mb-2",children:n==="complete"?"Welcome Back!":n==="error"?"Authentication Error":"Authenticating"}),e.jsx("p",{className:"text-slate-300 text-sm",children:l()})]}),n!=="error"&&e.jsxs("div",{className:"space-y-3 mb-6",children:[e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="exchanging"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="exchanging"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Validating credentials"})]}),e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="fetching"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="fetching"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Loading your profile"})]}),n==="complete"&&e.jsxs("div",{className:"flex items-center gap-3 text-sm transition-all duration-500 text-white",children:[e.jsx("div",{className:"w-2 h-2 rounded-full transition-all duration-500 bg-green-500"}),e.jsx("span",{children:"Setting up your session"})]})]}),n==="error"&&a&&e.jsxs("div",{className:"mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx("p",{className:"text-red-400 text-sm",children:a.message||"An error occurred during authentication"}),e.jsx("button",{onClick:()=>{window.location.href="/"},className:"mt-4 text-sm text-red-400 hover:text-red-300 underline",children:"Return to login"})]}),n!=="error"&&n!=="complete"&&e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"h-1.5 bg-slate-700/50 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-re-red rounded-full animate-pulse",style:{animation:"progress 2s ease-in-out infinite"}})}),e.jsx("style",{children:`
@keyframes progress {
0%, 100% { width: 20%; }
50% { width: 80%; }
}
`})]})]}),e.jsx("p",{className:"mt-6 text-slate-500 text-xs",children:n==="complete"?"Loading dashboard...":"Please wait while we secure your session"})]}),e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute top-1/4 left-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-1/4 right-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse delay-1000"})]})]})}function xb(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Qt(),[n,i]=p.useState("exchanging"),[l,o]=p.useState(""),c=p.useRef(!1);p.useEffect(()=>{if(a){i("error");return}if(s){const u=new URLSearchParams(window.location.search).get("code");i(u&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&(i("complete"),setTimeout(()=>{window.location.href="/"},1e3))},[t,s,a,r]),p.useEffect(()=>{if(c.current||window.location.pathname!=="/login/callback")return;const m=new URLSearchParams(window.location.search),u=m.get("code"),h=m.get("error");if(!u&&!h){console.log("🚪 Logout redirect detected: no code, no error - redirecting to home immediately"),c.current=!0;const f=new URLSearchParams;f.set("tanflow_logged_out","true"),f.set("logout",Date.now().toString());const y=`/?${f.toString()}`;console.log("🚪 Redirecting to:",y),window.location.replace(y);return}if(sessionStorage.getItem("auth_provider")!=="tanflow")return;(async()=>{c.current=!0;const f=new URLSearchParams(window.location.search),y=f.get("code"),b=f.get("state"),v=f.get("error");if(window.history.replaceState({},document.title,"/login/callback"),v){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}const A=sessionStorage.getItem("tanflow_auth_state");if(b&&b!==A){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}if(!y){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}try{i("exchanging");const w=await Dy(y,b||"");sessionStorage.removeItem("tanflow_auth_state"),i("fetching");const T=w.user||await dn();if(T)at.setUserData(T),i("complete"),setTimeout(()=>{window.history.replaceState({},document.title,"/"),window.location.href="/"},1e3);else throw new Error("User data not received")}catch(w){console.error("Tanflow callback error:",w),i("error"),o(w.message||"Authentication failed"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state")}})()},[]);const 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:Bi,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(Ve,{className:"w-16 h-16 text-red-500"})}),e.jsx(Ve,{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(Rs,{className:"w-16 h-16 text-green-500"})}),e.jsx(Rs,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Ze,{className:"w-16 h-16 animate-spin text-re-red"}),e.jsx("div",{className:"absolute inset-0 border-4 rounded-full border-re-red/20"}),e.jsx("div",{className:"absolute inset-0 border-4 border-transparent border-t-re-red rounded-full animate-spin"})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-white mb-2",children:n==="complete"?"Welcome Back!":n==="error"?"Authentication Error":"Authenticating"}),e.jsx("p",{className:"text-slate-300 text-sm",children: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 hb=Px("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function ie({className:t,variant:s,asChild:a=!1,...r}){const n=a?Hu:"span";return e.jsx(n,{"data-slot":"badge",className:Re(hb({variant:s}),t),...r})}function pb({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=Cy();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(J,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Authentication Debug Information"}),e.jsx(I,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(gt,{className:"h-4 w-4"})})]})}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold",children:"Status:"}),e.jsx(ie,{variant:r?"default":"destructive",children:n?"Loading...":r?"Authenticated":"Not Authenticated"})]}),i&&e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded p-3",children:[e.jsx("p",{className:"text-sm text-red-700 font-semibold",children:"Error:"}),e.jsx("p",{className:"text-sm text-red-600",children:i.message})]}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-semibold",children:"User Information:"}),e.jsx("pre",{className:"bg-gray-50 p-3 rounded text-xs overflow-auto",children:JSON.stringify(a,null,2)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-semibold",children:"All Auth Claims:"}),e.jsx("pre",{className:"bg-gray-50 p-3 rounded text-xs overflow-auto",children:JSON.stringify({isAuthenticated:r,isLoading:n,error:(i==null?void 0:i.message)||null,hasUser:!!a},null,2)})]})]})]})}):null}const es=p.forwardRef(({className:t,...s},a)=>e.jsx(Wu,{ref:a,"data-slot":"avatar",className:Re("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));es.displayName=Wu.displayName;const Vi=p.forwardRef(({className:t,...s},a)=>e.jsx(Gu,{ref:a,"data-slot":"avatar-image",className:Re("aspect-square size-full",t),...s}));Vi.displayName=Gu.displayName;const ts=p.forwardRef(({className:t,...s},a)=>e.jsx(Ku,{ref:a,"data-slot":"avatar-fallback",className:Re("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));ts.displayName=Ku.displayName;function sm({...t}){return e.jsx(Vg,{"data-slot":"dropdown-menu",...t})}function am({...t}){return e.jsx(zg,{"data-slot":"dropdown-menu-trigger",...t})}function rm({className:t,sideOffset:s=4,...a}){return e.jsx(Hg,{children:e.jsx(Wg,{"data-slot":"dropdown-menu-content",sideOffset:s,className:Re("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",t),...a})})}function cl({className:t,inset:s,variant:a="default",...r}){return e.jsx(Gg,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:Re("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r})}function Ox({...t}){return e.jsx(Yg,{"data-slot":"alert-dialog",...t})}function gb({...t}){return e.jsx(Kg,{"data-slot":"alert-dialog-portal",...t})}const $x=p.forwardRef(({className:t,...s},a)=>e.jsx(Yu,{"data-slot":"alert-dialog-overlay",className:Re("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...s,ref:a}));$x.displayName=Yu.displayName;const Io=p.forwardRef(({className:t,...s},a)=>e.jsxs(gb,{children:[e.jsx($x,{}),e.jsx(Zu,{"data-slot":"alert-dialog-content",ref:a,className:Re("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...s})]}));Io.displayName=Zu.displayName;function Ux({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:Re("flex flex-col gap-2 text-center sm:text-left",t),...s})}function Bx({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:Re("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function Vx({className:t,...s}){return e.jsx(Zg,{"data-slot":"alert-dialog-title",className:Re("text-lg font-semibold",t),...s})}function zx({className:t,...s}){return e.jsx(Xg,{"data-slot":"alert-dialog-description",className:Re("text-muted-foreground text-sm",t),...s})}function Hx({className:t,...s}){return e.jsx(Jg,{className:Re(jn(),t),...s})}function Wx({className:t,...s}){return e.jsx(Qg,{className:Re(jn({variant:"outline"}),t),...s})}const Wa={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}},fb=async()=>(await je.get("/notifications/subscriptions")).data.data.subscriptions;let or=null;function yb(){return"https://re-workflow-nt-dev.siplsolutions.com"}function Ur(t){const s=yb();return or||(or=z0(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),or.on("connect",()=>{}),or.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),or.on("disconnect",a=>{}),or)}function Kl(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function Gx(t,s){t.emit("leave:request",s)}function Kx(t,s){t.emit("join:user",{userId:s})}function cs({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([]),[u,h]=p.useState(0),[x,g]=p.useState(!1),{user:f}=Qt(),y=p.useMemo(()=>{try{const C=at.getUserData();return(C==null?void 0:C.jobTitle)==="Dealer"}catch(C){return console.error("[PageLayout] Error checking dealer status:",C),!1}},[]),b=()=>{var C,_;try{if(f!=null&&f.displayName&&typeof f.displayName=="string"){const D=f.displayName.split(" ").filter(Boolean);return D.length>=2?`${((C=D[0])==null?void 0:C[0])||""}${((_=D[D.length-1])==null?void 0:_[0])||""}`.toUpperCase():f.displayName.substring(0,2).toUpperCase()}return f!=null&&f.email&&typeof f.email=="string"?f.email.substring(0,2).toUpperCase():"U"}catch(D){return console.error("[PageLayout] Error getting user initials:",D),"U"}},v=p.useMemo(()=>{const C=[{id:"dashboard",label:"Dashboard",icon:l0},{id:"requests",label:"All Requests",icon:cx},{id:"admin/templates",label:"Admin Templates",icon:us,adminOnly:!0}];return y||C.push({id:"my-requests",label:"My Requests",icon:Lt}),C.push({id:"open-requests",label:"Open Requests",icon:De},{id:"closed-requests",label:"Closed Requests",icon:Pe},{id:"shared-summaries",label:"Shared Summary",icon:Hr}),C},[y]),A=()=>{l(!i)},w=async C=>{var _;try{if(C.isRead||(await Wa.markAsRead(C.notificationId),m(D=>D.map(S=>S.notificationId===C.notificationId?{...S,isRead:!0}:S)),h(D=>Math.max(0,D-1))),C.actionUrl&&a){const D=(_=C.metadata)==null?void 0:_.requestNumber;if(D){let S=`request/${D}`;(C.notificationType==="mention"||C.notificationType==="comment"||C.notificationType==="worknote")&&(S+="?tab=worknotes"),a(S)}}g(!1)}catch(D){console.error("[PageLayout] Error handling notification click:",D)}},T=async()=>{try{await Wa.markAllAsRead(),m(C=>C.map(_=>({..._,isRead:!0}))),h(0)}catch(C){console.error("[PageLayout] Error marking all as read:",C)}};return p.useEffect(()=>{const C=f==null?void 0:f.userId;if(!C)return;let _=!0;(async()=>{var j,P;try{const R=await Wa.list({page:1,limit:4,unreadOnly:!1});if(!_)return;const O=((j=R.data)==null?void 0:j.notifications)||[];m(O),h(((P=R.data)==null?void 0:P.unreadCount)||0)}catch(R){console.error("[PageLayout] Failed to fetch notifications:",R)}})();const S=Ur();if(S){Kx(S,C);const j=P=>{_&&(m(R=>[P.notification,...R].slice(0,4)),h(R=>R+1))};return S.on("notification:new",j),()=>{_=!1,S.off("notification:new",j)}}return()=>{_=!1}},[f]),p.useEffect(()=>{const C=()=>{window.innerWidth>=768?l(!0):l(!1)};return C(),window.addEventListener("resize",C),()=>window.removeEventListener("resize",C)},[]),e.jsxs("div",{className:"min-h-screen flex w-full bg-background",children:[i&&e.jsx("div",{className:"fixed inset-0 bg-black/50 z-40 md:hidden",onClick:()=>l(!1)}),e.jsx("aside",{className:`
fixed md:relative
inset-y-0 left-0
w-64
transform transition-transform duration-300 ease-in-out
${i?"translate-x-0":"-translate-x-full"}
md:translate-x-0
${i?"md:w-64":"md:w-0"}
z-50 md:z-auto
flex-shrink-0
border-r border-gray-800 bg-black
flex flex-col
overflow-hidden
`,children:e.jsxs("div",{className:`w-64 h-full flex flex-col overflow-hidden ${i?"":"md:hidden"}`,children:[e.jsx("div",{className:"p-4 border-b border-gray-800 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Bi,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(C=>!C.adminOnly||(f==null?void 0:f.role)==="ADMIN").map(C=>e.jsxs("button",{onClick:()=>{C.id==="admin/templates"?a==null||a("admin/templates"):a==null||a(C.id),window.innerWidth<768&&l(!1)},className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${s===C.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(C.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:C.label})]},C.id))}),!y&&e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(I,{onClick:r,className:"w-full bg-re-green hover:bg-re-green/90 text-white text-sm font-medium",size:"sm",children:[e.jsx(us,{className:"w-4 h-4 mr-2"}),"Raise New Request"]})})]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("header",{className:"h-16 border-b border-gray-200 bg-white flex items-center justify-between px-6 shrink-0",children:[e.jsx("div",{className:"flex items-center gap-4 min-w-0 flex-1",children:e.jsx(I,{variant:"ghost",size:"icon",onClick:A,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(o0,{className:"w-5 h-5 text-gray-600"}):e.jsx(c0,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[!y&&e.jsxs(I,{onClick:r,className:"bg-re-green hover:bg-re-green/90 text-white gap-2 hidden md:flex text-sm",size:"sm",children:[e.jsx(us,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(sm,{open:x,onOpenChange:g,children:[e.jsx(am,{asChild:!0,children:e.jsxs(I,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(Ds,{className:"w-5 h-5"}),u>0&&e.jsx(ie,{className:"absolute -top-1 -right-1 w-5 h-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center p-0",children:u>9?"9+":u})]})}),e.jsxs(rm,{align:"end",className:"w-96 max-h-[500px]",children:[e.jsxs("div",{className:"p-3 border-b flex items-center justify-between sticky top-0 bg-white z-10",children:[e.jsx("h4",{className:"font-semibold text-base",children:"Notifications"}),u>0&&e.jsx(I,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:C=>{C.stopPropagation(),T()},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(Ds,{className:"w-12 h-12 text-gray-300 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No notifications yet"})]}):e.jsx("div",{className:"divide-y",children:d.map(C=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${C.isRead?"":"bg-blue-50"}`,onClick:()=>w(C),children:e.jsxs("div",{className:"flex gap-2",children:[!C.isRead&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-600 mt-1.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm ${C.isRead?"font-medium":"font-semibold"}`,children:C.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:C.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:rx(new Date(C.createdAt),{addSuffix:!0})})]})]})},C.notificationId))})}),d.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(I,{variant:"ghost",className:"w-full text-sm text-blue-600 hover:text-blue-700",onClick:()=>{g(!1),a==null||a("notifications")},children:"View all notifications"})})]})]}),e.jsxs(sm,{children:[e.jsx(am,{asChild:!0,children:e.jsxs(es,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Vi,{src:(f==null?void 0:f.picture)||""}),e.jsx(ts,{className:"bg-re-green text-white text-sm",children:b()})]})}),e.jsxs(rm,{align:"end",children:[e.jsxs(cl,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(Lt,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(cl,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(Ga,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(cl,{onClick:()=>c(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(sl,{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(Ox,{open:o,onOpenChange:c,children:e.jsxs(Io,{children:[e.jsxs(Ux,{children:[e.jsxs(Vx,{className:"flex items-center gap-2",children:[e.jsx(sl,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(zx,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(Bx,{children:[e.jsx(Wx,{onClick:()=>c(!1),children:"Cancel"}),e.jsxs(Hx,{onClick:async()=>{if(c(!1),n)try{await n()}catch(C){console.error("🔴 Error calling onLogout:",C)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(sl,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const Dn=()=>py(),Yr=yy,bb=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},vb={viewAsUser:bb()},Yx=Gr({name:"dashboard",initialState:vb,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:jb}=Yx.actions;function Nb(){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(u=>{const h=u;s(h),h!=="custom"?(r(void 0),i(void 0),o(!1)):o(!0)},[]),d=p.useCallback(u=>{if(a&&n){if(a>n){const h=a;r(n),i(h),u(n,h)}else u(a,n);o(!1)}},[a,n]),m=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 wb(){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((y,b,v)=>{s({page:y,totalPages:b,totalRecords:v})},[]),d=p.useCallback((y,b,v)=>{r({page:y,totalPages:b,totalRecords:v})},[]),m=p.useCallback((y,b,v)=>{i({page:y,totalPages:b,totalRecords:v})},[]),u=p.useCallback((y,b,v)=>{o({page:y,totalPages:b,totalRecords:v})},[]),h=p.useCallback((y,b)=>{y>=1&&y<=t.totalPages&&(s(v=>({...v,page:y})),b(y))},[t.totalPages]),x=p.useCallback((y,b)=>{y>=1&&y<=a.totalPages&&(r(v=>({...v,page:y})),b(y))},[a.totalPages]),g=p.useCallback((y,b)=>{y>=1&&y<=n.totalPages&&(i(v=>({...v,page:y})),b(y))},[n.totalPages]),f=p.useCallback((y,b)=>{y>=1&&y<=l.totalPages&&(o(v=>({...v,page:y})),b(y))},[l.totalPages]);return{activity:t,critical:a,deadlines:n,approver:l,updateActivityPagination:c,updateCriticalPagination:d,updateDeadlinesPagination:m,updateApproverPagination:u,handleActivityPageChange:h,handleCriticalPageChange:x,handleDeadlinesPageChange:g,handleApproverPageChange:f}}class Cb{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,u,h,x){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),u&&(g.search=u),h&&h!=="all"&&(g.slaCompliance=h),x&&(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 u=await je.get("/dashboard/reports/activity-log",{params:m});return{activities:u.data.data,pagination:u.data.pagination}}catch(m){throw console.error("Failed to fetch activity log report:",m),m}}async getDepartments(){try{return(await 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 u={approverId:s,page:a,limit:r};n&&(u.dateRange=n),n==="custom"&&i&&l&&(u.startDate=i.toISOString(),u.endDate=l.toISOString()),o&&(u.status=o),c&&(u.priority=c),d&&(u.slaCompliance=d),m&&(u.search=m);const h=await je.get("/dashboard/requests/by-approver",{params:u});return{requests:h.data.data,pagination:h.data.pagination}}catch(u){throw console.error("Failed to fetch requests by approver:",u),u}}}const St=new Cb;function Ab({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([]),[u,h]=p.useState([]),[x,g]=p.useState([]),[f,y]=p.useState([]),[b,v]=p.useState([]),[A,w]=p.useState(null),[T,C]=p.useState([]),[_,D]=p.useState(!0),[S,j]=p.useState(!1),P=p.useRef(l);P.current=l;const R=p.useCallback(async(k=!1)=>{try{k?j(!0):D(!0);const N=[St.getKPIs(r,n,i,s),St.getRecentActivity(1,10,s),St.getCriticalRequests(1,10,s),St.getUpcomingDeadlines(1,10,s)],U=!t&&a?St.getRequestStats(r,n==null?void 0:n.toISOString(),i==null?void 0:i.toISOString(),void 0,void 0,void 0,void 0,a,void 0,void 0,void 0,void 0,s):null,$=t?[St.getDepartmentStats(r,n,i),St.getPriorityDistribution(r,n,i),St.getAIRemarkUtilization(r,n,i),St.getApproverPerformance(r,1,10,n,i)]:[],[L,se,G]=await Promise.all([Promise.all(N),U,Promise.all($)]),oe=L[0],Z=L[1],E=L[2],V=L[3];if(!t&&se&&(oe.requestVolume=se),c(oe),m(Z.activities),P.current.activity(Z.pagination.currentPage,Z.pagination.totalPages,Z.pagination.totalRecords),h(E.criticalRequests),P.current.critical(E.pagination.currentPage,E.pagination.totalPages,E.pagination.totalRecords),v(V.deadlines),P.current.deadlines(V.pagination.currentPage,V.pagination.totalPages,V.pagination.totalRecords),t&&G.length>=4){const H=G[0],Q=G[1],Y=G[2],W=G[3];g(H),y(Q),w(Y),C(W.performance),P.current.approver(W.pagination.currentPage,W.pagination.totalPages,W.pagination.totalRecords)}else t||(g([]),y([]),w(null),C([]))}catch(N){console.error("Failed to fetch dashboard data:",N)}finally{D(!1),j(!1)}},[t,s,a,r,n,i]),O=p.useCallback(async(k=1)=>{try{const N=await St.getRecentActivity(k,10,s);m(N.activities),P.current.activity(N.pagination.currentPage,N.pagination.totalPages,N.pagination.totalRecords)}catch(N){console.error("Failed to fetch recent activities:",N)}},[s]),F=p.useCallback(async(k=1)=>{try{const N=await St.getCriticalRequests(k,10,s);h(N.criticalRequests),P.current.critical(N.pagination.currentPage,N.pagination.totalPages,N.pagination.totalRecords)}catch(N){console.error("Failed to fetch critical requests:",N)}},[s]),M=p.useCallback(async(k=1)=>{try{const N=await St.getUpcomingDeadlines(k,10,s);v(N.deadlines),P.current.deadlines(N.pagination.currentPage,N.pagination.totalPages,N.pagination.totalRecords)}catch(N){console.error("Failed to fetch upcoming deadlines:",N)}},[s]),B=p.useCallback(async(k=1)=>{try{const N=await St.getApproverPerformance(r,k,10,n,i);C(N.performance),P.current.approver(N.pagination.currentPage,N.pagination.totalPages,N.pagination.totalRecords)}catch(N){console.error("Failed to fetch approver performance:",N)}},[r,n,i]);return{kpis:o,recentActivity:d,criticalRequests:u,departmentStats:x,priorityDistribution:f,upcomingDeadlines:b,aiRemarkUtilization:A,approverPerformance:T,loading:_,refreshing:S,fetchDashboardData:R,fetchRecentActivities:O,fetchCriticalRequests:F,fetchUpcomingDeadlines:M,fetchApproverPerformance:B}}const Ra={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 Sb{constructor(){Ji(this,"config",null);Ji(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{...Ra,...r,workingHours:{...Ra.workingHours,...r.workingHours},tat:{...Ra.tat,...r.tat},upload:{...Ra.upload,...r.upload},workflow:{...Ra.workflow,...r.workflow},workNotes:{...Ra.workNotes,...r.workNotes},features:{...Ra.features,...r.features},ui:{...Ra.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),Ra}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const Tb=new Sb;let kb=9,Rb=18,Db=1,Pb=5,nm=!1;async function Ib(){if(!nm)try{const t=await Tb.getConfig();kb=t.workingHours.START_HOUR,Rb=t.workingHours.END_HOUR,Db=t.workingHours.START_DAY,Pb=t.workingHours.END_DAY,nm=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}Ib().catch(()=>{});function Ot(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 Eb(t,s,a){const r=[];let n=1,i=!0;const l=100;for(;i&&n<=l;){const h=await St.getApproverPerformance(t,n,100,s,a);h.performance&&h.performance.length>0?(r.push(...h.performance),n++,i=n<=h.pagination.totalPages):i=!1}const o=[["Approver Name","Total Approved","TAT Compliance (%)","Avg Response Time","Pending Count"].join(",")];r.forEach(h=>{const x=[`"${(h.approverName||"Unknown").replace(/"/g,'""')}"`,h.totalApproved||0,h.tatCompliancePercent||0,Ot(h.avgResponseHours),h.pendingCount||0];o.push(x.join(","))});const c=o.join(`
`),d=new Blob([c],{type:"text/csv;charset=utf-8;"}),m=document.createElement("a"),u=URL.createObjectURL(d);m.setAttribute("href",u),m.setAttribute("download",`approver-performance-report-${new Date().toISOString().split("T")[0]}.csv`),m.style.visibility="hidden",document.body.appendChild(m),m.click(),document.body.removeChild(m),URL.revokeObjectURL(u)}async function Fb(t,s,a){const r=await St.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 Mb(){const[t,s]=p.useState(!1),[a,r]=p.useState(!1),n=p.useCallback(async(l,o,c)=>{try{s(!0),await Fb(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 Eb(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 Fs({className:t,...s}){return e.jsx(qg,{"data-slot":"switch",className:Re("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-switch-background focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(ef,{"data-slot":"switch-thumb",className:Re("bg-card dark:data-[state=unchecked]:bg-card-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}function ne({className:t,...s}){return e.jsx(tf,{"data-slot":"label",className:Re("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",t),...s})}function _b({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(J,{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(q,{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(No,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(ne,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-gray-300":"text-red-600"}`,children:"Org"})]}),e.jsx(Fs,{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(Lt,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(ne,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-red-600":"text-gray-300"}`,children:"Personal"})]})]})}),e.jsx("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 sm:gap-6",children:e.jsxs("div",{className:`text-white w-full lg:w-auto ${t?"pt-12 sm:pt-0":""}`,children:[e.jsx("div",{className:"flex items-center gap-3 sm:gap-4 mb-4 sm:mb-6",children:e.jsxs("div",{className:"pr-2 sm:pr-0",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl lg:text-4xl font-bold mb-1 sm:mb-2 text-white","data-testid":"hero-title",children:["Welcome, ",o,"!"]}),e.jsx("p",{className:"text-sm sm:text-lg lg:text-xl text-gray-200","data-testid":"hero-subtitle",children:s?"Organization-wide analytics and insights":"Track your requests and approvals"})]})}),e.jsx("div",{className:"flex flex-wrap gap-2 sm:gap-4 mt-4 sm:mt-8","data-testid":"quick-actions",children:n.map((c,d)=>e.jsxs(I,{onClick:c.action,className:`${c.color} text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200`,size:window.innerWidth<640?"sm":"lg","data-testid":`quick-action-${c.label.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsx(c.icon,{className:"w-4 h-4 sm:w-5 sm:h-5 mr-1 sm:mr-2"}),c.label]},d))})]})})]})]})}function He({...t}){return e.jsx(sf,{"data-slot":"select",...t})}function We({...t}){return e.jsx(nf,{"data-slot":"select-value",...t})}function Ge({className:t,size:s="default",children:a,...r}){return e.jsxs(af,{"data-slot":"select-trigger","data-size":s,className:Re("border-gray-400 data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground bg-white text-gray-900 flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap transition-all outline-none disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4","hover:border-gray-500","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...r,children:[a,e.jsx(rf,{asChild:!0,children:e.jsx(wo,{className:"size-4 opacity-50"})})]})}function Ke({className:t,children:s,position:a="popper",...r}){return e.jsx(lf,{children:e.jsxs(of,{"data-slot":"select-content",className:Re("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",a==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:a,...r,children:[e.jsx(Lb,{}),e.jsx(cf,{className:Re("p-1",a==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:s}),e.jsx(Ob,{})]})})}function X({className:t,children:s,...a}){return e.jsxs(df,{"data-slot":"select-item",className:Re("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...a,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(mf,{children:e.jsx(Nr,{className:"size-4"})})}),e.jsx(uf,{children:s})]})}function Lb({className:t,...s}){return e.jsx(xf,{"data-slot":"select-scroll-up-button",className:Re("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(dx,{className:"size-4"})})}function Ob({className:t,...s}){return e.jsx(hf,{"data-slot":"select-scroll-down-button",className:Re("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(wo,{className:"size-4"})})}function $t({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(pf,{"data-slot":"separator-root",decorative:a,orientation:s,className:Re("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",t),...r})}function Zs({...t}){return e.jsx(gf,{"data-slot":"popover",...t})}function Xs({...t}){return e.jsx(ff,{"data-slot":"popover-trigger",...t})}function Qs({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(yf,{children:e.jsx(bf,{"data-slot":"popover-content",align:s,sideOffset:a,className:Re("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",t),...r})})}var et=function(){return et=Object.assign||function(s){for(var a,r=1,n=arguments.length;r<n;r++){a=arguments[r];for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(s[i]=a[i])}return s},et.apply(this,arguments)};function $b(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 Zx(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 Pn(t){return t.mode==="multiple"}function In(t){return t.mode==="range"}function zi(t){return t.mode==="single"}var Ub={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 Bb(t,s){return Ye(t,"LLLL y",s)}function Vb(t,s){return Ye(t,"d",s)}function zb(t,s){return Ye(t,"LLLL",s)}function Hb(t){return"".concat(t)}function Wb(t,s){return Ye(t,"cccccc",s)}function Gb(t,s){return Ye(t,"yyyy",s)}var Kb=Object.freeze({__proto__:null,formatCaption:Bb,formatDay:Vb,formatMonthCaption:zb,formatWeekNumber:Hb,formatWeekdayName:Wb,formatYearCaption:Gb}),Yb=function(t,s,a){return Ye(t,"do MMMM (EEEE)",a)},Zb=function(){return"Month: "},Xb=function(){return"Go to next month"},Qb=function(){return"Go to previous month"},Jb=function(t,s){return Ye(t,"cccc",s)},qb=function(t){return"Week n. ".concat(t)},ev=function(){return"Year: "},tv=Object.freeze({__proto__:null,labelDay:Yb,labelMonthDropdown:Zb,labelNext:Xb,labelPrevious:Qb,labelWeekNumber:qb,labelWeekday:Jb,labelYearDropdown:ev});function sv(){var t="buttons",s=Ub,a=Kf,r={},n={},i=1,l={},o=new Date;return{captionLayout:t,classNames:s,formatters:Kb,labels:tv,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:l,today:o,mode:"default"}}function av(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,l=t.toDate;return r?i=Ks(r):s&&(i=new Date(s,0,1)),n?l=yo(n):a&&(l=new Date(a,11,31)),{fromDate:i?$d(i):void 0,toDate:l?$d(l):void 0}}var Xx=p.createContext(void 0);function rv(t){var s,a=t.initialProps,r=sv(),n=av(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;(zi(a)||Pn(a)||In(a))&&(c=a.onSelect);var d=et(et(et({},r),a),{captionLayout:o,classNames:et(et({},r.classNames),a.classNames),components:et({},a.components),formatters:et(et({},r.formatters),a.formatters),fromDate:i,labels:et(et({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:et(et({},r.modifiers),a.modifiers),modifiersClassNames:et(et({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:et(et({},r.styles),a.styles),toDate:l});return e.jsx(Xx.Provider,{value:d,children:t.children})}function It(){var t=p.useContext(Xx);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function Qx(t){var s=It(),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 nv(t){return e.jsx("svg",et({width:"8px",height:"8px",viewBox:"0 0 120 120","data-testid":"iconDropdown"},t,{children:e.jsx("path",{d:"M4.22182541,48.2218254 C8.44222828,44.0014225 15.2388494,43.9273804 19.5496459,47.9996989 L19.7781746,48.2218254 L60,88.443 L100.221825,48.2218254 C104.442228,44.0014225 111.238849,43.9273804 115.549646,47.9996989 L115.778175,48.2218254 C119.998577,52.4422283 120.07262,59.2388494 116.000301,63.5496459 L115.778175,63.7781746 L67.7781746,111.778175 C63.5577717,115.998577 56.7611506,116.07262 52.4503541,112.000301 L52.2218254,111.778175 L4.22182541,63.7781746 C-0.0739418023,59.4824074 -0.0739418023,52.5175926 4.22182541,48.2218254 Z",fill:"currentColor",fillRule:"nonzero"})}))}function Jx(t){var s,a,r=t.onChange,n=t.value,i=t.children,l=t.caption,o=t.className,c=t.style,d=It(),m=(a=(s=d.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:nv;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 iv(t){var s,a=It(),r=a.fromDate,n=a.toDate,i=a.styles,l=a.locale,o=a.formatters.formatMonthCaption,c=a.classNames,d=a.components,m=a.labels.labelMonthDropdown;if(!r)return e.jsx(e.Fragment,{});if(!n)return e.jsx(e.Fragment,{});var u=[];if(qf(r,n))for(var h=Ks(r),x=r.getMonth();x<=n.getMonth();x++)u.push(el(h,x));else for(var h=Ks(new Date),x=0;x<=11;x++)u.push(el(h,x));var g=function(y){var b=Number(y.target.value),v=el(Ks(t.displayMonth),b);t.onChange(v)},f=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Jx;return e.jsx(f,{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:u.map(function(y){return e.jsx("option",{value:y.getMonth(),children:o(y,{locale:l})},y.getMonth())})})}function lv(t){var s,a=t.displayMonth,r=It(),n=r.fromDate,i=r.toDate,l=r.locale,o=r.styles,c=r.classNames,d=r.components,m=r.formatters.formatYearCaption,u=r.labels.labelYearDropdown,h=[];if(!n)return e.jsx(e.Fragment,{});if(!i)return e.jsx(e.Fragment,{});for(var x=n.getFullYear(),g=i.getFullYear(),f=x;f<=g;f++)h.push(Ud(e0(new Date),f));var y=function(v){var A=Ud(Ks(a),Number(v.target.value));t.onChange(A)},b=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Jx;return e.jsx(b,{name:"years","aria-label":u(),className:c.dropdown_year,style:o.dropdown_year,onChange:y,value:a.getFullYear(),caption:m(a,{locale:l}),children:h.map(function(v){return e.jsx("option",{value:v.getFullYear(),children:m(v,{locale:l})},v.getFullYear())})})}function ov(t,s){var a=p.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function cv(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&&bn(i,n)<0){var d=-1*(c-1);n=Ca(i,d)}return l&&bn(n,l)<0&&(n=l),Ks(n)}function dv(){var t=It(),s=cv(t),a=ov(s,t.month),r=a[0],n=a[1],i=function(l){var o;if(!t.disableNavigation){var c=Ks(l);n(c),(o=t.onMonthChange)===null||o===void 0||o.call(t,c)}};return[r,i]}function mv(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=Ks(t),i=Ks(Ca(n,r)),l=bn(i,n),o=[],c=0;c<l;c++){var d=Ca(n,c);o.push(d)}return a&&(o=o.reverse()),o}function uv(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=Ks(t);if(!a)return Ca(o,l);var c=bn(a,t);if(!(c<i))return Ca(o,l)}}function xv(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=Ks(t);if(!a)return Ca(o,-l);var c=bn(o,a);if(!(c<=0))return Ca(o,-l)}}var qx=p.createContext(void 0);function hv(t){var s=It(),a=dv(),r=a[0],n=a[1],i=mv(r,s),l=uv(r,s),o=xv(r,s),c=function(u){return i.some(function(h){return bo(u,h)})},d=function(u,h){c(u)||(h&&nx(u,h)?n(Ca(u,1+s.numberOfMonths*-1)):n(u))},m={currentMonth:r,displayMonths:i,goToMonth:n,goToDate:d,previousMonth:o,nextMonth:l,isDateDisplayed:c};return e.jsx(qx.Provider,{value:m,children:t.children})}function En(){var t=p.useContext(qx);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function im(t){var s,a=It(),r=a.classNames,n=a.styles,i=a.components,l=En().goToMonth,o=function(m){l(Ca(m,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:Qx,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(iv,{onChange:o,displayMonth:t.displayMonth}),e.jsx(lv,{onChange:o,displayMonth:t.displayMonth})]})}function pv(t){return e.jsx("svg",et({width:"16px",height:"16px",viewBox:"0 0 120 120"},t,{children:e.jsx("path",{d:"M69.490332,3.34314575 C72.6145263,0.218951416 77.6798462,0.218951416 80.8040405,3.34314575 C83.8617626,6.40086786 83.9268205,11.3179931 80.9992143,14.4548388 L80.8040405,14.6568542 L35.461,60 L80.8040405,105.343146 C83.8617626,108.400868 83.9268205,113.317993 80.9992143,116.454839 L80.8040405,116.656854 C77.7463184,119.714576 72.8291931,119.779634 69.6923475,116.852028 L69.490332,116.656854 L18.490332,65.6568542 C15.4326099,62.5991321 15.367552,57.6820069 18.2951583,54.5451612 L18.490332,54.3431458 L69.490332,3.34314575 Z",fill:"currentColor",fillRule:"nonzero"})}))}function gv(t){return e.jsx("svg",et({width:"16px",height:"16px",viewBox:"0 0 120 120"},t,{children:e.jsx("path",{d:"M49.8040405,3.34314575 C46.6798462,0.218951416 41.6145263,0.218951416 38.490332,3.34314575 C35.4326099,6.40086786 35.367552,11.3179931 38.2951583,14.4548388 L38.490332,14.6568542 L83.8333725,60 L38.490332,105.343146 C35.4326099,108.400868 35.367552,113.317993 38.2951583,116.454839 L38.490332,116.656854 C41.5480541,119.714576 46.4651794,119.779634 49.602025,116.852028 L49.8040405,116.656854 L100.804041,65.6568542 C103.861763,62.5991321 103.926821,57.6820069 100.999214,54.5451612 L100.804041,54.3431458 L49.8040405,3.34314575 Z",fill:"currentColor"})}))}var fi=p.forwardRef(function(t,s){var a=It(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var l=i.join(" "),o=et(et({},n.button_reset),n.button);return t.style&&Object.assign(o,t.style),e.jsx("button",et({},t,{ref:s,type:"button",className:l,style:o}))});function fv(t){var s,a,r=It(),n=r.dir,i=r.locale,l=r.classNames,o=r.styles,c=r.labels,d=c.labelPrevious,m=c.labelNext,u=r.components;if(!t.nextMonth&&!t.previousMonth)return e.jsx(e.Fragment,{});var h=d(t.previousMonth,{locale:i}),x=[l.nav_button,l.nav_button_previous].join(" "),g=m(t.nextMonth,{locale:i}),f=[l.nav_button,l.nav_button_next].join(" "),y=(s=u==null?void 0:u.IconRight)!==null&&s!==void 0?s:gv,b=(a=u==null?void 0:u.IconLeft)!==null&&a!==void 0?a:pv;return e.jsxs("div",{className:l.nav,style:o.nav,children:[!t.hidePrevious&&e.jsx(fi,{name:"previous-month","aria-label":h,className:x,style:o.nav_button_previous,disabled:!t.previousMonth,onClick:t.onPreviousClick,children:n==="rtl"?e.jsx(y,{className:l.nav_icon,style:o.nav_icon}):e.jsx(b,{className:l.nav_icon,style:o.nav_icon})}),!t.hideNext&&e.jsx(fi,{name:"next-month","aria-label":g,className:f,style:o.nav_button_next,disabled:!t.nextMonth,onClick:t.onNextClick,children:n==="rtl"?e.jsx(b,{className:l.nav_icon,style:o.nav_icon}):e.jsx(y,{className:l.nav_icon,style:o.nav_icon})})]})}function lm(t){var s=It().numberOfMonths,a=En(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,l=a.displayMonths,o=l.findIndex(function(g){return bo(t.displayMonth,g)}),c=o===0,d=o===l.length-1,m=s>1&&(c||!d),u=s>1&&(d||!c),h=function(){r&&i(r)},x=function(){n&&i(n)};return e.jsx(fv,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:u,nextMonth:n,previousMonth:r,onPreviousClick:h,onNextClick:x})}function yv(t){var s,a=It(),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:Qx,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):l==="dropdown"?d=e.jsx(im,{displayMonth:t.displayMonth,id:t.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(im,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(lm,{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(lm,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function bv(t){var s=It(),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 vv(t,s,a){for(var r=a?vo(new Date):jo(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var l=Hs(r,i);n.push(l)}return n}function jv(){var t=It(),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=vv(n,i,l);return e.jsxs("tr",{style:a.head_row,className:s.head_row,children:[r&&e.jsx("td",{style:a.head_cell,className:s.head_cell}),d.map(function(m,u){return e.jsx("th",{scope:"col",className:s.head_cell,style:a.head_cell,"aria-label":c(m,{locale:n}),children:o(m,{locale:n})},u)})]})}function Nv(){var t,s=It(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:jv;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function wv(t){var s=It(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var Eo=p.createContext(void 0);function Cv(t){if(!Pn(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(Eo.Provider,{value:s,children:t.children})}return e.jsx(Av,{initialProps:t.initialProps,children:t.children})}function Av(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,l=function(d,m,u){var h,x;(h=s.onDayClick)===null||h===void 0||h.call(s,d,m,u);var g=!!(m.selected&&n&&(r==null?void 0:r.length)===n);if(!g){var f=!!(!m.selected&&i&&(r==null?void 0:r.length)===i);if(!f){var y=r?Zx([],r):[];if(m.selected){var b=y.findIndex(function(v){return Us(d,v)});y.splice(b,1)}else y.push(d);(x=s.onSelect)===null||x===void 0||x.call(s,y,d,m,u)}}},o={disabled:[]};r&&o.disabled.push(function(d){var m=i&&r.length>i-1,u=r.some(function(h){return Us(h,d)});return!!(m&&!u)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(Eo.Provider,{value:c,children:a})}function Fo(){var t=p.useContext(Eo);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function Sv(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?Us(n,t)&&Us(r,t)?void 0:Us(n,t)?{from:n,to:void 0}:Us(r,t)?void 0:Vl(r,t)?{from:t,to:n}:{from:r,to:t}:n?Vl(t,n)?{from:n,to:t}:{from:t,to:n}:r?nx(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var Mo=p.createContext(void 0);function Tv(t){if(!In(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(Mo.Provider,{value:s,children:t.children})}return e.jsx(kv,{initialProps:t.initialProps,children:t.children})}function kv(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(x,g,f){var y,b;(y=s.onDayClick)===null||y===void 0||y.call(s,x,g,f);var v=Sv(x,r);(b=s.onSelect)===null||b===void 0||b.call(s,v,x,g,f)},m={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(m.range_start=[i],l?(m.range_end=[l],Us(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:qi(i,o-1),before:Hs(i,o-1)}),i&&l&&m.disabled.push({after:i,before:Hs(i,o-1)}),!i&&l&&m.disabled.push({after:qi(l,o-1),before:Hs(l,o-1)})),c){if(i&&!l&&(m.disabled.push({before:Hs(i,-c+1)}),m.disabled.push({after:Hs(i,c-1)})),i&&l){var u=Pa(l,i)+1,h=c-u;m.disabled.push({before:qi(i,h)}),m.disabled.push({after:Hs(l,h)})}!i&&l&&(m.disabled.push({before:Hs(l,-c+1)}),m.disabled.push({after:Hs(l,c-1)}))}return e.jsx(Mo.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function _o(){var t=p.useContext(Mo);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function ei(t){return Array.isArray(t)?Zx([],t):t!==void 0?[t]:[]}function Rv(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=ei(n)}),s}var ha;(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"})(ha||(ha={}));var Dv=ha.Selected,Da=ha.Disabled,Pv=ha.Hidden,Iv=ha.Today,dl=ha.RangeEnd,ml=ha.RangeMiddle,ul=ha.RangeStart,Ev=ha.Outside;function Fv(t,s,a){var r,n=(r={},r[Dv]=ei(t.selected),r[Da]=ei(t.disabled),r[Pv]=ei(t.hidden),r[Iv]=[t.today],r[dl]=[],r[ml]=[],r[ul]=[],r[Ev]=[],r);return t.fromDate&&n[Da].push({before:t.fromDate}),t.toDate&&n[Da].push({after:t.toDate}),Pn(t)?n[Da]=n[Da].concat(s.modifiers[Da]):In(t)&&(n[Da]=n[Da].concat(a.modifiers[Da]),n[ul]=a.modifiers[ul],n[ml]=a.modifiers[ml],n[dl]=a.modifiers[dl]),n}var eh=p.createContext(void 0);function Mv(t){var s=It(),a=Fo(),r=_o(),n=Fv(s,a,r),i=Rv(s.modifiers),l=et(et({},n),i);return e.jsx(eh.Provider,{value:l,children:t.children})}function th(){var t=p.useContext(eh);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function _v(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function Lv(t){return!!(t&&typeof t=="object"&&"from"in t)}function Ov(t){return!!(t&&typeof t=="object"&&"after"in t)}function $v(t){return!!(t&&typeof t=="object"&&"before"in t)}function Uv(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function Bv(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=Pa(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var l=Pa(t,r)>=0&&Pa(n,t)>=0;return l}return n?Us(n,t):r?Us(r,t):!1}function Vv(t){return ox(t)}function zv(t){return Array.isArray(t)&&t.every(ox)}function Hv(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(Vv(a))return Us(t,a);if(zv(a))return a.includes(t);if(Lv(a))return Bv(t,a);if(Uv(a))return a.dayOfWeek.includes(t.getDay());if(_v(a)){var r=Pa(a.before,t),n=Pa(a.after,t),i=r>0,l=n<0,o=Vl(a.before,a.after);return o?l&&i:i||l}return Ov(a)?Pa(t,a.after)>0:$v(a)?Pa(a.before,t)>0:typeof a=="function"?a(t):!1})}function Lo(t,s,a){var r=Object.keys(s).reduce(function(i,l){var o=s[l];return Hv(t,o)&&i.push(l),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!bo(t,a)&&(n.outside=!0),n}function Wv(t,s){for(var a=Ks(t[0]),r=yo(t[t.length-1]),n,i,l=a;l<=r;){var o=Lo(l,s),c=!o.disabled&&!o.hidden;if(!c){l=Hs(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),n||(n=l),l=Hs(l,1)}return i||n}var Gv=365;function sh(t,s){var a=s.moveBy,r=s.direction,n=s.context,i=s.modifiers,l=s.retry,o=l===void 0?{count:0,lastFocused:t}:l,c=n.weekStartsOn,d=n.fromDate,m=n.toDate,u=n.locale,h={day:Hs,week:Bl,month:Ca,year:Xf,startOfWeek:function(y){return n.ISOWeek?vo(y):jo(y,{locale:u,weekStartsOn:c})},endOfWeek:function(y){return n.ISOWeek?ix(y):lx(y,{locale:u,weekStartsOn:c})}},x=h[a](t,r==="after"?1:-1);r==="before"&&d?x=Qf([d,x]):r==="after"&&m&&(x=Jf([m,x]));var g=!0;if(i){var f=Lo(x,i);g=!f.disabled&&!f.hidden}return g?x:o.count>Gv?o.lastFocused:sh(x,{moveBy:a,direction:r,context:n,modifiers:i,retry:et(et({},o),{count:o.count+1})})}var ah=p.createContext(void 0);function Kv(t){var s=En(),a=th(),r=p.useState(),n=r[0],i=r[1],l=p.useState(),o=l[0],c=l[1],d=Wv(s.displayMonths,a),m=n??(o&&s.isDateDisplayed(o))?o:d,u=function(){c(n),i(void 0)},h=function(y){i(y)},x=It(),g=function(y,b){if(n){var v=sh(n,{moveBy:y,direction:b,context:x,modifiers:a});Us(n,v)||(s.goToDate(v,n),h(v))}},f={focusedDay:n,focusTarget:m,blur:u,focus:h,focusDayAfter:function(){return g("day","after")},focusDayBefore:function(){return g("day","before")},focusWeekAfter:function(){return g("week","after")},focusWeekBefore:function(){return g("week","before")},focusMonthBefore:function(){return g("month","before")},focusMonthAfter:function(){return g("month","after")},focusYearBefore:function(){return g("year","before")},focusYearAfter:function(){return g("year","after")},focusStartOfWeek:function(){return g("startOfWeek","before")},focusEndOfWeek:function(){return g("endOfWeek","after")}};return e.jsx(ah.Provider,{value:f,children:t.children})}function Oo(){var t=p.useContext(ah);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function Yv(t,s){var a=th(),r=Lo(t,a,s);return r}var $o=p.createContext(void 0);function Zv(t){if(!zi(t.initialProps)){var s={selected:void 0};return e.jsx($o.Provider,{value:s,children:t.children})}return e.jsx(Xv,{initialProps:t.initialProps,children:t.children})}function Xv(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($o.Provider,{value:n,children:a})}function rh(){var t=p.useContext($o);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function Qv(t,s){var a=It(),r=rh(),n=Fo(),i=_o(),l=Oo(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,m=l.focusWeekBefore,u=l.blur,h=l.focus,x=l.focusMonthBefore,g=l.focusMonthAfter,f=l.focusYearBefore,y=l.focusYearAfter,b=l.focusStartOfWeek,v=l.focusEndOfWeek,A=function(k){var N,U,$,L;zi(a)?(N=r.onDayClick)===null||N===void 0||N.call(r,t,s,k):Pn(a)?(U=n.onDayClick)===null||U===void 0||U.call(n,t,s,k):In(a)?($=i.onDayClick)===null||$===void 0||$.call(i,t,s,k):(L=a.onDayClick)===null||L===void 0||L.call(a,t,s,k)},w=function(k){var N;h(t),(N=a.onDayFocus)===null||N===void 0||N.call(a,t,s,k)},T=function(k){var N;u(),(N=a.onDayBlur)===null||N===void 0||N.call(a,t,s,k)},C=function(k){var N;(N=a.onDayMouseEnter)===null||N===void 0||N.call(a,t,s,k)},_=function(k){var N;(N=a.onDayMouseLeave)===null||N===void 0||N.call(a,t,s,k)},D=function(k){var N;(N=a.onDayPointerEnter)===null||N===void 0||N.call(a,t,s,k)},S=function(k){var N;(N=a.onDayPointerLeave)===null||N===void 0||N.call(a,t,s,k)},j=function(k){var N;(N=a.onDayTouchCancel)===null||N===void 0||N.call(a,t,s,k)},P=function(k){var N;(N=a.onDayTouchEnd)===null||N===void 0||N.call(a,t,s,k)},R=function(k){var N;(N=a.onDayTouchMove)===null||N===void 0||N.call(a,t,s,k)},O=function(k){var N;(N=a.onDayTouchStart)===null||N===void 0||N.call(a,t,s,k)},F=function(k){var N;(N=a.onDayKeyUp)===null||N===void 0||N.call(a,t,s,k)},M=function(k){var N;switch(k.key){case"ArrowLeft":k.preventDefault(),k.stopPropagation(),a.dir==="rtl"?o():c();break;case"ArrowRight":k.preventDefault(),k.stopPropagation(),a.dir==="rtl"?c():o();break;case"ArrowDown":k.preventDefault(),k.stopPropagation(),d();break;case"ArrowUp":k.preventDefault(),k.stopPropagation(),m();break;case"PageUp":k.preventDefault(),k.stopPropagation(),k.shiftKey?f():x();break;case"PageDown":k.preventDefault(),k.stopPropagation(),k.shiftKey?y():g();break;case"Home":k.preventDefault(),k.stopPropagation(),b();break;case"End":k.preventDefault(),k.stopPropagation(),v();break}(N=a.onDayKeyDown)===null||N===void 0||N.call(a,t,s,k)},B={onClick:A,onFocus:w,onBlur:T,onKeyDown:M,onKeyUp:F,onMouseEnter:C,onMouseLeave:_,onPointerEnter:D,onPointerLeave:S,onTouchCancel:j,onTouchEnd:P,onTouchMove:R,onTouchStart:O};return B}function Jv(){var t=It(),s=rh(),a=Fo(),r=_o(),n=zi(t)?s.selected:Pn(t)?a.selected:In(t)?r.selected:void 0;return n}function qv(t){return Object.values(ha).includes(t)}function ej(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(qv(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function tj(t,s){var a=et({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=et(et({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function sj(t,s,a){var r,n,i,l=It(),o=Oo(),c=Yv(t,s),d=Qv(t,c),m=Jv(),u=!!(l.onDayClick||l.mode!=="default");p.useEffect(function(){var C;c.outside||o.focusedDay&&u&&Us(o.focusedDay,t)&&((C=a.current)===null||C===void 0||C.focus())},[o.focusedDay,t,a,u,c.outside]);var h=ej(l,c).join(" "),x=tj(l,c),g=!!(c.outside&&!l.showOutsideDays||c.hidden),f=(i=(n=l.components)===null||n===void 0?void 0:n.DayContent)!==null&&i!==void 0?i:wv,y=e.jsx(f,{date:t,displayMonth:s,activeModifiers:c}),b={style:x,className:h,children:y,role:"gridcell"},v=o.focusTarget&&Us(o.focusTarget,t)&&!c.outside,A=o.focusedDay&&Us(o.focusedDay,t),w=et(et(et({},b),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=A||v?0:-1,r)),d),T={isButton:u,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:w,divProps:b};return T}function aj(t){var s=p.useRef(null),a=sj(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(fi,et({name:"day",ref:s},a.buttonProps)):e.jsx("div",et({},a.divProps))}function rj(t){var s=t.number,a=t.dates,r=It(),n=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,m=d(Number(s),{locale:o});if(!n)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:m});var u=c(Number(s),{locale:o}),h=function(x){n(s,a,x)};return e.jsx(fi,{name:"week-number","aria-label":u,className:l.weeknumber,style:i.weeknumber,onClick:h,children:m})}function nj(t){var s,a,r=It(),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:aj,d=(a=o==null?void 0:o.WeekNumber)!==null&&a!==void 0?a:rj,m;return l&&(m=e.jsx("td",{className:i.cell,style:n.cell,children:e.jsx(d,{number:t.weekNumber,dates:t.dates})})),e.jsxs("tr",{className:i.row,style:n.row,children:[m,t.dates.map(function(u){return e.jsx("td",{className:i.cell,style:n.cell,role:"presentation",children:e.jsx(c,{displayMonth:t.displayMonth,date:u})},Zf(u))})]})}function om(t,s,a){for(var r=a!=null&&a.ISOWeek?ix(s):lx(s,a),n=a!=null&&a.ISOWeek?vo(t):jo(t,a),i=Pa(r,n),l=[],o=0;o<=i;o++)l.push(Hs(n,o));var c=l.reduce(function(d,m){var u=a!=null&&a.ISOWeek?t0(m):s0(m,a),h=d.find(function(x){return x.weekNumber===u});return h?(h.dates.push(m),d):(d.push({weekNumber:u,dates:[m]}),d)},[]);return c}function ij(t,s){var a=om(Ks(t),yo(t),s);if(s!=null&&s.useFixedWeeks){var r=Yf(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],l=Bl(i,6-r),o=om(Bl(i,1),l,s);a.push.apply(a,o)}}return a}function lj(t){var s,a,r,n=It(),i=n.locale,l=n.classNames,o=n.styles,c=n.hideHead,d=n.fixedWeeks,m=n.components,u=n.weekStartsOn,h=n.firstWeekContainsDate,x=n.ISOWeek,g=ij(t.displayMonth,{useFixedWeeks:!!d,ISOWeek:x,locale:i,weekStartsOn:u,firstWeekContainsDate:h}),f=(s=m==null?void 0:m.Head)!==null&&s!==void 0?s:Nv,y=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:nj,b=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:bv;return e.jsxs("table",{id:t.id,className:l.table,style:o.table,role:"grid","aria-labelledby":t["aria-labelledby"],children:[!c&&e.jsx(f,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:g.map(function(v){return e.jsx(y,{displayMonth:t.displayMonth,dates:v.dates,weekNumber:v.weekNumber},v.weekNumber)})}),e.jsx(b,{displayMonth:t.displayMonth})]})}function oj(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var cj=oj()?p.useLayoutEffect:p.useEffect,xl=!1,dj=0;function cm(){return"react-day-picker-".concat(++dj)}function mj(t){var s,a=t??(xl?cm():null),r=p.useState(a),n=r[0],i=r[1];return cj(function(){n===null&&i(cm())},[]),p.useEffect(function(){xl===!1&&(xl=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function uj(t){var s,a,r=It(),n=r.dir,i=r.classNames,l=r.styles,o=r.components,c=En().displayMonths,d=mj(r.id?"".concat(r.id,"-").concat(t.displayIndex):void 0),m=r.id?"".concat(r.id,"-grid-").concat(t.displayIndex):void 0,u=[i.month],h=l.month,x=t.displayIndex===0,g=t.displayIndex===c.length-1,f=!x&&!g;n==="rtl"&&(s=[x,g],g=s[0],x=s[1]),x&&(u.push(i.caption_start),h=et(et({},h),l.caption_start)),g&&(u.push(i.caption_end),h=et(et({},h),l.caption_end)),f&&(u.push(i.caption_between),h=et(et({},h),l.caption_between));var y=(a=o==null?void 0:o.Caption)!==null&&a!==void 0?a:yv;return e.jsxs("div",{className:u.join(" "),style:h,children:[e.jsx(y,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(lj,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function xj(t){var s=It(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function hj(t){var s,a,r=t.initialProps,n=It(),i=Oo(),l=En(),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 u=et(et({},n.styles.root),n.style),h=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,f){var y;return et(et({},g),(y={},y[f]=r[f],y))},{}),x=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:xj;return e.jsx("div",et({className:m.join(" "),style:u,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},h,{children:e.jsx(x,{children:l.displayMonths.map(function(g,f){return e.jsx(uj,{displayIndex:f,displayMonth:g},f)})})}))}function pj(t){var s=t.children,a=$b(t,["children"]);return e.jsx(rv,{initialProps:a,children:e.jsx(hv,{children:e.jsx(Zv,{initialProps:a,children:e.jsx(Cv,{initialProps:a,children:e.jsx(Tv,{initialProps:a,children:e.jsx(Mv,{children:e.jsx(Kv,{children:s})})})})})})})}function gj(t){return e.jsx(pj,et({},t,{children:e.jsx(hj,{initialProps:t})}))}function ti({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(gj,{showOutsideDays:a,className:Re("p-3",t),classNames:{months:"flex flex-col sm:flex-row gap-2",month:"flex flex-col gap-4",caption:"flex justify-center pt-1 relative items-center w-full",caption_label:"text-sm font-medium",nav:"flex items-center gap-1",nav_button:Re(jn({variant:"outline"}),"size-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-x-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:Re("relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-range-end)]:rounded-r-md",r.mode==="range"?"[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md":"[&:has([aria-selected])]:rounded-md"),day:Re(jn({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(mx,{className:Re("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(Ti,{className:Re("size-4",n),...i})},...r})}function Bs({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[u,h]=p.useState(!1),x=p.useMemo(()=>{if(t){if(t instanceof Date)return Sr(t)?t:void 0;if(typeof t=="string")try{const b=tl(t,"yyyy-MM-dd",new Date);return Sr(b)?b:void 0}catch{return}}},[t]),g=p.useMemo(()=>{if(a){if(a instanceof Date)return Sr(a)?a:void 0;if(typeof a=="string"){const b=tl(a,"yyyy-MM-dd",new Date);return Sr(b)?b:void 0}}},[a]),f=p.useMemo(()=>{if(r){if(r instanceof Date)return Sr(r)?r:void 0;if(typeof r=="string"){const b=tl(r,"yyyy-MM-dd",new Date);return Sr(b)?b:void 0}}},[r]),y=b=>{if(h(!1),!!s){if(!b){s(null);return}s(Ye(b,"yyyy-MM-dd"))}};return e.jsx("div",{className:Re("relative",o),children:e.jsxs(Zs,{open:u,onOpenChange:h,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{id:m,disabled:i,variant:"outline",className:Re("w-full justify-start text-left font-normal",!x&&"text-muted-foreground",c&&"border-destructive ring-destructive/20",l),children:[e.jsx(lt,{className:"mr-2 h-4 w-4"}),x?Ye(x,d):e.jsx("span",{children:n})]})}),e.jsx(Qs,{className:"w-auto p-0",align:"start",children:e.jsx(ti,{mode:"single",selected:x,onSelect:y,disabled:b=>!!(g&&b<g||f&&b>f),initialFocus:!0})})]})})}function fj({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,showCustomDatePicker:n,refreshing:i,onDateRangeChange:l,onCustomStartDateChange:o,onCustomEndDateChange:c,onShowCustomDatePickerChange:d,onApplyCustomDate:m,onResetCustomDates:u,onRefresh:h}){return e.jsx(J,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(q,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(ie,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200","data-testid":"management-badge",children:"Management View"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 w-full sm:w-auto",children:[t?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:s,onValueChange:l,"data-testid":"date-range-select",children:[e.jsx(Ge,{className:"w-[140px]",children:e.jsx(We,{placeholder:"Select period"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(Zs,{open:n,onOpenChange:d,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(lt,{className:"w-4 h-4"}),a&&r?`${Ye(a,"MMM d, yyyy")} - ${Ye(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Qs,{className:"w-auto p-4",align:"start",sideOffset:8,"data-testid":"custom-date-picker",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Bs,{value:a||null,onChange:x=>{const g=x?new Date(x):void 0;g?(o(g),r&&g>r&&c(g)):o(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Bs,{value:r||null,onChange:x=>{const g=x?new Date(x):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(I,{size:"sm",onClick:m,disabled:!a||!r,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-custom-date",children:"Apply"}),e.jsx(I,{size:"sm",variant:"outline",onClick:u,"data-testid":"cancel-custom-date",children:"Cancel"})]})]})})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:s,onValueChange:x=>l(x),"data-testid":"date-range-select-user",children:[e.jsx(Ge,{className:"w-[140px]",children:e.jsx(We,{placeholder:"Select period"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(Zs,{open:n,onOpenChange:d,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(lt,{className:"w-4 h-4"}),a&&r?`${Ye(a,"MMM d, yyyy")} - ${Ye(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Qs,{className:"w-auto p-4",align:"start",sideOffset:8,"data-testid":"custom-date-picker",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date-user",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Bs,{value:a||null,onChange:x=>{const g=x?new Date(x):void 0;g?(o(g),r&&g>r&&c(g)):o(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"start-date-input-user"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date-user",className:"text-sm font-medium",children:"End Date"}),e.jsx(Bs,{value:r||null,onChange:x=>{const g=x?new Date(x):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(I,{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(I,{size:"sm",variant:"outline",onClick:u,"data-testid":"cancel-custom-date-user",children:"Cancel"})]})]})})]})]}),e.jsx($t,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(I,{variant:"outline",size:"sm",onClick:h,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx(zt,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function gr({title:t,value:s,icon:a,iconBgColor:r,iconColor:n,subtitle:i,children:l,testId:o="kpi-card",onClick:c,onJustifyClick:d,showJustifyButton:m=!1}){const u=h=>{h.stopPropagation(),d==null||d()};return e.jsxs(J,{className:"hover:shadow-lg transition-all duration-200 shadow-md cursor-pointer h-full flex flex-col",onClick:c,"data-testid":o,children:[e.jsxs(me,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ue,{className:"text-sm font-medium text-muted-foreground","data-testid":`${o}-title`,children:t}),e.jsxs("div",{className:"flex items-center gap-2",children:[m&&d&&e.jsx("button",{type:"button",onClick:u,className:"p-1.5 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-colors","data-testid":`${o}-justify-button`,title:"View detailed breakdown of numbers","aria-label":"View detailed breakdown",children:e.jsx(Wr,{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(q,{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 ys({label:t,value:s,bgColor:a,textColor:r,testId:n="stat-card",children:i,onClick:l}){return e.jsxs("div",{className:`${a} rounded-lg p-2 sm:p-3 ${l?"cursor-pointer hover:shadow-md transition-shadow":""}`,"data-testid":n,onClick:l,children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1 leading-tight","data-testid":`${n}-label`,children:t}),e.jsx("p",{className:`text-lg sm:text-xl font-bold ${r}`,"data-testid":`${n}-value`,children:s}),i]})}function oa({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(vf,{"data-slot":"progress",className:Re("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(jf,{"data-slot":"progress-indicator",className:Re("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function yj({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(gr,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:De,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(ys,{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(ys,{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(ys,{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(ys,{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(ys,{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(gr,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:Ht,iconBgColor:"bg-green-50",iconColor:"text-green-600",testId:"kpi-sla-compliance",onClick:()=>i(l()),children:e.jsxs("div",{className:"flex flex-col flex-1",children:[e.jsx(oa,{value:(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0,className:"h-2 mb-2","data-testid":"sla-progress-bar"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(ys,{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(ys,{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(gr,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?Ot(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:Xe,iconBgColor:"bg-purple-50",iconColor:"text-purple-600",subtitle:`≈ ${(t==null?void 0:t.tatEfficiency.avgCycleTimeDays.toFixed(1))||0} working days`,testId:"kpi-avg-cycle-time",onClick:()=>i(l()),children:e.jsx("div",{className:"flex flex-col flex-1",children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(ys,{label:"Express",value:(()=>{const o=s.find(d=>d.priority==="express"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Ot(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(ys,{label:"Standard",value:(()=>{const o=s.find(d=>d.priority==="standard"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Ot(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:o=>{o.stopPropagation(),i({...l(),priority:"standard"})}})]})})})]})}function bj({kpis:t,criticalRequests:s,dateRange:a,customStartDate:r,customEndDate:n,onKPIClick:i,onNavigate:l,userId:o,userDisplayName:c}){const d=()=>({dateRange:a,startDate:r,endDate:n}),m=()=>{if(!o)return;const h=new URLSearchParams;h.set("approverId",o),h.set("approverName",c||"My Performance"),h.set("dateRange",a),a==="custom"&&r&&n&&(h.set("startDate",r.toISOString()),h.set("endDate",n.toISOString())),l==null||l(`/approver-performance?${h.toString()}`)},u=t&&t.requestVolume.totalRequests>0?t.requestVolume.approvedRequests/t.requestVolume.totalRequests*100:0;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 items-stretch","data-testid":"user-kpi-cards",children:[e.jsx(gr,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:De,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(ys,{label:"Approved",value:(t==null?void 0:t.requestVolume.approvedRequests)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-user-approved",onClick:h=>{h.stopPropagation(),i({...d(),status:"approved"})}}),e.jsx(ys,{label:"Pending",value:(t==null?void 0:t.requestVolume.openRequests)||0,bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-user-pending",onClick:h=>{h.stopPropagation(),i({...d(),status:"pending"})}}),e.jsx(ys,{label:"Paused",value:(t==null?void 0:t.requestVolume.pausedRequests)||0,bgColor:"bg-amber-50",textColor:"text-amber-600",testId:"stat-user-paused",onClick:h=>{h.stopPropagation(),i({...d(),status:"paused"})}}),e.jsx(ys,{label:"Rejected",value:(t==null?void 0:t.requestVolume.rejectedRequests)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-user-rejected",onClick:h=>{h.stopPropagation(),i({...d(),status:"rejected"})}}),e.jsx(ys,{label:"Closed",value:(t==null?void 0:t.requestVolume.closedRequests)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-user-closed",onClick:h=>{h.stopPropagation(),i({...d(),status:"closed"})}})]})}),e.jsx(gr,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:Xe,iconBgColor:"bg-orange-50",iconColor:"text-orange-600",subtitle:"at current level",testId:"kpi-pending-actions",onClick:()=>i({...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(ys,{label:"Approved Today",value:(t==null?void 0:t.approverLoad.completedToday)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-today",onClick:h=>{h.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}}),e.jsx(ys,{label:"This Week",value:(t==null?void 0:t.approverLoad.completedThisWeek)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-week",onClick:h=>{h.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}})]})}),e.jsx(gr,{title:"Critical Alerts",value:s.length,icon:ga,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(ys,{label:"Breached",value:s.filter(h=>h.breachCount>0).length,bgColor:"bg-orange-50",textColor:"text-red-600",testId:"stat-user-breached",onClick:h=>{h.stopPropagation(),i({...d(),targetPage:"open-requests"})}}),e.jsx(ys,{label:"Warning",value:s.filter(h=>h.breachCount===0).length,bgColor:"bg-yellow-50",textColor:"text-orange-600",testId:"stat-user-warning",onClick:h=>{h.stopPropagation(),i({...d(),targetPage:"open-requests"})}})]})}),e.jsx(gr,{title:"Success Rate",value:`${u.toFixed(0)}%`,icon:Pe,iconBgColor:"bg-green-50",iconColor:"text-green-600",subtitle:`of ${(t==null?void 0:t.requestVolume.totalRequests)||0} requests approved`,testId:"kpi-success-rate",children:e.jsxs("div",{className:"space-y-4 mt-3 flex flex-col flex-1",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(oa,{value:u,className:"h-4 bg-gray-200 [&>div]:bg-green-600","data-testid":"success-rate-progress"}),e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Rejected"}),e.jsx("span",{className:"font-semibold text-red-600",children:(t==null?void 0:t.requestVolume.rejectedRequests)||0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsxs("div",{className:"bg-green-50 rounded-lg p-2 text-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Approved"}),e.jsx("div",{className:"text-lg font-semibold text-green-600",children:(t==null?void 0:t.requestVolume.approvedRequests)||0})]}),e.jsxs("div",{className:"bg-red-50 rounded-lg p-2 text-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Rejected"}),e.jsx("div",{className:"text-lg font-semibold text-red-600",children:(t==null?void 0:t.requestVolume.rejectedRequests)||0})]})]})]})})]})}const vj=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)))},jj=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 Nj({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=vj(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(d0,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(ie,{variant:"destructive",className:"text-xs","data-testid":`${a}-breach-count`,children:t.breachCount})]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-700 line-clamp-2","data-testid":`${a}-title`,children:t.title})]}),e.jsx(ie,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:jj(t)})]}),e.jsxs("div",{className:"space-y-1 sm:space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs text-gray-600",children:[e.jsx("span",{children:"TAT Used"}),e.jsxs("span",{className:"font-medium","data-testid":`${a}-progress-percentage`,children:[r,"%"]})]}),e.jsx(oa,{value:r,className:`h-1.5 sm:h-2 ${r>=80?"[&>div]:bg-red-600":r>=50?"[&>div]:bg-orange-500":"[&>div]:bg-green-600"}`,"data-testid":`${a}-progress-bar`})]})]})}function wj(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 Cj(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function Aj(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 Sj(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 nh(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 Tj({isAdmin:t,breachedRequests:s,pagination:a,onPageChange:r,onNavigate:n}){return e.jsxs(J,{className:"lg:col-span-2 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden",style:{height:"100%"},"data-testid":"critical-alerts-section",children:[e.jsx(me,{className:"pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-red-100 rounded-lg",children:e.jsx(ga,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(Te,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(ie,{variant:"destructive",className:`font-semibold text-xs sm:text-sm ${a.totalRecords>0?"animate-pulse":""}`,"data-testid":"critical-count-badge",children:a.totalRecords})]})}),e.jsx(q,{className:"overflow-y-auto flex-1 p-4",style:{maxHeight:a.totalPages>1?"calc(100% - 140px)":"calc(100% - 80px)"},children:e.jsx("div",{className:"space-y-3 sm:space-y-4",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-critical-alerts",children:[e.jsx(Pe,{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(Nj,{alert:i,onNavigate:l=>n==null?void 0:n(`request/${l}`),testId:"dashboard-critical-alert"},i.requestId))})}),a.totalPages>1&&s.length>0&&e.jsx("div",{className:"border-t bg-gray-50 px-4 py-2 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Page ",a.page," of ",a.totalPages," (",a.totalRecords," total)"]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>r(a.page-1),disabled:a.page===1,className:"h-7 w-7 p-0","data-testid":"critical-pagination-prev",children:e.jsx(xs,{className:"h-3 w-3 rotate-180"})}),nh(a.page,a.totalPages,3).map(i=>e.jsx(I,{variant:i===a.page?"default":"outline",size:"sm",onClick:()=>r(i),className:`h-7 w-7 p-0 text-xs ${i===a.page?"bg-red-600 text-white hover:bg-red-700":""}`,"data-testid":`critical-pagination-page-${i}`,children:i},i)),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>r(a.page+1),disabled:a.page===a.totalPages,className:"h-7 w-7 p-0","data-testid":"critical-pagination-next",children:e.jsx(xs,{className:"h-3 w-3"})})]})]})})]})}const kj=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"}},Rj=t=>{const s=new Date,a=new Date(t),r=a0(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=r0(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=n0(s,a);return`${i} day${i>1?"s":""} ago`},Dj=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()},Pj=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(Pe,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-green-600"}):s.includes("reject")?e.jsx(ss,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-red-600"}):s.includes("comment")?e.jsx(Is,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(ga,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(De,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(ki,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(Pt,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function Ij({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(es,{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(Vi,{src:""}),e.jsx(ts,{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:Pj(t.action)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center justify-between gap-2 mb-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-xs sm:text-sm text-gray-900","data-testid":`${i}-request-number`,children:t.requestNumber}),e.jsx(ie,{variant:"outline",className:`text-xs ${kj(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:Dj(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:Rj(t.timestamp)})]})]}),e.jsx(xs,{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 Ej({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:l,currentUserId:o,currentUserDisplayName:c,currentUserEmail:d}){return e.jsxs(J,{className:"lg:col-span-1 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden",style:{height:"100%"},"data-testid":"recent-activity-section",children:[e.jsx(me,{className:"pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-blue-100 rounded-lg",children:e.jsx(Pt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(ue,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(Te,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(I,{variant:"ghost",size:"sm",className:"text-blue-600 hover:bg-blue-50 font-medium flex-shrink-0 h-8 sm:h-9 px-2 sm:px-3 sm:min-w-[100px]",onClick:i,disabled:r,"data-testid":"activity-refresh-button",children:[e.jsx(zt,{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(q,{className:"overflow-y-auto flex-1 p-4",style:{maxHeight:a.totalPages>1?"calc(100% - 140px)":"calc(100% - 80px)"},children:e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-recent-activity",children:[e.jsx(Pt,{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(Ij,{activity:m,currentUserId:o,currentUserDisplayName:c,currentUserEmail:d,onNavigate:u=>l==null?void 0:l(`request/${u}`),testId:"dashboard-activity"},m.activityId))})}),a.totalPages>1&&s.length>0&&e.jsx("div",{className:"border-t bg-gray-50 px-4 py-2 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Page ",a.page," of ",a.totalPages," (",a.totalRecords," total)"]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(a.page-1),disabled:a.page===1,className:"h-7 w-7 p-0","data-testid":"activity-pagination-prev",children:e.jsx(xs,{className:"h-3 w-3 rotate-180"})}),nh(a.page,a.totalPages,3).map(m=>e.jsx(I,{variant:m===a.page?"default":"outline",size:"sm",onClick:()=>n(m),className:`h-7 w-7 p-0 text-xs ${m===a.page?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`activity-pagination-page-${m}`,children:m},m)),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(a.page+1),disabled:a.page===a.totalPages,className:"h-7 w-7 p-0","data-testid":"activity-pagination-next",children:e.jsx(xs,{className:"h-3 w-3"})})]})]})})]})}function Fj({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(J,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Pt,{className:"h-4 w-4 text-blue-600"})}),e.jsx(ue,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(q,{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($t,{}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg Time/Level"}),e.jsxs("span",{className:"font-semibold",children:[s.length>0?(t.tatEfficiency.avgCycleTimeHours/s.length).toFixed(1):"0","h"]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"At Risk"}),e.jsx("span",{className:"font-semibold text-red-600",children:a.filter(u=>u.breachCount>0).length})]})]})]})})]}),e.jsxs(J,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(Is,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ue,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(q,{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($t,{}),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(J,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-blue-50 p-2 sm:p-3 rounded-lg",children:e.jsx(zl,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2 self-start sm:self-auto",onClick:()=>d(n,i,l),disabled:o,"data-testid":"export-dept-stats-button",children:[e.jsx(wt,{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(q,{children:e.jsx(Mr,{width:"100%",height:400,children:e.jsxs(Ul,{data:r,children:[e.jsx(oi,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ci,{dataKey:"department",stroke:"#999",tick:u=>{const{x:h,y:x,payload:g}=u;return e.jsx("g",{transform:`translate(${h},${x})`,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(di,{stroke:"#999",tick:{fontSize:11}}),e.jsx(_r,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(mi,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(va,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(va,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(va,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function Mj({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(J,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(Is,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ue,{className:"text-sm",children:"My Activity"})]})}),e.jsx(q,{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(J,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(Xe,{className:"h-4 w-4 text-purple-600"})}),e.jsx(ue,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(q,{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:Ot(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx($t,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function _j({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(J,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-green-50 p-2 sm:p-3 rounded-lg",children:e.jsx(Ht,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(q,{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: ",Ot(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Mr,{width:"100%",height:300,children:e.jsxs(tx,{children:[e.jsx(sx,{data:t.map(a=>({name:a.priority.charAt(0).toUpperCase()+a.priority.slice(1),value:a.totalCount,priority:a.priority,percentage:Math.round(a.totalCount/t.reduce((r,n)=>r+n.totalCount,0)*100)})),cx:"50%",cy:"50%",labelLine:!0,label:({cx:a,cy:r,midAngle:n,outerRadius:i,name:l,percentage:o})=>{const c=Math.PI/180,d=i+35,m=a+d*Math.cos(-n*c),u=r+d*Math.sin(-n*c);return e.jsx("text",{x:m,y:u,fill:"#1f2937",textAnchor:m>a?"start":"end",dominantBaseline:"central",style:{fontSize:"14px",fontWeight:"600",pointerEvents:"none"},children:`${l}: ${o}%`})},outerRadius:90,fill:"#8884d8",dataKey:"value",onClick:a=>{a&&a.priority&&s&&s(`requests?priority=${a.priority}`)},style:{cursor:"pointer"},children:t.map((a,r)=>e.jsx(ax,{fill:a.priority==="express"?"#ef4444":"#3b82f6",style:{cursor:"pointer"}},`cell-${r}`))}),e.jsx(_r,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"},formatter:(a,r,n)=>{var l;const i=((l=n.payload)==null?void 0:l.priority)||"";return[`${a} requests`,`Click for ${i}`]}})]})})})]})]})}function wr({currentPage:t,totalPages:s,itemsPerPage:a,totalRecords:r,onPageChange:n,loading:i=!1,itemLabel:l="items",testIdPrefix:o="pagination"}){const c=()=>{const u=[];let x=Math.max(1,t-Math.floor(2.5)),g=Math.min(s,x+5-1);g-x<4&&(x=Math.max(1,g-5+1));for(let f=x;f<=g;f++)u.push(f);return u},d=r>0?(t-1)*a+1:0,m=Math.min(t*a,r);return s<=1?e.jsx(J,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(q,{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(J,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(q,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-sm sm:text-base font-medium text-gray-700","data-testid":`${o}-info`,children:["Showing ",d," to ",m," of ",r," ",l]}),e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${o}-controls`,children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(t-1),disabled:t===1,className:"h-8 w-8 p-0","data-testid":`${o}-prev-btn`,"aria-label":"Previous page",children:e.jsx(xs,{className:"h-4 w-4 rotate-180"})}),t>3&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(1),className:"h-8 w-8 p-0","data-testid":`${o}-page-1`,children:"1"}),e.jsx("span",{className:"text-muted-foreground","data-testid":`${o}-ellipsis-start`,children:"..."})]}),c().map(u=>e.jsx(I,{variant:u===t?"default":"outline",size:"sm",onClick:()=>n(u),className:`h-8 w-8 p-0 ${u===t?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`${o}-page-${u}`,"aria-current":u===t?"page":void 0,children:u},u)),t<s-2&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground","data-testid":`${o}-ellipsis-end`,children:"..."}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${o}-page-${s}`,children:s})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(t+1),disabled:t===s,className:"h-8 w-8 p-0","data-testid":`${o}-next-btn`,"aria-label":"Next page",children:e.jsx(xs,{className:"h-4 w-4"})})]})]})})})}function Lj(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${Ye(s,"MMM d, yyyy")} - ${Ye(a,"MMM d, yyyy")}`:{all:"(All Time)",today:`${r} Today`,week:`${r} This Week`,month:`${r} This Month`,quarter:`${r} This Quarter`,year:`${r} This Year`,last30days:`${r} Last 30 Days`,custom:`${r} Custom Range`}[t]||`${r} Selected Period`}function Oj(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${Ye(s,"MMM d, yyyy")} to ${Ye(a,"MMM d, yyyy")}`:{all:"All historical data",today:"Today's data",week:"This week data",month:"This month data",quarter:"This quarter data",year:"This year data",last30days:"Last 30 days data",custom:"Custom date range"}[t]||"Filtered data"}function $j({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(J,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-red-50 p-2 sm:p-3 rounded-lg",children:e.jsx(ss,{className:"h-5 w-5 sm:h-6 sm:w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs(Te,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",Oj(a,r,n)]})]})]}),e.jsxs(ie,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[t.length," ",t.length===1?"Breach":"Breaches"]})]})}),e.jsxs(q,{children:[e.jsx("div",{className:"overflow-x-auto -mx-4 sm:mx-0",children:e.jsxs("table",{className:"w-full min-w-[1000px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 bg-gray-50",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Request ID"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[250px]",children:"Title"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Department"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Approver"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Level"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[140px]",children:"Breach Time"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[300px]",children:"Reason"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Priority"})]})}),e.jsx("tbody",{children:t.map((d,m)=>{const u=d.breachTime||0;return e.jsxs("tr",{className:"border-b border-gray-100 hover:bg-gray-50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-blue-600 cursor-pointer hover:underline",onClick:()=>o==null?void 0:o(`request/${d.requestNumber}`),"data-testid":`breach-request-${d.requestNumber}`,children:d.requestNumber}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-900 w-[250px]",children:e.jsx("p",{className:"break-words leading-relaxed",children:d.title})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{d.department&&d.department!=="Unknown"&&l({...c(),department:d.department})},children:d.department||"Unknown"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.approverId?e.jsx("span",{className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{if(o){const h=new URLSearchParams;h.set("approver",d.approverId),h.set("approverType","current"),h.set("slaCompliance","breached"),a&&h.set("dateRange",a),r&&h.set("startDate",r.toISOString()),n&&h.set("endDate",n.toISOString()),o(`requests?${h.toString()}`)}},title:"Click to view all requests for this approver",children:d.approver||"N/A"}):d.approver||"N/A"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.currentLevel&&d.totalLevels?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/",d.totalLevels]}):d.currentLevel?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/—"]}):e.jsx("span",{className:"text-gray-400",children:"—"})}),e.jsx("td",{className:"py-3 px-4 w-[140px]",children:e.jsx("span",{className:"bg-red-500 text-white px-2 py-1 rounded text-xs font-medium whitespace-nowrap",children:Aj(u)})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 w-[300px]",children:e.jsx("div",{className:"max-h-32 overflow-y-auto",children:e.jsx("p",{className:"whitespace-pre-line break-words leading-relaxed",children:d.breachReason||"TAT Exceeded"})})}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(ie,{variant:"outline",className:`text-xs font-medium ${d.priority==="express"?"bg-orange-100 text-orange-800 border-orange-200":"bg-blue-100 text-blue-800 border-blue-200"}`,children:d.priority})})]},m)})})]})}),e.jsx("div",{className:"mt-4",children:e.jsx(wr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function Uj({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(J,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(me,{children:e.jsx("div",{className:"flex items-center justify-between gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(q,{children:[e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.map((i,l)=>{const o=Number(i.tatPercentageUsed)||0,c=Number(i.elapsedHours)||0,d=Number(i.remainingHours)||0;return e.jsxs("div",{className:"p-3 sm:p-4 border rounded-lg hover:shadow-md transition-all cursor-pointer",onClick:()=>n==null?void 0:n(`request/${i.requestNumber}`),"data-testid":`deadline-item-${i.requestNumber}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-xs sm:text-sm",children:i.requestNumber}),e.jsx(ie,{variant:"outline",className:`text-xs ${i.priority==="express"?"bg-orange-50 text-orange-700":"bg-blue-50 text-blue-700"}`,children:i.priority})]}),e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground truncate",children:i.requestTitle}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground flex-wrap",children:[e.jsxs(ie,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:["Level ",i.levelNumber||"?","/",i.totalLevels||"?"]}),e.jsx("span",{className:"truncate",children:i.approverName})]})]}),e.jsxs("div",{className:"text-right flex-shrink-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"TAT Used"}),e.jsxs("p",{className:`text-base sm:text-lg font-bold ${o>=80?"text-red-600":o>=50?"text-orange-600":"text-green-600"}`,children:[o.toFixed(0),"%"]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(oa,{value:o,className:`h-1.5 sm:h-2 ${o>=80?"bg-red-100":o>=50?"bg-orange-100":"bg-green-100"}`}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[Ot(c)," elapsed"]}),e.jsxs("span",{children:[Ot(d)," left"]})]})]})]},l)})}),e.jsx("div",{className:"mt-4",children:e.jsx(wr,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function Bj({aiRemarkUtilization:t}){return t?e.jsxs(J,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-purple-50 p-2 sm:p-3 rounded-lg",children:e.jsx(Ri,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(q,{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(Mr,{width:"100%",height:250,children:e.jsxs(Wf,{data:t.monthlyTrends,children:[e.jsx(oi,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ci,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(di,{stroke:"#999",tick:{fontSize:11}}),e.jsx(_r,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(mi,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Od,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(Od,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function Vj({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(J,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-yellow-50 p-2 sm:p-3 rounded-lg",children:e.jsx(Bt,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(I,{onClick:()=>c(a,r,n),disabled:l||i,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-approver-performance-button",children:l?e.jsxs(e.Fragment,{children:[e.jsx(zt,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(q,{children:[e.jsx("div",{className:"space-y-3",children:t.map((m,u)=>{const h=m.tatCompliancePercent;return e.jsxs("div",{className:"border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{const x=new URLSearchParams;x.set("approverId",m.approverId),x.set("approverName",m.approverName),x.set("dateRange",a),a==="custom"&&r&&n&&(x.set("startDate",r.toISOString()),x.set("endDate",n.toISOString())),d==null||d(`/approver-performance?${x.toString()}`)},"data-testid":`approver-item-${m.approverId}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-orange-500 rounded-full flex items-center justify-center text-white font-semibold text-sm flex-shrink-0",children:u+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-gray-900 truncate",children:m.approverName}),e.jsxs("div",{className:"text-xs text-gray-500",children:[m.totalApproved," requests approved"]})]})]}),e.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium ${Sj(h)} flex-shrink-0`,children:[h,"% TAT"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"Avg Response"}),e.jsx("div",{className:"text-sm font-medium text-gray-900",children:Ot(m.avgResponseHours)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"Pending"}),e.jsx("div",{className:"text-sm font-medium text-gray-900",children:e.jsx("span",{className:"bg-gray-500 text-white px-2 py-1 rounded text-xs",children:m.pendingCount})})]})]})]},u)})}),e.jsx("div",{className:"mt-4",children:e.jsx(wr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:o,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function zj(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 Hj(t,s,a,r){const n=[];return r||n.push({label:"New Request",icon:De,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"}),n.push({label:"View Pending",icon:Xe,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:Ga,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:Pt,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),n}function Wj({onNavigate:t,onNewRequest:s}){const{user:a}=Qt(),r=Dn(),n=Yr(nt=>nt.dashboard.viewAsUser),i=p.useMemo(()=>Ui(a),[a]),l=i&&!n,o=p.useCallback(nt=>{r(jb(nt))},[r]),c=Nb(),{dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,handleDateRangeChange:x,handleApplyCustomDate:g,resetCustomDates:f,setCustomStartDate:y,setCustomEndDate:b,setShowCustomDatePicker:v}=c,A=wb(),{activity:w,critical:T,deadlines:C,approver:_,updateActivityPagination:D,updateCriticalPagination:S,updateDeadlinesPagination:j,updateApproverPagination:P,handleActivityPageChange:R,handleCriticalPageChange:O,handleDeadlinesPageChange:F,handleApproverPageChange:M}=A,B=Ab({isAdmin:l,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:u,onPaginationUpdate:{activity:D,critical:S,deadlines:j,approver:P}}),{kpis:k,recentActivity:N,criticalRequests:U,departmentStats:$,priorityDistribution:L,upcomingDeadlines:se,aiRemarkUtilization:G,approverPerformance:oe,loading:Z,refreshing:E,fetchDashboardData:V,fetchRecentActivities:H,fetchCriticalRequests:Q,fetchUpcomingDeadlines:Y,fetchApproverPerformance:W}=B,ce=Mb(),{exportingDeptStats:xe,exportingApproverPerformance:ke,handleExportDepartmentStats:Ae,handleExportApproverPerformance:ae}=ce,ye=p.useMemo(()=>wj(U),[U]),Ne=p.useMemo(()=>Cj(se),[se]),ve=p.useCallback(()=>{V(!0)},[d,m,u,V]),$e=p.useCallback(()=>{g(()=>{m&&u&&V(!1)})},[m,u,g,V]),re=p.useCallback(nt=>{R(nt,H)},[R,H]),Me=p.useCallback(nt=>{O(nt,Q)},[O,Q]),ot=p.useCallback(nt=>{F(nt,Y)},[F,Y]),pe=p.useCallback(nt=>{M(nt,()=>W(nt))},[M,W]);p.useEffect(()=>{d==="custom"?m&&u&&V(!1):V(!1)},[d,m,u,n]);const Oe=p.useMemo(()=>{try{const nt=at.getUserData();return(nt==null?void 0:nt.jobTitle)==="Dealer"}catch(nt){return console.error("[Dashboard] Error checking dealer status:",nt),!1}},[]),ft=p.useMemo(()=>Hj(i,s,t,Oe),[i,s,t,Oe]),mt=p.useCallback(nt=>{const _s=zj(nt);t==null||t(_s)},[t]);return Z?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(zt,{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(_b,{isAdmin:i,effectiveIsAdmin:l,viewAsUser:n,onToggleView:o,quickActions:ft,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(fj,{isAdmin:l,dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,refreshing:E,onDateRangeChange:x,onCustomStartDateChange:y,onCustomEndDateChange:b,onShowCustomDatePickerChange:v,onApplyCustomDate:$e,onResetCustomDates:f,onRefresh:ve}),l?e.jsx(yj,{kpis:k,priorityDistribution:L,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:mt}):e.jsx(bj,{kpis:k,criticalRequests:U,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:mt,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(Tj,{isAdmin:l,breachedRequests:ye,pagination:T,onPageChange:Me,onNavigate:t}),e.jsx(Ej,{isAdmin:l,recentActivity:N,pagination:w,refreshing:E,onPageChange:re,onRefresh:ve,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),l&&k&&e.jsx(Fj,{kpis:k,upcomingDeadlines:se,criticalRequests:U,departmentStats:$,dateRange:d,customStartDate:m,customEndDate:u,exportingDeptStats:xe,onKPIClick:mt,onExportDepartmentStats:Ae}),!l&&k&&e.jsx(Mj,{kpis:k}),l&&L.length>0&&e.jsx(_j,{priorityDistribution:L,onNavigate:t}),l&&ye.length>0&&e.jsx($j,{breachedRequests:ye,pagination:T,dateRange:d,customStartDate:m,customEndDate:u,onPageChange:Me,onKPIClick:mt,onNavigate:t}),Ne.length>0&&e.jsx(Uj,{isAdmin:l,upcomingDeadlines:Ne,pagination:C,onPageChange:ot,onNavigate:t}),l&&G&&e.jsx(Bj,{aiRemarkUtilization:G}),l&&oe.length>0&&e.jsx(Vj,{approverPerformance:oe,pagination:_,dateRange:d,customStartDate:m,customEndDate:u,loading:Z,exportingApproverPerformance:ke,onPageChange:pe,onExport:ae,onNavigate:t})]})}const Gj={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},ih=Gr({name:"openRequests",initialState:Gj,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:Kj,setStatusFilter:Yj,setPriorityFilter:Zj,setTemplateTypeFilter:Xj,setSortBy:Qj,setSortOrder:Jj,setCurrentPage:qj,clearFilters:eN}=ih.actions;function tN(){const t=Dn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,sortBy:i,sortOrder:l,currentPage:o}=Yr(b=>b.openRequests),c=p.useCallback(b=>t(Kj(b)),[t]),d=p.useCallback(b=>t(Yj(b)),[t]),m=p.useCallback(b=>t(Zj(b)),[t]),u=p.useCallback(b=>t(Xj(b)),[t]),h=p.useCallback(b=>t(Qj(b)),[t]),x=p.useCallback(b=>t(Jj(b)),[t]),g=p.useCallback(b=>t(qj(b)),[t]),f=p.useCallback(()=>t(eN()),[t]),y=[s,r!=="all"?r:null,a!=="all"?a:null,n!=="all"?n:null].filter(Boolean).length;return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,sortBy:i,sortOrder:l,currentPage:o,setSearchTerm:c,setStatusFilter:d,setPriorityFilter:m,setTemplateTypeFilter:u,setSortBy:h,setSortOrder:x,setCurrentPage:g,clearFilters:f,activeFiltersCount:y}}function hl(){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 sN(t){var o;const s=t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",a=Array.from({length:t.approverCount||1},(c,d)=>{const m=d,u=t.approvers[m]||{},h=m+1,x=u.tat??"";let g=0;typeof x=="number"&&(g=u.tatType==="days"?x*24:x);const f=u.email||"",y=u.name&&u.name.trim()||f.split("@")[0]||`Approver ${h}`;return{levelNumber:h,levelName:`Level ${h}`,approverId:hl(),approverEmail:f,approverName:y,tatHours:g>0?g:24,isFinalApprover:h===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:hl(),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:hl(),userEmail:c.email,userName:c.name||c.email.split("@")[0]||"CC",participantType:"CONSULTATION",canComment:!1,canViewDocuments:!0,canDownloadDocuments:!1,notificationEnabled:!0}))],n={templateType:t.templateType,title:t.title,description:t.description,priority:s,approvalLevels:a,participants:r.length?r:void 0},i=await je.post("/workflows",n),l=((o=i.data)==null?void 0:o.data)||i.data;return{id:l.id||l.workflowId||""}}async function Uo(t,s,a="SUPPORTING"){var o;const r={templateType:t.templateType,title:t.title,description:t.description,priority:t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",approvers:Array.from({length:t.approverCount||1},(c,d)=>{const m=t.approvers[d]||{},u=typeof m.tat=="number"?m.tat:0;if(!m.email||!m.email.trim())throw new Error(`Email is required for approver at level ${d+1}.`);return{email:m.email,tat:u,tatType:m.tatType||"hours"}})};t.spectators&&t.spectators.length>0&&(r.spectators=t.spectators.filter(c=>c==null?void 0:c.email).map(c=>({email:c.email})));const n=new FormData;n.append("payload",JSON.stringify(r)),n.append("category",a),s.forEach(c=>n.append("files",c));const i=await 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 aN(t={}){var f;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,slaCompliance:m,dateRange:u,startDate:h,endDate:x}=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:u,startDate:h,endDate:x}});return((f=g.data)==null?void 0:f.data)||g.data}async function rN(t={}){var y,b,v,A,w;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,approverType:m,slaCompliance:u,dateRange:h,startDate:x,endDate:g}=t,f=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:u,dateRange:h,startDate:x,endDate:g}});return{data:((b=(y=f.data)==null?void 0:y.data)==null?void 0:b.data)||((v=f.data)==null?void 0:v.data)||[],pagination:((w=(A=f.data)==null?void 0:A.data)==null?void 0:w.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function nN(t={}){var g,f,y,b,v;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:l,initiator:o,approver:c,slaCompliance:d,dateRange:m,startDate:u,endDate:h}=t,x=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:u,endDate:h}});return{data:((f=(g=x.data)==null?void 0:g.data)==null?void 0:f.data)||((y=x.data)==null?void 0:y.data)||[],pagination:((v=(b=x.data)==null?void 0:b.data)==null?void 0:v.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function iN(t={}){var x,g,f,y,b;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:c,dateRange:d,startDate:m,endDate:u}=t,h=await 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:u}});return{data:((g=(x=h.data)==null?void 0:x.data)==null?void 0:g.data)||((f=h.data)==null?void 0:f.data)||[],pagination:((b=(y=h.data)==null?void 0:y.data)==null?void 0:b.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function lN(t={}){var m,u,h,x,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:((u=(m=d.data)==null?void 0:m.data)==null?void 0:u.data)||((h=d.data)==null?void 0:h.data)||[],pagination:((g=(x=d.data)==null?void 0:x.data)==null?void 0:g.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function oN(t={}){var m,u,h,x,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:((u=(m=d.data)==null?void 0:m.data)==null?void 0:u.data)||((h=d.data)==null?void 0:h.data)||[],pagination:((g=(x=d.data)==null?void 0:x.data)==null?void 0:g.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Cs(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 Or(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 lh(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 oh(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 cN(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 ch(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 dN(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 mN(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 uN(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 dm(t){var a;const s=await je.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function xN(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function Zr(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/documents/${t}/preview`}function dh(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 js(t){const a=`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/documents/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const u=await i.text();throw new Error(`Download failed: ${i.status} - ${u}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=dh(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 mm(t){const a=`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const u=await i.text();throw new Error(`Download failed: ${i.status} - ${u}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=dh(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 Ms={createWorkflowFromForm:sN,createWorkflowMultipart:Uo,listWorkflows:aN,listParticipantRequests:rN,listMyWorkflows:nN,listMyInitiatedWorkflows:iN,listOpenForMe:lN,listClosedByMe:oN,submitWorkflow:Bo,getWorkflowDetails:Cs,getWorkNotes:Or,createWorkNoteMultipart:lh,handleInitiatorAction:mh};async function Bo(t){var a;const s=await je.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function hN(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 pN(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 mn(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 kr(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 gN(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 mh(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 fN(t){var a;return((a=(await je.get(`/workflows/${t}/history`)).data)==null?void 0:a.data)||[]}function is(t,s){if(!t)return"N/A";try{const a=typeof t=="string"?new Date(t):t;if(isNaN(a.getTime()))return"Invalid Date";const{includeTime:r=!0,includeSeconds:n=!1,format:i="medium"}=s||{};return r?a.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",...n&&{second:"2-digit"},hour12:!0}):a.toLocaleDateString("en-US",{year:"numeric",month:i==="short"?"short":"long",day:"numeric"})}catch(a){return console.error("Error formatting date:",a),String(t)}}function uh(t){return is(t,{includeTime:!1,format:"short"})}function pa(t,s=!1){if(!t)return"N/A";try{const a=typeof t=="string"?new Date(t):t;if(isNaN(a.getTime()))return"Invalid Date";const r=String(a.getDate()).padStart(2,"0"),i=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][a.getMonth()],l=a.getFullYear();if(s){const o=a.getHours(),c=o%12||12,d=String(a.getMinutes()).padStart(2,"0"),m=String(a.getSeconds()).padStart(2,"0"),u=o>=12?"PM":"AM";return`${r} ${i} ${l}, ${c}:${d}:${m} ${u}`}return`${r} ${i} ${l}`}catch(a){return console.error("Error formatting date:",a),String(t)}}function yN(t){return t?t.jobTitle==="Dealer"||t.jobTitle==="DEALER":!1}function Vo(t){return yN(t)?"DEALER":"STANDARD"}const zn=[{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 Fn({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),[u,h]=p.useState(!1),[x,g]=p.useState(null),[f,y]=p.useState("#FFEB3B"),[b,v]=p.useState(!1),[A,w]=p.useState(null),[T,C]=p.useState("#000000");p.useEffect(()=>{l.current&&l.current.innerHTML!==t&&l.current.innerHTML!==t&&(l.current.innerHTML=t||"")},[t]);const _=p.useCallback(k=>(k=k.replace(/<!--[\s\S]*?-->/g,""),k=k.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),k=k.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),k=k.replace(/<meta[^>]*>/gi,""),k=k.replace(/\s*class="Mso[^"]*"/gi,""),k=k.replace(/\s*class="mso[^"]*"/gi,""),k=k.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),k=k.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),k=k.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),k=k.replace(/<\/?o:p[^>]*>/gi,""),k=k.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),k=k.replace(/<v:[^>]*\/>/gi,""),k=k.replace(/<p[^>]*>\s*<\/p>/gi,""),k=k.replace(/<div[^>]*>\s*<\/div>/gi,""),k=k.replace(/\s+/g," "),k=k.trim(),k),[]),D=p.useCallback(k=>{k.preventDefault();const N=k.clipboardData;let U=N.getData("text/html")||N.getData("text/plain");if((U.includes("<!--")||U.includes("<style")||U.includes("MsoNormal"))&&(U=_(U)),!l.current)return;const $=window.getSelection();if(!$||$.rangeCount===0)return;const L=$.getRangeAt(0);L.deleteContents();const se=document.createElement("div");se.innerHTML=U;const G=document.createDocumentFragment();Array.from(se.childNodes).forEach(oe=>{if(oe.nodeType===Node.ELEMENT_NODE){const Z=oe;if(Z.tagName==="UL"||Z.tagName==="OL"){const E=Z.cloneNode(!0);E.removeAttribute("style"),E.removeAttribute("class"),E.querySelectorAll("li").forEach(V=>{V.removeAttribute("style"),V.removeAttribute("class");const H=V.textContent||"";H.trim()&&(V.textContent=H.trim())}),G.appendChild(E)}else if(Z.tagName==="TABLE"){const E=Z.cloneNode(!0);E.removeAttribute("style"),E.removeAttribute("class"),E.querySelectorAll("td, th").forEach(H=>{H.removeAttribute("style"),H.removeAttribute("class")});const V=document.createElement("div");V.className="table-wrapper",V.style.overflowX="auto",V.style.maxWidth="100%",V.style.margin="8px 0",V.appendChild(E),G.appendChild(V)}else if(Z.tagName==="P"||Z.tagName==="DIV"){const E=document.createElement("p"),H=Z.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");E.innerHTML=H,E.removeAttribute("style"),E.removeAttribute("class"),G.appendChild(E)}else if(Z.tagName==="BR")G.appendChild(Z.cloneNode(!0));else{const E=Z.textContent||"";if(E.trim()){const V=document.createElement("p");V.textContent=E.trim(),G.appendChild(V)}}}else if(oe.nodeType===Node.TEXT_NODE){const Z=oe.textContent||"";if(Z.trim()){const E=document.createElement("p");E.textContent=Z.trim(),G.appendChild(E)}}}),G.childNodes.length===0&&N.getData("text/plain").split(`
`).forEach(E=>{if(E.trim()){const V=document.createElement("p");V.textContent=E.trim(),G.appendChild(V)}else G.appendChild(document.createElement("br"))}),L.insertNode(G),L.collapse(!1),$.removeAllRanges(),$.addRange(L),l.current&&s(l.current.innerHTML)},[s,_]),S=p.useCallback(()=>{if(!l.current||!o)return;const k=new Set,N=window.getSelection();if(N&&N.rangeCount>0){const $=N.getRangeAt(0).commonAncestorContainer;let L=null;for($.nodeType===Node.TEXT_NODE?L=$.parentElement:L=$;L&&L!==l.current;){const se=L.tagName.toLowerCase();(se==="strong"||se==="b")&&k.add("bold"),(se==="em"||se==="i")&&k.add("italic"),se==="u"&&k.add("underline"),se==="h1"&&k.add("h1"),se==="h2"&&k.add("h2"),se==="h3"&&k.add("h3"),se==="ul"&&k.add("ul"),se==="ol"&&k.add("ol");const G=window.getComputedStyle(L);G.textAlign==="center"&&k.add("center"),G.textAlign==="right"&&k.add("right"),G.textAlign==="left"&&k.add("left");const oe=H=>{if(H.startsWith("#"))return H.toUpperCase();const Q=H.match(/\d+/g);if(!Q||Q.length<3)return null;const Y=Q[0],W=Q[1],ce=Q[2];if(!Y||!W||!ce)return null;const xe=parseInt(Y).toString(16).padStart(2,"0"),ke=parseInt(W).toString(16).padStart(2,"0"),Ae=parseInt(ce).toString(16).padStart(2,"0");return`#${xe}${ke}${Ae}`.toUpperCase()},Z=G.backgroundColor;if(Z&&Z!=="rgba(0, 0, 0, 0)"&&Z!=="transparent"&&Z!=="rgb(255, 255, 255)"&&Z!=="#ffffff"&&Z!=="#FFFFFF"){k.add("highlight");const H=oe(Z);if(H){const Q=zn.find(Y=>Y.value==="transparent"?!1:Y.value.toUpperCase()===H);g(Q?Q.value:H)}}else k.has("highlight")||g(null);const E=G.color,V=oe(E);if(E&&V&&E!=="rgba(0, 0, 0, 0)"&&V!=="#000000"){k.add("textColor");const H=zn.find(Q=>Q.value==="transparent"?!1:Q.value.toUpperCase()===V);w(H?H.value:V)}else k.has("textColor")||w(V==="#000000"||!V?"#000000":null);L=L.parentElement}}m(k)},[o]),j=p.useCallback((k,N)=>{if(!l.current)return;o||l.current.focus();const U=window.getSelection();if(!U||U.rangeCount===0){l.current.focus();return}document.execCommand(k,!1,N),l.current&&s(l.current.innerHTML),setTimeout(S,10)},[o,s,S]),P=p.useCallback(k=>{if(!l.current)return;o||l.current.focus();const N=window.getSelection();if(!N||N.rangeCount===0){l.current.focus();return}let U=!1;if(N.rangeCount>0){const se=N.getRangeAt(0).commonAncestorContainer;let G=null;for(se.nodeType===Node.TEXT_NODE?G=se.parentElement:G=se;G&&G!==l.current;){const Z=window.getComputedStyle(G).backgroundColor;if(Z&&Z!=="rgba(0, 0, 0, 0)"&&Z!=="transparent"&&Z!=="rgb(255, 255, 255)"&&Z!=="#ffffff"&&Z!=="#FFFFFF"){const V=(H=>{if(H.startsWith("#"))return H.toUpperCase();const Q=H.match(/\d+/g);if(!Q||Q.length<3)return null;const Y=Q[0],W=Q[1],ce=Q[2];if(!Y||!W||!ce)return null;const xe=parseInt(Y).toString(16).padStart(2,"0"),ke=parseInt(W).toString(16).padStart(2,"0"),Ae=parseInt(ce).toString(16).padStart(2,"0");return`#${xe}${ke}${Ae}`.toUpperCase()})(Z);if(V&&V===k.toUpperCase()){U=!0;break}}G=G.parentElement}}if(k==="transparent"||U){const L=N.getRangeAt(0);if(L.collapsed)document.execCommand("removeFormat",!1);else{const se=L.extractContents(),G=document.createDocumentFragment(),oe=Z=>{if(Z.nodeType===Node.TEXT_NODE)return Z.cloneNode(!0);if(Z.nodeType===Node.ELEMENT_NODE){const E=Z,V=document.createElement(E.tagName.toLowerCase());return Array.from(E.attributes).forEach(H=>{H.name!=="style"&&H.name!=="class"&&V.setAttribute(H.name,H.value)}),Array.from(E.childNodes).forEach(H=>{const Q=oe(H);Q&&V.appendChild(Q)}),E.style.backgroundColor&&(V.style.backgroundColor=""),V}return null};Array.from(se.childNodes).forEach(Z=>{const E=oe(Z);E&&G.appendChild(E)}),L.insertNode(G),document.execCommand("removeFormat",!1)}g(null),y("#FFEB3B")}else if(N.rangeCount>0&&!N.getRangeAt(0).collapsed)document.execCommand("backColor",!1,k),g(k),k!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(k)&&y(k);else return;const $=window.getSelection();$&&$.removeAllRanges(),l.current&&s(l.current.innerHTML),h(!1),setTimeout(()=>{l.current&&l.current.focus(),S()},50)},[o,s,S]),R=p.useCallback(k=>{if(!l.current)return;o||l.current.focus();const N=window.getSelection();if(!N||N.rangeCount===0){l.current.focus();return}let U=!1;if(N.rangeCount>0){const L=N.getRangeAt(0).commonAncestorContainer;let se=null;for(L.nodeType===Node.TEXT_NODE?se=L.parentElement:se=L;se&&se!==l.current;){const oe=window.getComputedStyle(se).color;if(oe){const E=(V=>{if(V.startsWith("#"))return V.toUpperCase();const H=V.match(/\d+/g);if(!H||H.length<3)return null;const Q=H[0],Y=H[1],W=H[2];if(!Q||!Y||!W)return null;const ce=parseInt(Q).toString(16).padStart(2,"0"),xe=parseInt(Y).toString(16).padStart(2,"0"),ke=parseInt(W).toString(16).padStart(2,"0");return`#${ce}${xe}${ke}`.toUpperCase()})(oe);if(k==="#000000"){if(E==="#000000"||!E){U=!0;break}}else if(E&&E===k.toUpperCase()){U=!0;break}}se=se.parentElement}}if(k==="transparent"||k==="default"||U){if(k==="#000000"&&U){v(!1);return}document.execCommand("removeFormat",!1),w(null),C("#000000")}else document.execCommand("foreColor",!1,k),w(k),k!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(k)&&C(k);l.current&&s(l.current.innerHTML),v(!1),setTimeout(S,10)},[o,s,S]),O=p.useCallback(()=>{l.current&&s(l.current.innerHTML),S()},[s,S]),F=p.useCallback(k=>{if(k.ctrlKey&&k.key==="b"){k.preventDefault(),j("bold");return}if(k.ctrlKey&&k.key==="i"){k.preventDefault(),j("italic");return}if(k.ctrlKey&&k.key==="u"){k.preventDefault(),j("underline");return}},[j]),M=p.useCallback(()=>{c(!0)},[]),B=p.useCallback(()=>{c(!1),l.current&&s(l.current.innerHTML)},[s]);return p.useEffect(()=>{if(!o)return;const k=()=>{S()};return document.addEventListener("selectionchange",k),()=>{document.removeEventListener("selectionchange",k)}},[o,S]),e.jsxs("div",{className:"relative border border-gray-300 rounded-md bg-white",children:[e.jsxs("div",{className:"flex items-center gap-1 p-2 border-b border-gray-200 bg-gray-50 rounded-t-md flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>j("bold"),title:"Bold (Ctrl+B)",children:e.jsx(m0,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>j("italic"),title:"Italic (Ctrl+I)",children:e.jsx(u0,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>j("underline"),title:"Underline (Ctrl+U)",children:e.jsx(x0,{className:"h-4 w-4"})}),e.jsxs(Zs,{open:u,onOpenChange:h,children:[e.jsx(Xs,{asChild:!0,children:e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("highlight")&&"bg-blue-100 text-blue-700"),title:"Text Highlight",children:e.jsx(h0,{className:"h-4 w-4"})})}),e.jsx(Qs,{className:"w-auto p-2",align:"start",onPointerDownOutside:k=>{k.target.closest("[data-popover-content]")&&k.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:k=>k.stopPropagation(),children:[e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:k=>{k.stopPropagation(),h(!1)},title:"Close",children:e.jsx(gt,{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:zn.map(k=>{const N=x===k.value,U=k.value==="transparent";return e.jsxs("button",{type:"button",onClick:$=>{$.preventDefault(),$.stopPropagation(),P(N&&!U?"transparent":k.value)},className:Re("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",k.class,N&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",U&&"border-gray-400 bg-white",!U&&!N&&"border-gray-300"),title:N&&!U?`${k.name} (Click to remove)`:k.name,style:U?{}:{backgroundColor:k.value},children:[U&&e.jsx("span",{className:"text-[10px] text-gray-600 font-bold",children:"×"}),N&&!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"})})]},k.value)})}),x&&x!=="transparent"&&e.jsx("div",{className:"mb-2",children:e.jsx(I,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:k=>{k.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:x&&x!=="transparent"?x:f,onChange:k=>{const N=k.target.value;y(N);const U=window.getSelection();U&&U.rangeCount>0&&!U.getRangeAt(0).collapsed&&P(N)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom color"}),e.jsx("input",{type:"text",value:x&&x!=="transparent"?x:f,onChange:k=>{k.stopPropagation();const N=k.target.value;y(N)},onKeyDown:k=>{if(k.stopPropagation(),k.key==="Enter"){k.preventDefault();const N=k.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(N)&&P(N)}},onPaste:k=>{k.stopPropagation();const N=k.clipboardData.getData("text").trim();k.preventDefault(),setTimeout(()=>{if(/^#[0-9A-Fa-f]{6}$/i.test(N)){y(N);const U=window.getSelection();U&&U.rangeCount>0&&!U.getRangeAt(0).collapsed&&P(N)}else{const U=N.match(/^([0-9A-Fa-f]{6})$/);if(U){const $=`#${U[1]}`;y($);const L=window.getSelection();L&&L.rangeCount>0&&!L.getRangeAt(0).collapsed&&P($)}}},0)},onClick:k=>{k.stopPropagation()},onFocus:k=>{k.stopPropagation(),k.target.select()},onBlur:k=>{const N=k.target.value.trim();if(/^#[0-9A-Fa-f]{6}$/i.test(N)){const U=window.getSelection();U&&U.rangeCount>0&&!U.getRangeAt(0).collapsed&&P(N)}else y(N===""?x||"#FFEB3B":N)},placeholder:"#FFEB3B",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply). Supports copy-paste.",autoComplete:"off",spellCheck:"false"}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{const k=f.trim();/^#[0-9A-Fa-f]{6}$/i.test(k)?P(k):y(x||"#FFEB3B")},title:"Apply custom color",children:"Apply"})]})]})]})})]}),e.jsxs(Zs,{open:b,onOpenChange:v,children:[e.jsx(Xs,{asChild:!0,children:e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("textColor")&&"bg-blue-100 text-blue-700"),title:"Text Color",children:e.jsx(p0,{className:"h-4 w-4"})})}),e.jsx(Qs,{className:"w-auto p-2",align:"start",onPointerDownOutside:k=>{k.target.closest("[data-popover-content]")&&k.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:k=>k.stopPropagation(),children:[e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:k=>{k.stopPropagation(),v(!1)},title:"Close",children:e.jsx(gt,{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:k=>{k.preventDefault(),k.stopPropagation(),A==="#000000"||!A&&!d.has("textColor")||R("#000000")},className:Re("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center bg-black",(A==="#000000"||!A&&!d.has("textColor"))&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",A!=="#000000"&&(A||d.has("textColor"))&&"border-gray-300"),title:"Default (Black)",children:[e.jsx("span",{className:"text-[10px] text-white font-bold",children:"A"}),(A==="#000000"||!A&&!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"})})]}),zn.filter(k=>k.value!=="transparent").map(k=>{const N=A===k.value;return e.jsxs("button",{type:"button",onClick:U=>{U.preventDefault(),U.stopPropagation(),R(N?"#000000":k.value)},className:Re("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center relative",N&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",!N&&"border-gray-300"),title:N?`${k.name} (Click to reset to default)`:k.name,style:{color:k.value,borderColor:N?"#2563eb":k.value},children:[e.jsx("span",{className:"text-xs font-bold",children:"A"}),N&&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-${k.value}`)})]}),A&&A!=="#000000"&&e.jsx("div",{className:"mb-2",children:e.jsx(I,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:k=>{k.stopPropagation(),R("#000000")},title:"Reset to default black",children:"Reset to Default"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:A||T,onChange:k=>{const N=k.target.value;C(N),R(N)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom text color"}),e.jsx("input",{type:"text",value:A||T,onChange:k=>{const N=k.target.value;C(N)},onKeyDown:k=>{if(k.key==="Enter"){k.preventDefault();const N=k.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(N)&&R(N)}},onBlur:k=>{const N=k.target.value;/^#[0-9A-Fa-f]{6}$/.test(N)?R(N):N===""&&C(A||"#000000")},placeholder:"#000000",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply)"}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>R(T),title:"Apply custom text color",children:"Apply"})]})]})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>j("formatBlock","<h1>"),title:"Heading 1",children:e.jsx(g0,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>j("formatBlock","<h2>"),title:"Heading 2",children:e.jsx(f0,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>j("formatBlock","<h3>"),title:"Heading 3",children:e.jsx(y0,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>j("insertUnorderedList"),title:"Bullet List",children:e.jsx(cx,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>j("insertOrderedList"),title:"Numbered List",children:e.jsx(b0,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>j("justifyLeft"),title:"Align Left",children:e.jsx(ux,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>j("justifyCenter"),title:"Align Center",children:e.jsx(v0,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>j("justifyRight"),title:"Align Right",children:e.jsx(j0,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:l,contentEditable:!0,onPaste:D,onInput:O,onFocus:M,onBlur:B,onKeyDown:F,onMouseUp:S,onKeyUp:S,"data-placeholder":a,className:Re("w-full rounded-b-md border-0 px-3 py-2 text-base transition-all outline-none","bg-white text-gray-900","min-h-[120px]","overflow-y-auto","overflow-x-auto","md:overflow-x-visible","md:text-sm","empty:before:content-[attr(data-placeholder)] empty:before:text-muted-foreground empty:before:pointer-events-none","focus-visible:outline-none","[&_ul]:list-disc [&_ul]:ml-6 [&_ul]:my-2 [&_ul]:list-outside","[&_ol]:list-decimal [&_ol]:ml-6 [&_ol]:my-2 [&_ol]:list-outside","[&_li]:my-1 [&_li]:pl-2","[&_.table-wrapper]:overflow-x-auto [&_.table-wrapper]:max-w-full [&_.table-wrapper]:my-2","[&_.table-wrapper_table]:border-collapse [&_.table-wrapper_table]:border [&_.table-wrapper_table]:border-gray-300 [&_.table-wrapper_table]:min-w-full","[&_.table-wrapper_table_td]:border [&_.table-wrapper_table_td]:border-gray-300 [&_.table-wrapper_table_td]:px-3 [&_.table-wrapper_table_td]:py-2 [&_.table-wrapper_table_td]:text-sm [&_.table-wrapper_table_td]:whitespace-nowrap","[&_.table-wrapper_table_th]:border [&_.table-wrapper_table_th]:border-gray-300 [&_.table-wrapper_table_th]:px-3 [&_.table-wrapper_table_th]:py-2 [&_.table-wrapper_table_th]:bg-gray-50 [&_.table-wrapper_table_th]:font-semibold [&_.table-wrapper_table_th]:text-sm [&_.table-wrapper_table_th]:text-left [&_.table-wrapper_table_th]:whitespace-nowrap","[&_.table-wrapper_table_tr:nth-child(even)]:bg-gray-50","[&_table]:border-collapse [&_table]:my-2 [&_table]:border [&_table]:border-gray-300 [&_table]:w-full","[&_table_td]:border [&_table_td]:border-gray-300 [&_table_td]:px-3 [&_table_td]:py-2 [&_table_td]:text-sm","[&_table_th]:border [&_table_th]:border-gray-300 [&_table_th]:px-3 [&_table_th]:py-2 [&_table_th]:bg-gray-50 [&_table_th]:font-semibold [&_table_th]:text-sm [&_table_th]:text-left","[&_table_tr:nth-child(even)]:bg-gray-50","[&_p]:my-1 [&_p]:leading-relaxed","[&_strong]:font-bold","[&_em]:italic","[&_u]:underline","[&_span[style*='background']]:px-0.5 [&_span[style*='background']]:rounded","[&_h1]:text-xl [&_h1]:font-bold [&_h1]:my-2","[&_h2]:text-lg [&_h2]:font-semibold [&_h2]:my-2","[&_h3]:text-base [&_h3]:font-semibold [&_h3]:my-1",r),style:{minHeight:n},...i})]})}function na({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" style="overflow-x: auto; max-width: 100%; margin: 8px 0;">${i}</div>`),r},[t]);return t?e.jsx("div",{className:Re("text-sm text-gray-700 max-w-none","overflow-x-auto","md:overflow-x-visible","[&_ul]:list-disc [&_ul]:ml-6 [&_ul]:my-2 [&_ul]:list-outside","[&_ol]:list-decimal [&_ol]:ml-6 [&_ol]:my-2 [&_ol]:list-outside","[&_li]:my-1 [&_li]:pl-2","[&_.table-wrapper]:overflow-x-auto [&_.table-wrapper]:max-w-full [&_.table-wrapper]:my-2 [&_.table-wrapper]:-mx-2 [&_.table-wrapper]:px-2","[&_.table-wrapper_table]:border-collapse [&_.table-wrapper_table]:border [&_.table-wrapper_table]:border-gray-300 [&_.table-wrapper_table]:min-w-full","[&_.table-wrapper_table_td]:border [&_.table-wrapper_table_td]:border-gray-300 [&_.table-wrapper_table_td]:px-3 [&_.table-wrapper_table_td]:py-2 [&_.table-wrapper_table_td]:text-sm [&_.table-wrapper_table_td]:whitespace-nowrap","[&_.table-wrapper_table_th]:border [&_.table-wrapper_table_th]:border-gray-300 [&_.table-wrapper_table_th]:px-3 [&_.table-wrapper_table_th]:py-2 [&_.table-wrapper_table_th]:bg-gray-50 [&_.table-wrapper_table_th]:font-semibold [&_.table-wrapper_table_th]:text-sm [&_.table-wrapper_table_th]:text-left [&_.table-wrapper_table_th]:whitespace-nowrap","[&_.table-wrapper_table_tr:nth-child(even)]:bg-gray-50","[&_table]:border-collapse [&_table]:my-2 [&_table]:border [&_table]:border-gray-300","[&_table_td]:border [&_table_td]:border-gray-300 [&_table_td]:px-3 [&_table_td]:py-2 [&_table_td]:text-sm","[&_table_th]:border [&_table_th]:border-gray-300 [&_table_th]:px-3 [&_table_th]:py-2 [&_table_th]:bg-gray-50 [&_table_th]:font-semibold [&_table_th]:text-sm [&_table_th]:text-left","[&_table_tr:nth-child(even)]:bg-gray-50","[&_p]:my-1 [&_p]:leading-relaxed","[&_strong]:font-bold","[&_em]:italic","[&_u]:underline","[&_h1]:text-xl [&_h1]:font-bold [&_h1]:my-2","[&_h2]:text-lg [&_h2]:font-semibold [&_h2]:my-2","[&_h3]:text-base [&_h3]:font-semibold [&_h3]:my-1",s),dangerouslySetInnerHTML:{__html:a}}):null}var xh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Ai,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",l="second",o="minute",c="hour",d="day",m="week",u="month",h="quarter",x="year",g="date",f="Invalid Date",y=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,b=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,v={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(F){var M=["th","st","nd","rd"],B=F%100;return"["+F+(M[(B-20)%10]||M[B]||M[0])+"]"}},A=function(F,M,B){var k=String(F);return!k||k.length>=M?F:""+Array(M+1-k.length).join(B)+F},w={s:A,z:function(F){var M=-F.utcOffset(),B=Math.abs(M),k=Math.floor(B/60),N=B%60;return(M<=0?"+":"-")+A(k,2,"0")+":"+A(N,2,"0")},m:function F(M,B){if(M.date()<B.date())return-F(B,M);var k=12*(B.year()-M.year())+(B.month()-M.month()),N=M.clone().add(k,u),U=B-N<0,$=M.clone().add(k+(U?-1:1),u);return+(-(k+(B-N)/(U?N-$:$-N))||0)},a:function(F){return F<0?Math.ceil(F)||0:Math.floor(F)},p:function(F){return{M:u,y:x,w:m,d,D:g,h:c,m:o,s:l,ms:i,Q:h}[F]||String(F||"").toLowerCase().replace(/s$/,"")},u:function(F){return F===void 0}},T="en",C={};C[T]=v;var _="$isDayjsObject",D=function(F){return F instanceof R||!(!F||!F[_])},S=function F(M,B,k){var N;if(!M)return T;if(typeof M=="string"){var U=M.toLowerCase();C[U]&&(N=U),B&&(C[U]=B,N=U);var $=M.split("-");if(!N&&$.length>1)return F($[0])}else{var L=M.name;C[L]=M,N=L}return!k&&N&&(T=N),N||!k&&T},j=function(F,M){if(D(F))return F.clone();var B=typeof M=="object"?M:{};return B.date=F,B.args=arguments,new R(B)},P=w;P.l=S,P.i=D,P.w=function(F,M){return j(F,{locale:M.$L,utc:M.$u,x:M.$x,$offset:M.$offset})};var R=function(){function F(B){this.$L=S(B.locale,null,!0),this.parse(B),this.$x=this.$x||B.x||{},this[_]=!0}var M=F.prototype;return M.parse=function(B){this.$d=function(k){var N=k.date,U=k.utc;if(N===null)return new Date(NaN);if(P.u(N))return new Date;if(N instanceof Date)return new Date(N);if(typeof N=="string"&&!/Z$/i.test(N)){var $=N.match(y);if($){var L=$[2]-1||0,se=($[7]||"0").substring(0,3);return U?new Date(Date.UTC($[1],L,$[3]||1,$[4]||0,$[5]||0,$[6]||0,se)):new Date($[1],L,$[3]||1,$[4]||0,$[5]||0,$[6]||0,se)}}return new Date(N)}(B),this.init()},M.init=function(){var B=this.$d;this.$y=B.getFullYear(),this.$M=B.getMonth(),this.$D=B.getDate(),this.$W=B.getDay(),this.$H=B.getHours(),this.$m=B.getMinutes(),this.$s=B.getSeconds(),this.$ms=B.getMilliseconds()},M.$utils=function(){return P},M.isValid=function(){return this.$d.toString()!==f},M.isSame=function(B,k){var N=j(B);return this.startOf(k)<=N&&N<=this.endOf(k)},M.isAfter=function(B,k){return j(B)<this.startOf(k)},M.isBefore=function(B,k){return this.endOf(k)<j(B)},M.$g=function(B,k,N){return P.u(B)?this[k]:this.set(N,B)},M.unix=function(){return Math.floor(this.valueOf()/1e3)},M.valueOf=function(){return this.$d.getTime()},M.startOf=function(B,k){var N=this,U=!!P.u(k)||k,$=P.p(B),L=function(Q,Y){var W=P.w(N.$u?Date.UTC(N.$y,Y,Q):new Date(N.$y,Y,Q),N);return U?W:W.endOf(d)},se=function(Q,Y){return P.w(N.toDate()[Q].apply(N.toDate("s"),(U?[0,0,0,0]:[23,59,59,999]).slice(Y)),N)},G=this.$W,oe=this.$M,Z=this.$D,E="set"+(this.$u?"UTC":"");switch($){case x:return U?L(1,0):L(31,11);case u:return U?L(1,oe):L(0,oe+1);case m:var V=this.$locale().weekStart||0,H=(G<V?G+7:G)-V;return L(U?Z-H:Z+(6-H),oe);case d:case g:return se(E+"Hours",0);case c:return se(E+"Minutes",1);case o:return se(E+"Seconds",2);case l:return se(E+"Milliseconds",3);default:return this.clone()}},M.endOf=function(B){return this.startOf(B,!1)},M.$set=function(B,k){var N,U=P.p(B),$="set"+(this.$u?"UTC":""),L=(N={},N[d]=$+"Date",N[g]=$+"Date",N[u]=$+"Month",N[x]=$+"FullYear",N[c]=$+"Hours",N[o]=$+"Minutes",N[l]=$+"Seconds",N[i]=$+"Milliseconds",N)[U],se=U===d?this.$D+(k-this.$W):k;if(U===u||U===x){var G=this.clone().set(g,1);G.$d[L](se),G.init(),this.$d=G.set(g,Math.min(this.$D,G.daysInMonth())).$d}else L&&this.$d[L](se);return this.init(),this},M.set=function(B,k){return this.clone().$set(B,k)},M.get=function(B){return this[P.p(B)]()},M.add=function(B,k){var N,U=this;B=Number(B);var $=P.p(k),L=function(oe){var Z=j(U);return P.w(Z.date(Z.date()+Math.round(oe*B)),U)};if($===u)return this.set(u,this.$M+B);if($===x)return this.set(x,this.$y+B);if($===d)return L(1);if($===m)return L(7);var se=(N={},N[o]=r,N[c]=n,N[l]=a,N)[$]||1,G=this.$d.getTime()+B*se;return P.w(G,this)},M.subtract=function(B,k){return this.add(-1*B,k)},M.format=function(B){var k=this,N=this.$locale();if(!this.isValid())return N.invalidDate||f;var U=B||"YYYY-MM-DDTHH:mm:ssZ",$=P.z(this),L=this.$H,se=this.$m,G=this.$M,oe=N.weekdays,Z=N.months,E=N.meridiem,V=function(Y,W,ce,xe){return Y&&(Y[W]||Y(k,U))||ce[W].slice(0,xe)},H=function(Y){return P.s(L%12||12,Y,"0")},Q=E||function(Y,W,ce){var xe=Y<12?"AM":"PM";return ce?xe.toLowerCase():xe};return U.replace(b,function(Y,W){return W||function(ce){switch(ce){case"YY":return String(k.$y).slice(-2);case"YYYY":return P.s(k.$y,4,"0");case"M":return G+1;case"MM":return P.s(G+1,2,"0");case"MMM":return V(N.monthsShort,G,Z,3);case"MMMM":return V(Z,G);case"D":return k.$D;case"DD":return P.s(k.$D,2,"0");case"d":return String(k.$W);case"dd":return V(N.weekdaysMin,k.$W,oe,2);case"ddd":return V(N.weekdaysShort,k.$W,oe,3);case"dddd":return oe[k.$W];case"H":return String(L);case"HH":return P.s(L,2,"0");case"h":return H(1);case"hh":return H(2);case"a":return Q(L,se,!0);case"A":return Q(L,se,!1);case"m":return String(se);case"mm":return P.s(se,2,"0");case"s":return String(k.$s);case"ss":return P.s(k.$s,2,"0");case"SSS":return P.s(k.$ms,3,"0");case"Z":return $}return null}(Y)||$.replace(":","")})},M.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},M.diff=function(B,k,N){var U,$=this,L=P.p(k),se=j(B),G=(se.utcOffset()-this.utcOffset())*r,oe=this-se,Z=function(){return P.m($,se)};switch(L){case x:U=Z()/12;break;case u:U=Z();break;case h:U=Z()/3;break;case m:U=(oe-G)/6048e5;break;case d:U=(oe-G)/864e5;break;case c:U=oe/n;break;case o:U=oe/r;break;case l:U=oe/a;break;default:U=oe}return N?U:P.a(U)},M.daysInMonth=function(){return this.endOf(u).$D},M.$locale=function(){return C[this.$L]},M.locale=function(B,k){if(!B)return this.$L;var N=this.clone(),U=S(B,k,!0);return U&&(N.$L=U),N},M.clone=function(){return P.w(this.$d,this)},M.toDate=function(){return new Date(this.valueOf())},M.toJSON=function(){return this.isValid()?this.toISOString():null},M.toISOString=function(){return this.$d.toISOString()},M.toString=function(){return this.$d.toUTCString()},F}(),O=R.prototype;return j.prototype=O,[["$ms",i],["$s",l],["$m",o],["$H",c],["$W",d],["$M",u],["$y",x],["$D",g]].forEach(function(F){O[F[1]]=function(M){return this.$g(M,F[0],F[1])}}),j.extend=function(F,M){return F.$i||(F(M,R,j),F.$i=!0),j},j.locale=S,j.isDayjs=D,j.unix=function(F){return j(1e3*F)},j.en=C[T],j.Ls=C,j.p={},j})})(xh);var bN=xh.exports;const Gt=Si(bN);var hh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Ai,function(){return function(a,r,n){a=a||{};var i=r.prototype,l={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function o(d,m,u,h){return i.fromToBase(d,m,u,h)}n.en.relativeTime=l,i.fromToBase=function(d,m,u,h,x){for(var g,f,y,b=u.$locale().relativeTime||l,v=a.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],A=v.length,w=0;w<A;w+=1){var T=v[w];T.d&&(g=h?n(d).diff(u,T.d,!0):u.diff(d,T.d,!0));var C=(a.rounding||Math.round)(Math.abs(g));if(y=g>0,C<=T.r||!T.r){C<=1&&w>0&&(T=v[w-1]);var _=b[T.l];x&&(C=x(""+C)),f=typeof _=="string"?_.replace("%d",C):_(C,m,T.l,y);break}}if(m)return f;var D=y?b.future:b.past;return typeof D=="function"?D(f):D.replace("%s",f)},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)}}})})(hh);var vN=hh.exports;const jN=Si(vN);Gt.extend(jN);function NN({request:t,isInitiator:s,needsClosure:a,conclusionRemark:r,setConclusionRemark:n,conclusionLoading:i,conclusionSubmitting:l,aiGenerated:o,handleGenerateConclusion:c,handleFinalizeConclusion:d,onPause:m,onResume:u,onRetrigger:h,currentUserIsApprover:x=!1,pausedByUserId:g,currentUserId:f,generationAttempts:y=0,generationFailed:b=!1,maxAttemptsReached:v=!1}){var j,P,R,O,F,M,B,k;const{user:A}=Qt(),w=t==null?void 0:t.pauseInfo,T=(w==null?void 0:w.isPaused)||!1,C=(j=w==null?void 0:w.pausedBy)==null?void 0:j.userId,_=(A==null?void 0:A.userId)||"",D=T&&u&&(x||s),S=T&&s&&C&&C!==_&&h;return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[e.jsxs(J,{"data-testid":"initiator-card",children:[e.jsx(me,{className:"pb-3 sm:pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Lt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(q,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(es,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(ts,{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(Ia,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((M=t.initiator)==null?void 0:M.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(Di,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((B=t.initiator)==null?void 0:B.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(J,{"data-testid":"request-details-card",children:[e.jsx(me,{className:"pb-3 sm:pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(De,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(q,{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(na,{content:t.description||"",className:"text-xs sm:text-sm"})})]}),(t.category||t.subcategory)&&e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t border-gray-300",children:[t.category&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Category"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.category})]}),t.subcategory&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Subcategory"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.subcategory})]})]}),t.amount&&e.jsxs("div",{className:"pt-4 border-t border-gray-300",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Amount"}),e.jsx("p",{className:"text-lg font-bold text-gray-900 mt-1",children:t.amount})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t border-gray-300",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Created"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:is(t.createdAt)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Last Updated"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:is(t.updatedAt)})]})]})]})]}),T&&w&&e.jsxs(J,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(me,{className:"pb-3 sm:pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(Ka,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(q,{className:"space-y-3 sm:space-y-4",children:[e.jsx("div",{className:"bg-white rounded-lg p-3 sm:p-4 border border-orange-200",children:e.jsxs("div",{className:"space-y-2 sm:space-y-3",children:[w.pauseReason&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Reason"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:w.pauseReason})]}),w.pausedBy&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused By"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:w.pausedBy.name||w.pausedBy.email})]}),w.pauseResumeDate&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Auto-Resume Date"}),e.jsxs("p",{className:"text-sm text-gray-900 mt-1",children:[is(w.pauseResumeDate),Gt(w.pauseResumeDate).isAfter(Gt())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",Gt(w.pauseResumeDate).fromNow(),")"]})]})]}),w.pausedAt&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused At"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:is(w.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[D&&u&&e.jsxs(I,{onClick:u,className:"bg-green-600 hover:bg-green-700 text-white text-xs sm:text-sm h-8 sm:h-9",size:"sm",children:[e.jsx(ui,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),S&&h&&e.jsxs(I,{onClick:h,variant:"outline",className:"border-orange-300 text-orange-700 hover:bg-orange-50 text-xs sm:text-sm h-8 sm:h-9",size:"sm",children:[e.jsx(Ve,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Request Resume"]})]})]})]}),t.claimDetails&&e.jsxs(J,{children:[e.jsx(me,{className:"pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(De,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(q,{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?uh(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(na,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(J,{children:[e.jsxs(me,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(Pe,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(Te,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(q,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(na,{content:t.conclusionRemark||"",className:"text-sm"})}),t.closureDate&&e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-gray-500 border-t border-gray-200 pt-3",children:[e.jsxs("span",{children:["Request closed on ",is(t.closureDate)]}),e.jsxs("span",{children:["By ",((k=t.initiator)==null?void 0:k.name)||"Initiator"]})]})]})]}),a&&e.jsxs(J,{"data-testid":"conclusion-remark-card",children:[e.jsx(me,{className:`bg-gradient-to-r border-b ${t.status==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(Pe,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(Te,{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(I,{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(zt,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),o?"Regenerate":"Generate with AI"]}),o&&!v&&!b&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-y," attempts remaining"]})]})]})}),e.jsx(q,{className:"pt-4",children:i?e.jsx("div",{className:"flex items-center justify-center py-8","data-testid":"conclusion-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ze,{className:"w-8 h-8 text-blue-600 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Preparing conclusion remark..."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Conclusion Remark"}),o&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),e.jsx(Fn,{value:r,onChange:N=>n(N),placeholder:"Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals...",className:"text-sm",minHeight:"160px","data-testid":"conclusion-remark-textarea"}),e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"This will be the final summary for this request"}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":"character-count",children:[r?r.replace(/<[^>]*>/g,"").length:0," / 2000 characters"]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-blue-900 mb-1.5",children:"Finalizing this request will:"}),e.jsxs("ul",{className:"text-xs sm:text-sm text-blue-800 space-y-0.5 pl-4",children:[e.jsx("li",{className:"list-disc",children:'Change request status to "CLOSED"'}),e.jsx("li",{className:"list-disc",children:"Notify all participants of closure"}),e.jsx("li",{className:"list-disc",children:"Move request to Closed Requests"}),e.jsx("li",{className:"list-disc",children:"Save conclusion remark permanently"})]})]}),e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(I,{onClick:d,disabled:l||!r.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:l?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function si({delayDuration:t=0,...s}){return e.jsx(Nf,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function pl({...t}){return e.jsx(si,{children:e.jsx(wf,{"data-slot":"tooltip",...t})})}function gl({...t}){return e.jsx(Cf,{"data-slot":"tooltip-trigger",...t})}function fl({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(Af,{children:e.jsxs(Sf,{"data-slot":"tooltip-content",sideOffset:s,className:Re("bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...r,children:[a,e.jsx(Tf,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function ht({...t}){return e.jsx(Df,{"data-slot":"dialog",...t})}function wN({...t}){return e.jsx(Rf,{"data-slot":"dialog-portal",...t})}const ph=p.forwardRef(({className:t,...s},a)=>e.jsx(Xu,{ref:a,"data-slot":"dialog-overlay",className:Re("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...s}));ph.displayName=Xu.displayName;const ct=p.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(wN,{"data-slot":"dialog-portal",children:[e.jsx(ph,{}),e.jsxs(Qu,{ref:r,"data-slot":"dialog-content",className:Re("bg-white data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...a,children:[s,e.jsxs(kf,{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(gt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));ct.displayName=Qu.displayName;const pt=p.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:Re("flex flex-col gap-2 text-center sm:text-left",t),...s}));pt.displayName="DialogHeader";const kt=p.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:Re("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));kt.displayName="DialogFooter";const dt=p.forwardRef(({className:t,...s},a)=>e.jsx(Ju,{ref:a,"data-slot":"dialog-title",className:Re("text-lg leading-none font-semibold",t),...s}));dt.displayName=Ju.displayName;const Et=p.forwardRef(({className:t,...s},a)=>e.jsx(qu,{ref:a,"data-slot":"dialog-description",className:Re("text-muted-foreground text-sm",t),...s}));Et.displayName=qu.displayName;function Ts({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:Re("resize-none border-gray-400 placeholder:text-muted-foreground bg-white text-gray-900 flex field-sizing-content min-h-16 w-full rounded-md border px-3 py-2 text-base transition-all outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","hover:border-gray-500","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...s})}const um=t=>{if(t<8)return Ot(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${Ot(r)}`:`${a}d`},CN=(t,s)=>{if(s)return e.jsx(Ve,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(Pe,{className:"w-4 h-4 sm:w-5 sm:w-5 text-green-600"});case"rejected":return e.jsx(Nt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"paused":return e.jsx(xx,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(Xe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(Xe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(Xe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function AN({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}=Qt(),[m,u]=p.useState(!1),[h,x]=p.useState(""),[g,f]=p.useState(!1),y=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";p.useEffect(()=>{m||x("")},[m]);const b=t.status==="pending"||t.status==="in-review",v=t.status==="approved",A=t.status==="rejected",w=t.status==="waiting",T=t.status==="paused",C=Number(t.tatHours||0),_=t.actualHours??0,D=v&&_?Math.max(0,C-_):0,S=C>0?_/C*100:0,j=S>=100,P=(d==null?void 0:d.role)==="ADMIN",R=Ui(d),O=t.approverId===(d==null?void 0:d.userId),F=P||R||O,M=async()=>{var B,k;if(!h.trim()){K.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}f(!0);try{await gN(t.levelId,h.trim()),u(!1),x(""),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(N){console.error("Error updating breach reason:",N);const U=((k=(B=N==null?void 0:N.response)==null?void 0:B.data)==null?void 0:k.error)||(N==null?void 0:N.message)||"Failed to update breach reason. Please try again.";K.error("Failed to Update Breach Reason",{description:U,duration:5e3})}finally{f(!1)}};return e.jsxs("div",{className:`relative p-3 sm:p-4 md:p-5 rounded-lg border-2 transition-all ${t.isSkipped?"border-orange-500 bg-orange-50":b?"border-blue-500 bg-blue-50 shadow-md":v?"border-green-500 bg-green-50":A?"border-red-500 bg-red-50":w?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${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":T?"bg-yellow-100":b?"bg-blue-100":v?"bg-green-100":A?"bg-red-100":w?"bg-gray-200":"bg-gray-100"}`,children:CN(t.status,t.isSkipped)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2 sm:gap-4 mb-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs("h4",{className:"font-semibold text-gray-900 text-base sm:text-lg","data-testid":`${c}-approver-label`,children:["Approver ",s+1]}),e.jsx(ie,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":b?"bg-yellow-100 text-yellow-800 border-yellow-200":v?"bg-green-100 text-green-800 border-green-200":A?"bg-red-100 text-red-800 border-red-200":w?"bg-gray-200 text-gray-600 border-gray-300":"bg-gray-100 text-gray-800 border-gray-200"}`,"data-testid":`${c}-status-badge`,children:t.isSkipped?"skipped":t.status}),t.isSkipped&&t.skipReason&&e.jsx(si,{delayDuration:200,children:e.jsxs(pl,{children:[e.jsx(gl,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:B=>B.stopPropagation(),children:e.jsx(Ve,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(fl,{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(Bd,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),v&&_&&e.jsx(ie,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:um(_)})]}),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:[C," 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?is(t.timestamp):"N/A"})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Completed in:"}),e.jsx("span",{className:"font-medium text-gray-900",children:um(_)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const B=Math.min(100,S),k=()=>j?"bg-red-600":S>=75?"bg-orange-500":S>=50?"bg-amber-500":"bg-green-600",N=()=>j?"text-red-600":S>=75?"text-orange-600":S>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(oa,{value:B,className:"h-2 bg-gray-200",indicatorClassName:k(),"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 ${N()}`,children:[Math.round(B),"% of TAT used"]}),j&&F&&e.jsx(si,{children:e.jsxs(pl,{children:[e.jsx(gl,{asChild:!0,children:e.jsx(I,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{x(y),u(!0)},children:e.jsx(Vn,{className:"w-3 h-3"})})}),e.jsx(fl,{children:e.jsx("p",{children:y?"Edit breach reason":"Add breach reason"})})]})})]}),D>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",Ot(D)]})]})]})})()}),j&&y&&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(Vn,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:y})]}),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(Is,{className:"w-3.5 h-3.5 text-blue-600"}),"Conclusion Remark:"]}),e.jsx("p",{className:"text-sm text-gray-700 italic leading-relaxed",children:t.comment})]})]}),i&&(b||T)&&(a==null?void 0:a.sla)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Due by:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.deadline?pa(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${T?"bg-gray-100 border-gray-300":(a.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(a.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(a.sla.percentageUsed||0)>=50?"bg-amber-50 border-amber-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",T&&"(Paused)"]}),e.jsxs("div",{className:"space-y-2 text-xs mb-3",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time elapsed since assigned:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.elapsedText})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time used:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[a.sla.elapsedText," / ",Ot(C)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const B=a.sla.percentageUsed||0,k=()=>T?"bg-gray-500":B>=100?"bg-red-600":B>=75?"bg-orange-500":B>=50?"bg-amber-500":"bg-green-600",N=()=>T?"text-gray-600":B>=100?"text-red-600":B>=75?"text-orange-600":B>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(oa,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:k(),"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 ${N()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&F&&e.jsx(si,{children:e.jsxs(pl,{children:[e.jsx(gl,{asChild:!0,children:e.jsx(I,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{x(y),u(!0)},children:e.jsx(Vn,{className:"w-3 h-3"})})}),e.jsx(fl,{children:e.jsx("p",{children:y?"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(xi,{className:"w-4 h-4"}),"Deadline Breached"]}),y&&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(Vn,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:y})]})]}),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(ss,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),w&&e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"bg-gray-100 border border-gray-300 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-gray-600 mb-1 flex items-center gap-1.5",children:[e.jsx(xx,{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 ",C," hours for approval"]})]})}),A&&t.comment&&e.jsxs("div",{className:"mt-3 p-3 sm:p-4 bg-red-50 border-l-4 border-red-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 mb-2 flex items-center gap-1.5",children:[e.jsx(Nt,{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(Bd,{className:"w-3.5 h-3.5"}),"Skip Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed",children:t.skipReason}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Skipped on ",is(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((B,k)=>{var N,U,$,L,se,G;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${B.isBreached?"bg-red-50 border-red-200":(B.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${k}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(B.thresholdPercentage||0)===50&&e.jsx(N0,{className:"w-5 h-5 text-yellow-600"}),(B.thresholdPercentage||0)===75&&e.jsx(ss,{className:"w-5 h-5 text-orange-600"}),(B.thresholdPercentage||0)===100&&e.jsx(xi,{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 ",k+1," - ",B.thresholdPercentage||0,"% TAT"]}),e.jsx(ie,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${B.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:B.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[B.thresholdPercentage||0,"% of SLA breach reminder have been sent"]}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-1.5 sm:gap-2 text-[10px] sm:text-xs",children:[e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Allocated:"}),e.jsx("span",{className:"ml-1 font-medium text-gray-900",children:Ot(Number(B.tatHoursAllocated||0))})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Elapsed:"}),e.jsxs("span",{className:"ml-1 font-medium text-gray-900",children:[Ot(Number(B.tatHoursElapsed||0)),((N=B.metadata)==null?void 0:N.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(B.tatHoursElapsed||0)*60).toFixed(0),"m)"]})]})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Remaining:"}),e.jsxs("span",{className:`ml-1 font-medium ${(B.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[Ot(Number(B.tatHoursRemaining||0)),((U=B.metadata)==null?void 0:U.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(B.tatHoursRemaining||0)*60).toFixed(0),"m)"]})]})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Due by:"}),e.jsx("span",{className:"ml-1 font-medium text-gray-900",children:B.expectedCompletionTime?pa(B.expectedCompletionTime,!0):"N/A"})]})]}),e.jsxs("div",{className:"mt-2 pt-2 border-t border-gray-200",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1",children:[e.jsx("p",{className:"text-[10px] sm:text-xs text-gray-500",children:"Reminder sent by system automatically"}),((($=B.metadata)==null?void 0:$.testMode)||((L=B.metadata)==null?void 0:L.tatTestMode))&&e.jsx(ie,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-300 text-[10px] px-1.5 py-0 shrink-0",children:"TEST MODE"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs text-gray-600 font-medium mt-0.5",children:["Sent at: ",B.alertSentAt?is(B.alertSentAt):"N/A"]}),(((se=B.metadata)==null?void 0:se.testMode)||((G=B.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)"})]})]})]})},k)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[v?"Approved":A?"Rejected":"Actioned"," on ",is(t.timestamp)]}),n&&!T&&(b||t.status==="pending")&&!v&&!A&&t.levelId&&l&&e.jsxs("div",{className:"mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-200",children:[e.jsxs(I,{variant:"outline",size:"sm",className:"w-full border-orange-300 text-orange-700 hover:bg-orange-50 h-9 sm:h-10 text-xs sm:text-sm",onClick:()=>l({levelId:t.levelId,approverName:t.approver,levelNumber:t.step}),"data-testid":`${c}-skip-button`,children:[e.jsx(Ve,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Skip This Approver"]}),e.jsx("p",{className:"text-[10px] sm:text-xs text-gray-500 mt-1 text-center",children:T?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(ht,{open:m,onOpenChange:u,children:e.jsxs(ct,{className:"sm:max-w-[500px]",children:[e.jsxs(pt,{children:[e.jsx(dt,{children:y?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(Et,{children:y?"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(Ts,{placeholder:"Enter the reason for the breach...",value:h,onChange:B=>x(B.target.value),className:"min-h-[100px]",maxLength:500}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[h.length,"/500 characters"]})]}),e.jsxs(kt,{children:[e.jsx(I,{variant:"outline",onClick:()=>{u(!1),x("")},disabled:g,children:"Cancel"}),e.jsx(I,{onClick:M,disabled:!h.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function SN({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(J,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ys,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(Te,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var x;const i=t.totalSteps||1,l=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,o=((x=t.approvalFlow)==null?void 0:x.filter(g=>{const f=(g.status||"").toLowerCase();return f==="approved"||f==="rejected"}).length)||0,c=o>=i,d=(t.status||"").toLowerCase(),m=d==="approved"||d==="rejected"||d==="closed",u=l>i,h=Math.min(Math.max(1,l),i);return u?e.jsxs(ie,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0 bg-blue-50 text-blue-700 border-blue-200",children:["Closure Step - ",o," of ",i," steps completed"]}):m||c?e.jsxs(ie,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0 bg-green-50 text-green-700 border-green-200",children:["Completed - ",o," of ",i," steps"]}):e.jsxs(ie,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",h," of ",i," - ",o," completed"]})})()]})}),e.jsx(q,{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 x,g,f;const o=(x=t.approvals)==null?void 0:x.find(y=>y.levelId===i.levelId),c=(g=s==null?void 0:s.email)==null?void 0:g.toLowerCase(),d=(f=i.approverEmail)==null?void 0:f.toLowerCase(),m=c&&d&&c===d,u=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,h=i.step===u;return e.jsx(AN,{step:i,index:l,approval:o,isCurrentUser:m,isInitiator:a,isCurrentLevel:h,onSkipApprover:r,onRefresh:n,testId:"workflow-step"},l)})}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-workflow-steps",children:"No workflow steps defined"})})]})}const zo=p.createContext({});function Ho(t){const s=p.useRef(null);return s.current===null&&(s.current=t()),s.current}const Wo=typeof window<"u",gh=Wo?p.useLayoutEffect:p.useEffect,Hi=p.createContext(null);function Go(t,s){t.indexOf(s)===-1&&t.push(s)}function Ko(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const Fa=(t,s,a)=>a>s?s:a<t?t:a;let Yo=()=>{};const Ma={},fh=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function yh(t){return typeof t=="object"&&t!==null}const bh=t=>/^0[^.\s]+$/u.test(t);function Zo(t){let s;return()=>(s===void 0&&(s=t()),s)}const ia=t=>t,TN=(t,s)=>a=>s(t(a)),Mn=(...t)=>t.reduce(TN),Nn=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class Xo{constructor(){this.subscriptions=[]}add(s){return Go(this.subscriptions,s),()=>Ko(this.subscriptions,s)}notify(s,a,r){const n=this.subscriptions.length;if(n)if(n===1)this.subscriptions[0](s,a,r);else for(let i=0;i<n;i++){const l=this.subscriptions[i];l&&l(s,a,r)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const ja=t=>t*1e3,ra=t=>t/1e3;function vh(t,s){return s?t*(1e3/s):0}const jh=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,kN=1e-7,RN=12;function DN(t,s,a,r,n){let i,l,o=0;do l=s+(a-s)/2,i=jh(l,r,n)-t,i>0?a=l:s=l;while(Math.abs(i)>kN&&++o<RN);return l}function _n(t,s,a,r){if(t===s&&a===r)return ia;const n=i=>DN(i,0,1,t,a);return i=>i===0||i===1?i:jh(n(i),s,r)}const Nh=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,wh=t=>s=>1-t(1-s),Ch=_n(.33,1.53,.69,.99),Qo=wh(Ch),Ah=Nh(Qo),Sh=t=>(t*=2)<1?.5*Qo(t):.5*(2-Math.pow(2,-10*(t-1))),Jo=t=>1-Math.sin(Math.acos(t)),Th=wh(Jo),kh=Nh(Jo),PN=_n(.42,0,1,1),IN=_n(0,0,.58,1),Rh=_n(.42,0,.58,1),EN=t=>Array.isArray(t)&&typeof t[0]!="number",Dh=t=>Array.isArray(t)&&typeof t[0]=="number",FN={linear:ia,easeIn:PN,easeInOut:Rh,easeOut:IN,circIn:Jo,circInOut:kh,circOut:Th,backIn:Qo,backInOut:Ah,backOut:Ch,anticipate:Sh},MN=t=>typeof t=="string",xm=t=>{if(Dh(t)){Yo(t.length===4);const[s,a,r,n]=t;return _n(s,a,r,n)}else if(MN(t))return FN[t];return t},Hn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function _N(t,s){let a=new Set,r=new Set,n=!1,i=!1;const l=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1};function c(m){l.has(m)&&(d.schedule(m),t()),m(o)}const d={schedule:(m,u=!1,h=!1)=>{const g=h&&n?a:r;return u&&l.add(m),g.has(m)||g.add(m),m},cancel:m=>{r.delete(m),l.delete(m)},process:m=>{if(o=m,n){i=!0;return}n=!0,[a,r]=[r,a],a.forEach(c),a.clear(),n=!1,i&&(i=!1,d.process(m))}};return d}const LN=40;function Ph(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,l=Hn.reduce((A,w)=>(A[w]=_N(i),A),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:m,update:u,preRender:h,render:x,postRender:g}=l,f=()=>{const A=Ma.useManualTiming?n.timestamp:performance.now();a=!1,Ma.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(A-n.timestamp,LN),1)),n.timestamp=A,n.isProcessing=!0,o.process(n),c.process(n),d.process(n),m.process(n),u.process(n),h.process(n),x.process(n),g.process(n),n.isProcessing=!1,a&&s&&(r=!1,t(f))},y=()=>{a=!0,r=!0,n.isProcessing||t(f)};return{schedule:Hn.reduce((A,w)=>{const T=l[w];return A[w]=(C,_=!1,D=!1)=>(a||y(),T.schedule(C,_,D)),A},{}),cancel:A=>{for(let w=0;w<Hn.length;w++)l[Hn[w]].cancel(A)},state:n,steps:l}}const{schedule:Vt,cancel:Za,state:vs,steps:yl}=Ph(typeof requestAnimationFrame<"u"?requestAnimationFrame:ia,!0);let ai;function ON(){ai=void 0}const Vs={now:()=>(ai===void 0&&Vs.set(vs.isProcessing||Ma.useManualTiming?vs.timestamp:performance.now()),ai),set:t=>{ai=t,queueMicrotask(ON)}},Ih=t=>s=>typeof s=="string"&&s.startsWith(t),qo=Ih("--"),$N=Ih("var(--"),ec=t=>$N(t)?UN.test(t.split("/*")[0].trim()):!1,UN=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Xr={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},wn={...Xr,transform:t=>Fa(0,1,t)},Wn={...Xr,default:1},hn=t=>Math.round(t*1e5)/1e5,tc=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function BN(t){return t==null}const VN=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,sc=(t,s)=>a=>!!(typeof a=="string"&&VN.test(a)&&a.startsWith(t)||s&&!BN(a)&&Object.prototype.hasOwnProperty.call(a,s)),Eh=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,l,o]=r.match(tc);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},zN=t=>Fa(0,255,t),bl={...Xr,transform:t=>Math.round(zN(t))},fr={test:sc("rgb","red"),parse:Eh("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+bl.transform(t)+", "+bl.transform(s)+", "+bl.transform(a)+", "+hn(wn.transform(r))+")"};function HN(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 Yl={test:sc("#"),parse:HN,transform:fr.transform},Ln=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),Ha=Ln("deg"),Na=Ln("%"),qe=Ln("px"),WN=Ln("vh"),GN=Ln("vw"),hm={...Na,parse:t=>Na.parse(t)/100,transform:t=>Na.transform(t*100)},Dr={test:sc("hsl","hue"),parse:Eh("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+Na.transform(hn(s))+", "+Na.transform(hn(a))+", "+hn(wn.transform(r))+")"},rs={test:t=>fr.test(t)||Yl.test(t)||Dr.test(t),parse:t=>fr.test(t)?fr.parse(t):Dr.test(t)?Dr.parse(t):Yl.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?fr.transform(t):Dr.transform(t),getAnimatableNone:t=>{const s=rs.parse(t);return s.alpha=0,rs.transform(s)}},KN=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function YN(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(tc))==null?void 0:s.length)||0)+(((a=t.match(KN))==null?void 0:a.length)||0)>0}const Fh="number",Mh="color",ZN="var",XN="var(",pm="${}",QN=/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 Cn(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const o=s.replace(QN,c=>(rs.test(c)?(r.color.push(i),n.push(Mh),a.push(rs.parse(c))):c.startsWith(XN)?(r.var.push(i),n.push(ZN),a.push(c)):(r.number.push(i),n.push(Fh),a.push(parseFloat(c))),++i,pm)).split(pm);return{values:a,split:o,indexes:r,types:n}}function _h(t){return Cn(t).values}function Lh(t){const{split:s,types:a}=Cn(t),r=s.length;return n=>{let i="";for(let l=0;l<r;l++)if(i+=s[l],n[l]!==void 0){const o=a[l];o===Fh?i+=hn(n[l]):o===Mh?i+=rs.transform(n[l]):i+=n[l]}return i}}const JN=t=>typeof t=="number"?0:rs.test(t)?rs.getAnimatableNone(t):t;function qN(t){const s=_h(t);return Lh(t)(s.map(JN))}const Xa={test:YN,parse:_h,createTransformer:Lh,getAnimatableNone:qN};function vl(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 ew({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=vl(c,o,t+1/3),i=vl(c,o,t),l=vl(c,o,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function yi(t,s){return a=>a>0?s:t}const Kt=(t,s,a)=>t+(s-t)*a,jl=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},tw=[Yl,fr,Dr],sw=t=>tw.find(s=>s.test(t));function gm(t){const s=sw(t);if(!s)return!1;let a=s.parse(t);return s===Dr&&(a=ew(a)),a}const fm=(t,s)=>{const a=gm(t),r=gm(s);if(!a||!r)return yi(t,s);const n={...a};return i=>(n.red=jl(a.red,r.red,i),n.green=jl(a.green,r.green,i),n.blue=jl(a.blue,r.blue,i),n.alpha=Kt(a.alpha,r.alpha,i),fr.transform(n))},Zl=new Set(["none","hidden"]);function aw(t,s){return Zl.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function rw(t,s){return a=>Kt(t,s,a)}function ac(t){return typeof t=="number"?rw:typeof t=="string"?ec(t)?yi:rs.test(t)?fm:lw:Array.isArray(t)?Oh:typeof t=="object"?rs.test(t)?fm:nw:yi}function Oh(t,s){const a=[...t],r=a.length,n=t.map((i,l)=>ac(i)(i,s[l]));return i=>{for(let l=0;l<r;l++)a[l]=n[l](i);return a}}function nw(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=ac(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function iw(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 lw=(t,s)=>{const a=Xa.createTransformer(s),r=Cn(t),n=Cn(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?Zl.has(t)&&!n.values.length||Zl.has(s)&&!r.values.length?aw(t,s):Mn(Oh(iw(r,n),n.values),a):yi(t,s)};function $h(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?Kt(t,s,a):ac(t)(t,s)}const ow=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>Vt.update(s,a),stop:()=>Za(s),now:()=>vs.isProcessing?vs.timestamp:Vs.now()}},Uh=(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)})`},bi=2e4;function rc(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<bi;)s+=a,r=t.next(s);return s>=bi?1/0:s}function cw(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(rc(r),bi);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:ra(n)}}const dw=5;function Bh(t,s,a){const r=Math.max(s-dw,0);return vh(a-t(r),s-r)}const Xt={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},Nl=.001;function mw({duration:t=Xt.duration,bounce:s=Xt.bounce,velocity:a=Xt.velocity,mass:r=Xt.mass}){let n,i,l=1-s;l=Fa(Xt.minDamping,Xt.maxDamping,l),t=Fa(Xt.minDuration,Xt.maxDuration,ra(t)),l<1?(n=d=>{const m=d*l,u=m*t,h=m-a,x=Xl(d,l),g=Math.exp(-u);return Nl-h/x*g},i=d=>{const u=d*l*t,h=u*a+a,x=Math.pow(l,2)*Math.pow(d,2)*t,g=Math.exp(-u),f=Xl(Math.pow(d,2),l);return(-n(d)+Nl>0?-1:1)*((h-x)*g)/f}):(n=d=>{const m=Math.exp(-d*t),u=(d-a)*t+1;return-Nl+m*u},i=d=>{const m=Math.exp(-d*t),u=(a-d)*(t*t);return m*u});const o=5/t,c=xw(n,i,o);if(t=ja(t),isNaN(c))return{stiffness:Xt.stiffness,damping:Xt.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:t}}}const uw=12;function xw(t,s,a){let r=a;for(let n=1;n<uw;n++)r=r-t(r)/s(r);return r}function Xl(t,s){return t*Math.sqrt(1-s*s)}const hw=["duration","bounce"],pw=["stiffness","damping","mass"];function ym(t,s){return s.some(a=>t[a]!==void 0)}function gw(t){let s={velocity:Xt.velocity,stiffness:Xt.stiffness,damping:Xt.damping,mass:Xt.mass,isResolvedFromDuration:!1,...t};if(!ym(t,pw)&&ym(t,hw))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*Fa(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:Xt.mass,stiffness:n,damping:i}}else{const a=mw(t);s={...s,...a,mass:Xt.mass},s.isResolvedFromDuration=!0}return s}function vi(t=Xt.visualDuration,s=Xt.bounce){const a=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:s}:t;let{restSpeed:r,restDelta:n}=a;const i=a.keyframes[0],l=a.keyframes[a.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:m,duration:u,velocity:h,isResolvedFromDuration:x}=gw({...a,velocity:-ra(a.velocity||0)}),g=h||0,f=d/(2*Math.sqrt(c*m)),y=l-i,b=ra(Math.sqrt(c/m)),v=Math.abs(y)<5;r||(r=v?Xt.restSpeed.granular:Xt.restSpeed.default),n||(n=v?Xt.restDelta.granular:Xt.restDelta.default);let A;if(f<1){const T=Xl(b,f);A=C=>{const _=Math.exp(-f*b*C);return l-_*((g+f*b*y)/T*Math.sin(T*C)+y*Math.cos(T*C))}}else if(f===1)A=T=>l-Math.exp(-b*T)*(y+(g+b*y)*T);else{const T=b*Math.sqrt(f*f-1);A=C=>{const _=Math.exp(-f*b*C),D=Math.min(T*C,300);return l-_*((g+f*b*y)*Math.sinh(D)+T*y*Math.cosh(D))/T}}const w={calculatedDuration:x&&u||null,next:T=>{const C=A(T);if(x)o.done=T>=u;else{let _=T===0?g:0;f<1&&(_=T===0?ja(g):Bh(A,T,C));const D=Math.abs(_)<=r,S=Math.abs(l-C)<=n;o.done=D&&S}return o.value=o.done?l:C,o},toString:()=>{const T=Math.min(rc(w),bi),C=Uh(_=>w.next(T*_).value,T,30);return T+"ms "+C},toTransition:()=>{}};return w}vi.applyToOptions=t=>{const s=cw(t,100,vi);return t.ease=s.ease,t.duration=ja(s.duration),t.type="keyframes",t};function Ql({keyframes:t,velocity:s=0,power:a=.8,timeConstant:r=325,bounceDamping:n=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:m}){const u=t[0],h={done:!1,value:u},x=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 f=a*s;const y=u+f,b=l===void 0?y:l(y);b!==y&&(f=b-u);const v=D=>-f*Math.exp(-D/r),A=D=>b+v(D),w=D=>{const S=v(D),j=A(D);h.done=Math.abs(S)<=d,h.value=h.done?b:j};let T,C;const _=D=>{x(h.value)&&(T=D,C=vi({keyframes:[h.value,g(h.value)],velocity:Bh(A,D,h.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return _(0),{calculatedDuration:null,next:D=>{let S=!1;return!C&&T===void 0&&(S=!0,w(D),_(D)),T!==void 0&&D>=T?C.next(D-T):(!S&&w(D),h)}}}function fw(t,s,a){const r=[],n=a||Ma.mix||$h,i=t.length-1;for(let l=0;l<i;l++){let o=n(t[l],t[l+1]);if(s){const c=Array.isArray(s)?s[l]||ia:s;o=Mn(c,o)}r.push(o)}return r}function yw(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(Yo(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=fw(s,r,n),c=o.length,d=m=>{if(l&&m<t[0])return s[0];let u=0;if(c>1)for(;u<t.length-2&&!(m<t[u+1]);u++);const h=Nn(t[u],t[u+1],m);return o[u](h)};return a?m=>d(Fa(t[0],t[i-1],m)):d}function bw(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=Nn(0,s,r);t.push(Kt(a,1,n))}}function vw(t){const s=[0];return bw(s,t.length-1),s}function jw(t,s){return t.map(a=>a*s)}function Nw(t,s){return t.map(()=>s||Rh).splice(0,t.length-1)}function pn({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=EN(r)?r.map(xm):xm(r),i={done:!1,value:s[0]},l=jw(a&&a.length===s.length?a:vw(s),t),o=yw(l,s,{ease:Array.isArray(n)?n:Nw(s,n)});return{calculatedDuration:t,next:c=>(i.value=o(c),i.done=c>=t,i)}}const ww=t=>t!==null;function nc(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(ww),o=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const Cw={decay:Ql,inertia:Ql,tween:pn,keyframes:pn,spring:vi};function Vh(t){typeof t.type=="string"&&(t.type=Cw[t.type])}class ic{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 Aw=t=>t/100;class lc extends ic{constructor(s){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var r,n;const{motionValue:a}=this.options;a&&a.updatedAt!==Vs.now()&&this.tick(Vs.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(n=(r=this.options).onStop)==null||n.call(r))},this.options=s,this.initAnimation(),this.play(),s.autoplay===!1&&this.pause()}initAnimation(){const{options:s}=this;Vh(s);const{type:a=pn,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:l=0}=s;let{keyframes:o}=s;const c=a||pn;c!==pn&&typeof o[0]!="number"&&(this.mixKeyframes=Mn(Aw,$h(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=rc(d));const{calculatedDuration:m}=d;this.calculatedDuration=m,this.resolvedDuration=m+n,this.totalDuration=this.resolvedDuration*(r+1)-n,this.generator=d}updateTime(s){const a=Math.round(s-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=a}tick(s,a=!1){const{generator:r,totalDuration:n,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:m,repeat:u,repeatType:h,repeatDelay:x,type:g,onUpdate:f,finalKeyframe:y}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,s):this.speed<0&&(this.startTime=Math.min(s-n/this.speed,this.startTime)),a?this.currentTime=s:this.updateTime(s);const b=this.currentTime-d*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?b<0:b>n;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let A=this.currentTime,w=r;if(u){const D=Math.min(this.currentTime,n)/o;let S=Math.floor(D),j=D%1;!j&&D>=1&&(j=1),j===1&&S--,S=Math.min(S,u+1),!!(S%2)&&(h==="reverse"?(j=1-j,x&&(j-=x/o)):h==="mirror"&&(w=l)),A=Fa(0,1,j)*o}const T=v?{done:!1,value:m[0]}:w.next(A);i&&(T.value=i(T.value));let{done:C}=T;!v&&c!==null&&(C=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const _=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&C);return _&&g!==Ql&&(T.value=nc(m,this.options,y,this.speed)),f&&f(T.value),_&&this.finish(),T}then(s,a){return this.finished.then(s,a)}get duration(){return ra(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ra(s)}get time(){return ra(this.currentTime)}set time(s){var a;s=ja(s),this.currentTime=s,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=s:this.driver&&(this.startTime=this.driver.now()-s/this.playbackSpeed),(a=this.driver)==null||a.start(!1)}get speed(){return this.playbackSpeed}set speed(s){this.updateTime(Vs.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=ra(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=ow,startTime:a}=this.options;this.driver||(this.driver=s(l=>this.tick(l))),(i=(n=this.options).onPlay)==null||i.call(n);const r=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=r):this.holdTime!==null?this.startTime=r-this.holdTime:this.startTime||(this.startTime=a??r),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Vs.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var s,a;this.notifyFinished(),this.teardown(),this.state="finished",(a=(s=this.options).onComplete)==null||a.call(s)}cancel(){var s,a;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(a=(s=this.options).onCancel)==null||a.call(s)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(s){return this.startTime=0,this.tick(s,!0)}attachTimeline(s){var a;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(a=this.driver)==null||a.stop(),s.observe(this)}}function Sw(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const yr=t=>t*180/Math.PI,Jl=t=>{const s=yr(Math.atan2(t[1],t[0]));return ql(s)},Tw={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Jl,rotateZ:Jl,skewX:t=>yr(Math.atan(t[1])),skewY:t=>yr(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},ql=t=>(t=t%360,t<0&&(t+=360),t),bm=Jl,vm=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),jm=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),kw={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:vm,scaleY:jm,scale:t=>(vm(t)+jm(t))/2,rotateX:t=>ql(yr(Math.atan2(t[6],t[5]))),rotateY:t=>ql(yr(Math.atan2(-t[2],t[0]))),rotateZ:bm,rotate:bm,skewX:t=>yr(Math.atan(t[4])),skewY:t=>yr(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function eo(t){return t.includes("scale")?1:0}function to(t,s){if(!t||t==="none")return eo(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=kw,n=a;else{const o=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=Tw,n=o}if(!n)return eo(s);const i=r[s],l=n[1].split(",").map(Dw);return typeof i=="function"?i(l):l[i]}const Rw=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return to(a,s)};function Dw(t){return parseFloat(t.trim())}const Qr=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Jr=new Set(Qr),Nm=t=>t===Xr||t===qe,Pw=new Set(["x","y","z"]),Iw=Qr.filter(t=>!Pw.has(t));function Ew(t){const s=[];return Iw.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const br={width:({x:t},{paddingLeft:s="0",paddingRight:a="0"})=>t.max-t.min-parseFloat(s)-parseFloat(a),height:({y:t},{paddingTop:s="0",paddingBottom:a="0"})=>t.max-t.min-parseFloat(s)-parseFloat(a),top:(t,{top:s})=>parseFloat(s),left:(t,{left:s})=>parseFloat(s),bottom:({y:t},{top:s})=>parseFloat(s)+(t.max-t.min),right:({x:t},{left:s})=>parseFloat(s)+(t.max-t.min),x:(t,{transform:s})=>to(s,"x"),y:(t,{transform:s})=>to(s,"y")};br.translateX=br.x;br.translateY=br.y;const vr=new Set;let so=!1,ao=!1,ro=!1;function zh(){if(ao){const t=Array.from(vr).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=Ew(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)})}ao=!1,so=!1,vr.forEach(t=>t.complete(ro)),vr.clear()}function Hh(){vr.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(ao=!0)})}function Fw(){ro=!0,Hh(),zh(),ro=!1}class oc{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?(vr.add(this),so||(so=!0,Vt.read(Hh),Vt.resolveKeyframes(zh))):(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])}Sw(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),vr.delete(this)}cancel(){this.state==="scheduled"&&(vr.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Mw=t=>t.startsWith("--");function _w(t,s,a){Mw(s)?t.style.setProperty(s,a):t.style[s]=a}const Lw=Zo(()=>window.ScrollTimeline!==void 0),Ow={};function $w(t,s){const a=Zo(t);return()=>Ow[s]??a()}const Wh=$w(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),un=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,wm={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:un([0,.65,.55,1]),circOut:un([.55,0,1,.45]),backIn:un([.31,.01,.66,-.59]),backOut:un([.33,1.53,.69,.99])};function Gh(t,s){if(t)return typeof t=="function"?Wh()?Uh(t,s):"ease-out":Dh(t)?un(t):Array.isArray(t)?t.map(a=>Gh(a,s)||wm.easeOut):wm[t]}function Uw(t,s,a,{delay:r=0,duration:n=300,repeat:i=0,repeatType:l="loop",ease:o="easeOut",times:c}={},d=void 0){const m={[s]:a};c&&(m.offset=c);const u=Gh(o,n);Array.isArray(u)&&(m.easing=u);const h={delay:r,duration:n,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(h.pseudoElement=d),t.animate(m,h)}function Kh(t){return typeof t=="function"&&"applyToOptions"in t}function Bw({type:t,...s}){return Kh(t)&&Wh()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class Vw extends ic{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,Yo(typeof s.type!="string");const d=Bw(s);this.animation=Uw(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=nc(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(m):_w(a,r,m),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var s,a;(a=(s=this.animation).finish)==null||a.call(s)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:s}=this;s==="idle"||s==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var s,a;this.isPseudoElement||(a=(s=this.animation).commitStyles)==null||a.call(s)}get duration(){var a,r;const s=((r=(a=this.animation.effect)==null?void 0:a.getComputedTiming)==null?void 0:r.call(a).duration)||0;return ra(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ra(s)}get time(){return ra(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=ja(s)}get speed(){return this.animation.playbackRate}set speed(s){s<0&&(this.finishedTime=null),this.animation.playbackRate=s}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(s){this.animation.startTime=s}attachTimeline({timeline:s,observe:a}){var r;return this.allowFlatten&&((r=this.animation.effect)==null||r.updateTiming({easing:"linear"})),this.animation.onfinish=null,s&&Lw()?(this.animation.timeline=s,ia):a(this)}}const Yh={anticipate:Sh,backInOut:Ah,circInOut:kh};function zw(t){return t in Yh}function Hw(t){typeof t.ease=="string"&&zw(t.ease)&&(t.ease=Yh[t.ease])}const Cm=10;class Ww extends Vw{constructor(s){Hw(s),Vh(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 lc({...l,autoplay:!1}),c=ja(this.finishedTime??this.time);a.setWithVelocity(o.sample(c-Cm).value,o.sample(c).value,Cm),o.stop()}}const Am=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Xa.test(t)||t==="0")&&!t.startsWith("url("));function Gw(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 Kw(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=Am(n,s),o=Am(i,s);return!l||!o?!1:Gw(t)||(a==="spring"||Kh(a))&&r}function no(t){t.duration=0,t.type="keyframes"}const Yw=new Set(["opacity","clipPath","filter","transform"]),Zw=Zo(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Xw(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 Zw()&&a&&Yw.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&l!=="inertia"}const Qw=40;class Jw extends ic{constructor({autoplay:s=!0,delay:a=0,type:r="keyframes",repeat:n=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:m,...u}){var g;super(),this.stop=()=>{var f,y;this._animation&&(this._animation.stop(),(f=this.stopTimeline)==null||f.call(this)),(y=this.keyframeResolver)==null||y.cancel()},this.createdAt=Vs.now();const h={autoplay:s,delay:a,type:r,repeat:n,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:m,...u},x=(m==null?void 0:m.KeyframeResolver)||oc;this.keyframeResolver=new x(o,(f,y,b)=>this.onKeyframesResolved(f,y,h,!b),c,d,m),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(s,a,r,n){this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:m}=r;this.resolvedAt=Vs.now(),Kw(s,i,l,o)||((Ma.instantAnimations||!c)&&(m==null||m(nc(s,r,a))),s[0]=s[s.length-1],no(r),r.repeat=0);const h={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>Qw?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},x=!d&&Xw(h)?new Ww({...h,element:h.motionValue.owner.current}):new lc(h);x.finished.then(()=>this.notifyFinished()).catch(ia),this.pendingTimeline&&(this.stopTimeline=x.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=x}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(),Fw()),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 qw=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function e1(t){const s=qw.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Zh(t,s,a=1){const[r,n]=e1(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const l=i.trim();return fh(l)?parseFloat(l):l}return ec(n)?Zh(n,s,a+1):n}function cc(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const Xh=new Set(["width","height","top","left","right","bottom",...Qr]),t1={test:t=>t==="auto",parse:t=>t},Qh=t=>s=>s.test(t),Jh=[Xr,qe,Na,Ha,GN,WN,t1],Sm=t=>Jh.find(Qh(t));function s1(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||bh(t):!0}const a1=new Set(["brightness","contrast","saturate","opacity"]);function r1(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(tc)||[];if(!r)return t;const n=a.replace(r,"");let i=a1.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const n1=/\b([a-z-]*)\(.*?\)/gu,io={...Xa,getAnimatableNone:t=>{const s=t.match(n1);return s?s.map(r1).join(" "):t}},Tm={...Xr,transform:Math.round},i1={rotate:Ha,rotateX:Ha,rotateY:Ha,rotateZ:Ha,scale:Wn,scaleX:Wn,scaleY:Wn,scaleZ:Wn,skew:Ha,skewX:Ha,skewY:Ha,distance:qe,translateX:qe,translateY:qe,translateZ:qe,x:qe,y:qe,z:qe,perspective:qe,transformPerspective:qe,opacity:wn,originX:hm,originY:hm,originZ:qe},dc={borderWidth:qe,borderTopWidth:qe,borderRightWidth:qe,borderBottomWidth:qe,borderLeftWidth:qe,borderRadius:qe,radius:qe,borderTopLeftRadius:qe,borderTopRightRadius:qe,borderBottomRightRadius:qe,borderBottomLeftRadius:qe,width:qe,maxWidth:qe,height:qe,maxHeight:qe,top:qe,right:qe,bottom:qe,left:qe,padding:qe,paddingTop:qe,paddingRight:qe,paddingBottom:qe,paddingLeft:qe,margin:qe,marginTop:qe,marginRight:qe,marginBottom:qe,marginLeft:qe,backgroundPositionX:qe,backgroundPositionY:qe,...i1,zIndex:Tm,fillOpacity:wn,strokeOpacity:wn,numOctaves:Tm},l1={...dc,color:rs,backgroundColor:rs,outlineColor:rs,fill:rs,stroke:rs,borderColor:rs,borderTopColor:rs,borderRightColor:rs,borderBottomColor:rs,borderLeftColor:rs,filter:io,WebkitFilter:io},qh=t=>l1[t];function ep(t,s){let a=qh(t);return a!==io&&(a=Xa),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const o1=new Set(["auto","none","0"]);function c1(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!o1.has(i)&&Cn(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=ep(a,n)}class d1 extends oc{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(),ec(d))){const m=Zh(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!Xh.has(r)||s.length!==2)return;const[n,i]=s,l=Sm(n),o=Sm(i);if(l!==o)if(Nm(l)&&Nm(o))for(let c=0;c<s.length;c++){const d=s[c];typeof d=="string"&&(s[c]=parseFloat(d))}else br[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||s1(s[n]))&&r.push(n);r.length&&c1(s,r,a)}measureInitialState(){const{element:s,unresolvedKeyframes:a,name:r}=this;if(!s||!s.current)return;r==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=br[r](s.measureViewportBox(),window.getComputedStyle(s.current)),a[0]=this.measuredOrigin;const n=a[a.length-1];n!==void 0&&s.getValue(r,n).jump(n,!1)}measureEndState(){var o;const{element:s,name:a,unresolvedKeyframes:r}=this;if(!s||!s.current)return;const n=s.getValue(a);n&&n.jump(this.measuredOrigin,!1);const i=r.length-1,l=r[i];r[i]=br[a](s.measureViewportBox(),window.getComputedStyle(s.current)),l!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=l),(o=this.removedTransforms)!=null&&o.length&&this.removedTransforms.forEach(([c,d])=>{s.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function m1(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 tp=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function sp(t){return yh(t)&&"offsetHeight"in t}const km=30,u1=t=>!isNaN(parseFloat(t));class x1{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=Vs.now();if(this.updatedAt!==n&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(r),this.current!==this.prev&&((i=this.events.change)==null||i.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty()},this.hasAnimated=!1,this.setCurrent(s),this.owner=a.owner}setCurrent(s){this.current=s,this.updatedAt=Vs.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=u1(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 Xo);const r=this.events[s].add(a);return s==="change"?()=>{r(),Vt.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const s in this.events)this.events[s].clear()}attach(s,a){this.passiveEffect=s,this.stopPassiveEffect=a}set(s){this.passiveEffect?this.passiveEffect(s,this.updateAndNotify):this.updateAndNotify(s)}setWithVelocity(s,a,r){this.set(a),this.prev=void 0,this.prevFrameValue=s,this.prevUpdatedAt=this.updatedAt-r}jump(s,a=!0){this.updateAndNotify(s),this.prev=s,this.prevUpdatedAt=this.prevFrameValue=void 0,a&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var s;(s=this.events.change)==null||s.notify(this.current)}addDependent(s){this.dependents||(this.dependents=new Set),this.dependents.add(s)}removeDependent(s){this.dependents&&this.dependents.delete(s)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const s=Vs.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>km)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,km);return vh(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 Br(t,s){return new x1(t,s)}const{schedule:mc}=Ph(queueMicrotask,!1),xa={x:!1,y:!1};function ap(){return xa.x||xa.y}function h1(t){return t==="x"||t==="y"?xa[t]?null:(xa[t]=!0,()=>{xa[t]=!1}):xa.x||xa.y?null:(xa.x=xa.y=!0,()=>{xa.x=xa.y=!1})}function rp(t,s){const a=m1(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function Rm(t){return!(t.pointerType==="touch"||ap())}function p1(t,s,a={}){const[r,n,i]=rp(t,a),l=o=>{if(!Rm(o))return;const{target:c}=o,d=s(c,o);if(typeof d!="function"||!c)return;const m=u=>{Rm(u)&&(d(u),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(o=>{o.addEventListener("pointerenter",l,n)}),i}const np=(t,s)=>s?t===s?!0:np(t,s.parentElement):!1,uc=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,g1=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function f1(t){return g1.has(t.tagName)||t.tabIndex!==-1}const ri=new WeakSet;function Dm(t){return s=>{s.key==="Enter"&&t(s)}}function wl(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const y1=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=Dm(()=>{if(ri.has(a))return;wl(a,"down");const n=Dm(()=>{wl(a,"up")}),i=()=>wl(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 Pm(t){return uc(t)&&!ap()}function b1(t,s,a={}){const[r,n,i]=rp(t,a),l=o=>{const c=o.currentTarget;if(!Pm(o))return;ri.add(c);const d=s(c,o),m=(x,g)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",h),ri.has(c)&&ri.delete(c),Pm(x)&&typeof d=="function"&&d(x,{success:g})},u=x=>{m(x,c===window||c===document||a.useGlobalTarget||np(c,x.target))},h=x=>{m(x,!1)};window.addEventListener("pointerup",u,n),window.addEventListener("pointercancel",h,n)};return r.forEach(o=>{(a.useGlobalTarget?window:o).addEventListener("pointerdown",l,n),sp(o)&&(o.addEventListener("focus",d=>y1(d,n)),!f1(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function ip(t){return yh(t)&&"ownerSVGElement"in t}function v1(t){return ip(t)&&t.tagName==="svg"}const As=t=>!!(t&&t.getVelocity),j1=[...Jh,rs,Xa],N1=t=>j1.find(Qh(t)),xc=p.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function Im(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function w1(...t){return s=>{let a=!1;const r=t.map(n=>{const i=Im(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():Im(t[n],null)}}}}function C1(...t){return p.useCallback(w1(...t),t)}class A1 extends p.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=sp(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 S1({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(xc),c=C1(i,t==null?void 0:t.ref);return p.useInsertionEffect(()=>{const{width:d,height:m,top:u,left:h,right:x}=l.current;if(s||!i.current||!d||!m)return;const g=a==="left"?`left: ${h}`:`right: ${x}`;i.current.dataset.motionPopId=n;const f=document.createElement("style");o&&(f.nonce=o);const y=r??document.head;return y.appendChild(f),f.sheet&&f.sheet.insertRule(`
[data-motion-pop-id="${n}"] {
position: absolute !important;
width: ${d}px !important;
height: ${m}px !important;
${g}px !important;
top: ${u}px !important;
}
`),()=>{y.contains(f)&&y.removeChild(f)}},[s]),e.jsx(A1,{isPresent:s,childRef:i,sizeRef:l,children:p.cloneElement(t,{ref:c})})}const T1=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=Ho(k1),m=p.useId();let u=!0,h=p.useMemo(()=>(u=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:x=>{d.set(x,!0);for(const g of d.values())if(!g)return;r&&r()},register:x=>(d.set(x,!1),()=>d.delete(x))}),[a,d,r]);return i&&u&&(h={...h}),p.useMemo(()=>{d.forEach((x,g)=>d.set(g,!1))},[a]),p.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(S1,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(Hi.Provider,{value:h,children:t})};function k1(){return new Map}function lp(t=!0){const s=p.useContext(Hi);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 Gn=t=>t.key||"";function Em(t){const s=[];return p.Children.forEach(t,a=>{p.isValidElement(a)&&s.push(a)}),s}const Wi=({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]=lp(l),u=p.useMemo(()=>Em(t),[t]),h=l&&!d?[]:u.map(Gn),x=p.useRef(!0),g=p.useRef(u),f=Ho(()=>new Map),[y,b]=p.useState(u),[v,A]=p.useState(u);gh(()=>{x.current=!1,g.current=u;for(let C=0;C<v.length;C++){const _=Gn(v[C]);h.includes(_)?f.delete(_):f.get(_)!==!0&&f.set(_,!1)}},[v,h.length,h.join("-")]);const w=[];if(u!==y){let C=[...u];for(let _=0;_<v.length;_++){const D=v[_],S=Gn(D);h.includes(S)||(C.splice(_,0,D),w.push(D))}return i==="wait"&&w.length&&(C=w),A(Em(C)),b(u),null}const{forceRender:T}=p.useContext(zo);return e.jsx(e.Fragment,{children:v.map(C=>{const _=Gn(C),D=l&&!d?!1:u===v||h.includes(_),S=()=>{if(f.has(_))f.set(_,!0);else return;let j=!0;f.forEach(P=>{P||(j=!1)}),j&&(T==null||T(),A(g.current),l&&(m==null||m()),r&&r())};return e.jsx(T1,{isPresent:D,initial:!x.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:D?void 0:S,anchorX:o,children:C},_)})})},op=p.createContext({strict:!1}),Fm={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"]},Vr={};for(const t in Fm)Vr[t]={isEnabled:s=>Fm[t].some(a=>!!s[a])};function R1(t){for(const s in t)Vr[s]={...Vr[s],...t[s]}}const D1=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 ji(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||D1.has(t)}let cp=t=>!ji(t);function P1(t){typeof t=="function"&&(cp=s=>s.startsWith("on")?!ji(s):t(s))}try{P1(require("@emotion/is-prop-valid").default)}catch{}function I1(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(cp(n)||a===!0&&ji(n)||!s&&!ji(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Gi=p.createContext({});function Ki(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function An(t){return typeof t=="string"||Array.isArray(t)}const hc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],pc=["initial",...hc];function Yi(t){return Ki(t.animate)||pc.some(s=>An(t[s]))}function dp(t){return!!(Yi(t)||t.variants)}function E1(t,s){if(Yi(t)){const{initial:a,animate:r}=t;return{initial:a===!1||An(a)?a:void 0,animate:An(r)?r:void 0}}return t.inherit!==!1?s:{}}function F1(t){const{initial:s,animate:a}=E1(t,p.useContext(Gi));return p.useMemo(()=>({initial:s,animate:a}),[Mm(s),Mm(a)])}function Mm(t){return Array.isArray(t)?t.join(" "):t}const Sn={};function M1(t){for(const s in t)Sn[s]=t[s],qo(s)&&(Sn[s].isCSSVariable=!0)}function mp(t,{layout:s,layoutId:a}){return Jr.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!Sn[t]||t==="opacity")}const _1={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},L1=Qr.length;function O1(t,s,a){let r="",n=!0;for(let i=0;i<L1;i++){const l=Qr[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=tp(o,dc[l]);if(!c){n=!1;const m=_1[l]||l;r+=`${m}(${d}) `}a&&(s[l]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function gc(t,s,a){const{style:r,vars:n,transformOrigin:i}=t;let l=!1,o=!1;for(const c in s){const d=s[c];if(Jr.has(c)){l=!0;continue}else if(qo(c)){n[c]=d;continue}else{const m=tp(d,dc[c]);c.startsWith("origin")?(o=!0,i[c]=m):r[c]=m}}if(s.transform||(l||a?r.transform=O1(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 fc=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function up(t,s,a){for(const r in s)!As(s[r])&&!mp(r,a)&&(t[r]=s[r])}function $1({transformTemplate:t},s){return p.useMemo(()=>{const a=fc();return gc(a,s,t),Object.assign({},a.vars,a.style)},[s])}function U1(t,s){const a=t.style||{},r={};return up(r,a,t),Object.assign(r,$1(t,s)),r}function B1(t,s){const a={},r=U1(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 V1={offset:"stroke-dashoffset",array:"stroke-dasharray"},z1={offset:"strokeDashoffset",array:"strokeDasharray"};function H1(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?V1:z1;t[i.offset]=qe.transform(-r);const l=qe.transform(s),o=qe.transform(a);t[i.array]=`${l} ${o}`}function xp(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(gc(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:u,style:h}=t;u.transform&&(h.transform=u.transform,delete u.transform),(h.transform||u.transformOrigin)&&(h.transformOrigin=u.transformOrigin??"50% 50%",delete u.transformOrigin),h.transform&&(h.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete u.transformBox),s!==void 0&&(u.x=s),a!==void 0&&(u.y=a),r!==void 0&&(u.scale=r),n!==void 0&&H1(u,n,i,l,!1)}const hp=()=>({...fc(),attrs:{}}),pp=t=>typeof t=="string"&&t.toLowerCase()==="svg";function W1(t,s,a,r){const n=p.useMemo(()=>{const i=hp();return xp(i,s,pp(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};up(i,t.style,t),n.style={...i,...n.style}}return n}const G1=["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 yc(t){return typeof t!="string"||t.includes("-")?!1:!!(G1.indexOf(t)>-1||/[A-Z]/u.test(t))}function K1(t,s,a,{latestValues:r},n,i=!1){const o=(yc(t)?W1:B1)(s,r,n,t),c=I1(s,typeof t=="string",i),d=t!==p.Fragment?{...c,...o,ref:a}:{},{children:m}=s,u=p.useMemo(()=>As(m)?m.get():m,[m]);return p.createElement(t,{...d,children:u})}function _m(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function bc(t,s,a,r){if(typeof s=="function"){const[n,i]=_m(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]=_m(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function ni(t){return As(t)?t.get():t}function Y1({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:Z1(a,r,n,t),renderState:s()}}function Z1(t,s,a,r){const n={},i=r(t,{});for(const h in i)n[h]=ni(i[h]);let{initial:l,animate:o}=t;const c=Yi(t),d=dp(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const u=m?o:l;if(u&&typeof u!="boolean"&&!Ki(u)){const h=Array.isArray(u)?u:[u];for(let x=0;x<h.length;x++){const g=bc(t,h[x]);if(g){const{transitionEnd:f,transition:y,...b}=g;for(const v in b){let A=b[v];if(Array.isArray(A)){const w=m?A.length-1:0;A=A[w]}A!==null&&(n[v]=A)}for(const v in f)n[v]=f[v]}}}return n}const gp=t=>(s,a)=>{const r=p.useContext(Gi),n=p.useContext(Hi),i=()=>Y1(t,s,r,n);return a?i():Ho(i)};function vc(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(As(r[l])||s.style&&As(s.style[l])||mp(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const X1=gp({scrapeMotionValuesFromProps:vc,createRenderState:fc});function fp(t,s,a){const r=vc(t,s,a);for(const n in t)if(As(t[n])||As(s[n])){const i=Qr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const Q1=gp({scrapeMotionValuesFromProps:fp,createRenderState:hp}),J1=Symbol.for("motionComponentSymbol");function Pr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function q1(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):Pr(a)&&(a.current=r))},[s])}const jc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),e2="framerAppearId",yp="data-"+jc(e2),bp=p.createContext({});function t2(t,s,a,r,n){var f,y;const{visualElement:i}=p.useContext(Gi),l=p.useContext(op),o=p.useContext(Hi),c=p.useContext(xc).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,u=p.useContext(bp);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&s2(d.current,a,n,u);const h=p.useRef(!1);p.useInsertionEffect(()=>{m&&h.current&&m.update(a,o)});const x=a[yp],g=p.useRef(!!x&&!((f=window.MotionHandoffIsComplete)!=null&&f.call(window,x))&&((y=window.MotionHasOptimisedAnimation)==null?void 0:y.call(window,x)));return gh(()=>{m&&(h.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 b;(b=window.MotionHandoffMarkAsComplete)==null||b.call(window,x)}),g.current=!1),m.enteringChildren=void 0)}),m}function s2(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:vp(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Pr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function vp(t){if(t)return t.options.allowProjection!==!1?t.projection:vp(t.parent)}function Cl(t,{forwardMotionProps:s=!1}={},a,r){a&&R1(a);const n=yc(t)?Q1:X1;function i(o,c){let d;const m={...p.useContext(xc),...o,layoutId:a2(o)},{isStatic:u}=m,h=F1(o),x=n(o,u);if(!u&&Wo){r2();const g=n2(m);d=g.MeasureLayout,h.visualElement=t2(t,x,m,r,g.ProjectionNode)}return e.jsxs(Gi.Provider,{value:h,children:[d&&h.visualElement?e.jsx(d,{visualElement:h.visualElement,...m}):null,K1(t,o,q1(x,h.visualElement,c),x,u,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=p.forwardRef(i);return l[J1]=t,l}function a2({layoutId:t}){const s=p.useContext(zo).id;return s&&t!==void 0?s+"-"+t:t}function r2(t,s){p.useContext(op).strict}function n2(t){const{drag:s,layout:a}=Vr;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 i2(t,s){if(typeof Proxy>"u")return Cl;const a=new Map,r=(i,l)=>Cl(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,Cl(l,void 0,t,s)),a.get(l))})}function jp({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function l2({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function o2(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 Al(t){return t===void 0||t===1}function lo({scale:t,scaleX:s,scaleY:a}){return!Al(t)||!Al(s)||!Al(a)}function ur(t){return lo(t)||Np(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Np(t){return Lm(t.x)||Lm(t.y)}function Lm(t){return t&&t!=="0%"}function Ni(t,s,a){const r=t-a,n=s*r;return a+n}function Om(t,s,a,r,n){return n!==void 0&&(t=Ni(t,n,r)),Ni(t,a,r)+s}function oo(t,s=0,a=1,r,n){t.min=Om(t.min,s,a,r,n),t.max=Om(t.max,s,a,r,n)}function wp(t,{x:s,y:a}){oo(t.x,s.translate,s.scale,s.originPoint),oo(t.y,a.translate,a.scale,a.originPoint)}const $m=.999999999999,Um=1.0000000000001;function c2(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&&Er(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),l&&(s.x*=l.x.scale,s.y*=l.y.scale,wp(t,l)),r&&ur(i.latestValues)&&Er(t,i.latestValues))}s.x<Um&&s.x>$m&&(s.x=1),s.y<Um&&s.y>$m&&(s.y=1)}function Ir(t,s){t.min=t.min+s,t.max=t.max+s}function Bm(t,s,a,r,n=.5){const i=Kt(t.min,t.max,n);oo(t,s,a,i,r)}function Er(t,s){Bm(t.x,s.x,s.scaleX,s.scale,s.originX),Bm(t.y,s.y,s.scaleY,s.scale,s.originY)}function Cp(t,s){return jp(o2(t.getBoundingClientRect(),s))}function d2(t,s,a){const r=Cp(t,a),{scroll:n}=s;return n&&(Ir(r.x,n.offset.x),Ir(r.y,n.offset.y)),r}const Vm=()=>({translate:0,scale:1,origin:0,originPoint:0}),Fr=()=>({x:Vm(),y:Vm()}),zm=()=>({min:0,max:0}),Jt=()=>({x:zm(),y:zm()}),co={current:null},Ap={current:!1};function m2(){if(Ap.current=!0,!!Wo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>co.current=t.matches;t.addEventListener("change",s),s()}else co.current=!1}const u2=new WeakMap;function x2(t,s,a){for(const r in s){const n=s[r],i=a[r];if(As(n))t.addValue(r,n);else if(As(i))t.addValue(r,Br(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,Br(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Hm=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class h2{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=oc,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=Vs.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,Vt.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=Yi(a),this.isVariantNode=dp(a),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(s&&s.current);const{willChange:m,...u}=this.scrapeMotionValuesFromProps(a,{},this);for(const h in u){const x=u[h];c[h]!==void 0&&As(x)&&x.set(c[h])}}mount(s){var a;this.current=s,u2.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)),Ap.current||m2(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:co.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Za(this.notifyUpdate),Za(this.render),this.valueSubscriptions.forEach(a=>a()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(s=this.parent)==null||s.removeChild(this);for(const a in this.events)this.events[a].clear();for(const a in this.features){const r=this.features[a];r&&(r.unmount(),r.isMounted=!1)}this.current=null}addChild(s){this.children.add(s),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(s)}removeChild(s){this.children.delete(s),this.enteringChildren&&this.enteringChildren.delete(s)}bindToMotionValue(s,a){this.valueSubscriptions.has(s)&&this.valueSubscriptions.get(s)();const r=Jr.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&Vt.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 Vr){const a=Vr[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):Jt()}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<Hm.length;r++){const n=Hm[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=x2(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=Br(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"&&(fh(r)||bh(r))?r=parseFloat(r):!N1(r)&&Xa.test(a)&&(r=ep(s,a)),this.setBaseTarget(s,As(r)?r.get():r)),As(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=bc(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&&!As(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 Xo),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){mc.render(this.render)}}class Sp extends h2{constructor(){super(...arguments),this.KeyframeResolver=d1}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;As(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Tp(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 p2(t){return window.getComputedStyle(t)}class g2 extends Sp{constructor(){super(...arguments),this.type="html",this.renderInstance=Tp}readValueFromInstance(s,a){var r;if(Jr.has(a))return(r=this.projection)!=null&&r.isProjecting?eo(a):Rw(s,a);{const n=p2(s),i=(qo(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return Cp(s,a)}build(s,a,r){gc(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return vc(s,a,r)}}const kp=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 f2(t,s,a,r){Tp(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(kp.has(n)?n:jc(n),s.attrs[n])}class y2 extends Sp{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Jt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Jr.has(a)){const r=qh(a);return r&&r.default||0}return a=kp.has(a)?a:jc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return fp(s,a,r)}build(s,a,r){xp(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){f2(s,a,r,n)}mount(s){this.isSVGTag=pp(s.tagName),super.mount(s)}}const b2=(t,s)=>yc(t)?new y2(s):new g2(s,{allowProjection:t!==p.Fragment});function $r(t,s,a){const r=t.getProps();return bc(r,s,a!==void 0?a:r.custom,t)}const mo=t=>Array.isArray(t);function v2(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,Br(a))}function j2(t){return mo(t)?t[t.length-1]||0:t}function N2(t,s){const a=$r(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=j2(i[l]);v2(t,l,o)}}function w2(t){return!!(As(t)&&t.add)}function uo(t,s){const a=t.getValue("willChange");if(w2(a))return a.add(s);if(!a&&Ma.WillChange){const r=new Ma.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function Rp(t){return t.props[yp]}const C2=t=>t!==null;function A2(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(C2),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const S2={type:"spring",stiffness:500,damping:25,restSpeed:10},T2=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),k2={type:"keyframes",duration:.8},R2={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},D2=(t,{keyframes:s})=>s.length>2?k2:Jr.has(t)?t.startsWith("scale")?T2(s[1]):S2:R2;function P2({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 Nc=(t,s,a,r={},n,i)=>l=>{const o=cc(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-ja(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:h=>{s.set(h),o.onUpdate&&o.onUpdate(h)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};P2(o)||Object.assign(m,D2(t,m)),m.duration&&(m.duration=ja(m.duration)),m.repeatDelay&&(m.repeatDelay=ja(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let u=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(no(m),m.delay===0&&(u=!0)),(Ma.instantAnimations||Ma.skipAnimations)&&(u=!0,no(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,u&&!i&&s.get()!==void 0){const h=A2(m.keyframes,o);if(h!==void 0){Vt.update(()=>{m.onUpdate(h),m.onComplete()});return}}return o.isSync?new lc(m):new Jw(m)};function I2({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Dp(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const u=t.getValue(m,t.latestValues[m]??null),h=o[m];if(h===void 0||d&&I2(d,m))continue;const x={delay:a,...cc(i||{},m)},g=u.get();if(g!==void 0&&!u.isAnimating&&!Array.isArray(h)&&h===g&&!x.velocity)continue;let f=!1;if(window.MotionHandoffAnimation){const b=Rp(t);if(b){const v=window.MotionHandoffAnimation(b,m,Vt);v!==null&&(x.startTime=v,f=!0)}}uo(t,m),u.start(Nc(m,u,h,t.shouldReduceMotion&&Xh.has(m)?{type:!1}:x,t,f));const y=u.animation;y&&c.push(y)}return l&&Promise.all(c).then(()=>{Vt.update(()=>{l&&N2(t,l)})}),c}function Pp(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 xo(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(Dp(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:u,staggerDirection:h}=n;return E2(t,s,d,m,u,h,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function E2(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(xo(c,s,{...l,delay:a+(typeof r=="function"?0:r)+Pp(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function F2(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>xo(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=xo(t,s,a);else{const n=typeof s=="function"?$r(t,s,a.custom):s;r=Promise.all(Dp(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function Ip(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 M2=pc.length;function Ep(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?Ep(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<M2;a++){const r=pc[a],n=t.props[r];(An(n)||n===!1)&&(s[r]=n)}return s}const _2=[...hc].reverse(),L2=hc.length;function O2(t){return s=>Promise.all(s.map(({animation:a,options:r})=>F2(t,a,r)))}function $2(t){let s=O2(t),a=Wm(),r=!0;const n=c=>(d,m)=>{var h;const u=$r(t,m,c==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(u){const{transition:x,transitionEnd:g,...f}=u;d={...d,...f,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=Ep(t.parent)||{},u=[],h=new Set;let x={},g=1/0;for(let y=0;y<L2;y++){const b=_2[y],v=a[b],A=d[b]!==void 0?d[b]:m[b],w=An(A),T=b===c?v.isActive:null;T===!1&&(g=y);let C=A===m[b]&&A!==d[b]&&w;if(C&&r&&t.manuallyAnimateOnMount&&(C=!1),v.protectedKeys={...x},!v.isActive&&T===null||!A&&!v.prevProp||Ki(A)||typeof A=="boolean")continue;const _=U2(v.prevProp,A);let D=_||b===c&&v.isActive&&!C&&w||y>g&&w,S=!1;const j=Array.isArray(A)?A:[A];let P=j.reduce(n(b),{});T===!1&&(P={});const{prevResolvedValues:R={}}=v,O={...R,...P},F=k=>{D=!0,h.has(k)&&(S=!0,h.delete(k)),v.needsAnimating[k]=!0;const N=t.getValue(k);N&&(N.liveStyle=!1)};for(const k in O){const N=P[k],U=R[k];if(x.hasOwnProperty(k))continue;let $=!1;mo(N)&&mo(U)?$=!Ip(N,U):$=N!==U,$?N!=null?F(k):h.add(k):N!==void 0&&h.has(k)?F(k):v.protectedKeys[k]=!0}v.prevProp=A,v.prevResolvedValues=P,v.isActive&&(x={...x,...P}),r&&t.blockInitialAnimation&&(D=!1);const M=C&&_;D&&(!M||S)&&u.push(...j.map(k=>{const N={type:b};if(typeof k=="string"&&r&&!M&&t.manuallyAnimateOnMount&&t.parent){const{parent:U}=t,$=$r(U,k);if(U.enteringChildren&&$){const{delayChildren:L}=$.transition||{};N.delay=Pp(U.enteringChildren,t,L)}}return{animation:k,options:N}}))}if(h.size){const y={};if(typeof d.initial!="boolean"){const b=$r(t,Array.isArray(d.initial)?d.initial[0]:d.initial);b&&b.transition&&(y.transition=b.transition)}h.forEach(b=>{const v=t.getBaseTarget(b),A=t.getValue(b);A&&(A.liveStyle=!0),y[b]=v??null}),u.push({animation:y})}let f=!!u.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(f=!1),r=!1,f?s(u):Promise.resolve()}function o(c,d){var u;if(a[c].isActive===d)return Promise.resolve();(u=t.variantChildren)==null||u.forEach(h=>{var x;return(x=h.animationState)==null?void 0:x.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const h in a)a[h].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Wm()}}}function U2(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!Ip(s,t):!1}function cr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Wm(){return{animate:cr(!0),whileInView:cr(),whileHover:cr(),whileTap:cr(),whileDrag:cr(),whileFocus:cr(),exit:cr()}}class Ja{constructor(s){this.isMounted=!1,this.node=s}update(){}}class B2 extends Ja{constructor(s){super(s),s.animationState||(s.animationState=$2(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Ki(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 V2=0;class z2 extends Ja{constructor(){super(...arguments),this.id=V2++}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 H2={animation:{Feature:B2},exit:{Feature:z2}};function Tn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function On(t){return{point:{x:t.pageX,y:t.pageY}}}const W2=t=>s=>uc(s)&&t(s,On(s));function gn(t,s,a,r){return Tn(t,s,W2(a),r)}const Fp=1e-4,G2=1-Fp,K2=1+Fp,Mp=.01,Y2=0-Mp,Z2=0+Mp;function Ps(t){return t.max-t.min}function X2(t,s,a){return Math.abs(t-s)<=a}function Gm(t,s,a,r=.5){t.origin=r,t.originPoint=Kt(s.min,s.max,t.origin),t.scale=Ps(a)/Ps(s),t.translate=Kt(a.min,a.max,t.origin)-t.originPoint,(t.scale>=G2&&t.scale<=K2||isNaN(t.scale))&&(t.scale=1),(t.translate>=Y2&&t.translate<=Z2||isNaN(t.translate))&&(t.translate=0)}function fn(t,s,a,r){Gm(t.x,s.x,a.x,r?r.originX:void 0),Gm(t.y,s.y,a.y,r?r.originY:void 0)}function Km(t,s,a){t.min=a.min+s.min,t.max=t.min+Ps(s)}function Q2(t,s,a){Km(t.x,s.x,a.x),Km(t.y,s.y,a.y)}function Ym(t,s,a){t.min=s.min-a.min,t.max=t.min+Ps(s)}function yn(t,s,a){Ym(t.x,s.x,a.x),Ym(t.y,s.y,a.y)}function aa(t){return[t("x"),t("y")]}const _p=({current:t})=>t?t.ownerDocument.defaultView:null,Zm=(t,s)=>Math.abs(t-s);function J2(t,s){const a=Zm(t.x,s.x),r=Zm(t.y,s.y);return Math.sqrt(a**2+r**2)}class Lp{constructor(s,a,{transformPagePoint:r,contextWindow:n=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=Tl(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,g=J2(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!g)return;const{point:f}=h,{timestamp:y}=vs;this.history.push({...f,timestamp:y});const{onStart:b,onMove:v}=this.handlers;x||(b&&b(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,h)},this.handlePointerMove=(h,x)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=Sl(x,this.transformPagePoint),Vt.update(this.updatePoint,!0)},this.handlePointerUp=(h,x)=>{this.end();const{onEnd:g,onSessionEnd:f,resumeAnimation:y}=this.handlers;if(this.dragSnapToOrigin&&y&&y(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=Tl(h.type==="pointercancel"?this.lastMoveEventInfo:Sl(x,this.transformPagePoint),this.history);this.startEvent&&g&&g(h,b),f&&f(h,b)},!uc(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=On(s),c=Sl(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=vs;this.history=[{...d,timestamp:m}];const{onSessionStart:u}=a;u&&u(s,Tl(c,this.history)),this.removeListeners=Mn(gn(this.contextWindow,"pointermove",this.handlePointerMove),gn(this.contextWindow,"pointerup",this.handlePointerUp),gn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),Za(this.updatePoint)}}function Sl(t,s){return s?{point:s(t.point)}:t}function Xm(t,s){return{x:t.x-s.x,y:t.y-s.y}}function Tl({point:t},s){return{point:t,delta:Xm(t,Op(s)),offset:Xm(t,q2(s)),velocity:eC(s,.1)}}function q2(t){return t[0]}function Op(t){return t[t.length-1]}function eC(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Op(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>ja(s)));)a--;if(!r)return{x:0,y:0};const i=ra(n.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const l={x:(n.x-r.x)/i,y:(n.y-r.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function tC(t,{min:s,max:a},r){return s!==void 0&&t<s?t=r?Kt(s,t,r.min):Math.max(t,s):a!==void 0&&t>a&&(t=r?Kt(a,t,r.max):Math.min(t,a)),t}function Qm(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 sC(t,{top:s,left:a,bottom:r,right:n}){return{x:Qm(t.x,a,n),y:Qm(t.y,s,r)}}function Jm(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 aC(t,s){return{x:Jm(t.x,s.x),y:Jm(t.y,s.y)}}function rC(t,s){let a=.5;const r=Ps(t),n=Ps(s);return n>r?a=Nn(s.min,s.max-r,t.min):r>n&&(a=Nn(t.min,t.max-n,s.min)),Fa(0,1,a)}function nC(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 ho=.35;function iC(t=ho){return t===!1?t=0:t===!0&&(t=ho),{x:qm(t,"left","right"),y:qm(t,"top","bottom")}}function qm(t,s,a){return{min:eu(t,s),max:eu(t,a)}}function eu(t,s){return typeof t=="number"?t:t[s]||0}const lC=new WeakMap;class oC{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=Jt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:a=!1,distanceThreshold:r}={}){const{presenceContext:n}=this.visualElement;if(n&&n.isPresent===!1)return;const i=u=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(On(u).point)},l=(u,h)=>{const{drag:x,dragPropagation:g,onDragStart:f}=this.getProps();if(x&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=h1(x),!this.openDragLock))return;this.latestPointerEvent=u,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),aa(b=>{let v=this.getAxisMotionValue(b).get()||0;if(Na.test(v)){const{projection:A}=this.visualElement;if(A&&A.layout){const w=A.layout.layoutBox[b];w&&(v=Ps(w)*(parseFloat(v)/100))}}this.originPoint[b]=v}),f&&Vt.postRender(()=>f(u,h)),uo(this.visualElement,"transform");const{animationState:y}=this.visualElement;y&&y.setActive("whileDrag",!0)},o=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h;const{dragPropagation:x,dragDirectionLock:g,onDirectionLock:f,onDrag:y}=this.getProps();if(!x&&!this.openDragLock)return;const{offset:b}=h;if(g&&this.currentDirection===null){this.currentDirection=cC(b),this.currentDirection!==null&&f&&f(this.currentDirection);return}this.updateAxis("x",h.point,b),this.updateAxis("y",h.point,b),this.visualElement.render(),y&&y(u,h)},c=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h,this.stop(u,h),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>aa(u=>{var h;return this.getAnimationState(u)==="paused"&&((h=this.getAxisMotionValue(u).animation)==null?void 0:h.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new Lp(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:_p(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&&Vt.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||!Kn(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=tC(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&&Pr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=sC(r.layoutBox,s):this.constraints=!1,this.elastic=iC(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&aa(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=nC(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Pr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=d2(r,n.root,this.visualElement.getTransformPagePoint());let l=aC(n.layout.layoutBox,i);if(a){const o=a(l2(l));this.hasMutatedConstraints=!!o,o&&(l=jp(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=aa(m=>{if(!Kn(m,a,this.currentDirection))return;let u=c&&c[m]||{};l&&(u={min:0,max:0});const h=n?200:1e6,x=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:h,bounceDamping:x,timeConstant:750,restDelta:1,restSpeed:10,...i,...u};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return uo(this.visualElement,s),r.start(Nc(s,r,0,a,this.visualElement,!1))}stopAnimation(){aa(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){aa(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){aa(a=>{const{drag:r}=this.getProps();if(!Kn(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]-Kt(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Pr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};aa(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=rC({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(),aa(l=>{if(!Kn(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(Kt(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;lC.set(this.visualElement,this);const s=this.visualElement.current,a=gn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();Pr(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()),Vt.read(r);const l=Tn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(aa(m=>{const u=this.getAxisMotionValue(m);u&&(this.originPoint[m]+=c[m].translate,u.set(u.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=ho,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Kn(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function cC(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class dC extends Ja{constructor(s){super(s),this.removeGroupControls=ia,this.removeListeners=ia,this.controls=new oC(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ia}unmount(){this.removeGroupControls(),this.removeListeners()}}const tu=t=>(s,a)=>{t&&Vt.postRender(()=>t(s,a))};class mC extends Ja{constructor(){super(...arguments),this.removePointerDownListener=ia}onPointerDown(s){this.session=new Lp(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:_p(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:tu(s),onStart:tu(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&Vt.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=gn(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 ii={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function su(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const ln={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(qe.test(t))t=parseFloat(t);else return t;const a=su(t,s.target.x),r=su(t,s.target.y);return`${a}% ${r}%`}},uC={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Xa.parse(t);if(n.length>5)return r;const i=Xa.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=Kt(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 kl=!1;class xC extends p.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;M1(hC),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),kl&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),ii.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,kl=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||Vt.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),mc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;kl=!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 $p(t){const[s,a]=lp(),r=p.useContext(zo);return e.jsx(xC,{...t,layoutGroup:r,switchLayoutGroup:p.useContext(bp),isPresent:s,safeToRemove:a})}const hC={borderRadius:{...ln,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:ln,borderTopRightRadius:ln,borderBottomLeftRadius:ln,borderBottomRightRadius:ln,boxShadow:uC};function pC(t,s,a){const r=As(t)?t:Br(t);return r.start(Nc("",r,s,a)),r.animation}const gC=(t,s)=>t.depth-s.depth;class fC{constructor(){this.children=[],this.isDirty=!1}add(s){Go(this.children,s),this.isDirty=!0}remove(s){Ko(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(gC),this.isDirty=!1,this.children.forEach(s)}}function yC(t,s){const a=Vs.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Za(r),t(i-s))};return Vt.setup(r,!0),()=>Za(r)}const Up=["TopLeft","TopRight","BottomLeft","BottomRight"],bC=Up.length,au=t=>typeof t=="string"?parseFloat(t):t,ru=t=>typeof t=="number"||qe.test(t);function vC(t,s,a,r,n,i){n?(t.opacity=Kt(0,a.opacity??1,jC(r)),t.opacityExit=Kt(s.opacity??1,0,NC(r))):i&&(t.opacity=Kt(s.opacity??1,a.opacity??1,r));for(let l=0;l<bC;l++){const o=`border${Up[l]}Radius`;let c=nu(s,o),d=nu(a,o);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||ru(c)===ru(d)?(t[o]=Math.max(Kt(au(c),au(d),r),0),(Na.test(d)||Na.test(c))&&(t[o]+="%")):t[o]=d}(s.rotate||a.rotate)&&(t.rotate=Kt(s.rotate||0,a.rotate||0,r))}function nu(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const jC=Bp(0,.5,Th),NC=Bp(.5,.95,ia);function Bp(t,s,a){return r=>r<t?0:r>s?1:a(Nn(t,s,r))}function iu(t,s){t.min=s.min,t.max=s.max}function sa(t,s){iu(t.x,s.x),iu(t.y,s.y)}function lu(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function ou(t,s,a,r,n){return t-=s,t=Ni(t,1/a,r),n!==void 0&&(t=Ni(t,1/n,r)),t}function wC(t,s=0,a=1,r=.5,n,i=t,l=t){if(Na.test(s)&&(s=parseFloat(s),s=Kt(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=Kt(i.min,i.max,r);t===i&&(o-=s),t.min=ou(t.min,s,a,o,n),t.max=ou(t.max,s,a,o,n)}function cu(t,s,[a,r,n],i,l){wC(t,s[a],s[r],s[n],s.scale,i,l)}const CC=["x","scaleX","originX"],AC=["y","scaleY","originY"];function du(t,s,a,r){cu(t.x,s,CC,a?a.x:void 0,r?r.x:void 0),cu(t.y,s,AC,a?a.y:void 0,r?r.y:void 0)}function mu(t){return t.translate===0&&t.scale===1}function Vp(t){return mu(t.x)&&mu(t.y)}function uu(t,s){return t.min===s.min&&t.max===s.max}function SC(t,s){return uu(t.x,s.x)&&uu(t.y,s.y)}function xu(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function zp(t,s){return xu(t.x,s.x)&&xu(t.y,s.y)}function hu(t){return Ps(t.x)/Ps(t.y)}function pu(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class TC{constructor(){this.members=[]}add(s){Go(this.members,s),s.scheduleRender()}remove(s){if(Ko(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 kC(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:u,rotateY:h,skewX:x,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),u&&(r+=`rotateX(${u}deg) `),h&&(r+=`rotateY(${h}deg) `),x&&(r+=`skewX(${x}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 Rl=["","X","Y","Z"],RC=1e3;let DC=0;function Dl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Hp(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=Rp(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Vt,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Hp(r)}function Wp({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=DC++,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(EC),this.nodes.forEach(LC),this.nodes.forEach(OC),this.nodes.forEach(FC)},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 fC)}addEventListener(l,o){return this.eventHandlers.has(l)||this.eventHandlers.set(l,new Xo),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=ip(l)&&!v1(l),this.instance=l;const{layoutId:o,layout:c,visualElement:d}=this.options;if(d&&!d.current&&d.mount(l),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||o)&&(this.isLayoutDirty=!0),t){let m,u=0;const h=()=>this.root.updateBlockedByResize=!1;Vt.read(()=>{u=window.innerWidth}),t(l,()=>{const x=window.innerWidth;x!==u&&(u=x,this.root.updateBlockedByResize=!0,m&&m(),m=yC(h,250),ii.hasAnimatedSinceResize&&(ii.hasAnimatedSinceResize=!1,this.nodes.forEach(yu)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:u,hasRelativeLayoutChanged:h,layout:x})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||zC,{onLayoutAnimationStart:f,onLayoutAnimationComplete:y}=d.getProps(),b=!this.targetLayout||!zp(this.targetLayout,x),v=!u&&h;if(this.options.layoutRoot||this.resumeFrom||v||u&&(b||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const A={...cc(g,"layout"),onPlay:f,onComplete:y};(d.shouldReduceMotion||this.options.layoutRoot)&&(A.delay=0,A.type=!1),this.startAnimation(A),this.setAnimationOrigin(m,v)}else u||yu(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=x})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Za(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach($C),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&&Hp(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let m=0;m<this.path.length;m++){const u=this.path[m];u.shouldResetTransform=!0,u.updateScroll("snapshot"),u.options.layoutRoot&&u.willUpdate(!1)}const{layoutId:o,layout:c}=this.options;if(o===void 0&&!c)return;const d=this.getTransformTemplate();this.prevTransformTemplateValue=d?d(this.latestValues,""):void 0,this.updateSnapshot(),l&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(gu);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(fu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(_C),this.nodes.forEach(PC),this.nodes.forEach(IC)):this.nodes.forEach(fu),this.clearAllSnapshots();const o=Vs.now();vs.delta=Fa(0,1e3/60,o-vs.timestamp),vs.timestamp=o,vs.isProcessing=!0,yl.update.process(vs),yl.preRender.process(vs),yl.render.process(vs),vs.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,mc.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(MC),this.sharedNodes.forEach(UC)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Vt.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Vt.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ps(this.snapshot.measuredBox.x)&&!Ps(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=Jt(),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&&!Vp(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,m=d!==this.prevTransformTemplateValue;l&&this.instance&&(o||ur(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)),HC(c),{animationId:this.root.animationId,measuredBox:o,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var d;const{visualElement:l}=this.options;if(!l)return Jt();const o=l.measureViewportBox();if(!(((d=this.scroll)==null?void 0:d.wasRoot)||this.path.some(WC))){const{scroll:m}=this.root;m&&(Ir(o.x,m.offset.x),Ir(o.y,m.offset.y))}return o}removeElementScroll(l){var c;const o=Jt();if(sa(o,l),(c=this.scroll)!=null&&c.wasRoot)return o;for(let d=0;d<this.path.length;d++){const m=this.path[d],{scroll:u,options:h}=m;m!==this.root&&u&&h.layoutScroll&&(u.wasRoot&&sa(o,l),Ir(o.x,u.offset.x),Ir(o.y,u.offset.y))}return o}applyTransform(l,o=!1){const c=Jt();sa(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&&Er(c,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),ur(m.latestValues)&&Er(c,m.latestValues)}return ur(this.latestValues)&&Er(c,this.latestValues),c}removeTransform(l){const o=Jt();sa(o,l);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!ur(d.latestValues))continue;lo(d.latestValues)&&d.updateSnapshot();const m=Jt(),u=d.measurePageBox();sa(m,u),du(o,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return ur(this.latestValues)&&du(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!==vs.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(l=!1){var h;const o=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=o.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=o.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=o.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==o;if(!(l||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:m,layoutId:u}=this.options;if(!(!this.layout||!(m||u))){if(this.resolvedRelativeTargetAt=vs.timestamp,!this.targetDelta&&!this.relativeTarget){const x=this.getClosestProjectingParent();x&&x.layout&&this.animationProgress!==1?(this.relativeParent=x,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Jt(),this.relativeTargetOrigin=Jt(),yn(this.relativeTargetOrigin,this.layout.layoutBox,x.layout.layoutBox),sa(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Jt(),this.targetWithTransforms=Jt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Q2(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):sa(this.target,this.layout.layoutBox),wp(this.target,this.targetDelta)):sa(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const x=this.getClosestProjectingParent();x&&!!x.resumingFrom==!!this.resumingFrom&&!x.options.layoutScroll&&x.target&&this.animationProgress!==1?(this.relativeParent=x,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Jt(),this.relativeTargetOrigin=Jt(),yn(this.relativeTargetOrigin,this.target,x.target),sa(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||lo(this.parent.latestValues)||Np(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var g;const l=this.getLead(),o=!!this.resumingFrom||this!==l;let c=!0;if((this.isProjectionDirty||(g=this.parent)!=null&&g.isProjectionDirty)&&(c=!1),o&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===vs.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;sa(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,h=this.treeScale.y;c2(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=Jt());const{target:x}=l;if(!x){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(lu(this.prevProjectionDelta.x,this.projectionDelta.x),lu(this.prevProjectionDelta.y,this.projectionDelta.y)),fn(this.projectionDelta,this.layoutCorrected,x,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==h||!pu(this.projectionDelta.x,this.prevProjectionDelta.x)||!pu(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",x))}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=Fr(),this.projectionDelta=Fr(),this.projectionDeltaWithTransform=Fr()}setAnimationOrigin(l,o=!1){const c=this.snapshot,d=c?c.latestValues:{},m={...this.latestValues},u=Fr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!o;const h=Jt(),x=c?c.source:void 0,g=this.layout?this.layout.source:void 0,f=x!==g,y=this.getStack(),b=!y||y.members.length<=1,v=!!(f&&!b&&this.options.crossfade===!0&&!this.path.some(VC));this.animationProgress=0;let A;this.mixTargetDelta=w=>{const T=w/1e3;bu(u.x,l.x,T),bu(u.y,l.y,T),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(yn(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),BC(this.relativeTarget,this.relativeTargetOrigin,h,T),A&&SC(this.relativeTarget,A)&&(this.isProjectionDirty=!1),A||(A=Jt()),sa(A,this.relativeTarget)),f&&(this.animationValues=m,vC(m,d,this.latestValues,T,v,b)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=T},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(Za(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Vt.update(()=>{ii.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Br(0)),this.currentAnimation=pC(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(RC),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&&Gp(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Jt();const u=Ps(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+u;const h=Ps(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+h}sa(o,c),Er(o,m),fn(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new TC),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&&Dl("z",l,d,this.animationValues);for(let m=0;m<Rl.length;m++)Dl(`rotate${Rl[m]}`,l,d,this.animationValues),Dl(`skew${Rl[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=ni(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=ni(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!ur(this.latestValues)&&(l.transform=c?c({},""):"none",this.hasProjected=!1);return}l.visibility="";const m=d.animationValues||d.latestValues;this.applyTransformsToTarget();let u=kC(this.projectionDeltaWithTransform,this.treeScale,m);c&&(u=c(m,u)),l.transform=u;const{x:h,y:x}=this.projectionDelta;l.transformOrigin=`${h.origin*100}% ${x.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 Sn){if(m[g]===void 0)continue;const{correct:f,applyTo:y,isCSSVariable:b}=Sn[g],v=u==="none"?m[g]:f(m[g],d);if(y){const A=y.length;for(let w=0;w<A;w++)l[y[w]]=v}else b?this.options.visualElement.renderState.vars[g]=v:l[g]=v}this.options.layoutId&&(l.pointerEvents=d===this?ni(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(gu),this.root.sharedNodes.clear()}}}function PC(t){t.updateLayout()}function IC(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"?aa(u=>{const h=l?s.measuredBox[u]:s.layoutBox[u],x=Ps(h);h.min=r[u].min,h.max=h.min+x}):Gp(i,s.layoutBox,r)&&aa(u=>{const h=l?s.measuredBox[u]:s.layoutBox[u],x=Ps(r[u]);h.max=h.min+x,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+x)});const o=Fr();fn(o,r,s.layoutBox);const c=Fr();l?fn(c,t.applyTransform(n,!0),s.measuredBox):fn(c,r,s.layoutBox);const d=!Vp(o);let m=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:h,layout:x}=u;if(h&&x){const g=Jt();yn(g,s.layoutBox,h.layoutBox);const f=Jt();yn(f,r,x.layoutBox),zp(g,f)||(m=!0),u.options.layoutRoot&&(t.relativeTarget=f,t.relativeTargetOrigin=g,t.relativeParent=u)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function EC(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 FC(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function MC(t){t.clearSnapshot()}function gu(t){t.clearMeasurements()}function fu(t){t.isLayoutDirty=!1}function _C(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function yu(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function LC(t){t.resolveTargetDelta()}function OC(t){t.calcProjection()}function $C(t){t.resetSkewAndRotation()}function UC(t){t.removeLeadSnapshot()}function bu(t,s,a){t.translate=Kt(s.translate,0,a),t.scale=Kt(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function vu(t,s,a,r){t.min=Kt(s.min,a.min,r),t.max=Kt(s.max,a.max,r)}function BC(t,s,a,r){vu(t.x,s.x,a.x,r),vu(t.y,s.y,a.y,r)}function VC(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const zC={duration:.45,ease:[.4,0,.1,1]},ju=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Nu=ju("applewebkit/")&&!ju("chrome/")?Math.round:ia;function wu(t){t.min=Nu(t.min),t.max=Nu(t.max)}function HC(t){wu(t.x),wu(t.y)}function Gp(t,s,a){return t==="position"||t==="preserve-aspect"&&!X2(hu(s),hu(a),.2)}function WC(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const GC=Wp({attachResizeListener:(t,s)=>Tn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Pl={current:void 0},Kp=Wp({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Pl.current){const t=new GC({});t.mount(window),t.setOptions({layoutScroll:!0}),Pl.current=t}return Pl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),KC={pan:{Feature:mC},drag:{Feature:dC,ProjectionNode:Kp,MeasureLayout:$p}};function Cu(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&&Vt.postRender(()=>i(s,On(s)))}class YC extends Ja{mount(){const{current:s}=this.node;s&&(this.unmount=p1(s,(a,r)=>(Cu(this.node,r,"Start"),n=>Cu(this.node,n,"End"))))}unmount(){}}class ZC extends Ja{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=Mn(Tn(this.node.current,"focus",()=>this.onFocus()),Tn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Au(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&&Vt.postRender(()=>i(s,On(s)))}class XC extends Ja{mount(){const{current:s}=this.node;s&&(this.unmount=b1(s,(a,r)=>(Au(this.node,r,"Start"),(n,{success:i})=>Au(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const po=new WeakMap,Il=new WeakMap,QC=t=>{const s=po.get(t.target);s&&s(t)},JC=t=>{t.forEach(QC)};function qC({root:t,...s}){const a=t||document;Il.has(a)||Il.set(a,{});const r=Il.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(JC,{root:t,...s})),r[n]}function eA(t,s,a){const r=qC(s);return po.set(t,a),r.observe(t),()=>{po.delete(t),r.unobserve(t)}}const tA={some:0,all:1};class sA extends Ja{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:tA[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:u}=this.node.getProps(),h=d?m:u;h&&h(c)};return eA(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(aA(s,a))&&this.startObserver()}unmount(){}}function aA({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const rA={inView:{Feature:sA},tap:{Feature:XC},focus:{Feature:ZC},hover:{Feature:YC}},nA={layout:{ProjectionNode:Kp,MeasureLayout:$p}},iA={...H2,...rA,...KC,...nA},ms=i2(iA,b2),on=[{id:"claim-management",name:"Claim Management",description:"End-to-end dealer claim processing workflow with automatic IO generation and budget blocking",category:"Dealer Operations",icon:ls,color:"from-blue-500 to-indigo-600",estimatedTime:"5-7 days",steps:7,features:["Automatic IO confirmation","Budget blocking","Document verification","E-invoice generation","Credit note issuance"],disabled:!1},{id:"vendor-payment",name:"Vendor Payment",description:"Streamlined vendor payment approval with PO validation and financial controls",category:"Finance",icon:hx,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 lA({open:t,onClose:s,onSelectTemplate:a}){var d,m,u;const[r,n]=p.useState(null),[i,l]=p.useState(!1);p.useEffect(()=>{const h=at.getUserData();l((h==null?void 0:h.jobTitle)==="Dealer")},[]);const o=h=>{if(i)return;const x=on.find(g=>g.id===h);x!=null&&x.disabled||n(h)},c=()=>{r&&(a(r),s())};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(ct,{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(dt,{className:"sr-only",children:"Select a Template"}),e.jsx(Et,{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(Ss,{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(ms.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(Pi,{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:on.map((h,x)=>{const g=h.icon,f=r===h.id,y=i||h.disabled;return e.jsx(ms.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:x*.1},whileHover:y?{}:{scale:1.03},whileTap:y?{}:{scale:.98},children:e.jsxs(J,{className:`h-full transition-all duration-300 border-2 ${y?"opacity-50 cursor-not-allowed border-gray-200":f?"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(h.id),children:[e.jsxs(me,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${h.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),f&&e.jsx(ms.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(Nr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ue,{className:"text-xl mb-2",children:h.name}),e.jsx(Te,{className:"text-sm leading-relaxed",children:h.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(Ve,{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"})]}),h.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(Ve,{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(q,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(ie,{variant:"secondary",className:"text-xs",children:h.category})}),e.jsx($t,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Xe,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:h.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ht,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[h.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:[h.features.slice(0,3).map((b,v)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(Pe,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:b})]},v)),h.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",h.features.length-3," more features"]})]})]})]})]})},h.id)})}),e.jsxs(ms.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"flex flex-col sm:flex-row justify-center gap-4 mt-4",children:[e.jsx(I,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(I,{onClick:c,disabled:!r||i||((d=on.find(h=>h.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=on.find(h=>h.id===r))!=null&&m.disabled)?"bg-blue-600 hover:bg-blue-700":"bg-gray-400 cursor-not-allowed"}`,children:["Continue with Template",e.jsx(xs,{className:"w-4 h-4"})]})]}),e.jsx(Wi,{children:r&&e.jsx(ms.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"mt-6 text-center",children:e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold text-blue-600",children:(u=on.find(h=>h.id===r))==null?void 0:u.name})]})})})]})})]})})}function Cr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=p.useState(100),[m,u]=p.useState(0),[h,x]=p.useState(null),[g,f]=p.useState(!1),[y,b]=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"),A=s.toLowerCase().includes("pdf"),w=v||A;p.useEffect(()=>{if(!l||!w||!a){x(null);return}return(async()=>{f(!0),b(null);try{let R=a;a.startsWith("/")&&!a.startsWith("//")&&(R=`${window.location.origin}${a}`);const F=await fetch(R,{headers:{Accept:A?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!F.ok){const k=await F.text().catch(()=>"");throw new Error(`Failed to load file: ${F.status} ${F.statusText}. ${k}`)}const M=await F.blob();if(M.size===0)throw new Error("File is empty or could not be loaded");A&&!M.type.includes("pdf")&&M.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${M.type}`);const B=window.URL.createObjectURL(M);x(B)}catch(j){console.error("Failed to load file for preview:",j),b(j instanceof Error?j.message:"Failed to load file for preview")}finally{f(!1)}})(),()=>{h&&(window.URL.revokeObjectURL(h),x(null))}},[l,a,w,A]);const T=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},C=()=>d(S=>Math.min(S+25,200)),_=()=>d(S=>Math.max(S-25,50)),D=()=>u(S=>(S+90)%360);return e.jsx(ht,{open:l,onOpenChange:o,children:e.jsx(ct,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(pt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(xt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(dt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`• ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[v&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(I,{variant:"ghost",size:"sm",onClick:_,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(w0,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[c,"%"]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:C,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(C0,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(px,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(I,{variant:"outline",size:"sm",onClick:T,className:"gap-2 h-9",children:[e.jsx(wt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})]})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:g?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx(Ze,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):y?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(gt,{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:y}),i&&n&&e.jsxs(I,{onClick:T,className:"gap-2",children:[e.jsx(wt,{className:"h-4 w-4"}),"Download ",t]})]}):w&&h?e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:h,alt:t,style:{transform:`scale(${c/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),A&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:h,className:"w-full h-full rounded-lg border-0",title:t,style:{minHeight:"70vh",height:"100%"},onError:()=>{b("Failed to load PDF preview")}})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(xt,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),i&&n&&e.jsxs(I,{onClick:T,className:"gap-2",children:[e.jsx(wt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function $n({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(dt,{className:"flex items-center gap-2",children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Et,{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(kt,{children:e.jsx(I,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const Js=async t=>{const s=t?{category:t}:{};return(await je.get("/users/configurations",{params:s})).data.data},Zi=async t=>{const s=t?{category:t}:{};return(await je.get("/admin/configurations",{params:s})).data.data},ks=async(t,s)=>{await je.put(`/admin/configurations/${t}`,{configValue:s})},oA=async t=>{await je.post(`/admin/configurations/${t}/reset`)},cA=async t=>{const s=t?{year:t}:{};return(await je.get("/admin/holidays",{params:s})).data.data},dA=async t=>(await je.post("/admin/holidays",t)).data.data,mA=async(t,s)=>(await je.put(`/admin/holidays/${t}`,s)).data.data,uA=async t=>{await je.delete(`/admin/holidays/${t}`)},xA=async()=>(await je.get("/config/activity-types")).data.data,hA=async t=>{const s={activeOnly:t.toString()};return(await je.get("/admin/activity-types",{params:s})).data.data},pA=async t=>(await je.post("/admin/activity-types",t)).data.data,gA=async(t,s)=>(await je.put(`/admin/activity-types/${t}`,s)).data.data,fA=async t=>{await je.delete(`/admin/activity-types/${t}`)},yA={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 bA(t,s,a){const[r,n]=p.useState(yA),[i,l]=p.useState(null),[o,c]=p.useState(t),[d,m]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[u,h]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[x,g]=p.useState([]);return p.useEffect(()=>{(async()=>{var b;try{const v=await Js("DOCUMENT_POLICY"),A={};v.forEach(P=>{A[P.configKey]=P.configValue});const w=parseInt(A.MAX_FILE_SIZE_MB||"10"),C=(A.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(P=>P.trim().toLowerCase());h({maxFileSizeMB:w,allowedFileTypes:C});const _=await Js("SYSTEM_SETTINGS"),D=await Js("WORKFLOW_SHARING"),S=[..._,...D],j={};S.forEach(P=>{j[P.configKey]=P.configValue}),m({maxApprovalLevels:parseInt(j.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(j.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((b=j.ALLOW_ADD_SPECTATOR)==null?void 0:b.toLowerCase())==="true",maxSpectators:parseInt(j.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(v){console.error("Failed to load policies:",v)}})()},[]),p.useEffect(()=>{if(!t||!s)return;let y=!0;return(async()=>{try{c(!0);const b=await Cs(s);if(!y||!b)return;const v=b.workflow||{},A=Array.isArray(b.approvals)?b.approvals:[],w=Array.isArray(b.participants)?b.participants:[],T=Array.isArray(b.documents)?b.documents.filter(R=>!R.isDeleted):[];g(T);const C=(v.priority||"").toString().toLowerCase(),_={standard:"standard",express:"express"},D=v.templateType==="TEMPLATE"?"existing-template":"custom",S=a.find(R=>R.id===D)||a[0]||null;l(S);const j=A.sort((R,O)=>(R.levelNumber||0)-(O.levelNumber||0)).map(R=>{const O=Number(R.tatHours||24),F=Math.floor(O/24),M=O%24;return{id:R.approverId||`temp-${R.levelNumber}`,name:R.approverName||R.approverEmail||"",email:R.approverEmail||"",role:R.levelName||`Level ${R.levelNumber}`,department:"",avatar:(R.approverName||R.approverEmail||"XX").substring(0,2).toUpperCase(),level:R.levelNumber||1,canClose:!1,tat:F>0?F:M,tatType:F>0?"days":"hours",userId:R.approverId}}),P=w.filter(R=>(R.participantType||R.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(R.userEmail||R.user_email||R.email):!1).map((R,O)=>{const F=R.userId||R.user_id||R.id,M=R.userName||R.user_name||R.name||"",B=R.userEmail||R.user_email||R.email||"",N=(M||B||"XX").split(" ").map(U=>U[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${O}-${Date.now()}`,userId:F,name:M||B||"Spectator",email:B,role:"Spectator",department:R.department||"",avatar:N,level:1,canClose:!1}});n(R=>({...R,template:D,title:v.title||"",description:v.description||"",priority:_[C]||"standard",approvers:j,approverCount:j.length||1,spectators:P,maxLevel:Math.max(...j.map(O=>O.level||1),1)}))}catch(b){console.error("Failed to load draft:",b)}finally{y&&c(!1)}})(),()=>{y=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(y,b)=>{n(v=>({...v,[y]:b}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:u,existingDocuments:x,setExistingDocuments:g}}const Su=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function vA(t,s,a){const[r,n]=p.useState(t?2:1),i=Su.length,l=u=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u),o=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(u=>{if(!u||!u.email||!l(u.email))return!1;if(!u.userId)return!0;const h=u.tatType||"hours";return h==="hours"?u.tat&&u.tat>0&&u.tat<=720:h==="days"?u.tat&&u.tat>0&&u.tat<=30:!1});case 4:return!0;case 5:return!0;case 6:return!0;default:return!1}};return{currentStep:r,setCurrentStep:n,totalSteps:i,stepNames:Su,isStepValid:o,nextStep:()=>{o()&&(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),r<i&&n(r+1))},prevStep:()=>{r>1&&(n(r-1),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}))},goToStep:u=>{u>=1&&u<=i&&n(u)},validateEmail:l}}function jA(){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:(h,x,g="")=>{s({open:!0,type:h,email:x,message:g})},closeValidationModal:()=>{s(h=>({...h,open:!1}))},openPolicyViolationModal:h=>{r({open:!0,violations:h})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:h=>{i({open:!0,errors:h})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function NA(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function wA(t,s,a){var n;const r=NA(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 CA(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return wA(a,n,n===s)})}function Tu(t,s,a){const r=new Set((t.approvers||[]).map(i=>{var l;return(l=i==null?void 0:i.email)==null?void 0:l.toLowerCase()}).filter(Boolean)),n=(t.spectators||[]).filter(i=>(i==null?void 0:i.email)&&!r.has(i.email.toLowerCase()));return{templateId:(s==null?void 0:s.id)||null,templateType:(s==null?void 0:s.id)==="custom"?"CUSTOM":"TEMPLATE",title:t.title,description:t.description,priorityUi:t.priority==="express"?"express":"standard",approverCount:t.approverCount||1,approvers:(t.approvers||[]).map(i=>({userId:(i==null?void 0:i.userId)||"",email:(i==null?void 0:i.email)||"",name:i==null?void 0:i.name,tat:(i==null?void 0:i.tat)||"",tatType:(i==null?void 0:i.tatType)||"hours"})),spectators:n.map(i=>({userId:(i==null?void 0:i.userId)||"",name:(i==null?void 0:i.name)||"",email:(i==null?void 0:i.email)||""})),ccList:[],participants:[]}}function ku(t,s,a){const r=CA(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:r,participants:[],deleteDocumentIds:a.length>0?a:void 0}}function AA(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 Yp(t,s){return{id:(await Uo(t,s||[],"SUPPORTING")).id}}async function Zp(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await pN(t,s,a||[],r):await hN(t,s)}async function Xp(t){await Bo(t)}async function SA(t,s){const a=await Yp(t,s);return await Xp(a.id),a}async function TA(t,s,a,r){await Zp(t,s,a,r),await Xp(t)}function kA({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=p.useState(!1),[m,u]=p.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var f,y;if(c||m)return;const g=AA(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const b=ku(t,n,r);await TA(l,b,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 b=Tu(t,s,n),v=await SA(b,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(b){console.error("Failed to submit workflow:",b),K.error("Failed to Submit Request",{description:((y=(f=b==null?void 0:b.response)==null?void 0:f.data)==null?void 0:y.message)||(b==null?void 0:b.message)||"An error occurred while submitting the request.",duration:5e3}),d(!1)}},handleSaveDraft:async()=>{var g,f;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){u(!0);try{if(i&&l){const y=ku(t,n,r);await Zp(l,y,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 y=Tu(t,s,n),b=await Yp(y,a);K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:b.id,template:s})}}catch(y){console.error("Failed to save draft:",y),K.error("Failed to Save Draft",{description:((f=(g=y==null?void 0:y.response)==null?void 0:g.data)==null?void 0:f.message)||(y==null?void 0:y.message)||"An error occurred while saving the draft.",duration:5e3}),u(!1)}}}}}async function ca(t,s=10){return await je.get("/users/search",{params:{q:t,limit:s}})}async function la(t){var a;const s=await je.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function RA(t,s){return await je.post("/admin/users/assign-role",{email:t,role:s})}async function DA(t,s){return await je.put(`/admin/users/${t}/role`,{role:s})}async function PA(t,s=1,a=10){return await je.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function IA(){return await je.get("/admin/users/role-statistics")}async function EA(){var s,a;return((a=(s=(await je.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const Gs={searchUsers:ca,ensureUserExists:la,assignRole:RA,updateUserRole:DA,getUsersByRole:PA,getRoleStatistics:IA,getAllUsers:EA};async function FA(t,s){var a;if(t.email.toLowerCase()===s.toLowerCase())return{success:!1,error:{type:"self-assign",email:t.email,message:""}};try{const n=((a=(await ca(t.email,1)).data)==null?void 0:a.data)||[];if(n.length===0)return{success:!1,error:{type:"not-found",email:t.email,message:""}};const i=n[0];return i?(await la({userId:i.userId,email:i.email,displayName:i.displayName,firstName:i.firstName,lastName:i.lastName,department:i.department,phone:i.phone,mobilePhone:i.mobilePhone,designation:i.designation,jobTitle:i.jobTitle,manager:i.manager,employeeId:i.employeeId,employeeNumber:i.employeeNumber,secondEmail:i.secondEmail,location:i.location}),{success:!0}):{success:!1,error:{type:"error",email:t.email,message:"Could not retrieve user details. Please try again."}}}catch(r){return console.error(`Failed to validate approver ${t.email}:`,r),{success:!1,error:{type:"error",email:t.email,message:"Failed to validate user. Please try again or select a different user."}}}}async function MA(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 FA(l,s);if(!o.success)return{success:!1,error:o.error};try{const m=(((n=(await ca(l.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const u=await la({userId:m.userId,email:m.email,displayName:m.displayName,firstName:m.firstName,lastName:m.lastName,department:m.department,phone:m.phone,mobilePhone:m.mobilePhone,designation:m.designation,jobTitle:m.jobTitle,manager:m.manager,employeeId:m.employeeId,employeeNumber:m.employeeNumber,secondEmail:m.secondEmail,location:m.location});r[i]={...l,userId:u.userId,name:u.displayName||l.name,department:u.department||l.department,avatar:(u.displayName||u.email).substring(0,2).toUpperCase()}}}catch(c){console.error(`Failed to update approver ${l.email}:`,c)}}return{success:!0,validatedApprovers:r}}function _A({selectedTemplate:t,setSelectedTemplate:s,updateFormData:a,formData:r,currentStep:n,isStepValid:i,wizardNextStep:l,wizardPrevStep:o,user:c,openValidationModal:d,systemPolicy:m,onPolicyViolation:u,onSubmit:h}){const x=qs(),[g,f]=p.useState(!1),[y,b]=p.useState(null);return{showTemplateModal:g,setShowTemplateModal:f,previewDocument:y,selectTemplate:D=>{s(D),a("template",D.id),a("category",D.category),a("priority",D.priority);const S=new Date;S.setDate(S.getDate()+D.suggestedSLA),a("slaEndDate",S),D.id!=="custom"&&D.id!=="existing-template"&&x(`/create-admin-request/${D.id}`)},handleTemplateSelection:D=>{D==="claim-management"?x("/claim-management"):D==="vendor-payment"?x("/vendor-payment"):h&&h({templateType:D})},nextStep:async()=>{var D;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){f(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&u){const P=r.approverCount||1;if(P>m.maxApprovalLevels){u([{type:"Maximum Approval Levels Exceeded",message:`The request has ${P} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:P,maxValue:m.maxApprovalLevels}]);return}}const S=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",j=await MA(r.approvers,S);if(!j.success&&j.error){d(j.error.type,j.error.email,j.error.message);return}j.validatedApprovers&&a("approvers",j.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(D,S)=>{if(S){const j=D.documentId||D.document_id||"";b({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:Zr(j),fileSize:Number(D.fileSize||D.file_size||0),documentId:j})}else{const j=URL.createObjectURL(D);b({fileName:D.name,fileType:D.type||"application/octet-stream",fileUrl:j,fileSize:D.size,file:D})}},closePreview:()=>{y!=null&&y.fileUrl&&(y!=null&&y.file)&&URL.revokeObjectURL(y.fileUrl),b(null)}}}const Ru=[{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:Ii,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:De,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let wa=null;const Du=()=>wa,LA=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 wa&&wa.push(r),r},Xi=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 wa=a,a},OA=async t=>{await je.delete(`/templates/${t}`),wa&&(wa=wa.filter(s=>s.id!==t))},$A=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 wa&&(wa=wa.map(i=>i.id===t?n:i)),n};function Qp({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(Nr,{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 UA({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:c,loadingDraft:d,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(I,{variant:"outline",onClick:r,disabled:t===1,size:"sm",className:"sm:size-lg order-2 sm:order-1","data-testid":"wizard-footer-prev-button",children:[e.jsx(Ss,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Previous"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 order-1 sm:order-2","data-testid":"wizard-footer-actions",children:[e.jsx(I,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||o||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),e.jsx("span",{children:m?"Updating...":"Saving..."})]}):e.jsx("span",{children:m?"Update Draft":"Save Draft"})}),t===s?e.jsx(I,{onClick:i,disabled:!a||d||o||c,size:"sm",className:"sm:size-lg bg-green-600 hover:bg-green-700 flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-submit-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gx,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(I,{onClick:n,disabled:!a,size:"sm",className:"sm:size-lg flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-next-button",children:[e.jsx("span",{className:"hidden sm:inline",children:"Next Step"}),e.jsx("span",{className:"sm:hidden",children:"Next"}),e.jsx(xs,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const Pu=t=>{switch(t){case"high":return e.jsx(ga,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ht,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ys,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ht,{className:"w-4 h-4 text-gray-600"})}};function BA({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=p.useState("main"),l=qs(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},c=n==="main"?[...t,{id:"admin-templates-category",name:"Admin Templates",description:"Browse standardized request workflows created by your organization administrators",category:"Organization",icon:Vd,estimatedTime:"Variable",commonApprovers:[],suggestedSLA:0,priority:"medium",fields:{}}]:r;return e.jsxs(ms.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(I,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(Ss,{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(Vd,{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 f;const u=m.id==="existing-template"&&n==="main",h=u,x=m.id==="admin-templates-category",g=(s==null?void 0:s.id)===m.id;return e.jsx(ms.div,{whileHover:h?{}:{scale:1.03},whileTap:h?{}:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(J,{className:`h-full transition-all duration-300 border-2 ${h?"border-gray-200 bg-gray-50/50 opacity-85 cursor-not-allowed":g?"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:h?void 0:()=>o(m),"data-testid":`template-card-${m.id}-clickable`,children:[e.jsxs(me,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl flex items-center justify-center ${g||x?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${g||x?"text-blue-600":"text-gray-600"}`})}),g&&e.jsx(ms.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(Nr,{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(ue,{className:"text-xl","data-testid":`template-card-${m.id}-name`,children:m.name}),u&&e.jsx(ie,{variant:"outline",className:"text-xs bg-yellow-100 text-yellow-700 border-yellow-300 font-semibold","data-testid":`template-card-${m.id}-coming-soon-badge`,children:"Coming Soon"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ie,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),Pu(m.priority)]})]})]}),e.jsxs(q,{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($t,{}),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(Xe,{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(Bt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[((f=m.commonApprovers)==null?void 0:f.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(Wi,{children:s&&e.jsx(ms.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(J,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Wr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-sla",children:[e.jsx(ne,{className:"text-blue-900 font-semibold",children:"Suggested SLA"}),e.jsxs("p",{className:"text-blue-700 mt-1",children:[s.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-priority",children:[e.jsx(ne,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[Pu(s.priority),e.jsx("span",{className:"text-blue-700 capitalize",children:s.priority})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-duration",children:[e.jsx(ne,{className:"text-blue-900 font-semibold",children:"Estimated Duration"}),e.jsx("p",{className:"text-blue-700 mt-1",children:s.estimatedTime})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-approvers",children:[e.jsx(ne,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,u)=>e.jsx(ie,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${u}`,children:m},`${s.id}-approver-${u}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function Ie({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:Re("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground flex h-9 w-full min-w-0 rounded-md border border-gray-400 bg-white px-3 py-1 text-base text-gray-900 transition-all outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","hover:border-gray-500","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...a})}function VA({className:t,...s}){return e.jsx(Pf,{"data-slot":"radio-group",className:Re("grid gap-3",t),...s})}function Iu({className:t,...s}){return e.jsx(If,{"data-slot":"radio-group-item",className:Re("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(Ef,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(A0,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function zA({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(ms.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(De,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(ne,{htmlFor:"title",className:"text-base font-semibold",children:"Request Title *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Be specific and descriptive. This will be visible to all participants."}),e.jsx(Ie,{id:"title",placeholder:"e.g., Approval on new office location",value:t.title,onChange:r=>a("title",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-title-input"})]}),e.jsxs("div",{"data-testid":"basic-information-description-field",children:[e.jsx(ne,{htmlFor:"description",className:"text-base font-semibold",children:"Detailed Description *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Fn,{value:t.description||"",onChange:r=>a("description",r),placeholder:"Provide comprehensive details about your request including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px","data-testid":"basic-information-description-textarea"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6","data-testid":"basic-information-priority-section",children:e.jsxs("div",{"data-testid":"basic-information-priority-field",children:[e.jsx(ne,{className:"text-base font-semibold",children:"Priority Level *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"select priority for your request"}),e.jsxs(VA,{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(Iu,{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(Ri,{className:"w-4 h-4 text-red-600"}),e.jsx(ne,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ie,{variant:"destructive",className:"text-xs",children:"URGENT"})]}),e.jsx("p",{className:"text-xs text-red-700",children:"Includes calendar days in TAT - faster processing timeline"})]})]}),e.jsxs("div",{className:`flex items-center space-x-3 p-3 rounded-lg border cursor-pointer transition-all ${t.priority==="standard"?"border-blue-500 bg-blue-50":"border-gray-200 hover:bg-gray-50"}`,onClick:()=>a("priority","standard"),"data-testid":"basic-information-priority-standard-option",children:[e.jsx(Iu,{value:"standard",id:"standard"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Xe,{className:"w-4 h-4 text-blue-600"}),e.jsx(ne,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ie,{variant:"secondary",className:"text-xs",children:"DEFAULT"})]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Includes working days in TAT - regular processing timeline"})]})]})]})]})}),((s==null?void 0:s.fields.amount)||(s==null?void 0:s.fields.vendor)||(s==null?void 0:s.fields.timeline)||(s==null?void 0:s.fields.impact))&&e.jsxs("div",{className:"border-t pt-6","data-testid":"basic-information-additional-details",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Additional Details"}),e.jsxs("div",{className:"space-y-6",children:[(s==null?void 0:s.fields.amount)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-testid":"basic-information-amount-field",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Ie,{id:"amount",placeholder:"Enter amount",value:t.amount,onChange:r=>a("amount",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-amount-input"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(He,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Ge,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"USD",children:"USD ($)"}),e.jsx(X,{value:"EUR",children:"EUR (€)"}),e.jsx(X,{value:"GBP",children:"GBP (£)"}),e.jsx(X,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(ne,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Ie,{id:"vendor",placeholder:"Enter vendor or supplier name",value:t.vendor,onChange:r=>a("vendor",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-vendor-input"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{"data-testid":"basic-information-cost-center-field",children:[e.jsx(ne,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Ie,{id:"costCenter",placeholder:"e.g., Marketing, IT, Operations",value:t.costCenter,onChange:r=>a("costCenter",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-cost-center-input"})]}),e.jsxs("div",{"data-testid":"basic-information-project-field",children:[e.jsx(ne,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Ie,{id:"project",placeholder:"Associated project name or code",value:t.project,onChange:r=>a("project",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-project-input"})]})]})]})]})]})]})}function Jp(){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 u=c.slice(1),x=((m=(await ca(u,d)).data)==null?void 0:m.data)||[];s(x)}catch(u){console.error("User search failed:",u),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await la({userId:c.userId,email:c.email,displayName:c.displayName,firstName:c.firstName,lastName:c.lastName,department:c.department,phone:c.phone,mobilePhone:c.mobilePhone,designation:c.designation,jobTitle:c.jobTitle,manager:c.manager,employeeId:c.employeeId,employeeNumber:c.employeeNumber,secondEmail:c.secondEmail,location:c.location})}catch(d){throw console.error("Failed to ensure user exists:",d),d}}}}function qp(){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 u=c.slice(1),x=((m=(await ca(u,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:x}))}catch(u){console.error(`User search failed for index ${o}:`,u),s(h=>({...h,[o]:[]}))}finally{r(u=>({...u,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function HA({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var u;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=qp();p.useEffect(()=>{const h=t.approverCount||1,x=t.approvers||[];if(x.length<h){const g=[...x];for(let f=x.length;f<h;f++)g[f]||(g[f]={email:"",name:"",level:f+1,tat:""});s("approvers",g)}else x.length>h&&s("approvers",x.slice(0,h))},[t.approverCount,s]);const d=(h,x)=>{var b,v,A,w,T;const g=[...t.approvers],y=((b=g[h])==null?void 0:b.email)!==x;if(g[h]={...g[h],email:x,level:h+1,userId:y||(v=g[h])==null?void 0:v.userId,name:y||(A=g[h])==null?void 0:A.name,department:y||(w=g[h])==null?void 0:w.department,avatar:y||(T=g[h])==null?void 0:T.avatar},s("approvers",g),!x||!x.startsWith("@")||x.length<2){c(h);return}o(h,x,10)},m=async(h,x)=>{var g,f;try{if((g=t.approvers)==null?void 0:g.some((w,T)=>{var C,_;return T!==h&&(w.userId===x.userId||((C=w.email)==null?void 0:C.toLowerCase())===((_=x.email)==null?void 0:_.toLowerCase()))})){a({type:"error",email:x.email,message:"This user is already added as an approver in another level."});return}if((f=t.spectators)==null?void 0:f.some(w=>{var T,C;return w.userId===x.userId||((T=w.email)==null?void 0:T.toLowerCase())===((C=x.email)==null?void 0:C.toLowerCase())})){a({type:"error",email:x.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const v=await la({userId:x.userId,email:x.email,displayName:x.displayName,firstName:x.firstName,lastName:x.lastName,department:x.department,phone:x.phone,mobilePhone:x.mobilePhone,designation:x.designation,jobTitle:x.jobTitle,manager:x.manager,employeeId:x.employeeId,employeeNumber:x.employeeNumber,secondEmail:x.secondEmail,location:x.location}),A=[...t.approvers];A[h]={...A[h],email:x.email,name:x.displayName||[x.firstName,x.lastName].filter(Boolean).join(" "),userId:v.userId,level:h+1},s("approvers",A),c(h)}catch(y){console.error("Failed to ensure user exists:",y),a({type:"error",email:x.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(ms.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(Bt,{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(J,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(Ga,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(Te,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(q,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(ne,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:()=>{const h=t.approverCount||1,x=Math.max(1,h-1);s("approverCount",x),t.approvers.length>x&&s("approvers",t.approvers.slice(0,x))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(Co,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-2xl font-semibold w-12 text-center","data-testid":"approval-workflow-count-display",children:t.approverCount||1}),e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:()=>{const x=(t.approverCount||1)+1;if(x>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:x,maxValue:r.maxApprovalLevels}]);return}s("approverCount",x)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(us,{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(J,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(ds,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(Te,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(q,{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(Lt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-blue-900",children:"Request Initiator"}),e.jsx(ie,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-sm text-blue-700",children:"Creates and submits the request"})]})]})}),Array.from({length:t.approverCount||1},(h,x)=>{var b,v;const g=x+1,f=g===(t.approverCount||1),y=t.approvers[x]||{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 ${y.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 ${y.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]}),f&&e.jsx(ie,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(ne,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),y.email&&y.userId&&e.jsxs(ie,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Pe,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ie,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:y.email||"",onChange:A=>d(x,A.target.value),className:"h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full","data-testid":`approval-workflow-approver-${g}-email-input`}),(l[x]||(((b=i[x])==null?void 0:b.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:l[x]?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[x])==null?void 0:v.map(A=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(x,A),"data-testid":`approval-workflow-approver-${g}-search-result-${A.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:A.displayName||A.email}),e.jsx("div",{className:"text-xs text-gray-600",children:A.email})]},A.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-tat-field`,children:[e.jsx(ne,{htmlFor:`tat-${g}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ie,{id:`tat-${g}`,type:"number",placeholder:y.tatType==="days"?"7":"24",min:"1",max:y.tatType==="days"?"30":"720",value:y.tat||"",onChange:A=>{const w=[...t.approvers];w[x]={...w[x],tat:parseInt(A.target.value)||"",level:g,tatType:y.tatType||"hours"},s("approvers",w)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(He,{value:y.tatType||"hours",onValueChange:A=>{const w=[...t.approvers];w[x]={...w[x],tatType:A,level:g,tat:""},s("approvers",w)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(Ge,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"hours",children:"Hours"}),e.jsx(X,{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(Wr,{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},(h,x)=>`Level ${x+1} Approver`).join(" → "),". The final approver can close the request."]})]})]})}),e.jsx("div",{className:"p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Xe,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{var g;const h=((g=t.approvers)==null?void 0:g.reduce((f,y)=>{const b=Number(y.tat||0);return(y.tatType||"hours")==="days"?f+b:f+b/24},0))||0,x=Math.ceil(h);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[x," ",x===1?"Day":"Days"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Duration"})]})})()})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:(u=t.approvers)==null?void 0:u.map((h,x)=>{const g=Number(h.tat||0),y=(h.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 ",x+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[y," ",y===1?"hour":"hours"]})]})},x):null})}),(()=>{var g;const h=((g=t.approvers)==null?void 0:g.reduce((f,y)=>{const b=Number(y.tat||0);return(y.tatType||"hours")==="days"?f+b*24:f+b},0))||0,x=Math.ceil(h/8);return h===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:[h,"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:x}),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 WA({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=p.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=Jp(),u=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},h=async g=>{var f,y;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const b=t.spectators.some(A=>{var w,T;return A.userId===g.userId||((w=A.email)==null?void 0:w.toLowerCase())===((T=g.email)==null?void 0:T.toLowerCase())}),v=(f=t.approvers)==null?void 0:f.some(A=>{var w,T;return A.userId===g.userId||((w=A.email)==null?void 0:w.toLowerCase())===((T=g.email)==null?void 0:T.toLowerCase())});if(b){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(v){a({type:"error",email:g.email,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}try{const A=await m(g),w={id:A.userId,userId:A.userId,name:A.displayName||g.email.split("@")[0],email:A.email,avatar:(A.displayName||A.email).substring(0,2).toUpperCase(),role:"Spectator",department:A.department||"",level:1,canClose:!1},T=[...t.spectators,w];s("spectators",T),i(""),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 b=t.spectators.some(A=>{var w;return((w=A.email)==null?void 0:w.toLowerCase())===n.toLowerCase()}),v=(y=t.approvers)==null?void 0:y.some(A=>{var w;return((w=A.email)==null?void 0:w.toLowerCase())===n.toLowerCase()});if(b){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(v){a({type:"error",email:n,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}}},x=g=>{const f=t.spectators.filter(y=>y.id!==g);s("spectators",f)};return e.jsxs(ms.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(xt,{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(J,{"data-testid":"participants-spectators-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{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(xt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ie,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(Te,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2","data-testid":"participants-spectators-add-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-full",children:[e.jsx(Ie,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>u(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await h())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(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:()=>h(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(I,{size:"sm",onClick:()=>h(),disabled:!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"data-testid":"participants-spectators-add-button",children:"Add"})]}),e.jsxs("p",{className:"text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1",children:[e.jsx(Wr,{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(es,{className:"h-6 w-6",children:e.jsx(ts,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>x(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(gt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function GA({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const u=f=>{const y=Array.from(f.target.files||[]);if(y.length===0)return;const b=t.maxFileSizeMB*1024*1024,v=[],A=[];y.forEach(w=>{if(w.size>b){v.push({fileName:w.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(w.size/1048576).toFixed(2)}MB`});return}const T=w.name.toLowerCase(),C=T.substring(T.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(C)){v.push({fileName:w.name,reason:`File type "${C}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}A.push(w)}),A.length>0&&i([...a,...A]),v.length>0&&d&&d(v),f.target&&(f.target.value="")},h=f=>{const y=a.filter((b,v)=>v!==f);i(y)},x=f=>{o([...n,f])},g=(f,y=!1)=>{if(y){const b=(f.fileType||f.file_type||"").toLowerCase(),v=(f.originalFileName||f.fileName||"").toLowerCase();return b.includes("image")||b.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}else{const b=(f.type||"").toLowerCase(),v=(f.name||"").toLowerCase();return b.includes("image")||b.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}};return e.jsxs(ms.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(Es,{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(J,{"data-testid":"documents-upload-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(De,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(Te,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(q,{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(Es,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"Drag and drop files here, or click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(f=>`.${f}`).join(","),onChange:u,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(I,{variant:"outline",size:"lg",type:"button",onClick:()=>{var f;return(f=m.current)==null?void 0:f.click()},"data-testid":"documents-browse-button",children:[e.jsx(us,{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(f=>f.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(J,{"data-testid":"documents-existing-card",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ie,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(f=>!n.includes(f.documentId||f.document_id||"")).length," file",r.filter(f=>!n.includes(f.documentId||f.document_id||"")).length!==1?"s":""]})]})}),e.jsx(q,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(f=>{const y=f.documentId||f.document_id||"";return n.includes(y)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${y}`,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(De,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:f.originalFileName||f.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:f.fileSize?(Number(f.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(f,!0)&&e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>c(f,!0),"data-testid":`documents-existing-${y}-preview`,children:e.jsx(xt,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>x(y),"data-testid":`documents-existing-${y}-delete`,children:e.jsx(gt,{className:"h-4 w-4 text-red-600"})})]})]},y)})})})]}),a.length>0&&e.jsxs(J,{"data-testid":"documents-new-card",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ie,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(q,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((f,y)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${y}`,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(De,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:f.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(f.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(f,!1)&&e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>c(f,!1),"data-testid":`documents-new-${y}-preview`,children:e.jsx(xt,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>h(y),"data-testid":`documents-new-${y}-remove`,children:e.jsx(gt,{className:"h-4 w-4"})})]})]},y))})})]})]})]})}const KA=t=>{switch(t){case"high":return e.jsx(ga,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ht,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ys,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ht,{className:"w-4 h-4 text-gray-600"})}};function YA({formData:t,selectedTemplate:s}){return e.jsxs(ms.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(Pe,{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(J,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(gx,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(q,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6","data-testid":"review-submit-overview-grid",children:[e.jsxs("div",{"data-testid":"review-submit-overview-type",children:[e.jsx(ne,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(ie,{variant:"outline",className:"mt-2 text-xs border-green-300 text-green-700",children:s==null?void 0:s.category})]}),e.jsxs("div",{"data-testid":"review-submit-overview-priority",children:[e.jsx(ne,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[KA(t.priority),e.jsx("span",{className:"text-green-800 capitalize",children:t.priority})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-workflow",children:[e.jsx(ne,{className:"text-green-900 font-semibold",children:"Workflow Type"}),e.jsx("p",{className:"text-green-800 mt-1 capitalize",children:t.workflowType}),e.jsxs("p",{className:"text-sm text-green-700",children:[t.approverCount||1," Level",(t.approverCount||1)>1?"s":""]})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-title",children:[e.jsx(ne,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(J,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(De,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(ne,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(na,{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(Ea,{className:"w-4 h-4 text-blue-600"}),e.jsx(ne,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(J,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(Bt,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(Te,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(q,{className:"space-y-6",children:e.jsx("div",{className:"space-y-4","data-testid":"review-submit-approval-levels",children:Array.from({length:t.approverCount||1},(a,r)=>{const n=r+1,i=n===(t.approverCount||1),l=t.approvers[r];return e.jsx("div",{className:"p-4 bg-white rounded-lg border border-orange-200","data-testid":`review-submit-approval-level-${n}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${l!=null&&l.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:n})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",n]}),i&&e.jsx(ie,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(l==null?void 0:l.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l!=null&&l.tat?`${l.tat} ${l.tatType==="days"?"day":"hour"}${l.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(J,{"data-testid":"review-submit-participants-card",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(xt,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(q,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(ne,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(ie,{variant:"outline",className:"text-xs","data-testid":`review-submit-spectator-${a.id}`,children:[a.name," (",a.email,")"]},a.id))})]})})]}),t.documents.length>0&&e.jsxs(J,{"data-testid":"review-submit-documents-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(Es,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(Te,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(q,{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(De,{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(J,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(q,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Pe,{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 ZA({isEditing:t,currentStep:s,totalSteps:a,stepNames:r,onBack:n}){return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0","data-testid":"create-request-header",children:e.jsxs("div",{className:"flex items-center justify-between max-w-6xl mx-auto gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-1 min-w-0",children:[e.jsx(I,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"create-request-back-button",children:e.jsx(Ss,{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 XA({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(Wi,{mode:"wait",children:t})})})}function QA({modal:t,onClose:s}){return e.jsx(ht,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(ct,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(dt,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Et,{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(Ii,{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(kt,{children:e.jsx(I,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function JA({modal:t,documentPolicy:s,onClose:a}){return e.jsx(ht,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(ct,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(dt,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Et,{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(kt,{children:e.jsx(I,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function Eu({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=La(),i=qs(),l=n.requestId||a||"",o=r&&!!l,{user:c}=Qt(),[d,m]=p.useState([]);p.useEffect(()=>{(async()=>{try{const ft=(await Xi()).map(mt=>({id:mt.id,name:mt.name,description:mt.description,category:mt.category,icon:De,estimatedTime:mt.estimatedTime,commonApprovers:mt.approvers.map(nt=>nt.name),workflowApprovers:mt.approvers,suggestedSLA:mt.suggestedSLA,priority:mt.priority,fields:mt.fields||{}}));m(ft)}catch(Oe){console.error("Failed to fetch admin templates:",Oe)}})()},[]);const u=p.useMemo(()=>[...Ru,...d],[d]),{formData:h,updateFormData:x,selectedTemplate:g,setSelectedTemplate:f,loadingDraft:y,systemPolicy:b,documentPolicy:v,existingDocuments:A,setExistingDocuments:w}=bA(o,l,u),{currentStep:T,totalSteps:C,stepNames:_,isStepValid:D,nextStep:S,prevStep:j}=vA(o,g,h),[P,R]=p.useState([]),[O,F]=p.useState([]),M=p.useRef(null),{validationModal:B,policyViolationModal:k,documentErrorModal:N,openValidationModal:U,closeValidationModal:$,openPolicyViolationModal:L,closePolicyViolationModal:se,openDocumentErrorModal:G,closeDocumentErrorModal:oe}=jA(),{submitting:Z,savingDraft:E,handleSubmit:V,handleSaveDraft:H}=kA({formData:h,selectedTemplate:g,documents:P,documentsToDelete:O,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:Q,setShowTemplateModal:Y,previewDocument:W,selectTemplate:ce,handleTemplateSelection:xe,nextStep:ke,prevStep:Ae,handlePreviewDocument:ae,closePreview:ye}=_A({selectedTemplate:g,setSelectedTemplate:f,updateFormData:x,formData:h,currentStep:T,isStepValid:D,wizardNextStep:S,wizardPrevStep:j,user:c,openValidationModal:U,systemPolicy:b,onPolicyViolation:L,onSubmit:s}),Ne=p.useCallback(()=>{if(T===1){i("/dashboard",{replace:!0});return}T===3||T===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Ae()},[T,t,i,Ae]),ve=p.useRef(!0),$e=p.useRef(!1);p.useEffect(()=>{ve.current&&h.documents&&h.documents.length>0&&!$e.current&&(R(h.documents),$e.current=!0),ve.current=!1},[h.documents]);const re=p.useRef(!1),Me=p.useRef(P);p.useEffect(()=>{if(re.current){re.current=!1,Me.current=P;return}Me.current!==P&&(x("documents",P),Me.current=P)},[P]);const ot=()=>{switch(T){case 1:return e.jsx(BA,{templates:Ru,selectedTemplate:g,onSelectTemplate:ce,adminTemplates:d});case 2:return e.jsx(zA,{formData:h,selectedTemplate:g,updateFormData:x});case 3:return e.jsx(HA,{formData:h,updateFormData:x,systemPolicy:b,onValidationError:pe=>U(pe.type,pe.email,pe.message),onPolicyViolation:L});case 4:return e.jsx(WA,{formData:h,updateFormData:x,onValidationError:pe=>U(pe.type,pe.email,pe.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(GA,{documentPolicy:v,isEditing:o,documents:P,existingDocuments:A,documentsToDelete:O,onDocumentsChange:R,onExistingDocumentsChange:w,onDocumentsToDeleteChange:F,onPreviewDocument:ae,onDocumentErrors:pe=>G(pe),fileInputRef:M});case 6:return e.jsx(YA,{formData:h,selectedTemplate:g});default:return null}};return y?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(ZA,{isEditing:o,currentStep:T,totalSteps:C,stepNames:_,onBack:Ne}),e.jsx(Qp,{currentStep:T,totalSteps:C,stepNames:_}),e.jsx(XA,{children:ot()}),e.jsx(UA,{currentStep:T,totalSteps:C,isStepValid:D(),onPrev:Ae,onNext:ke,onSubmit:V,onSaveDraft:H,submitting:Z,savingDraft:E,loadingDraft:y,isEditing:o}),e.jsx(lA,{open:Q,onClose:()=>Y(!1),onSelectTemplate:xe}),W&&e.jsx(Cr,{fileName:W.fileName,fileType:W.fileType,fileUrl:W.fileUrl,fileSize:W.fileSize,open:!!W,onClose:ye,onDownload:async()=>{if(W.file){const pe=document.createElement("a");pe.href=W.fileUrl,pe.download=W.fileName,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe)}else W.documentId&&await js(W.documentId)},attachmentId:W.documentId}),e.jsx(QA,{modal:B,onClose:$}),e.jsx(JA,{modal:N,documentPolicy:v,onClose:oe}),e.jsx($n,{open:k.open,onClose:se,violations:k.violations,policyDetails:{maxApprovalLevels:b.maxApprovalLevels,maxParticipants:b.maxParticipants,allowSpectators:b.allowSpectators,maxSpectators:b.maxSpectators}})]})}function Un({className:t,...s}){return e.jsx(Ff,{"data-slot":"tabs",className:Re("flex flex-col gap-2",t),...s})}function Bn({className:t,...s}){return e.jsx(Mf,{"data-slot":"tabs-list",className:Re("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function Dt({className:t,...s}){return e.jsx(_f,{"data-slot":"tabs-trigger",className:Re("data-[state=active]:bg-card dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-xl border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}function Tt({className:t,...s}){return e.jsx(Lf,{"data-slot":"tabs-content",className:Re("flex-1 outline-none",t),...s})}const eg={"RE-REQ-2024-001":{id:"RE-REQ-2024-001",title:"Himalayan 450 Launch Campaign - Digital Media Blitz",description:`Comprehensive digital marketing campaign for Himalayan 450 adventure motorcycle launch. Includes social media campaigns, influencer partnerships, performance marketing, content creation, and digital advertising across platforms. Target: Reach 10M adventure enthusiasts across India.
Equipment Specifications:
• 10x MacBook Pro 16-inch (M2 Pro chip)
• 5x Professional Camera Kits (Canon EOS R5)
• Video Editing Workstations
• Social Media Management Tools`,category:"Marketing & Campaigns",subcategory:"Digital Marketing",status:"pending",priority:"express",amount:"₹3,75,00,000",slaProgress:65,slaRemaining:"8 hours 45 minutes",slaEndDate:"Oct 9, 2024 5:00 PM",currentStep:1,totalSteps:3,template:"custom",initiator:{name:"Priya Sharma",role:"Senior Digital Marketing Manager",department:"Marketing",email:"priya.sharma@royalenfield.com",phone:"+91 98765 43210",avatar:"PS"},department:"Marketing",createdAt:"Oct 6, 2024 10:30 AM",updatedAt:"Oct 7, 2024 2:15 PM",dueDate:"2024-10-09T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Rajesh Kumar",role:"Marketing Director - India",status:"pending",tatHours:24,elapsedHours:22,assignedAt:"2024-10-06T10:30:00Z",comment:null,timestamp:null},{step:2,approver:"Amit Desai",role:"VP Product Marketing",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Himalayan_450_Digital_Strategy.pdf",size:"5.2 MB",type:"PDF",uploadedBy:"Priya Sharma",uploadedAt:"Oct 6, 2024 10:45 AM"},{name:"Budget_Breakdown_Q4_2024.xlsx",size:"980 KB",type:"Excel",uploadedBy:"Priya Sharma",uploadedAt:"Oct 6, 2024 11:15 AM"},{name:"Influencer_Partnership_List.xlsx",size:"450 KB",type:"Excel",uploadedBy:"Marketing Team",uploadedAt:"Oct 6, 2024 2:30 PM"},{name:"Creative_Campaign_Assets.zip",size:"125 MB",type:"ZIP",uploadedBy:"Creative Team",uploadedAt:"Oct 6, 2024 4:15 PM"}],spectators:[{name:"Sarah Khan",role:"Brand Strategy Lead",avatar:"SK"},{name:"Finance Team",role:"Budget Approval",avatar:"FT"}],auditTrail:[{type:"created",action:"Request Created",details:"New digital marketing campaign request submitted",user:"Priya Sharma",timestamp:"Oct 6, 2024 10:30 AM"},{type:"assignment",action:"Assigned to Rajesh Kumar",details:"Forwarded to Marketing Director for review",user:"System",timestamp:"Oct 6, 2024 10:31 AM"},{type:"comment",action:"Work Note Added",details:"Reviewed budget allocation and target metrics",user:"Rajesh Kumar",timestamp:"Oct 7, 2024 2:15 PM"},{type:"reminder",action:"SLA Reminder",details:"TAT approaching - 8 hours remaining",user:"System",timestamp:"Oct 7, 2024 8:15 AM"}],tags:["digital-marketing","launch-campaign","himalayan-450","high-priority"]},"RE-REQ-2024-002":{id:"RE-REQ-2024-002",title:"New Laptop Procurement - Design Team Expansion",description:"Purchase of 10 high-performance laptops for the newly expanded Product Design team. Required specifications: Latest generation processor, 32GB RAM, dedicated graphics card for 3D modeling and rendering work.",category:"IT & Infrastructure",subcategory:"Hardware Procurement",status:"in-review",priority:"standard",amount:"₹12,50,000",slaProgress:45,slaRemaining:"2 days 8 hours",slaEndDate:"Oct 11, 2024 5:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Vikram Singh",role:"Head - IT Operations",department:"Information Technology",email:"vikram.singh@royalenfield.com",phone:"+91 98765 43221",avatar:"VS"},department:"Information Technology",createdAt:"Oct 5, 2024 9:15 AM",updatedAt:"Oct 7, 2024 3:45 PM",dueDate:"2024-10-11T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Meera Patel",role:"IT Manager",status:"approved",tatHours:24,actualHours:18,assignedAt:"2024-10-05T09:15:00Z",comment:"Technical specifications verified. Hardware meets design team requirements.",timestamp:"2024-10-06T03:15:00Z"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"in-review",tatHours:48,elapsedHours:32,assignedAt:"2024-10-06T03:15:00Z",comment:null,timestamp:null},{step:3,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Laptop_Specifications.pdf",size:"850 KB",type:"PDF",uploadedBy:"Vikram Singh",uploadedAt:"Oct 5, 2024 9:20 AM"},{name:"Vendor_Quotations.xlsx",size:"1.2 MB",type:"Excel",uploadedBy:"Procurement Team",uploadedAt:"Oct 5, 2024 11:45 AM"},{name:"Team_Expansion_Plan.pdf",size:"620 KB",type:"PDF",uploadedBy:"Design Team",uploadedAt:"Oct 5, 2024 2:30 PM"}],spectators:[{name:"Design Team Lead",role:"End Users",avatar:"DT"},{name:"Procurement Team",role:"Vendor Management",avatar:"PT"}],auditTrail:[{type:"created",action:"Request Created",details:"Laptop procurement request for design team",user:"Vikram Singh",timestamp:"Oct 5, 2024 9:15 AM"},{type:"assignment",action:"Assigned to Meera Patel",details:"IT Manager to verify specifications",user:"System",timestamp:"Oct 5, 2024 9:16 AM"},{type:"approval",action:"Approved by Meera Patel",details:"Technical specifications approved",user:"Meera Patel",timestamp:"Oct 6, 2024 3:15 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance for budget approval",user:"System",timestamp:"Oct 6, 2024 3:15 AM"}],tags:["hardware","procurement","design-team","laptops"]},"RE-REQ-2024-003":{id:"RE-REQ-2024-003",title:"Annual Service Center Expansion - Western Region",description:"Proposal for opening 15 new authorized service centers across tier-2 cities in Western region. Includes infrastructure setup, technician training, spare parts inventory, and marketing support. Expected to improve service accessibility by 35% in the target region.",category:"Operations & Expansion",subcategory:"Service Network",status:"pending",priority:"standard",amount:"₹8,75,00,000",slaProgress:78,slaRemaining:"1 day 4 hours",slaEndDate:"Oct 10, 2024 5:00 PM",currentStep:1,totalSteps:4,template:"custom",initiator:{name:"Sanjay Reddy",role:"Regional Service Manager - West",department:"After Sales Service",email:"sanjay.reddy@royalenfield.com",phone:"+91 98765 43232",avatar:"SR"},department:"After Sales Service",createdAt:"Oct 3, 2024 8:45 AM",updatedAt:"Oct 6, 2024 5:45 PM",dueDate:"2024-10-10T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Ramesh Kulkarni",role:"Head - After Sales Service",status:"pending",tatHours:72,elapsedHours:85,assignedAt:"2024-10-03T08:45:00Z",comment:null,timestamp:null},{step:2,approver:"Finance Team",role:"Budget Allocation",status:"waiting",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Legal Team",role:"Compliance Review",status:"waiting",tatHours:120,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Western_Region_Expansion_Plan.pdf",size:"7.5 MB",type:"PDF",uploadedBy:"Sanjay Reddy",uploadedAt:"Oct 3, 2024 9:00 AM"},{name:"Service_Center_Requirements.xlsx",size:"2.8 MB",type:"Excel",uploadedBy:"Planning Team",uploadedAt:"Oct 3, 2024 11:30 AM"},{name:"Customer_Demand_Analysis.pptx",size:"4.2 MB",type:"PowerPoint",uploadedBy:"Analytics Team",uploadedAt:"Oct 4, 2024 2:15 PM"},{name:"ROI_Projections_Service_Network.xlsx",size:"1.9 MB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Oct 5, 2024 10:45 AM"}],spectators:[{name:"Regional Managers",role:"Service Operations",avatar:"RM"},{name:"Training Team",role:"Technician Development",avatar:"TT"}],auditTrail:[{type:"created",action:"Request Created",details:"Service center expansion proposal submitted",user:"Sanjay Reddy",timestamp:"Oct 3, 2024 8:45 AM"},{type:"assignment",action:"Assigned to Ramesh Kulkarni",details:"Forwarded to Head of After Sales Service",user:"System",timestamp:"Oct 3, 2024 8:46 AM"},{type:"reminder",action:"Reminder Sent",details:"TAT breach reminder sent to approver",user:"System",timestamp:"Oct 6, 2024 5:45 PM"},{type:"updated",action:"Additional Documents",details:"ROI projections added by finance team",user:"Finance Team",timestamp:"Oct 5, 2024 10:45 AM"}],tags:["service-expansion","western-region","tier2-cities","overdue"]},"RE-REQ-2024-004":{id:"RE-REQ-2024-004",title:"Employee Training Program - Advanced Motorcycle Mechanics",description:"Comprehensive training program for 50 service center technicians covering advanced diagnostics, electrical systems, fuel injection troubleshooting, and customer service excellence. Program duration: 3 weeks. Includes certification upon completion.",category:"Human Resources",subcategory:"Training & Development",status:"approved",priority:"standard",amount:"₹18,50,000",slaProgress:100,slaRemaining:"Completed",slaEndDate:"Oct 5, 2024 5:00 PM",currentStep:3,totalSteps:3,template:"custom",initiator:{name:"Kavita Menon",role:"Training Manager",department:"Human Resources",email:"kavita.menon@royalenfield.com",phone:"+91 98765 43243",avatar:"KM"},department:"Human Resources",createdAt:"Sep 28, 2024 11:00 AM",updatedAt:"Oct 5, 2024 4:30 PM",dueDate:"2024-10-05T17:00:00Z",submittedDate:"2024-09-28T11:00:00Z",estimatedCompletion:"Oct 5, 2024",currentApprover:"Completed",approverLevel:"3 of 3",conclusionRemark:"All approvals completed. Training program scheduled for November 2024.",approvalFlow:[{step:1,approver:"Ramesh Kulkarni",role:"Head - After Sales Service",status:"approved",tatHours:48,actualHours:36,assignedAt:"2024-09-28T11:00:00Z",comment:"Excellent initiative. Training content approved.",timestamp:"Sep 29, 2024 11:00 PM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"approved",tatHours:72,actualHours:48,assignedAt:"2024-09-29T23:00:00Z",comment:"Budget approved. Cost per participant is reasonable.",timestamp:"Oct 1, 2024 11:00 PM"},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"approved",tatHours:96,actualHours:72,assignedAt:"2024-10-01T23:00:00Z",comment:"Final approval granted. Proceed with program execution.",timestamp:"Oct 5, 2024 4:30 PM"}],documents:[{name:"Training_Curriculum.pdf",size:"3.2 MB",type:"PDF",uploadedBy:"Kavita Menon",uploadedAt:"Sep 28, 2024 11:15 AM"},{name:"Trainer_Profiles.pdf",size:"1.8 MB",type:"PDF",uploadedBy:"HR Team",uploadedAt:"Sep 28, 2024 2:45 PM"},{name:"Budget_Training_Program.xlsx",size:"680 KB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Sep 29, 2024 10:30 AM"}],spectators:[{name:"Service Center Managers",role:"Participant Coordination",avatar:"SC"},{name:"Quality Assurance",role:"Training Quality",avatar:"QA"}],auditTrail:[{type:"created",action:"Request Created",details:"Training program proposal submitted",user:"Kavita Menon",timestamp:"Sep 28, 2024 11:00 AM"},{type:"assignment",action:"Assigned to Ramesh Kulkarni",details:"Forwarded to After Sales Service Head",user:"System",timestamp:"Sep 28, 2024 11:01 AM"},{type:"approval",action:"Approved by Ramesh Kulkarni",details:"Level 1 approval completed",user:"Ramesh Kulkarni",timestamp:"Sep 29, 2024 11:00 PM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Sep 29, 2024 11:01 PM"},{type:"approval",action:"Approved by Anil Kapoor",details:"Budget approval completed",user:"Anil Kapoor",timestamp:"Oct 1, 2024 11:00 PM"},{type:"assignment",action:"Assigned to Deepika Sharma",details:"Forwarded to VP for final approval",user:"System",timestamp:"Oct 1, 2024 11:01 PM"},{type:"approval",action:"Approved by Deepika Sharma",details:"Final approval - Request completed",user:"Deepika Sharma",timestamp:"Oct 5, 2024 4:30 PM"},{type:"completed",action:"Request Completed",details:"All approvals obtained. Training scheduled.",user:"System",timestamp:"Oct 5, 2024 4:31 PM"}],tags:["training","technicians","approved","completed"]},"RE-REQ-2024-005":{id:"RE-REQ-2024-005",title:"Showroom Renovation - Chennai Flagship Store",description:"Complete renovation of Chennai flagship showroom including modern interior design, interactive display zones, customer lounge upgrade, motorcycle test ride facility, and digital experience center. Project timeline: 8 weeks.",category:"Infrastructure",subcategory:"Retail & Showroom",status:"rejected",priority:"standard",amount:"₹65,00,000",slaProgress:100,slaRemaining:"Rejected",slaEndDate:"Oct 4, 2024 5:00 PM",currentStep:2,totalSteps:4,template:"custom",initiator:{name:"Arjun Nair",role:"Showroom Manager - South",department:"Retail Operations",email:"arjun.nair@royalenfield.com",phone:"+91 98765 43254",avatar:"AN"},department:"Retail Operations",createdAt:"Oct 1, 2024 9:30 AM",updatedAt:"Oct 4, 2024 3:15 PM",dueDate:"2024-10-04T17:00:00Z",submittedDate:"2024-10-01T09:30:00Z",estimatedCompletion:"N/A",currentApprover:"Rejected by Anil Kapoor",approverLevel:"2 of 4",conclusionRemark:"Request rejected due to insufficient budget justification. Please revise with detailed ROI analysis.",approvalFlow:[{step:1,approver:"Suresh Iyer",role:"Regional Manager - South",status:"approved",tatHours:48,actualHours:24,assignedAt:"2024-10-01T09:30:00Z",comment:"Renovation is necessary. Current showroom needs upgrade.",timestamp:"Oct 2, 2024 9:30 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"rejected",tatHours:72,actualHours:48,assignedAt:"2024-10-02T09:30:00Z",comment:"Budget allocation not justified. Need detailed ROI analysis and comparison with alternative renovation options. Please revise and resubmit with comprehensive financial projections.",timestamp:"Oct 4, 2024 3:15 PM"},{step:3,approver:"Legal Team",role:"Compliance & Contracts",status:"cancelled",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Ramesh Kulkarni",role:"VP Operations",status:"cancelled",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Showroom_Renovation_Plan.pdf",size:"12.5 MB",type:"PDF",uploadedBy:"Arjun Nair",uploadedAt:"Oct 1, 2024 9:45 AM"},{name:"Interior_Design_Mockups.zip",size:"85 MB",type:"ZIP",uploadedBy:"Design Team",uploadedAt:"Oct 1, 2024 2:30 PM"},{name:"Contractor_Quotations.xlsx",size:"2.1 MB",type:"Excel",uploadedBy:"Procurement Team",uploadedAt:"Oct 2, 2024 11:15 AM"}],spectators:[{name:"Marketing Team",role:"Brand Experience",avatar:"MT"},{name:"Customer Experience",role:"Feedback & Analysis",avatar:"CX"}],auditTrail:[{type:"created",action:"Request Created",details:"Showroom renovation request submitted",user:"Arjun Nair",timestamp:"Oct 1, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Suresh Iyer",details:"Forwarded to Regional Manager",user:"System",timestamp:"Oct 1, 2024 9:31 AM"},{type:"approval",action:"Approved by Suresh Iyer",details:"Level 1 approval completed",user:"Suresh Iyer",timestamp:"Oct 2, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 2, 2024 9:31 AM"},{type:"rejection",action:"Rejected by Anil Kapoor",details:"Budget justification insufficient",user:"Anil Kapoor",timestamp:"Oct 4, 2024 3:15 PM"},{type:"completed",action:"Request Rejected",details:"Workflow terminated. Requires resubmission with revisions.",user:"System",timestamp:"Oct 4, 2024 3:16 PM"}],tags:["showroom","renovation","rejected","south-region"]},"RE-REQ-2024-006":{id:"RE-REQ-2024-006",title:"Spare Parts Inventory Optimization System",description:"Implementation of AI-powered inventory management system for spare parts across all service centers. Features include demand forecasting, automated reordering, stock level optimization, and real-time tracking. Expected to reduce inventory costs by 20% and improve part availability.",category:"Technology & Innovation",subcategory:"Software Implementation",status:"pending",priority:"express",amount:"₹42,00,000",slaProgress:35,slaRemaining:"1 day 16 hours",slaEndDate:"Oct 12, 2024 5:00 PM",currentStep:1,totalSteps:4,template:"custom",initiator:{name:"Rahul Deshmukh",role:"Head - Supply Chain Technology",department:"Supply Chain",email:"rahul.deshmukh@royalenfield.com",phone:"+91 98765 43265",avatar:"RD"},department:"Supply Chain",createdAt:"Oct 7, 2024 10:00 AM",updatedAt:"Oct 8, 2024 9:15 AM",dueDate:"2024-10-12T17:00:00Z",submittedDate:"2024-10-07T10:00:00Z",estimatedCompletion:"Oct 12, 2024",currentApprover:"Vikram Singh",approverLevel:"1 of 4",conclusionRemark:"",approvalFlow:[{step:1,approver:"Vikram Singh",role:"Head - IT Operations",status:"pending",tatHours:48,elapsedHours:23,assignedAt:"2024-10-07T10:00:00Z",comment:null,timestamp:null},{step:2,approver:"Supply Chain Director",role:"Operations Approval",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Anil Kapoor",role:"Finance Manager",status:"waiting",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"AI_Inventory_System_Proposal.pdf",size:"8.9 MB",type:"PDF",uploadedBy:"Rahul Deshmukh",uploadedAt:"Oct 7, 2024 10:15 AM"},{name:"Vendor_Comparison_Analysis.xlsx",size:"3.4 MB",type:"Excel",uploadedBy:"IT Procurement",uploadedAt:"Oct 7, 2024 2:45 PM"},{name:"Cost_Benefit_Analysis.pptx",size:"6.2 MB",type:"PowerPoint",uploadedBy:"Analytics Team",uploadedAt:"Oct 7, 2024 4:30 PM"},{name:"Implementation_Timeline.pdf",size:"1.5 MB",type:"PDF",uploadedBy:"Project Management",uploadedAt:"Oct 8, 2024 9:15 AM"}],spectators:[{name:"Service Center Network",role:"End Users",avatar:"SN"},{name:"Data Analytics Team",role:"System Integration",avatar:"DA"}],auditTrail:[{type:"created",action:"Request Created",details:"AI inventory system proposal submitted",user:"Rahul Deshmukh",timestamp:"Oct 7, 2024 10:00 AM"},{type:"assignment",action:"Assigned to Vikram Singh",details:"Forwarded to IT Operations Head",user:"System",timestamp:"Oct 7, 2024 10:01 AM"},{type:"updated",action:"Documents Added",details:"Implementation timeline document uploaded",user:"Project Management",timestamp:"Oct 8, 2024 9:15 AM"}],tags:["technology","ai","inventory","supply-chain","high-priority"]},"RE-REQ-2024-007":{id:"RE-REQ-2024-007",title:"Dealer Network Meeting - Q4 Business Review",description:"Quarterly business review meeting for all authorized dealers across India. Venue: Bangalore. Topics include Q3 performance review, Q4 targets, new model launches, marketing initiatives, service excellence programs, and dealer support policies. Expected attendance: 250 dealers.",category:"Events & Conferences",subcategory:"Dealer Meetings",status:"in-review",priority:"standard",amount:"₹28,50,000",slaProgress:58,slaRemaining:"1 day 12 hours",slaEndDate:"Oct 11, 2024 5:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Neha Kapoor",role:"Dealer Network Manager",department:"Sales & Distribution",email:"neha.kapoor@royalenfield.com",phone:"+91 98765 43276",avatar:"NK"},department:"Sales & Distribution",createdAt:"Oct 6, 2024 2:00 PM",updatedAt:"Oct 8, 2024 11:30 AM",dueDate:"2024-10-11T17:00:00Z",submittedDate:"2024-10-06T14:00:00Z",estimatedCompletion:"Oct 11, 2024",currentApprover:"Anil Kapoor",approverLevel:"2 of 3",conclusionRemark:"",approvalFlow:[{step:1,approver:"Suresh Mehta",role:"Sales Director",status:"approved",tatHours:48,actualHours:36,assignedAt:"2024-10-06T14:00:00Z",comment:"Dealer meeting approved. Agenda looks comprehensive.",timestamp:"Oct 8, 2024 2:00 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"in-review",tatHours:72,elapsedHours:33,assignedAt:"2024-10-08T02:00:00Z",comment:null,timestamp:null},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Q4_Dealer_Meeting_Agenda.pdf",size:"2.8 MB",type:"PDF",uploadedBy:"Neha Kapoor",uploadedAt:"Oct 6, 2024 2:15 PM"},{name:"Venue_Booking_Confirmation.pdf",size:"980 KB",type:"PDF",uploadedBy:"Events Team",uploadedAt:"Oct 6, 2024 4:45 PM"},{name:"Event_Budget_Breakdown.xlsx",size:"1.2 MB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Oct 7, 2024 10:30 AM"},{name:"Dealer_Invitations_List.xlsx",size:"580 KB",type:"Excel",uploadedBy:"Sales Team",uploadedAt:"Oct 7, 2024 3:15 PM"}],spectators:[{name:"Marketing Team",role:"Presentation Support",avatar:"MT"},{name:"Events Management",role:"Logistics Coordination",avatar:"EM"}],auditTrail:[{type:"created",action:"Request Created",details:"Dealer meeting proposal submitted",user:"Neha Kapoor",timestamp:"Oct 6, 2024 2:00 PM"},{type:"assignment",action:"Assigned to Suresh Mehta",details:"Forwarded to Sales Director",user:"System",timestamp:"Oct 6, 2024 2:01 PM"},{type:"approval",action:"Approved by Suresh Mehta",details:"Sales approval completed",user:"Suresh Mehta",timestamp:"Oct 8, 2024 2:00 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 8, 2024 2:01 AM"},{type:"updated",action:"Documents Added",details:"Dealer invitations list uploaded",user:"Sales Team",timestamp:"Oct 7, 2024 3:15 PM"}],tags:["dealer-meeting","q4-review","event","bangalore"]},"RE-REQ-2024-008":{id:"RE-REQ-2024-008",title:"Cybersecurity Infrastructure Upgrade",description:"Comprehensive upgrade of cybersecurity infrastructure including next-gen firewall, intrusion detection system, endpoint protection for 500+ devices, security information and event management (SIEM) system, and employee security awareness training. Critical for protecting customer data and business operations.",category:"IT & Infrastructure",subcategory:"Security & Compliance",status:"pending",priority:"urgent",amount:"₹52,00,000",slaProgress:82,slaRemaining:"4 hours 20 minutes",slaEndDate:"Oct 8, 2024 6:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Sameer Joshi",role:"Chief Information Security Officer",department:"Information Technology",email:"sameer.joshi@royalenfield.com",phone:"+91 98765 43287",avatar:"SJ"},department:"Information Technology",createdAt:"Oct 5, 2024 11:30 AM",updatedAt:"Oct 8, 2024 12:45 PM",dueDate:"2024-10-08T18:00:00Z",submittedDate:"2024-10-05T11:30:00Z",estimatedCompletion:"Oct 8, 2024",currentApprover:"Anil Kapoor",approverLevel:"2 of 3",conclusionRemark:"",approvalFlow:[{step:1,approver:"Vikram Singh",role:"Head - IT Operations",status:"approved",tatHours:24,actualHours:18,assignedAt:"2024-10-05T11:30:00Z",comment:"Critical security upgrade. Approve immediately.",timestamp:"Oct 6, 2024 5:30 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"pending",tatHours:48,elapsedHours:55,assignedAt:"2024-10-06T05:30:00Z",comment:null,timestamp:null},{step:3,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Security_Assessment_Report.pdf",size:"15.3 MB",type:"PDF",uploadedBy:"Sameer Joshi",uploadedAt:"Oct 5, 2024 11:45 AM"},{name:"Vendor_Solutions_Comparison.xlsx",size:"4.8 MB",type:"Excel",uploadedBy:"IT Security Team",uploadedAt:"Oct 5, 2024 3:30 PM"},{name:"Implementation_Roadmap.pptx",size:"7.6 MB",type:"PowerPoint",uploadedBy:"Project Management",uploadedAt:"Oct 6, 2024 10:15 AM"},{name:"Risk_Analysis_Report.pdf",size:"5.9 MB",type:"PDF",uploadedBy:"Security Consultant",uploadedAt:"Oct 6, 2024 4:45 PM"}],spectators:[{name:"Legal & Compliance",role:"Data Protection",avatar:"LC"},{name:"IT Infrastructure",role:"System Integration",avatar:"IT"}],auditTrail:[{type:"created",action:"Request Created",details:"Cybersecurity upgrade proposal submitted",user:"Sameer Joshi",timestamp:"Oct 5, 2024 11:30 AM"},{type:"assignment",action:"Assigned to Vikram Singh",details:"Forwarded to IT Operations Head",user:"System",timestamp:"Oct 5, 2024 11:31 AM"},{type:"approval",action:"Approved by Vikram Singh",details:"IT approval - marked as critical",user:"Vikram Singh",timestamp:"Oct 6, 2024 5:30 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 6, 2024 5:31 AM"},{type:"reminder",action:"Urgent Reminder",details:"TAT breach warning - 4 hours remaining",user:"System",timestamp:"Oct 8, 2024 12:45 PM"}],tags:["cybersecurity","urgent","critical","infrastructure","overdue"]}},qA={"RE-REQ-2024-CM-001":{id:"RE-REQ-2024-CM-001",title:"Dealer Marketing Activity Claim - Diwali Festival Campaign",description:"Claim request for dealer-led Diwali festival marketing campaign including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution. Activity conducted at Royal Motors Mumbai dealership.",category:"Dealer Operations",subcategory:"Claim Management",status:"pending",priority:"standard",amount:"TBD",slaProgress:35,slaRemaining:"4 days 12 hours",slaEndDate:"Oct 16, 2024 5:00 PM",currentStep:1,totalSteps:8,template:"claim-management",templateName:"Claim Management",initiator:{name:"Sneha Patil",role:"Regional Marketing Coordinator",department:"Marketing - West Zone",email:"sneha.patil@royalenfield.com",phone:"+91 98765 43250",avatar:"SP"},department:"Marketing - West Zone",createdAt:"Oct 7, 2024 9:30 AM",updatedAt:"Oct 7, 2024 9:30 AM",dueDate:"2024-10-16T17:00:00Z",conclusionRemark:"",claimDetails:{activityName:"Diwali Festival Campaign 2024",activityType:"Marketing Activity",activityDate:"Oct 5, 2024",location:"Mumbai, Maharashtra",dealerCode:"RE-MH-001",dealerName:"Royal Motors Mumbai",dealerEmail:"dealer@royalmotorsmumbai.com",dealerPhone:"+91 98765 12345",dealerAddress:"123 Main Street, Andheri West, Mumbai, Maharashtra 400053",requestDescription:"Marketing campaign for Diwali festival including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution at Royal Motors Mumbai dealership.",estimatedBudget:"₹2,45,000",periodStart:"Oct 1, 2024",periodEnd:"Oct 10, 2024"},approvalFlow:[{step:1,approver:"Royal Motors Mumbai (Dealer)",role:"Dealer - Document Upload",status:"pending",tatHours:72,elapsedHours:12,assignedAt:"2024-10-07T09:30:00Z",comment:null,timestamp:null,description:"Dealer uploads proposal document, cost breakup, timeline for closure, and other supporting documents"},{step:2,approver:"Sneha Patil (Initiator)",role:"Initiator Evaluation",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator reviews dealer documents and approves or requests modifications"},{step:3,approver:"System Auto-Process",role:"IO Confirmation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Automatic IO (Internal Order) confirmation generated upon initiator approval"},{step:4,approver:"Rajesh Kumar",role:"Department Lead Approval",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Department head approves and blocks budget in IO for this activity"},{step:5,approver:"Royal Motors Mumbai (Dealer)",role:"Dealer - Completion Documents",status:"waiting",tatHours:120,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Dealer submits activity completion documents and description"},{step:6,approver:"Sneha Patil (Initiator)",role:"Initiator Verification",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator verifies completion documents and can modify approved amount"},{step:7,approver:"System Auto-Process",role:"E-Invoice Generation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Auto-generate e-invoice based on final approved amount"},{step:8,approver:"Meera Patel",role:"Finance - Credit Note Issuance",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Finance team issues credit note to dealer"}],documents:[{name:"Claim_Proposal_Diwali_2024.pdf",size:"1.8 MB",type:"PDF",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:35 AM"},{name:"Cost_Breakup_Detailed.xlsx",size:"450 KB",type:"Excel",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:38 AM"},{name:"Activity_Timeline.pdf",size:"320 KB",type:"PDF",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:40 AM"}],spectators:[{name:"Arjun Menon",role:"Brand Manager",avatar:"AM"},{name:"Finance Team",role:"Budget Monitoring",avatar:"FT"}],auditTrail:[{type:"created",action:"Claim Request Created",details:"Diwali festival campaign claim initiated using Claim Management template",user:"Sneha Patil",timestamp:"Oct 7, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Dealer",details:"Dealer Royal Motors Mumbai assigned for document upload",user:"System",timestamp:"Oct 7, 2024 9:31 AM"},{type:"status_change",action:"Workflow Started",details:"Step 1: Dealer document upload phase initiated",user:"System",timestamp:"Oct 7, 2024 9:31 AM"}],tags:["claim-management","dealer-activity","marketing","diwali-campaign","template"]}};function wc(t,s=[],a){const[r,n]=p.useState(null),[i,l]=p.useState(!1),[o,c]=p.useState(!0),[d,m]=p.useState(null),[u,h]=p.useState(null),[x,g]=p.useState(!1),f=(T,C)=>(T||C||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),y=T=>{const C=(T||"").toUpperCase();return C==="IN_PROGRESS"?"in-review":C==="PENDING"?"pending":C==="APPROVED"?"approved":C==="REJECTED"?"rejected":C==="CLOSED"?"closed":C==="SKIPPED"?"skipped":(T||"").toLowerCase()},b=p.useCallback(async()=>{var T,C,_,D,S,j,P,R,O,F,M,B,k;l(!0);try{const N=await Ms.getWorkflowDetails(t);if(!N){console.warn("[useRequestDetails] No details returned from API");return}const U=N.workflow||{},$=Array.isArray(N.approvals)?N.approvals:[],L=Array.isArray(N.participants)?N.participants:[],se=Array.isArray(N.documents)?N.documents:[],G=N.summary||{},oe=Array.isArray(N.tatAlerts)?N.tatAlerts:[];oe.length>0;const Z=(G==null?void 0:G.currentLevel)||U.currentLevel||1,E=$.map(re=>{const Me=re.levelNumber||0,ot=(re.status||"").toString().toUpperCase(),pe=re.levelId||re.level_id;let Oe=y(re.status);Me>Z&&ot!=="APPROVED"&&ot!=="REJECTED"?Oe="waiting":Me===Z&&ot==="PENDING"&&(Oe="pending");const ft=oe.filter(mt=>mt.levelId===pe);return{step:Me,levelId:pe,role:re.levelName||re.approverName||"Approver",status:Oe,approver:re.approverName||re.approverEmail,approverId:re.approverId||re.approver_id,approverEmail:re.approverEmail,tatHours:Number(re.tatHours||0),elapsedHours:Number(re.elapsedHours||0),remainingHours:Number(re.remainingHours||0),tatPercentageUsed:Number(re.tatPercentageUsed||0),actualHours:re.levelEndTime&&re.levelStartTime?Math.max(0,(new Date(re.levelEndTime).getTime()-new Date(re.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:re.comments||void 0,timestamp:re.actionDate||void 0,levelStartTime:re.levelStartTime||re.tatStartTime,tatAlerts:ft,skipReason:re.skipReason||void 0,isSkipped:ot==="SKIPPED"||re.isSkipped||!1}}),V=L.filter(re=>(re.participantType||re.participant_type||"").toUpperCase()==="SPECTATOR").map(re=>({name:re.userName||re.user_name||re.userEmail||re.user_email,role:"Spectator",email:re.userEmail||re.user_email,avatar:f(re.userName||re.user_name,re.userEmail||re.user_email)})),H=re=>{var ot,pe;if(!re)return;const Me=L.find(Oe=>Oe.userId===re||Oe.user_id===re);return Me!=null&&Me.userName||Me!=null&&Me.user_name?Me.userName||Me.user_name:U.initiatorId===re?((ot=U.initiator)==null?void 0:ot.displayName)||((pe=U.initiator)==null?void 0:pe.email):re},Q=se.map(re=>{const Me=Number(re.fileSize||re.file_size||0),ot=(Me/(1024*1024)).toFixed(2)+" MB";return{documentId:re.documentId||re.document_id,name:re.originalFileName||re.fileName||re.file_name,fileType:re.fileType||re.file_type||"",size:ot,sizeBytes:Me,uploadedBy:H(re.uploadedBy||re.uploaded_by),uploadedAt:re.uploadedAt||re.uploaded_at}}),Y=Array.isArray(N.activities)?N.activities.filter(re=>(re.type||"").toLowerCase()!=="sla_warning"):[];let W=null;if(U.isPaused||!1)try{W=await dm(U.requestId)}catch{}let xe=null,ke=null,Ae=null,ae=null;if(U.workflowType==="CLAIM_MANAGEMENT"||U.templateType==="claim-management")try{const re=await je.get(`/dealer-claims/${U.requestId}`),Me=((T=re.data)==null?void 0:T.data)||re.data;if(Me){xe=Me.claimDetails||Me.claim_details,ke=Me.proposalDetails||Me.proposal_details,Ae=Me.completionDetails||Me.completion_details,ae=Me.internalOrder||Me.internal_order||null;const ot=Me.budgetTracking||Me.budget_tracking||null,pe=Me.invoice||null,Oe=Me.creditNote||Me.credit_note||null,ft=Me.completionExpenses||Me.completion_expenses||null;xe&&(xe.budgetTracking=ot,xe.invoice=pe,xe.creditNote=Oe,xe.completionExpenses=ft)}else console.warn("[useRequestDetails] No claimData found in response")}catch(re){console.error("[useRequestDetails] Error fetching claim details:",{error:(re==null?void 0:re.message)||re,status:(C=re==null?void 0:re.response)==null?void 0:C.status,statusText:(_=re==null?void 0:re.response)==null?void 0:_.statusText,responseData:(D=re==null?void 0:re.response)==null?void 0:D.data,requestId:U.requestId})}const ye={...U,id:U.requestNumber||U.requestId,requestId:U.requestId,requestNumber:U.requestNumber,title:U.title,description:U.description,status:y(U.status),priority:(U.priority||"").toString().toLowerCase(),workflowType:U.workflowType||(U.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:E,approvals:$,participants:L,documents:Q,spectators:V,summary:G,sla:(G==null?void 0:G.sla)||U.sla||null,initiator:{name:((S=U.initiator)==null?void 0:S.displayName)||((j=U.initiator)==null?void 0:j.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:f((M=U.initiator)==null?void 0:M.displayName,(B=U.initiator)==null?void 0:B.email)},createdAt:U.createdAt,updatedAt:U.updatedAt,totalSteps:U.totalLevels||1,currentStepRaw:(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:Y,conclusionRemark:U.conclusionRemark||null,closureDate:U.closureDate||null,pauseInfo:W||null,claimDetails:xe||null,proposalDetails:ke||null,completionDetails:Ae||null,internalOrder:ae||null,budgetTracking:(xe==null?void 0:xe.budgetTracking)||null,invoice:(xe==null?void 0:xe.invoice)||null,creditNote:(xe==null?void 0:xe.creditNote)||null,completionExpenses:(xe==null?void 0:xe.completionExpenses)||null};n(ye);const Ne=(k=a==null?void 0:a.email)==null?void 0:k.toLowerCase(),ve=$.find(re=>{const Me=(re.status||"").toString().toUpperCase(),ot=(re.approverEmail||"").toLowerCase(),pe=re.levelNumber||0;return(Me==="PENDING"||Me==="IN_PROGRESS"||Me==="PAUSED")&&ot===Ne&&pe===Z});h(ve||null);const $e=a==null?void 0:a.userId;if($e){const re=L.some(Me=>(Me.participantType||Me.participant_type||"").toUpperCase()==="SPECTATOR"&&(Me.userId||Me.user_id)===$e);g(re)}else g(!1)}catch(N){console.error("[useRequestDetails] Error refreshing details:",N),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);p.useEffect(()=>{if(!t){c(!1);return}let T=!0;return c(!0),m(null),(async()=>{var C,_,D,S,j,P,R,O,F,M,B,k,N,U;try{const $=await Ms.getWorkflowDetails(t);if(!T||!$){T&&c(!1);return}const L=$.workflow||{},se=Array.isArray($.approvals)?$.approvals:[],G=Array.isArray($.participants)?$.participants:[],oe=Array.isArray($.documents)?$.documents:[],Z=$.summary||{},E=Array.isArray($.tatAlerts)?$.tatAlerts:[],V=(L.priority||"").toString().toLowerCase(),H=(Z==null?void 0:Z.currentLevel)||L.currentLevel||1,Q=se.map(pe=>{const Oe=pe.levelNumber||0,ft=(pe.status||"").toString().toUpperCase(),mt=pe.levelId||pe.level_id;let nt=y(pe.status);ft==="PAUSED"?nt="paused":Oe>H&&ft!=="APPROVED"&&ft!=="REJECTED"?nt="waiting":Oe===H&&(ft==="PENDING"||ft==="IN_PROGRESS")&&(nt=ft==="IN_PROGRESS"?"in-review":"pending");const _s=E.filter(ea=>ea.levelId===mt);return{step:Oe,levelId:mt,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:_s}}),Y=G.filter(pe=>(pe.participantType||"").toUpperCase()==="SPECTATOR").map(pe=>({name:pe.userName||pe.userEmail,role:"Spectator",avatar:f(pe.userName,pe.userEmail)})),W=pe=>{var ft,mt;if(!pe)return;const Oe=G.find(nt=>nt.userId===pe);return Oe!=null&&Oe.userName?Oe.userName:L.initiatorId===pe?((ft=L.initiator)==null?void 0:ft.displayName)||((mt=L.initiator)==null?void 0:mt.email):pe},ce=oe.map(pe=>{const Oe=Number(pe.fileSize||0),ft=(Oe/(1024*1024)).toFixed(2)+" MB";return{documentId:pe.documentId||pe.document_id,name:pe.originalFileName||pe.fileName,fileType:pe.fileType||pe.file_type||"",size:ft,sizeBytes:Oe,uploadedBy:W(pe.uploadedBy),uploadedAt:pe.uploadedAt}}),xe=Array.isArray($.activities)?$.activities.filter(pe=>(pe.type||"").toLowerCase()!=="sla_warning"):[];let ke=null;if(L.isPaused||!1)try{ke=await dm(L.requestId)}catch{}let ae=null,ye=null,Ne=null,ve=null;if(L.workflowType==="CLAIM_MANAGEMENT"||L.templateType==="claim-management")try{const pe=await je.get(`/dealer-claims/${L.requestId}`),Oe=((C=pe.data)==null?void 0:C.data)||pe.data;if(Oe){ae=Oe.claimDetails||Oe.claim_details,ye=Oe.proposalDetails||Oe.proposal_details,Ne=Oe.completionDetails||Oe.completion_details,ve=Oe.internalOrder||Oe.internal_order||null;const ft=Oe.budgetTracking||Oe.budget_tracking||null,mt=Oe.invoice||null,nt=Oe.creditNote||Oe.credit_note||null,_s=Oe.completionExpenses||Oe.completion_expenses||null;ae&&(ae.budgetTracking=ft,ae.invoice=mt,ae.creditNote=nt,ae.completionExpenses=_s)}}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:L.requestId})}const $e={id:L.requestNumber||L.requestId,requestId:L.requestId,title:L.title,description:L.description,priority:V,status:y(L.status),workflowType:L.workflowType||(L.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:Z,initiator:{name:((D=L.initiator)==null?void 0:D.displayName)||((S=L.initiator)==null?void 0:S.email),role:((j=L.initiator)==null?void 0:j.designation)||void 0,department:((P=L.initiator)==null?void 0:P.department)||void 0,email:((R=L.initiator)==null?void 0:R.email)||void 0,phone:((O=L.initiator)==null?void 0:O.phone)||void 0,avatar:f((F=L.initiator)==null?void 0:F.displayName,(M=L.initiator)==null?void 0:M.email)},createdAt:L.createdAt,updatedAt:L.updatedAt,totalSteps:L.totalLevels||1,currentStepRaw:(Z==null?void 0:Z.currentLevel)||L.currentLevel||1,currentStep:Math.min(Math.max(1,(Z==null?void 0:Z.currentLevel)||L.currentLevel||1),L.totalLevels||1),approvalFlow:Q,approvals:se,documents:ce,spectators:Y,auditTrail:xe,conclusionRemark:L.conclusionRemark||null,closureDate:L.closureDate||null,pauseInfo:ke||null,claimDetails:ae||null,proposalDetails:ye||null,completionDetails:Ne||null,internalOrder:ve||null,budgetTracking:(ae==null?void 0:ae.budgetTracking)||null,invoice:(ae==null?void 0:ae.invoice)||null,creditNote:(ae==null?void 0:ae.creditNote)||null,completionExpenses:(ae==null?void 0:ae.completionExpenses)||null};n($e);const re=(B=a==null?void 0:a.email)==null?void 0:B.toLowerCase(),Me=se.find(pe=>{const Oe=(pe.status||"").toString().toUpperCase(),ft=(pe.approverEmail||"").toLowerCase(),mt=pe.levelNumber||0;return(Oe==="PENDING"||Oe==="IN_PROGRESS"||Oe==="PAUSED")&&ft===re&&mt===H});h(Me||null);const ot=a==null?void 0:a.userId;if(ot){const pe=G.some(Oe=>(Oe.participantType||"").toUpperCase()==="SPECTATOR"&&Oe.userId===ot);g(pe)}else g(!1)}catch($){if(console.error("[useRequestDetails] Error loading request details:",$),T){if(((k=$==null?void 0:$.response)==null?void 0:k.status)===403){const L=((U=(N=$==null?void 0:$.response)==null?void 0:N.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:L})}n(null)}}finally{T&&c(!1)}})(),()=>{T=!1}},[t,a]);const v=p.useMemo(()=>{if(r)return r;const T=eg[t];if(T)return T;const C=qA[t];if(C)return C;const _=s.find(D=>D.id===t||D.requestNumber===t||D.request_number===t);return _||null},[t,s,r]),A=p.useMemo(()=>{var _,D,S;if(!v||!a)return!1;const T=(_=a==null?void 0:a.email)==null?void 0:_.toLowerCase(),C=(S=(D=v.initiator)==null?void 0:D.email)==null?void 0:S.toLowerCase();return T===C},[v,a]),w=p.useMemo(()=>{var C;if(!v)return[];const T=[];return(C=v.initiator)!=null&&C.email&&T.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(_=>{_.approverEmail&&T.push({email:_.approverEmail.toLowerCase(),participantType:"APPROVER",name:_.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(_=>{_.email&&T.push({email:_.email.toLowerCase(),participantType:"SPECTATOR",name:_.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(_=>{const D=(_.userEmail||_.email||"").toLowerCase(),S=(_.participantType||_.participant_type||"").toUpperCase(),j=_.userName||_.user_name||_.name;D&&S&&!T.find(P=>P.email===D)&&T.push({email:D,participantType:S,name:j})}),T},[v]);return p.useEffect(()=>{if(!t||!r)return;const T=Ur();if(!T)return;const C=_=>{((_==null?void 0:_.requestId)===r.requestId||(_==null?void 0:_.requestNumber)===t)&&b()};return T.on("request:updated",C),()=>{T.off("request:updated",C)}},[t,r,b]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:b,currentApprovalLevel:u,isSpectator:x,isInitiator:A,existingParticipants:w,accessDenied:d}}function tg(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,u=t;return(async()=>{var f;try{const y=await Ms.getWorkflowDetails(t);(f=y==null?void 0:y.workflow)!=null&&f.requestId&&m&&(u=y.workflow.requestId)}catch(y){console.error("[useRequestSocket] Failed to resolve UUID:",y)}if(!m)return;const h=Ur();if(!h){console.error("[useRequestSocket] Socket not available");return}const x=r==null?void 0:r.userId,g=()=>{Kl(h,u,x)};return h.connected?g():h.on("connect",g),()=>{m&&(h.off("connect",g),Gx(h,u))}})(),()=>{m=!1}},[t,r]),p.useEffect(()=>{!t||!s||(async()=>{try{const m=await Or(t),u=s.auditTrail||[],h=[...m,...u];h.sort((x,g)=>{const f=new Date(x.createdAt||x.created_at||x.timestamp||0).getTime(),y=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return f-y}),i(h)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),p.useEffect(()=>{if(!t)return;const m=Ur();if(!m)return;const u=x=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await Or(t),f=(s==null?void 0:s.auditTrail)||[],y=[...g,...f].sort((b,v)=>{const A=new Date(b.createdAt||b.created_at||b.timestamp||0).getTime(),w=new Date(v.createdAt||v.created_at||v.timestamp||0).getTime();return A-w});i(y)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},h=x=>{const g=x.type==="breach"?"⏰":x.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const f=await Ms.getWorkflowDetails(t);f&&(Array.isArray(f.tatAlerts)&&f.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:x.message,icon:"/favicon.ico",tag:`tat-${x.requestId}-${x.type}`,requireInteraction:!1}))}catch(f){console.error("[useRequestSocket] Failed to refresh after TAT alert:",f)}})()};return m.on("noteHandler",u),m.on("worknote:new",u),m.on("tat:alert",h),()=>{m.off("noteHandler",u),m.off("worknote:new",u),m.off("tat:alert",h)}},[t,a,s]),p.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function xn(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 sg(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 Js("DOCUMENT_POLICY"),f={};g.forEach(A=>{f[A.configKey]=A.configValue});const y=parseInt(f.MAX_FILE_SIZE_MB||"10"),v=(f.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(A=>A.trim().toLowerCase());o({maxFileSizeMB:y,allowedFileTypes:v})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=x=>{const g=l.maxFileSizeMB*1024*1024;if(x.size>g)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 f=x.name.toLowerCase(),y=f.substring(f.lastIndexOf(".")+1);return l.allowedFileTypes.includes(y)?{valid:!0}:{valid:!1,reason:`File type "${y}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},u=async x=>{var v,A;const g=x.target.files;if(!g||g.length===0)return;const f=Array.from(g),y=[],b=[];if(f.forEach(w=>{const T=m(w);T.valid?b.push(w):y.push({fileName:w.name,reason:T.reason||"Unknown validation error"})}),y.length>0&&d({show:!0,errors:y}),b.length===0){x.target&&(x.target.value="");return}r(!0);try{const w=b[0],T=t==null?void 0:t.requestId;if(!T){K.error("Request ID not found");return}w&&await xn(w,T,"SUPPORTING"),await s(),b.length<f.length?K.warning(`${b.length} of ${f.length} file(s) were uploaded. ${y.length} file(s) were rejected.`):K.success("Document uploaded successfully")}catch(w){console.error("[useDocumentUpload] Upload error:",w),K.error(((A=(v=w==null?void 0:w.response)==null?void 0:v.data)==null?void 0:A.error)||"Failed to upload document")}finally{r(!1),x.target&&(x.target.value="")}};return{uploadingDocument:a,handleDocumentUpload:u,triggerFileInput:()=>{const x=document.createElement("input");x.type="file",x.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),x.onchange=u,x.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const eS="modulepreload",tS=function(t){return"/"+t},Fu={},El=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=tS(c),c in Fu)return;Fu[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const u=document.createElement("link");if(u.rel=d?"stylesheet":eS,d||(u.as="script"),u.crossOrigin="",u.href=c,o&&u.setAttribute("nonce",o),document.head.appendChild(u),d)return new Promise((h,x)=>{u.addEventListener("load",h),u.addEventListener("error",()=>x(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 ag(t,s,a,r,n,i,l){const[o,c]=p.useState(""),[d,m]=p.useState(!1),[u,h]=p.useState(!1),[x,g]=p.useState(!1),[f,y]=p.useState(0),[b,v]=p.useState(!1),[A,w]=p.useState(!1),[T,C]=p.useState(0),_=async()=>{var R;const j=(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(j||P){c(j||P),g(!!P);return}try{const{getConclusion:O}=await El(async()=>{const{getConclusion:M}=await import("./conclusionApi-DFaefruY.js");return{getConclusion:M}},__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(!A)try{m(!0),v(!1);const{generateConclusion:j}=await El(async()=>{const{generateConclusion:F}=await import("./conclusionApi-DFaefruY.js");return{generateConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7])),P=await j(t.requestId||s),R=f+1;if(y(R),!(P!=null&&P.aiGeneratedRemark)||P.aiGeneratedRemark.toLowerCase().includes("unable to generate")||P.aiGeneratedRemark.toLowerCase().includes("sorry")){const F=T+1;C(F),F>=2?(w(!0),i==null||i({success:!1,title:"AI Generation Limit Reached",message:"We're unable to process a conclusion remark at this time after 2 attempts. Please proceed with a manual approach using the editor below."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process a conclusion remark at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0),c((P==null?void 0:P.aiGeneratedRemark)||""),g(!1);return}c(P.aiGeneratedRemark),g(!0),C(0),R>=2&&(w(!0),i==null||i({success:!0,title:"Maximum Attempts Reached",message:"You've reached the maximum of 2 regeneration attempts. Feel free to manually edit the current suggestion to fit your specific needs."}),l==null||l(!0))}catch(j){console.error("[useConclusionRemark] AI generation failed:",j);const P=T+1;C(P),g(!1),P>=2?(w(!0),i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. Since the maximum of 2 attempts is reached, please proceed with a manual approach."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0)}finally{m(!1)}},S=async()=>{var P,R;const j=o.replace(/<[^>]*>/g,"").trim();if(!j){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(j.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),l==null||l(!0);return}try{h(!0);const{finalizeConclusion:O}=await El(async()=>{const{finalizeConclusion:F}=await import("./conclusionApi-DFaefruY.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{h(!1)}};return p.useEffect(()=>{var F;const j=(F=t==null?void 0:t.status)==null?void 0:F.toLowerCase();if(!((j==="approved"||j==="rejected"||j==="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:u,aiGenerated:x,handleGenerateConclusion:D,handleFinalizeConclusion:S,generationAttempts:f,generationFailed:b,maxAttemptsReached:A}}function rg(t,s,a){const[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState(!1),[d,m]=p.useState(!1),[u,h]=p.useState(!1),[x,g]=p.useState(!1),[f,y]=p.useState(null),[b,v]=p.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:u,setShowSkipApproverModal:h,showActionStatusModal:x,setShowActionStatusModal:g,skipApproverData:f,setSkipApproverData:y,actionStatus:b,setActionStatus:v,handleApproveConfirm:async D=>{var j,P;const S=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!S){alert("Approval level not found");return}await mn(t,S,D||""),await new Promise(R=>setTimeout(R,500)),await a(),(j=window==null?void 0:window.closeModal)==null||j.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var j,P;if(!(D!=null&&D.trim())){alert("Comments & remarks are required");return}const S=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!S){alert("Approval level not found");return}await kr(t,S,D.trim(),D.trim()),await a(),(j=window==null?void 0:window.closeModal)==null||j.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Rejected successfully")},handleAddApprover:async(D,S,j)=>{var P,R;try{await oh(t,D,S,j),await a(),c(!1),v==null||v({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${j} with ${S}h TAT`}),g==null||g(!0)}catch(O){throw v==null||v({success:!1,title:"Failed to Add Approver",message:((R=(P=O==null?void 0:O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to add approver. Please try again."}),g==null||g(!0),O}},handleSkipApprover:async D=>{var S,j;if(f)try{await cN(t,f.levelId,D),await a(),h(!1),y(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:((j=(S=P==null?void 0:P.response)==null?void 0:S.data)==null?void 0:j.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),P}},handleAddSpectator:async D=>{var S,j;try{await ch(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:((j=(S=P==null?void 0:P.response)==null?void 0:S.data)==null?void 0:j.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),P}}}}const sS=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 zr({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(De,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900","data-testid":`${n}-name`,children:t.name}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${n}-metadata`,children:[t.size&&e.jsxs("span",{children:[t.size," • "]}),t.uploadedBy&&e.jsxs("span",{children:["Uploaded by ",t.uploadedBy," on "]}),is(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&sS(t.fileType)&&s&&e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>s({fileName:t.name,fileType:t.fileType,documentId:t.documentId,fileSize:t.sizeBytes}),title:"Preview file","data-testid":`${n}-preview-btn`,children:e.jsx(xt,{className:"w-4 h-4"})}),a&&e.jsx(I,{variant:"ghost",size:"sm",onClick:async()=>{if(!t.documentId){alert("Document ID not available");return}try{await a(t.documentId)}catch{alert("Failed to download document")}},title:"Download file","data-testid":`${n}-download-btn`,children:e.jsx(wt,{className:"w-4 h-4"})})]})]})}function aS({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(J,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(De,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx(Te,{className:"text-xs sm:text-sm mt-1",children:"Documents attached while creating the request"})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsxs(I,{size:"sm",onClick:n,disabled:a||t.status==="closed",className:"gap-1 sm:gap-2 h-8 sm:h-9 text-xs sm:text-sm shrink-0","data-testid":"upload-document-btn",children:[e.jsx(Es,{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(q,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((o,c)=>e.jsx(zr,{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(J,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Is,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(q,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((o,c)=>e.jsx(zr,{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 rS=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"}}},nS=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}}},iS=t=>{switch(t){case"approval":case"approved":return e.jsx(Pe,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(Nt,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(Is,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(zt,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(Ei,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(De,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(Xe,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(ki,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(ss,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(Pt,{className:"w-5 h-5 text-gray-600"})}};function lS({request:t}){return e.jsxs(J,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Pt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(q,{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:iS(s.type)})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-gray-900",children:s.action}),e.jsx("span",{className:"text-xs text-gray-500 whitespace-nowrap ml-4",children:is(s.timestamp)})]}),e.jsx("div",{className:"text-sm text-gray-600 leading-relaxed",children:e.jsx("p",{className:"whitespace-pre-line break-words",children:s.details})})]})})]},a)):e.jsxs("div",{className:"text-center py-12","data-testid":"no-activity",children:[e.jsx(Pt,{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 ng({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"sm:max-w-md",children:[e.jsx(pt,{children:e.jsxs(dt,{className:"flex items-center gap-2",children:[a?e.jsx(Pe,{className:"w-5 h-5 text-green-600"}):e.jsx(Ve,{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(Pe,{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(Nt,{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(kt,{children:e.jsx(I,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function ig({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=p.useState(""),[l,o]=p.useState(!1),[c,d]=p.useState([]),[m,u]=p.useState(!1),[h,x]=p.useState(null),g=p.useRef(null),f=p.useRef(null),[y,b]=p.useState({open:!1,type:"error",email:"",message:""}),[v,A]=p.useState({open:!1,violations:[]}),[w,T]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});p.useEffect(()=>{t&&(async()=>{var P;try{const R=await Js("WORKFLOW_SHARING"),O=await Js("TAT_SETTINGS"),F=[...R,...O],M={};F.forEach(B=>{M[B.configKey]=B.configValue}),T({maxApprovalLevels:parseInt(M.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(M.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((P=M.ALLOW_ADD_SPECTATOR)==null?void 0:P.toLowerCase())==="true",maxSpectators:parseInt(M.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(R){console.error("Failed to load system policy:",R)}})()},[t]);const C=async()=>{var k,N;const j=n.trim().toLowerCase();if(!j){b({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(j)){b({open:!0,type:"error",email:j,message:"Please enter a valid email address"});return}const R=r.find(U=>(U.email||"").toLowerCase()===j);if(R){const U=((k=R.participantType)==null?void 0:k.toUpperCase())||"PARTICIPANT",$=R.name||j;if(U==="INITIATOR"){b({open:!0,type:"error",email:j,message:`${$} is the request initiator and cannot be added as a spectator.`});return}else if(U==="APPROVER"){b({open:!0,type:"error",email:j,message:`${$} is already an approver on this request and cannot be added as a spectator.`});return}else if(U==="SPECTATOR"){b({open:!0,type:"error",email:j,message:`${$} is already a spectator on this request.`});return}else{b({open:!0,type:"error",email:j,message:`${$} is already a participant on this request.`});return}}const O=[];w.allowSpectators||O.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const M=r.filter(U=>(U.participantType||"").toUpperCase()==="SPECTATOR").length;M>=w.maxSpectators&&O.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:M,maxValue:w.maxSpectators});const B=r.length+1;if(B>w.maxParticipants&&O.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:B,maxValue:w.maxParticipants}),O.length>0){A({open:!0,violations:O});return}if(!h||h.email.toLowerCase()!==j)try{const $=((N=(await ca(j,1)).data)==null?void 0:N.data)||[];if($.length===0){b({open:!0,type:"not-found",email:j,message:""});return}const L=$[0];await la({userId:L.userId,email:L.email,displayName:L.displayName,firstName:L.firstName,lastName:L.lastName,department:L.department,phone:L.phone,mobilePhone:L.mobilePhone,designation:L.designation,jobTitle:L.jobTitle,manager:L.manager,employeeId:L.employeeId,employeeNumber:L.employeeNumber,secondEmail:L.secondEmail,location:L.location})}catch(U){console.error("Failed to validate spectator:",U),b({open:!0,type:"error",email:j,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(j),i(""),x(null),s()}catch(U){console.error("Failed to add spectator:",U)}finally{o(!1)}},_=()=>{l||(i(""),x(null),d([]),u(!1),s())};p.useEffect(()=>{c.length>0&&f.current&&f.current.scrollTo({top:f.current.scrollHeight,behavior:"smooth"})},[c.length]),p.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const D=j=>{if(i(j),h&&h.email.toLowerCase()!==j.toLowerCase()&&x(null),g.current&&clearTimeout(g.current),!j||!j.startsWith("@")||j.length<2){d([]),u(!1);return}u(!0),g.current=setTimeout(async()=>{var P;try{const R=j.slice(1),F=((P=(await ca(R,10)).data)==null?void 0:P.data)||[];d(F)}catch(R){console.error("Search failed:",R),d([])}finally{u(!1)}},300)},S=async j=>{try{await la({userId:j.userId,email:j.email,displayName:j.displayName,firstName:j.firstName,lastName:j.lastName,department:j.department,phone:j.phone,mobilePhone:j.mobilePhone,designation:j.designation,jobTitle:j.jobTitle,manager:j.manager,employeeId:j.employeeId,employeeNumber:j.employeeNumber,secondEmail:j.secondEmail,location:j.location}),i(j.email),x(j),d([]),u(!1)}catch(P){console.error("Failed to ensure user exists:",P),b({open:!0,type:"error",email:j.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ht,{open:t,onOpenChange:_,children:[e.jsxs(ct,{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(gt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center",children:e.jsx(xt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(dt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:f,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(Fi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ie,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:j=>D(j.target.value),className:"pl-10 h-11 border-gray-300",disabled:l,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(j=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>S(j),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(es,{className:"h-8 w-8",children:e.jsx(ts,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(j.displayName||j.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: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(I,{type:"button",variant:"outline",onClick:_,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(I,{type:"button",onClick:C,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(xt,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(ht,{open:y.open,onOpenChange:j=>b(P=>({...P,open:j})),children:e.jsxs(ct,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(dt,{className:"flex items-center gap-2",children:y.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Et,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[y.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:y.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(Ii,{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."]})})]}),y.type==="error"&&e.jsxs(e.Fragment,{children:[y.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:y.email}),"."]}),y.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:y.message})})]})]})})]}),e.jsx(kt,{children:e.jsx(I,{onClick:()=>b(j=>({...j,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx($n,{open:v.open,onClose:()=>A({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:w.maxApprovalLevels,maxParticipants:w.maxParticipants,allowSpectators:w.allowSpectators,maxSpectators:w.maxSpectators}})]})}function lg({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=p.useState(""),[d,m]=p.useState(24),[u,h]=p.useState(null),[x,g]=p.useState(!1),[f,y]=p.useState([]),[b,v]=p.useState(!1),[A,w]=p.useState(null),T=p.useRef(null),C=p.useRef(null),[_,D]=p.useState({open:!1,type:"error",email:"",message:""}),S=n.filter(N=>N&&(N.status==="approved"||N.status==="rejected"||N.status==="skipped")),j=Math.max(1,S.length+1),P=Math.max(1,n.length+1),R=P>=j?Array.from({length:P-j+1},(N,U)=>j+U):[j];p.useEffect(()=>{R.length>0&&u===null&&h(R[0]||null)},[R.length,u]);const O=async()=>{var G,oe;const N=o.trim().toLowerCase();if(!N){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){D({open:!0,type:"error",email:N,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(!u){D({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(u<j){D({open:!0,type:"error",email:"",message:`Cannot add approver at level ${u}. Minimum allowed level is ${j} (after completed levels)`});return}const $=n.length>0?Math.max(...n.map(Z=>Z.levelNumber),0):0,L=u>$?u:$+1;if(i&&L>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${u} would result in ${L} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:L,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${$} level(s).`});return}const se=r.find(Z=>(Z.email||"").toLowerCase()===N);if(se){const Z=((G=se.participantType)==null?void 0:G.toUpperCase())||"PARTICIPANT",E=se.name||N;if(Z==="INITIATOR"){D({open:!0,type:"error",email:N,message:`${E} is the request initiator and cannot be added as an approver.`});return}else if(Z==="APPROVER"){D({open:!0,type:"error",email:N,message:`${E} is already an approver on this request.`});return}else if(Z==="SPECTATOR"){D({open:!0,type:"error",email:N,message:`${E} 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:N,message:`${E} is already a participant on this request.`});return}}if(!A||A.email.toLowerCase()!==N)try{const E=((oe=(await ca(N,1)).data)==null?void 0:oe.data)||[];if(E.length===0){D({open:!0,type:"not-found",email:N,message:""});return}const V=E[0];await la({userId:V.userId,email:V.email,displayName:V.displayName,firstName:V.firstName,lastName:V.lastName,department:V.department,phone:V.phone,mobilePhone:V.mobilePhone,designation:V.designation,jobTitle:V.jobTitle,manager:V.manager,employeeId:V.employeeId,employeeNumber:V.employeeNumber,secondEmail:V.secondEmail,location:V.location})}catch(Z){console.error("Failed to validate approver:",Z),D({open:!0,type:"error",email:N,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(N,d,u),c(""),m(24),h(null),w(null),s()}catch(Z){console.error("Failed to add approver:",Z)}finally{g(!1)}},F=()=>{x||(c(""),m(24),h(null),w(null),y([]),v(!1),s())},M=N=>{const U=N.toLowerCase();return U==="approved"?e.jsx(Pe,{className:"w-4 h-4 text-green-600"}):U==="rejected"?e.jsx(Nt,{className:"w-4 h-4 text-red-600"}):U==="skipped"?e.jsx(Ve,{className:"w-4 h-4 text-orange-600"}):U==="in-review"||U==="pending"?e.jsx(Xe,{className:"w-4 h-4 text-blue-600"}):e.jsx(Xe,{className:"w-4 h-4 text-gray-400"})};p.useEffect(()=>{f.length>0&&C.current&&C.current.scrollTo({top:C.current.scrollHeight,behavior:"smooth"})},[f.length]),p.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const B=N=>{if(c(N),A&&A.email.toLowerCase()!==N.toLowerCase()&&w(null),T.current&&clearTimeout(T.current),!N||!N.startsWith("@")||N.length<2){y([]),v(!1);return}v(!0),T.current=setTimeout(async()=>{var U;try{const $=N.slice(1),se=((U=(await ca($,10)).data)==null?void 0:U.data)||[];y(se)}catch($){console.error("Search failed:",$),y([])}finally{v(!1)}},300)},k=async N=>{try{await la({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}),c(N.email),w(N),y([]),v(!1)}catch(U){console.error("Failed to ensure user exists:",U),D({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ht,{open:t,onOpenChange:F,children:[e.jsxs(ct,{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:x,children:[e.jsx(gt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Bt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(dt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:C,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(N=>N.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(N=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${N.status==="approved"?"bg-green-100 border border-green-200":N.status==="rejected"?"bg-red-100 border border-red-200":N.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:N.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:N.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[N.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[M(N.status),e.jsx(ie,{variant:"outline",className:`text-xs ${N.status==="approved"?"bg-green-50 text-green-700 border-green-300":N.status==="rejected"?"bg-red-50 text-red-700 border-red-300":N.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:N.status})]})]},N.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:[" New approver can only be added at level ",j," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(He,{value:(u==null?void 0:u.toString())||"",onValueChange:N=>h(Number(N)),disabled:x,children:[e.jsx(Ge,{className:"h-11 border-gray-300",children:e.jsx(We,{placeholder:"Select level"})}),e.jsx(Ke,{children:R.map(N=>e.jsx(X,{value:N.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ds,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",N]}),N<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",N,")"]})]})},N))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Choose where to insert the new approver. Existing levels will be automatically shifted."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{type:"number",min:"1",max:"720",value:d,onChange:N=>m(Number(N.target.value)),className:"h-11 border-gray-300 flex-1",disabled:x,placeholder:"24"}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-600 bg-gray-100 px-3 h-11 rounded-md border border-gray-300",children:[e.jsx(Xe,{className:"w-4 h-4"}),"hours"]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum time for this approver to respond (1-720 hours)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ie,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:N=>B(N.target.value),className:"pl-10 h-11 border-gray-300",disabled:x,autoFocus:!0}),(b||f.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:b?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):f.length>0?e.jsx("ul",{className:"divide-y",children:f.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>k(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(es,{className:"h-8 w-8",children:e.jsx(ts,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(N.displayName||N.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: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(I,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:x,children:"Cancel"}),e.jsxs(I,{type:"button",onClick:O,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:x||!o.trim()||!u||!d,children:[e.jsx(Bt,{className:"w-4 h-4 mr-2"}),x?"Adding...":`Add at Level ${u||"?"}`]})]})]}),e.jsx(ht,{open:_.open,onOpenChange:N=>D(U=>({...U,open:N})),children:e.jsxs(ct,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(dt,{className:"flex items-center gap-2",children:_.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Et,{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(Ii,{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(kt,{children:e.jsx(I,{onClick:()=>D(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const oS=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"}},cS=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},dS=t=>t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(s,a,r,n)=>{const i=r+s.length,l=n[i];return!l||/\s|[.,!?;:]|@/.test(l)?'<span class="inline-flex items-center px-2.5 py-0.5 rounded-md bg-blue-50 text-blue-800 font-black text-base border-2 border-blue-400 shadow-sm">@'+a+"</span>":s}).replace(/\n/g,"<br />"),mS=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Mu=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(De,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(k0,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(De,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(De,{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(Jn,{className:`${s} text-purple-600`}):e.jsx(ki,{className:`${s} text-gray-600`})};function og({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:u}){const h=La(),x=t||h.requestId||"",[g,f]=p.useState(""),[y,b]=p.useState(""),[v,A]=p.useState(!1),[w,T]=p.useState([]),[C,_]=p.useState(!1),[D,S]=p.useState([]),[j,P]=p.useState(null),[R,O]=p.useState(null),[F,M]=p.useState(!1),[B,k]=p.useState(!1),[N,U]=p.useState(!1),[$,L]=p.useState({success:!0,title:"",message:""}),se=p.useRef(null),G=p.useRef(null),oe=p.useRef(null),Z=p.useRef(!1),[E,V]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[H,Q]=p.useState({open:!1,errors:[]}),Y=p.useMemo(()=>({id:x,title:n||"Request Details"}),[x,n]),[W,ce]=p.useState([]),xe=W.filter(ee=>ee.status==="online"),ke=w.filter(ee=>ee.content.toLowerCase().includes(y.toLowerCase())||ee.user.name.toLowerCase().includes(y.toLowerCase())),Ae=p.useMemo(()=>o!==void 0?o:!j||W.length===0?!1:W.some(ee=>{const we=ee.userId||ee.user_id,te=(ee.role||"").toString().toUpperCase(),_e=(ee.participantType||ee.participant_type||"").toString().toUpperCase();return we===j&&(te==="SPECTATOR"||_e==="SPECTATOR")}),[o,j,W]);p.useEffect(()=>{},[W]),p.useEffect(()=>{!x||!j||s||(async()=>{try{const ee=await Or(x),we=Array.isArray(ee)?ee.map(te=>{const _e=te.userId||te.user_id;return{id:te.noteId||te.id||String(Math.random()),user:{name:te.userName||"User",avatar:(te.userName||"U").slice(0,2).toUpperCase(),role:te.userRole||"Participant"},content:te.message||"",timestamp:te.createdAt||new Date().toISOString(),isCurrentUser:_e===j,attachments:Array.isArray(te.attachments)?te.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}}):[];T(we)}catch(ee){console.error("[WorkNoteChat] Failed to load messages:",ee)}})()},[x,j,s]);const ae=p.useMemo(()=>{const ee=[];return w.forEach(we=>{we.attachments&&we.attachments.length>0&&we.attachments.forEach(te=>{ee.push({attachmentId:te.attachmentId||te.attachment_id,name:te.fileName||te.file_name||te.name||"Untitled",fileName:te.fileName||te.file_name||te.name||"Untitled",size:te.fileSize||te.file_size,type:te.fileType||te.file_type||te.type||"file",uploadedBy:we.user.name,uploadedAt:we.timestamp,url:te.storageUrl||te.storage_url||te.url||"#"})})}),ee},[w]);p.useEffect(()=>{i&&ae.length>=0&&i(ae)},[ae,i]);const ye=p.useMemo(()=>W.map(ee=>({email:(ee.email||"").toLowerCase(),participantType:ee.role==="Initiator"?"INITIATOR":ee.role==="Approver"?"APPROVER":ee.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:ee.name})),[W]),Ne=ee=>{if(!ee)return"Participant";switch(ee.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return ee.charAt(0).toUpperCase()+ee.slice(1).toLowerCase()}},ve=()=>{var ee;(ee=se.current)==null||ee.scrollIntoView({behavior:"smooth"})};p.useEffect(()=>{ve()},[w]);const $e=ee=>{switch(ee.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return ee.charAt(0).toUpperCase()+ee.slice(1).toLowerCase()}};p.useEffect(()=>{Z.current||x&&(async()=>{try{const ee=await Cs(x),we=Array.isArray(ee==null?void 0:ee.participants)?ee.participants:[];if(we.length===0)return;const te=we.map(Le=>{const Je=Le.participantType||Le.participant_type||"participant",Be=Le.userId||Le.user_id||"";return{name:Le.userName||Le.user_name||Le.user_email||Le.userEmail||"User",avatar:(Le.userName||Le.user_name||Le.user_email||"U").toString().split(" ").map(tt=>tt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:$e(Je.toString()),status:"offline",email:Le.userEmail||Le.user_email||"",permissions:["read","write","mention"],userId:Be}});Z.current=!0,ce(te);let _e=0;const Fe=3,ze=()=>{oe.current&&oe.current.connected?(oe.current.emit("request:online-users",{requestId:x}),_e++,_e<Fe&&setTimeout(ze,500)):(_e++,_e<Fe&&setTimeout(ze,200))};setTimeout(ze,100)}catch(ee){console.error("[WorkNoteChat] ❌ Failed to load participants:",ee)}})()},[x]),p.useEffect(()=>()=>{x&&(Z.current=!1)},[x]),p.useEffect(()=>{const ee=localStorage.getItem("userData");if(ee)try{const we=JSON.parse(ee),te=(we==null?void 0:we.id)||(we==null?void 0:we.userId)||(we==null?void 0:we.user_id)||null;P(te)}catch(we){console.error("[WorkNoteChat] Failed to parse userData:",we)}},[]),p.useEffect(()=>{(async()=>{try{const we=await Js("DOCUMENT_POLICY"),te={};we.forEach(Le=>{te[Le.configKey]=Le.configValue});const _e=parseInt(te.MAX_FILE_SIZE_MB||"10"),ze=(te.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Le=>Le.trim().toLowerCase());V({maxFileSizeMB:_e,allowedFileTypes:ze})}catch(we){console.error("Failed to load document policy:",we)}})()},[]),p.useEffect(()=>{if(!j)return;let ee=x;return(async()=>{var we;try{const te=await Cs(x);(we=te==null?void 0:te.workflow)!=null&&we.requestId&&(ee=te.workflow.requestId)}catch{}try{const te=Ur();r?ce(rt=>rt.map(bt=>bt.userId===j?{...bt,status:"online"}:bt)):(Kl(te,ee,j),ce(rt=>rt.map(bt=>bt.userId===j?{...bt,status:"online"}:bt)));const _e=rt=>{const st=(rt==null?void 0:rt.note)||rt;if(!st)return;const bt=st.noteId||st.id;T(as=>{if(as.some(At=>At.id===bt))return as;const Ft=st.userName||st.user_name||"User",fa=st.userRole||st.user_role,ya=Ne(fa),Oa=st.userId||st.user_id,Sa={id:bt||String(Date.now()),user:{name:Ft,avatar:Ft.split(" ").map(At=>At[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:ya},content:st.message||"",timestamp:st.createdAt||new Date().toISOString(),isCurrentUser:Oa===j,attachments:Array.isArray(st.attachments)?st.attachments.map(At=>({attachmentId:At.attachmentId||At.attachment_id,name:At.fileName||At.file_name||At.name,fileName:At.fileName||At.file_name||At.name,url:At.storageUrl||At.storage_url||At.url||"#",type:At.fileType||At.file_type||At.type||"file",fileType:At.fileType||At.file_type||At.type||"file",fileSize:At.fileSize||At.file_size})):void 0};return[...as,Sa]})},Fe=rt=>{ce(st=>st.length===0||!st.find(Ft=>Ft.userId===rt.userId)?st:st.map(Ft=>Ft.userId===rt.userId?{...Ft,status:"online"}:Ft))},ze=rt=>{rt.userId!==j&&ce(st=>st.length===0||!st.find(Ft=>Ft.userId===rt.userId)?st:st.map(Ft=>Ft.userId===rt.userId?{...Ft,status:"offline"}:Ft))},Le=rt=>{ce(st=>st.length===0?st:st.map(as=>{const Ft=as.userId||"";if(Ft===j)return{...as,status:"online"};const ya=rt.userIds.includes(Ft);return{...as,status:ya?"online":"offline"}}))},Je=()=>{ce(rt=>rt.map(bt=>bt.userId===j?{...bt,status:"online"}:bt)),r||Kl(te,ee,j),Z.current&&(te.emit("request:online-users",{requestId:ee}),setTimeout(()=>te.emit("request:online-users",{requestId:ee}),300),setTimeout(()=>te.emit("request:online-users",{requestId:ee}),800))},Be=rt=>{console.error("[WorkNoteChat] ❌ Socket error:",rt)},tt=rt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",rt),ce(st=>st.map(bt=>bt.userId===j?bt:{...bt,status:"offline"}))},ws=rt=>{rt.includes("presence")||rt.includes("worknote")||rt.includes("request")};te.on("connect",Je),te.on("disconnect",tt),te.on("error",Be),te.on("worknote:new",_e),te.on("presence:join",Fe),te.on("presence:leave",ze),te.on("presence:online",Le),te.onAny(ws),oe.current=te,te.connected&&Z.current&&(te.emit("request:online-users",{requestId:ee}),setTimeout(()=>{te.emit("request:online-users",{requestId:ee})},300),setTimeout(()=>{te.emit("request:online-users",{requestId:ee})},800),setTimeout(()=>{te.emit("request:online-users",{requestId:ee})},1500));const Yt=()=>{te.off("connect",Je),te.off("disconnect",tt),te.off("error",Be),te.off("worknote:new",_e),te.off("presence:join",Fe),te.off("presence:leave",ze),te.off("presence:online",Le),te.offAny(ws),r||Gx(te,ee),oe.current=null};window.__wn_cleanup=Yt}catch{}})(),()=>{var we;try{(we=window.__wn_cleanup)==null||we.call(window)}catch{}}},[x,j,r]);const re=async()=>{if(g.trim()||D.length>0){const ee=ea(g),we=ee.map(Fe=>{const ze=W.find(Le=>Le.name.toLowerCase().includes(Fe.toLowerCase()));return ze==null?void 0:ze.userId}).filter(Boolean),te=D.map(Fe=>({name:Fe.name,url:URL.createObjectURL(Fe),type:Fe.type.split("/")[1]||"file"})),_e={id:Date.now().toString(),user:{name:"You",avatar:"YO",role:"Current User"},content:g,timestamp:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),mentions:ee,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:te.length>0?te:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await lh(x,{message:g,mentions:we},D);const Fe=await Or(x),ze=Array.isArray(Fe)?Fe.map(Le=>{const Je=Le.userId||Le.user_id;return{id:Le.noteId||Le.id||String(Math.random()),user:{name:Le.userName||"User",avatar:(Le.userName||"U").slice(0,2).toUpperCase(),role:Le.userRole||"Participant"},content:Le.message||"",timestamp:Le.createdAt||new Date().toISOString(),isCurrentUser:Je===j,attachments:Array.isArray(Le.attachments)?Le.attachments.map(Be=>({attachmentId:Be.attachmentId||Be.attachment_id,name:Be.fileName||Be.file_name||Be.name,fileName:Be.fileName||Be.file_name||Be.name,url:Be.storageUrl||Be.storage_url||Be.url||"#",type:Be.fileType||Be.file_type||Be.type||"file",fileType:Be.fileType||Be.file_type||Be.type||"file",fileSize:Be.fileSize||Be.file_size})):void 0}}):[];T(ze)}catch{T(Fe=>[...Fe,_e])}f(""),S([])}};p.useEffect(()=>{if(s&&Array.isArray(s))try{const we=s.filter(te=>(te.type||"").toLowerCase()!=="sla_warning").map(te=>{var Fe;if(te.type||te.activityType||te.isSystem)return{id:te.id||`activity-${te.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:te.details||te.action||te.content||"",timestamp:te.timestamp||te.createdAt||te.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const ze=te.userName||te.user_name||((Fe=te.user)==null?void 0:Fe.name)||"User",Le=te.userRole||te.user_role,Je=Ne(Le),Be=te.userId||te.user_id;return{id:te.noteId||te.note_id||te.id||String(Math.random()),user:{name:ze,avatar:ze.split(" ").map(tt=>tt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Je},content:te.message||te.content||"",timestamp:te.createdAt||te.created_at||te.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(te.attachments)?te.attachments.map(tt=>({attachmentId:tt.attachmentId||tt.attachment_id,name:tt.fileName||tt.file_name||tt.name,fileName:tt.fileName||tt.file_name||tt.name,url:tt.storageUrl||tt.storage_url||tt.url||"#",type:tt.fileType||tt.file_type||tt.type||"file",fileType:tt.fileType||tt.file_type||tt.type||"file",fileSize:tt.fileSize||tt.file_size})):void 0,isCurrentUser:Be===j}}}).sort((te,_e)=>new Date(te.timestamp).getTime()-new Date(_e.timestamp).getTime());T(we)}catch(ee){console.error("[WorkNoteChat] Error mapping messages:",ee)}else(async()=>{try{const ee=await Or(x),we=Array.isArray(ee)?ee.map(te=>{const _e=te.userName||te.user_name||"User",Fe=te.userRole||te.user_role,ze=Ne(Fe),Le=te.userId||te.user_id;return{id:te.noteId||te.note_id||te.id||String(Math.random()),user:{name:_e,avatar:_e.split(" ").map(Je=>Je[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:ze},content:te.message||"",timestamp:te.createdAt||te.created_at||new Date().toISOString(),attachments:Array.isArray(te.attachments)?te.attachments.map(Je=>({attachmentId:Je.attachmentId||Je.attachment_id,name:Je.fileName||Je.file_name||Je.name,fileName:Je.fileName||Je.file_name||Je.name,url:Je.storageUrl||Je.storage_url||Je.url||"#",type:Je.fileType||Je.file_type||Je.type||"file",fileType:Je.fileType||Je.file_type||Je.type||"file",fileSize:Je.fileSize||Je.file_size})):void 0,isCurrentUser:Le===j}}):[];T(we)}catch(ee){console.error("[WorkNoteChat] Error loading work notes:",ee)}})()},[s,x,W]);const Me=ee=>{const we=E.maxFileSizeMB*1024*1024;if(ee.size>we)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${E.maxFileSizeMB}MB. Current size: ${(ee.size/(1024*1024)).toFixed(2)}MB`};const te=ee.name.toLowerCase(),_e=te.substring(te.lastIndexOf(".")+1);return E.allowedFileTypes.includes(_e)?{valid:!0}:{valid:!1,reason:`File type "${_e}" is not allowed. Allowed types: ${E.allowedFileTypes.join(", ")}`}},ot=ee=>{if(!ee.target.files||ee.target.files.length===0)return;const we=Array.from(ee.target.files),te=[],_e=[];we.forEach(Fe=>{const ze=Me(Fe);ze.valid?_e.push(Fe):te.push({fileName:Fe.name,reason:ze.reason||"Unknown validation error"})}),te.length>0&&Q({open:!0,errors:te}),_e.length>0&&(S(Fe=>[...Fe,..._e]),_e.length<we.length?K.warning(`${_e.length} of ${we.length} file(s) were added. ${te.length} file(s) were rejected.`):K.success(`${_e.length} file(s) added successfully`)),ee.target&&(ee.target.value="")},pe=ee=>{S(we=>we.filter((te,_e)=>_e!==ee)),G.current&&(G.current.value="")},Oe=ee=>{f(we=>we+ee),A(!1)},ft=()=>{var ee;(ee=G.current)==null||ee.click()},mt=async ee=>{var we,te;try{await ch(x,ee);const _e=await Cs(x),Fe=Array.isArray(_e==null?void 0:_e.participants)?_e.participants:[];if(Fe.length){const ze=Fe.map(Le=>{const Je=Le.participantType||Le.participant_type||"participant",Be=Le.userId||Le.user_id||"",tt=Le.userName||Le.user_name||Le.userEmail||Le.user_email||"User",ws=Le.userEmail||Le.user_email||"",Yt=tt.split(" ").map(rt=>rt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:tt,avatar:Yt,role:$e(Je),status:"offline",email:ws,lastSeen:void 0,permissions:["read"],userId:Be}});ce(ze),oe.current&&oe.current.connected&&oe.current.emit("request:online-users",{requestId:x})}M(!1),L({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),U(!0)}catch(_e){throw console.error("Failed to add spectator:",_e),L({success:!1,title:"Failed to Add Spectator",message:((te=(we=_e==null?void 0:_e.response)==null?void 0:we.data)==null?void 0:te.error)||"Failed to add spectator. Please try again."}),U(!0),_e}},nt=async(ee,we,te)=>{var _e,Fe;if(d)await d(ee,we,te),k(!1);else try{await oh(x,ee,we,te);const ze=await Cs(x),Le=Array.isArray(ze==null?void 0:ze.participants)?ze.participants:[];if(Le.length){const Je=Le.map(Be=>{const tt=Be.participantType||Be.participant_type||"participant",ws=Be.userId||Be.user_id||"",Yt=Be.userName||Be.user_name||Be.userEmail||Be.user_email||"User",rt=Be.userEmail||Be.user_email||"",st=Yt.split(" ").map(bt=>bt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Yt,avatar:st,role:$e(tt),status:"offline",email:rt,lastSeen:void 0,permissions:["read"],userId:ws}});ce(Je),oe.current&&oe.current.connected&&oe.current.emit("request:online-users",{requestId:x})}k(!1),L({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${te} with ${we}h TAT`}),U(!0)}catch(ze){throw console.error("Failed to add approver:",ze),L({success:!1,title:"Failed to Add Approver",message:((Fe=(_e=ze==null?void 0:ze.response)==null?void 0:_e.data)==null?void 0:Fe.error)||"Failed to add approver. Please try again."}),U(!0),ze}},_s=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","","","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],ea=ee=>{const we=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,te=[];let _e;for(;(_e=we.exec(ee))!==null;)if(_e[1]){const Fe=_e.index+_e[0].length,ze=ee.slice(Fe),Le=ee[Fe];(ze.startsWith("@")||!Le||/\s|[.,!?;:]|@/.test(Le))&&te.push(_e[1].trim())}return te},Aa=ee=>{ee.key==="Enter"&&!ee.shiftKey&&(ee.preventDefault(),re())},qa=(ee,we)=>{T(te=>te.map(_e=>{if(_e.id===ee){const Fe=_e.reactions||[],ze=Fe.find(Le=>Le.emoji===we);if(ze)if(ze.users.includes("You")){if(ze.users=ze.users.filter(Le=>Le!=="You"),ze.users.length===0)return{..._e,reactions:Fe.filter(Le=>Le.emoji!==we)}}else ze.users.push("You");else Fe.push({emoji:we,users:["You"]});return{..._e,reactions:Fe}}return _e}))};return e.jsxs("div",{className:"h-full flex flex-col bg-gray-50 overflow-hidden",children:[e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg shrink-0",children:e.jsx(Is,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"text-lg sm:text-2xl font-bold text-gray-900",children:"Work Notes"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("p",{className:"text-gray-600 text-sm sm:text-base truncate",children:Y.title}),e.jsx(ie,{variant:"outline",className:"text-xs shrink-0",children:t})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:e.jsxs("div",{className:"flex -space-x-2",children:[xe.slice(0,3).map((ee,we)=>e.jsx(es,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(ts,{className:"bg-blue-500 text-white text-xs font-semibold",children:ee.avatar})},we)),xe.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:["+",xe.length-3]})]})}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>_(!C),className:"lg:hidden",children:e.jsx(Bt,{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(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ie,{placeholder:"Search messages...",value:y,onChange:ee=>b(ee.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:[ke.map(ee=>{const we=ee.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${ee.isSystem?"justify-center":we?"justify-end":""}`,children:[!ee.isSystem&&!we&&e.jsx(es,{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(ts,{className:`text-white font-semibold text-xs sm:text-sm ${ee.user.role==="Initiator"?"bg-green-600":ee.user.role==="Current User"?"bg-blue-500":ee.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:ee.user.avatar})}),e.jsx("div",{className:`${we?"max-w-[70%]":"flex-1"} min-w-0 ${ee.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:ee.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(Pt,{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:ee.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:is(ee.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:[ee.user.name," ",we&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ie,{variant:"outline",className:"text-xs flex-shrink-0",children:ee.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(Xe,{className:"w-3 h-3"}),is(ee.timestamp)]}),ee.isHighPriority&&e.jsxs(ie,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(S0,{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:dS(ee.content)}}),ee.attachments&&ee.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:ee.attachments.map((te,_e)=>{const Fe=te.fileSize||te.file_size,ze=te.fileName||te.file_name||te.name,Le=te.fileType||te.file_type||te.type||"",Je=te.attachmentId||te.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(Mu,{type:Le})}),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:ze}),Fe&&e.jsx("p",{className:"text-xs text-gray-500",children:mS(Fe)})]}),Je&&(()=>{const Be=(Le||"").toLowerCase();return Be.includes("image")||Be.includes("pdf")||Be.includes("jpg")||Be.includes("jpeg")||Be.includes("png")||Be.includes("gif")})()&&e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-purple-100 hover:text-purple-600",onClick:Be=>{Be.preventDefault(),Be.stopPropagation();const tt=xN(Je);O({fileName:ze,fileType:Le,fileUrl:tt,fileSize:Fe,attachmentId:Je})},title:"Preview file",children:e.jsx(xt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-blue-100 hover:text-blue-600",onClick:async Be=>{if(Be.preventDefault(),Be.stopPropagation(),!Je){K.error("Cannot download: Attachment ID missing");return}try{await mm(Je)}catch{K.error("Failed to download file")}},title:"Download file",children:e.jsx(wt,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},_e)})})}),ee.reactions&&ee.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:[ee.reactions.map((te,_e)=>e.jsxs("button",{onClick:()=>qa(ee.id,te.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${te.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:te.emoji}),e.jsx("span",{className:"text-xs font-medium",children:te.users.length})]},_e)),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>A(!v),children:e.jsx(us,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!ee.isSystem&&we&&e.jsx(es,{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(ts,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:ee.user.avatar})})]},ee.id)}),e.jsx("div",{ref:se})]})}),e.jsx("div",{className:"bg-white border-t border-gray-200 p-2 sm:p-3 lg:p-6 flex-shrink-0",children:e.jsxs("div",{className:"max-w-full",children:[e.jsx("input",{type:"file",ref:G,onChange:ot,className:"hidden",multiple:!0,accept:E.allowedFileTypes.map(ee=>`.${ee}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((ee,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(Mu,{type:ee.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:ee.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(ee.size/1024).toFixed(1)," KB"]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>pe(we),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(gt,{className:"h-3 w-3 text-red-600"})})]},we))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const ee=g.lastIndexOf("@"),we=ee>=0;if(!we)return null;const te=g.slice(ee+1),_e=te.trim(),Fe=te.endsWith(" "),ze=_e.length>0,Le=_e.includes(" ")&&!Fe,Je=Fe&&ze;if(!(we&&te.length<=20&&!Le&&!Je))return null;const tt=_e.toLowerCase(),ws=W.filter(Yt=>Yt.userId===j?!1:tt?Yt.name.toLowerCase().includes(tt):!0);return e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border-2 border-blue-300 rounded-lg shadow-2xl p-3 z-[100] w-full sm:max-w-md",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 mb-2",children:"💬 Mention someone"}),e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-1",children:ws.length>0?ws.map((Yt,rt)=>e.jsxs("button",{type:"button",onClick:st=>{st.preventDefault(),st.stopPropagation();const bt=g.lastIndexOf("@"),as=g.slice(0,bt);f(as+"@"+Yt.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(es,{className:"h-10 w-10",children:e.jsx(ts,{className:`text-white text-sm font-semibold ${Yt.role==="Initiator"?"bg-green-600":Yt.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:Yt.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:Yt.name}),e.jsx("p",{className:"text-xs text-gray-600",children:Yt.role})]})]},rt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:tt?`No participants found matching "${tt}"`:"No other participants available"})})]})})(),e.jsx(Ts,{placeholder:"Type your message... Use @username to mention someone",value:g,onChange:ee=>f(ee.target.value),onKeyPress:Aa,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(I,{variant:"ghost",size:"sm",onClick:()=>A(!1),className:"h-6 w-6 p-0",children:e.jsx(gt,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:_s.map((ee,we)=>e.jsx("button",{onClick:()=>Oe(ee),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:ee,children:ee},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(I,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:ft,title:"Attach file",children:e.jsx(ki,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>A(!v),title:"Add emoji",children:e.jsx(T0,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>f(ee=>ee+"@"),title:"Mention someone",children:e.jsx(Fi,{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(I,{onClick:re,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(fx,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),C&&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
${C?"fixed right-0 top-0 bottom-0 z-50 shadow-xl":"hidden lg:flex"}
`,children:[e.jsxs("div",{className:"p-4 sm:p-6 border-b border-gray-200 flex-1 flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900",children:"Participants"}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>_(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(gt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:W.map((ee,we)=>{const te=ee.userId===j;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(es,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(ts,{className:`text-white font-semibold text-sm ${ee.role==="Initiator"?"bg-green-600":te?"bg-blue-500":"bg-slate-600"}`,children:ee.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${oS(ee.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:[ee.name," ",te&&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:ee.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:cS(ee.status)})]}),ee.lastSeen&&ee.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:ee.lastSeen})]})]},we)})})]}),!Ae&&e.jsxs("div",{className:"p-4 sm:p-6 flex-shrink-0",children:[e.jsx("h4",{className:"font-semibold text-gray-900 mb-3 text-sm sm:text-base",children:"Quick Actions"}),e.jsxs("div",{className:"space-y-2",children:[l&&e.jsxs(I,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>k(!0),children:[e.jsx(Ei,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(I,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>M(!0),children:[e.jsx(xt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),R&&e.jsx(Cr,{fileName:R.fileName,fileType:R.fileType,fileUrl:R.fileUrl,fileSize:R.fileSize,attachmentId:R.attachmentId,onDownload:mm,open:!!R,onClose:()=>O(null)}),!Ae&&e.jsx(ig,{open:F,onClose:()=>M(!1),onConfirm:mt,requestIdDisplay:x,requestTitle:Y.title,existingParticipants:ye}),!Ae&&l&&e.jsx(lg,{open:B,onClose:()=>k(!1),onConfirm:nt,requestIdDisplay:x,requestTitle:Y.title,existingParticipants:ye,currentLevels:c,maxApprovalLevels:m,onPolicyViolation:u}),e.jsx(ht,{open:H.open,onOpenChange:ee=>Q(we=>({...we,open:ee})),children:e.jsxs(ct,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(dt,{className:"flex items-center gap-2",children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Et,{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((ee,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:ee.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:ee.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: ",E.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",E.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(kt,{children:e.jsx(I,{onClick:()=>Q({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(ng,{open:N,onClose:()=>U(!1),success:$.success,title:$.title,message:$.message})]})}function uS({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(og,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d})})}function xS({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const c=o.toLowerCase();return c==="approved"?e.jsx(Pe,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(Nt,{className:"h-4 w-4 text-red-600"}):c==="pending"||c==="in progress"?e.jsx(Xe,{className:"h-4 w-4 text-orange-600"}):e.jsx(De,{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(Ze,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):t?e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:t.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",t.requestNumber]})]}),r&&a?e.jsxs(I,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(Hr,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(ie,{className:i(t.workflow.status),children:[n(t.workflow.status),e.jsx("span",{className:"ml-1 capitalize",children:t.workflow.status})]})]}),t.description&&e.jsx("div",{className:"mb-4",children:e.jsx(na,{content:t.description,className:"text-gray-700"})})]}),e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Initiator"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:Ye(new Date(t.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),t.approvers&&t.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),t.approvers.map((o,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:Ye(new Date(o.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:o.remarks||"—"})]})]},c))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),t.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(ie,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),t.closingRemarks?e.jsx(na,{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(De,{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 hS({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(vn,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(Pe,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(Nt,{className:"h-4 w-4 text-red-600"}):e.jsx(Xe,{className:"h-4 w-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-medium text-gray-700",children:s==="closed"?"Request Closed":s==="approved"?"Request Approved":s==="rejected"?"Request Rejected":"SLA Not Available"})]});const i=t.percentageUsed!==void 0?t.percentageUsed:0,l=t.status||"on_track",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(vn,{className:`h-4 w-4 ${c.icon}`}):e.jsx(Xe,{className:`h-4 w-4 ${c.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(ie,{className:`text-xs ${c.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(oa,{value:i,className:"h-3 mb-2",indicatorClassName:c.progress,"data-testid":`${r}-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("span",{className:"text-gray-600","data-testid":`${r}-elapsed`,children:[Ot(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${d==="breached"||d==="critical"?c.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[Ot(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",pa(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(ss,{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(xi,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function pS({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var m;const c=rS((t==null?void 0:t.priority)||"standard"),d=nS((t==null?void 0:t.status)||"pending");return e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-300 mb-4 sm:mb-6","data-testid":"request-detail-header",children:[e.jsxs("div",{className:"p-3 sm:p-4 md:p-6 border-b border-gray-300",children:[e.jsxs("div",{className:"flex items-start sm:items-center justify-between gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx(I,{variant:"ghost",size:"icon",onClick:a,className:"rounded-lg flex-shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"back-button",children:e.jsx(Ss,{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(De,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 min-w-0 flex-1",children:[e.jsx("h1",{className:"text-sm sm:text-base md:text-lg font-bold text-gray-900 truncate","data-testid":"request-id",children:t.id||"N/A"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2",children:[e.jsx(ie,{className:`${c.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:c.label}),e.jsx(ie,{className:`${d.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:d.label}),(()=>{const u=(t==null?void 0:t.workflowType)||(t==null?void 0:t.workflow_type),h=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",x=(h==null?void 0:h.toUpperCase())||"",g=u==="CLAIM_MANAGEMENT"||u==="DEALER_CLAIM"||h==="claim-management"||x==="DEALER CLAIM"||x==="DEALER_CLAIM";let f="Non-Templatized",y="bg-purple-100 !text-purple-600 border-purple-200";return g?(f="Dealer Claim",y="bg-blue-100 !text-blue-700 border-blue-200"):x==="TEMPLATE"&&(f="Template"),e.jsx(ie,{className:`${y} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:f})})()]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&i&&((m=t==null?void 0:t.status)==null?void 0:m.toLowerCase())==="closed"&&e.jsxs(I,{variant:"default",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:n,"data-testid":"share-summary-button",children:[e.jsx(Hr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Share Summary"})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:r,disabled:s,"data-testid":"refresh-button",children:[e.jsx(zt,{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(hS,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function Cc(t){return(await je.get(`/summaries/${t}`)).data.data}async function gS(t,s){return(await je.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function fS(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 cg(t){await je.patch(`/summaries/shared/${t}/view`)}async function dg(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 yS(t){return(await je.get(`/summaries/${t}/recipients`)).data.data||[]}function bS({activityInfo:t,className:s,createdAt:a,updatedAt:r}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(J,{className:s,children:e.jsx(q,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Activity information not available"})})});const n=l=>{const o=typeof l=="string"?parseFloat(l):l;return isNaN(o)?"N/A":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`},i=l=>{if(!l)return"N/A";try{return Ye(new Date(l),"MMM d, yyyy")}catch{return l}};return e.jsxs(J,{className:s,children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(lt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(q,{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(Ao,{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(Ea,{className:"w-4 h-4 text-green-600"}),t.estimatedBudget?n(t.estimatedBudget):"TBD"]})]}),t.closedExpenses!==void 0&&t.closedExpenses!==null&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Closed Expenses"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(ls,{className:"w-4 h-4 text-blue-600"}),n(t.closedExpenses)]})]}),t.period&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Period"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1",children:[i(t.period.startDate)," - ",i(t.period.endDate)]})]})]}),t.closedExpensesBreakdown&&t.closedExpensesBreakdown.length>0&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Closed Expenses Breakdown"}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-2",children:[t.closedExpensesBreakdown.map((l,o)=>e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsx("span",{className:"text-gray-700",children:l.description}),e.jsx("span",{className:"font-medium text-gray-900",children:n(l.amount)})]},o)),e.jsxs("div",{className:"pt-2 border-t border-blue-300 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900",children:"Total"}),e.jsx("span",{className:"font-bold text-blue-600",children:n(t.closedExpensesBreakdown.reduce((l,o)=>l+o.amount,0))})]})]})]}),t.description&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Description"}),e.jsx("div",{className:"mt-2 bg-gray-50 p-3 rounded-lg border border-gray-200",children:e.jsx(na,{content:t.description||"",className:"text-sm"})})]}),(a||r)&&e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t border-gray-300",children:[a&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Created"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:is(a)})]}),r&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Last Updated"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:is(r)})]})]})]})]})}function vS({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(J,{className:s,children:e.jsx(q,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(J,{className:s,children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(Mi,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(q,{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(Ia,{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(Di,{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(Ao,{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(J,{className:s,children:e.jsx(q,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function jS({ioDetails:t,dmsDetails:s,claimAmount:a,estimatedBudgetBreakdown:r,closedExpensesBreakdown:n,visibility:i,onEditClaimAmount:l,className:o}){const c=h=>h==null||Number.isNaN(h)?"₹0.00":`₹${h.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,d=h=>{if(!h)return"";try{return Ye(new Date(h),"MMM d, yyyy, h:mm a")}catch{return h||""}},m=h=>!h||h.length===0?0:h.reduce((x,g)=>x+(g.amount??0),0);return i.showIODetails&&t||i.showDMSDetails&&s||i.showClaimAmount&&a&&a.amount!==void 0&&a.amount!==null||r&&r.length>0||n&&n.length>0?e.jsxs(J,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${o}`,children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"text-base flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(Te,{children:"Workflow reference numbers"})]}),e.jsxs(q,{className:"space-y-3",children:[i.showIODetails&&t&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ls,{className:"w-4 h-4 text-blue-600"}),e.jsx(ne,{className:"text-xs font-semibold text-blue-900 uppercase tracking-wide",children:"IO Number"})]}),e.jsx("p",{className:"font-bold text-gray-900 mb-2",children:t.ioNumber}),t.remarks&&e.jsxs("div",{className:"pt-2 border-t border-blue-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Remark:"}),e.jsx("p",{className:"text-xs text-gray-900",children:t.remarks})]}),(t.availableBalance!==void 0||t.blockedAmount!==void 0)&&e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2 space-y-1",children:[t.availableBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Available Balance:"}),e.jsx("span",{className:"font-medium text-gray-900",children:c(t.availableBalance)})]}),t.blockedAmount!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Blocked Amount:"}),e.jsx("span",{className:"font-medium text-blue-700",children:c(t.blockedAmount)})]}),t.remainingBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Remaining Balance:"}),e.jsx("span",{className:"font-medium text-green-700",children:c(t.remainingBalance)})]})]}),e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["By ",t.blockedByName]}),e.jsx("p",{className:"text-xs text-gray-500",children:d(t.blockedAt)})]})]}),i.showDMSDetails&&s&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-purple-600"}),e.jsx(ne,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"DMS Number"})]}),e.jsx("p",{className:"font-bold text-gray-900 mb-2",children:s.dmsNumber}),s.remarks&&e.jsxs("div",{className:"pt-2 border-t border-purple-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Remarks:"}),e.jsx("p",{className:"text-xs text-gray-900",children:s.remarks})]}),e.jsxs("div",{className:"pt-2 border-t border-purple-100 mt-2",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["By ",s.createdByName]}),e.jsx("p",{className:"text-xs text-gray-500",children:d(s.createdAt)})]})]}),i.showClaimAmount&&a&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ea,{className:"w-4 h-4 text-green-600"}),e.jsx(ne,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),i.canEditClaimAmount&&l&&e.jsxs(I,{variant:"outline",size:"sm",onClick:l,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(hi,{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(ls,{className:"w-4 h-4 text-amber-600"}),e.jsx(ne,{className:"text-xs font-semibold text-amber-900 uppercase tracking-wide",children:"Estimated Budget Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[r.map((h,x)=>e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-gray-700",children:h.description}),e.jsx("span",{className:"font-medium text-gray-900",children:c(h.amount)})]},x)),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(ls,{className:"w-4 h-4 text-indigo-600"}),e.jsx(ne,{className:"text-xs font-semibold text-indigo-900 uppercase tracking-wide",children:"Closed Expenses Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[n.map((h,x)=>e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-gray-700",children:h.description}),e.jsx("span",{className:"font-medium text-gray-900",children:c(h.amount)})]},x)),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 NS({proposalDetails:t,className:s}){const r=t.estimatedBudgetTotal!==void 0&&t.estimatedBudgetTotal!==null?t.estimatedBudgetTotal:t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((c,d)=>{const m=d.amount||0;return c+(Number.isNaN(m)?0:m)},0):0,n=o=>o==null||Number.isNaN(o)?"₹0.00":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,i=o=>{if(!o)return"";try{return Ye(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return Ye(new Date(o),"MMM d, yyyy")}catch{return o||"-"}};return e.jsxs(J,{className:s,children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(ls,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs(Te,{children:["Submitted on ",i(t.submittedOn)]})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Cost Breakup"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Item Description"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-200",children:[(t.costBreakup||[]).map((o,c)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900",children:o.description}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right font-medium",children:n(o.amount)})]},c)),e.jsxs("tr",{className:"bg-green-50 font-semibold",children:[e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900",children:"Estimated Budget (Total)"}),e.jsx("td",{className:"px-4 py-3 text-sm text-green-700 text-right",children:n(r)})]})]})]})})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Timeline for Closure"}),e.jsx("div",{className:"mt-2 bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{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 wS({initiatorInfo:t,className:s}){const a=r=>r.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2);return e.jsxs(J,{className:s,children:[e.jsx(me,{children:e.jsx(ue,{className:"text-base",children:"Request Initiator"})}),e.jsx(q,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(es,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(ts,{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(Ia,{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(Di,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function Qi(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 mg(t,s){var a,r;try{if(!Qi(t))return null;const n=t.claimDetails||{},i=t.proposalDetails||{},l=t.completionDetails||{},o=t.internalOrder||t.internal_order||{},c=t.budgetTracking||t.budget_tracking||{},d=t.invoice||{},m=t.creditNote||t.credit_note||{},u=t.completionExpenses||t.completion_expenses||[],h=n.periodStartDate||n.period_start_date,x=n.periodEndDate||n.period_end_date,g=n.activityName||n.activity_name||"",f=n.activityType||n.activity_type||"",y=n.location||"",b=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),A=v!=null?Number(v):void 0,w=Array.isArray(u)&&u.length>0?u.map(R=>({description:R.description||R.itemDescription||"",amount:Number(R.amount)||0})):(l==null?void 0:l.closedExpenses)||(l==null?void 0:l.closed_expenses)||(l==null?void 0:l.closedExpensesBreakdown)||[],T={activityName:g,activityType:f,requestedDate:n.activityDate||n.activity_date||t.createdAt,location:y,period:h&&x?{startDate:h,endDate:x}:void 0,estimatedBudget:b,closedExpenses:A,closedExpensesBreakdown:w,description:t.description||""},C={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)||""};(!C.dealerCode||!C.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!n,dealerCode:C.dealerCode,dealerName:C.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:i.costBreakup||i.cost_breakup||[],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,S={ioNumber:o.ioNumber||o.io_number||n.ioNumber||n.io_number,ioRemark:o.ioRemark||o.io_remark||"",availableBalance:o.ioAvailableBalance||o.io_available_balance||n.ioAvailableBalance||n.io_available_balance,blockedAmount:o.ioBlockedAmount||o.io_blocked_amount||n.ioBlockedAmount||n.io_blocked_amount,remainingBalance:o.ioRemainingBalance||o.io_remaining_balance||n.ioRemainingBalance||n.io_remaining_balance,organizedBy:((a=o.organizer)==null?void 0:a.displayName)||((r=o.organizer)==null?void 0:r.name)||o.organizedBy||"",organizedAt:o.organizedAt||o.organized_at||""},j={eInvoiceNumber:d.invoiceNumber||d.invoice_number||n.eInvoiceNumber||n.e_invoice_number,eInvoiceDate:d.invoiceDate||d.invoice_date||n.eInvoiceDate||n.e_invoice_date,dmsNumber:d.dmsNumber||d.dms_number||n.dmsNumber||n.dms_number,creditNoteNumber:m.creditNoteNumber||m.credit_note_number||n.creditNoteNumber||n.credit_note_number,creditNoteDate:m.creditNoteDate||m.credit_note_date||n.creditNoteDate||n.credit_note_date,creditNoteAmount:m.creditNoteAmount?Number(m.creditNoteAmount):m.credit_note_amount?Number(m.credit_note_amount):m.creditNoteAmount?Number(m.creditNoteAmount):n.creditNoteAmount?Number(n.creditNoteAmount):n.credit_note_amount?Number(n.credit_note_amount):void 0},P={estimated:T.estimatedBudget||0,closed:T.closedExpenses||0};return{activityInfo:T,dealerInfo:C,proposalDetails:D,ioDetails:Object.keys(S).some(R=>S[R])?S:void 0,dmsDetails:Object.keys(j).some(R=>j[R])?j:void 0,claimAmount:P}}catch(n){return console.error("[claimDataMapper] Error mapping claim data:",n),null}}function ug(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 xg(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 CS({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:l,onReject:o,onPause:c,onResume:d,onRetrigger:m,summaryId:u,refreshTrigger:h,pausedByUserId:x,currentUserId:g,apiRequest:f,onEditClaimAmount:y}){var B,k,N,U,$;const{user:b}=Qt(),[v,A]=p.useState([]),[w,T]=p.useState(!1),[C,_]=p.useState(!1),D=(t==null?void 0:t.status)==="closed",S=((B=t==null?void 0:t.pauseInfo)==null?void 0:B.isPaused)||!1,j=x||((N=(k=t==null?void 0:t.pauseInfo)==null?void 0:k.pausedBy)==null?void 0:N.userId),P=g||(b==null?void 0:b.userId)||"",R=!S&&!D&&(r||s),O=S&&d&&(r||s),F=S&&s&&j&&j!==P&&m;p.useEffect(()=>{if(!S||!r||!(t!=null&&t.requestId)){_(!1);return}(async()=>{var se;try{const Z=(((se=(await Wa.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:se.notifications)||[]).some(E=>E.requestId===t.requestId&&E.notificationType==="pause_retrigger_request");_(Z)}catch(G){console.error("Failed to check retrigger notifications:",G),_(!1)}})()},[S,r,t==null?void 0:t.requestId,h]),p.useEffect(()=>{(async()=>{if(!D||!u||!s){A([]);return}try{T(!0);const se=await yS(u);A(se)}catch(se){console.error("Failed to fetch shared recipients:",se),A([])}finally{T(!1)}})()},[D,u,s,h]);const M=p.useMemo(()=>{if(!f||!Qi(f))return null;const L=mg(f);if(!L)return null;const se=ug(f,P),G=xg(se);return{claimRequest:L,visibility:G}},[f,P]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(J,{"data-testid":"quick-actions-card",children:[e.jsx(me,{className:"pb-2",children:e.jsx(ue,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(q,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(I,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:n,"data-testid":"add-approver-button",children:[e.jsx(Ei,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(I,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:i,"data-testid":"add-spectator-button",children:[e.jsx(xt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),R&&c&&e.jsxs(I,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:c,"data-testid":"pause-workflow-button",children:[e.jsx(Ka,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),O&&e.jsxs(I,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-green-700 border-green-300 hover:bg-green-50 hover:text-green-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:d,"data-testid":"resume-workflow-button",children:[e.jsx(ui,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),F&&e.jsxs(I,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:m,"data-testid":"request-resume-button",children:[e.jsx(Ve,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Request Resume"]}),e.jsxs("div",{className:"pt-3 sm:pt-4 space-y-2",children:[r&&!S&&e.jsxs(e.Fragment,{children:[e.jsxs(I,{className:"w-full bg-green-600 hover:bg-green-700 text-white h-9 sm:h-10 text-xs sm:text-sm",onClick:l,"data-testid":"approve-request-button",children:[e.jsx(Pe,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(I,{variant:"destructive",className:"w-full h-9 sm:h-10 text-xs sm:text-sm",onClick:o,"data-testid":"reject-request-button",children:[e.jsx(Nt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),S&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:j===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:[C&&e.jsx(Ve,{className:"w-3.5 h-3.5"}),C?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:C?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&j!==P&&C?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(Ve,{className:"w-3.5 h-3.5"}),"Initiator has requested resume"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Please review and resume if appropriate"})]}):r&&j!==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&&j&&j!==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(J,{"data-testid":"spectators-card",children:[e.jsx(me,{className:"pb-2",children:e.jsx(ue,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(q,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((L,se)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${se}`,children:[e.jsx(es,{className:"h-8 w-8",children:e.jsx(ts,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:L.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:L.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:L.role})]})]},se)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),D&&s&&e.jsxs(J,{"data-testid":"shared-recipients-card",children:[e.jsx(me,{className:"pb-2",children:e.jsxs(ue,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Hr,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(q,{className:"space-y-3",children:w?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):v.length>0?v.map((L,se)=>{const G=(L.displayName||"NA").split(" ").map(oe=>oe[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${se}`,children:[e.jsx(es,{className:"h-8 w-8",children:e.jsx(ts,{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:L.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:L.email}),L.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},L.userId||se)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),M&&e.jsx(jS,{ioDetails:M.claimRequest.ioDetails,dmsDetails:M.claimRequest.dmsDetails,claimAmount:{amount:M.claimRequest.claimAmount.closed||M.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(U=M.claimRequest.proposalDetails)==null?void 0:U.costBreakup,closedExpensesBreakdown:($=M.claimRequest.activityInfo)==null?void 0:$.closedExpensesBreakdown,visibility:M.visibility,onEditClaimAmount:y})]})}function AS({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),u=(o==null?void 0:o.length)||0,h=p.useMemo(()=>o.slice(0,500),[o]),x=async()=>{try{m(!0),await a(h),s()}finally{m(!1)}};return e.jsx(ht,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(ct,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(pt,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex items-center justify-center",children:e.jsx(Pe,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(dt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide your approval comments and remarks"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:l||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(ie,{className:"bg-green-100 text-green-800 border-green-200",variant:"outline",children:"APPROVE"})]})]}),e.jsxs("div",{className:"space-y-2 mt-4",children:[e.jsx("label",{className:"text-sm font-semibold text-gray-800",children:"Comments & Remarks *"}),e.jsx(Ts,{value:h,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(u,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-green-50 border-green-200 text-green-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Pe,{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(kt,{className:"mt-4",children:[e.jsx(I,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(I,{onClick:x,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function SS({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),u=(o==null?void 0:o.length)||0,h=p.useMemo(()=>o.slice(0,500),[o]),x=async()=>{if(!h.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(h),s()}finally{m(!1)}};return e.jsx(ht,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(ct,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(pt,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx(Nt,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(dt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide detailed reasons for rejection"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:l||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(ie,{className:"bg-red-100 text-red-800 border-red-200",variant:"outline",children:"REJECT"})]})]}),e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("label",{className:"text-sm font-semibold text-gray-800",children:"Comments & Remarks *"}),e.jsx(Ts,{value:h,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(u,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-red-50 border-red-200 text-red-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Ve,{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(kt,{className:"mt-4",children:[e.jsx(I,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(I,{variant:"destructive",onClick:x,disabled:d,children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function TS({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,c]=p.useState(""),[d,m]=p.useState(!1),u=async()=>{if(o.trim())try{m(!0),await a(o.trim()),c(""),s()}catch(x){console.error("Failed to skip approver:",x)}finally{m(!1)}},h=()=>{d||(c(""),s())};return e.jsx(ht,{open:t,onOpenChange:h,children:e.jsxs(ct,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:h,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:d,children:[e.jsx(gt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center",children:e.jsx(Ve,{className:"w-5 h-5 text-orange-600"})}),e.jsx(dt,{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(Ve,{className:"w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-orange-900 mb-1",children:"Important Notice"}),e.jsx("p",{className:"text-sm text-orange-800",children:"You are about to skip the current approver. The request will be moved to the next approval level."})]})]})}),(i||l)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-semibold text-gray-700",children:"Request Details"}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3 space-y-1",children:[i&&e.jsxs("p",{className:"text-sm text-gray-900",children:[e.jsx("span",{className:"font-medium",children:"Request ID:"})," ",i]}),l&&e.jsxs("p",{className:"text-sm text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Title:"})," ",l]})]})]}),(r||n)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-semibold text-gray-700",children:"Approver Being Skipped"}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-1",children:[n&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Level:"})," ",n]}),r&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Approver:"})," ",r]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(Ts,{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:x=>c(x.target.value),className:"min-h-[100px] border-2 border-gray-300 focus:border-orange-500",disabled:d,autoFocus:!0}),e.jsx("p",{className:"text-xs text-gray-500",children:"This reason will be recorded in the activity log and all participants will be notified."})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(I,{type:"button",variant:"outline",onClick:h,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(I,{type:"button",onClick:u,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:d||!o.trim(),children:[e.jsx(Ve,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function kS({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:l,documentError:o,request:c,skipApproverData:d,actionStatus:m,existingParticipants:u,currentLevels:h,maxApprovalLevels:x,onPolicyViolation:g,setShowApproveModal:f,setShowRejectModal:y,setShowAddApproverModal:b,setShowAddSpectatorModal:v,setShowSkipApproverModal:A,setShowActionStatusModal:w,setPreviewDocument:T,setDocumentError:C,setSkipApproverData:_,setActionStatus:D,handleApproveConfirm:S,handleRejectConfirm:j,handleAddApprover:P,handleAddSpectator:R,handleSkipApprover:O,downloadDocument:F,documentPolicy:M}){return e.jsxs(e.Fragment,{children:[e.jsx(AS,{open:t,onClose:()=>f(!1),onConfirm:S,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(SS,{open:s,onClose:()=>y(!1),onConfirm:j,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(lg,{open:a,onClose:()=>b(!1),onConfirm:P,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u,currentLevels:h,maxApprovalLevels:x,onPolicyViolation:g}),e.jsx(ig,{open:r,onClose:()=>v(!1),onConfirm:R,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u}),e.jsx(TS,{open:n,onClose:()=>{A(!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(Cr,{fileName:l.fileName,fileType:l.fileType,fileUrl:Zr(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:F,open:!!l,onClose:()=>T(null)}),m&&e.jsx(ng,{open:i,onClose:()=>{w(!1),D(null)},success:m.success,title:m.title,message:m.message}),e.jsx(ht,{open:o.show,onOpenChange:B=>C(k=>({...k,show:B})),children:e.jsxs(ct,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(dt,{className:"flex items-center gap-2",children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Et,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:o.errors.map((B,k)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:B.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:B.reason})]},k))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",M.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",M.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(kt,{children:e.jsx(I,{onClick:()=>C({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const hg={DocumentsTab:aS,ActivityTab:lS,WorkNotesTab:uS,SummaryTab:xS,RequestDetailHeader:pS,QuickActionsSidebar:CS,RequestDetailModals:kS};function Ac({className:t,...s}){return e.jsx(Of,{"data-slot":"checkbox",className:Re("peer border bg-input-background dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx($f,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Nr,{className:"size-3.5"})})})}function pg({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),[u,h]=p.useState(!1),[x,g]=p.useState(!1);p.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),h(!1);return}const v=setTimeout(async()=>{var A;try{h(!0);const w=i.slice(1),T=await ca(w,10),C=((A=T==null?void 0:T.data)==null?void 0:A.data)||(T==null?void 0:T.data)||[];c(Array.isArray(C)?C:[])}catch(w){console.error("Failed to search users:",w),K.error("Failed to search users")}finally{h(!1)}},300);return()=>clearTimeout(v)},[i,t]);const f=v=>{m(A=>{const w=new Set(A);return w.has(v)?w.delete(v):w.add(v),w})},y=async()=>{var v,A;if(d.size===0){K.error("Please select at least one user to share with");return}try{g(!0),await gS(a,Array.from(d)),K.success(`Summary shared with ${d.size} user(s)`),m(new Set),l(""),c([]),n==null||n(),s()}catch(w){console.error("Failed to share summary:",w),K.error(((A=(v=w==null?void 0:w.response)==null?void 0:v.data)==null?void 0:A.message)||"Failed to share summary")}finally{g(!1)}},b=()=>{m(new Set),l(""),c([]),s()};return e.jsx(ht,{open:t,onOpenChange:b,children:e.jsxs(ct,{className:"sm:max-w-[500px]",children:[e.jsx(pt,{children:e.jsx(dt,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Request"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:r})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ie,{id:"user-search",placeholder:"Type @ to search users...",value:i,onChange:v=>l(v.target.value),className:"pl-10"})]}),i&&!i.startsWith("@")&&e.jsx("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:"Start with @ to search users (e.g., @john)"})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ze,{className:"h-5 w-5 animate-spin text-blue-600"})}),!u&&o.length>0&&e.jsx("div",{className:"border rounded-lg max-h-[300px] overflow-y-auto",children:o.map(v=>{const A=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:()=>f(v.userId),children:[e.jsx("div",{onClick:w=>w.stopPropagation(),onMouseDown:w=>w.stopPropagation(),className:"flex items-center",children:e.jsx(Ac,{checked:A,onCheckedChange:()=>f(v.userId)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lt,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:v.displayName||v.email})]}),(v.designation||v.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:v.designation||v.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:v.email})]})]},v.userId)})}),!u&&i&&i.startsWith("@")&&o.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),!u&&i&&!i.startsWith("@")&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"Start typing with @ to search users"}),d.size>0&&e.jsxs("div",{className:"border rounded-lg p-3 bg-blue-50",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-700 mb-2",children:["Selected (",d.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(d).map(v=>{const A=o.find(w=>w.userId===v);return e.jsxs("div",{className:"flex items-center gap-1 bg-white px-2 py-1 rounded-full text-xs",children:[e.jsx("span",{children:(A==null?void 0:A.displayName)||(A==null?void 0:A.email)||v}),e.jsx("button",{onClick:()=>f(v),className:"ml-1 hover:text-red-600",children:e.jsx(gt,{className:"h-3 w-3"})})]},v)})})]})]}),e.jsxs(kt,{children:[e.jsx(I,{variant:"outline",onClick:b,disabled:x,children:"Cancel"}),e.jsx(I,{onClick:y,disabled:x||d.size===0,children:x?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function gg({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=p.useState(""),[o,c]=p.useState(""),[d,m]=p.useState(!1),u=()=>Gt().add(1,"month").format("YYYY-MM-DD"),h=()=>Gt().add(1,"month").format("YYYY-MM-DD"),x=()=>Gt().add(1,"day").format("YYYY-MM-DD");p.useEffect(()=>{t&&!o&&c(u())},[t]);const g=async()=>{var A,w,T,C;if(!i.trim()){K.error("Please provide a reason for pausing");return}if(!o){K.error("Please select a resume date");return}const y=Gt(o),b=Gt().add(1,"month"),v=Gt().add(1,"day");if(y.isAfter(b)){K.error("Resume date cannot be more than 1 month from now");return}if(y.isBefore(v,"day")){K.error("Resume date must be at least 1 day from now");return}try{m(!0),await dN(a,r,i.trim(),y.toDate()),K.success("Workflow paused successfully"),n&&await n(),l(""),c(u()),s()}catch(_){console.error("Failed to pause workflow:",_),K.error(((w=(A=_==null?void 0:_.response)==null?void 0:A.data)==null?void 0:w.error)||((C=(T=_==null?void 0:_.response)==null?void 0:T.data)==null?void 0:C.message)||"Failed to pause workflow")}finally{m(!1)}},f=()=>{d||(l(""),c(u()),s())};return e.jsx(ht,{open:t,onOpenChange:f,children:e.jsxs(ct,{className:"sm:max-w-[500px]",children:[e.jsx(pt,{children:e.jsxs(dt,{className:"flex items-center gap-2",children:[e.jsx(Ka,{className:"w-5 h-5 text-orange-600"}),"Pause Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-orange-800",children:[e.jsx("strong",{children:"Note:"})," Pausing will temporarily halt TAT calculations and notifications. The workflow will automatically resume on the selected date."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ts,{id:"pause-reason",value:i,onChange:y=>l(y.target.value),placeholder:"Enter the reason for pausing this workflow...",className:"min-h-[100px] text-sm",disabled:d}),e.jsxs("p",{className:"text-xs text-gray-500",children:[i.length," / 1000 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ie,{id:"resume-date",type:"date",value:o,onChange:y=>c(y.target.value),min:x(),max:h(),className:"text-sm",disabled:d}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum 1 month from today. The workflow will automatically resume on this date."})]})]}),e.jsxs(kt,{children:[e.jsx(I,{variant:"outline",onClick:f,disabled:d,children:"Cancel"}),e.jsx(I,{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(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ka,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function fg({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=p.useState(""),[l,o]=p.useState(!1),c=async()=>{var m,u,h,x;try{o(!0),await mN(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(((u=(m=g==null?void 0:g.response)==null?void 0:m.data)==null?void 0:u.error)||((x=(h=g==null?void 0:g.response)==null?void 0:h.data)==null?void 0:x.message)||"Failed to resume workflow")}finally{o(!1)}},d=()=>{l||(i(""),s())};return e.jsx(ht,{open:t,onOpenChange:d,children:e.jsxs(ct,{className:"sm:max-w-[500px]",children:[e.jsx(pt,{children:e.jsxs(dt,{className:"flex items-center gap-2",children:[e.jsx(ui,{className:"w-5 h-5 text-green-600"}),"Resume Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-green-50 border border-green-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-green-800",children:[e.jsx("strong",{children:"Note:"})," Resuming will restart TAT calculations and notifications. The workflow will continue from where it was paused."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(Ts,{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(kt,{children:[e.jsx(I,{variant:"outline",onClick:d,disabled:l,children:"Cancel"}),e.jsx(I,{onClick:c,disabled:l,className:"bg-green-600 hover:bg-green-700 text-white",children:l?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ui,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function yg({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=p.useState(!1),o=async()=>{var c,d,m,u;try{l(!0),await uN(a),K.success("Retrigger request sent to approver"),n&&await n(),s()}catch(h){console.error("Failed to retrigger pause:",h),K.error(((d=(c=h==null?void 0:h.response)==null?void 0:c.data)==null?void 0:d.error)||((u=(m=h==null?void 0:h.response)==null?void 0:m.data)==null?void 0:u.message)||"Failed to send retrigger request")}finally{l(!1)}};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"sm:max-w-[450px]",children:[e.jsx(pt,{children:e.jsxs(dt,{className:"flex items-center gap-2",children:[e.jsx(Ve,{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(kt,{children:[e.jsx(I,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(I,{onClick:o,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:RS,ActivityTab:DS,WorkNotesTab:PS,SummaryTab:IS,RequestDetailHeader:ES,QuickActionsSidebar:FS,RequestDetailModals:MS}=hg;let _S=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(ss,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(I,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(I,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function LS({requestId:t,onBack:s,dynamicRequests:a=[]}){var tr,sr,ar,rr,nr,$a,ba,Ua;const n=La().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=p.useState(l),[d,m]=p.useState(!1),[u,h]=p.useState(null),[x,g]=p.useState(null),[f,y]=p.useState(!1),[b,v]=p.useState(0),[A,w]=p.useState(!1),[T,C]=p.useState(!1),[_,D]=p.useState(!1),[S,j]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[P,R]=p.useState({open:!1,violations:[]}),{user:O}=Qt(),{request:F,apiRequest:M,loading:B,refreshing:k,refreshDetails:N,currentApprovalLevel:U,isSpectator:$,isInitiator:L,existingParticipants:se,accessDenied:G}=wc(n,a,O),{mergedMessages:oe,unreadWorkNotes:Z,workNoteAttachments:E,setWorkNoteAttachments:V}=tg(n,M,o,O),{uploadingDocument:H,triggerFileInput:Q,previewDocument:Y,setPreviewDocument:W,documentPolicy:ce,documentError:xe,setDocumentError:ke}=sg(M,N),{showApproveModal:Ae,setShowApproveModal:ae,showRejectModal:ye,setShowRejectModal:Ne,showAddApproverModal:ve,setShowAddApproverModal:$e,showAddSpectatorModal:re,setShowAddSpectatorModal:Me,showSkipApproverModal:ot,setShowSkipApproverModal:pe,showActionStatusModal:Oe,setShowActionStatusModal:ft,skipApproverData:mt,setSkipApproverData:nt,actionStatus:_s,setActionStatus:ea,handleApproveConfirm:Aa,handleRejectConfirm:qa,handleAddApprover:ee,handleSkipApprover:we,handleAddSpectator:te}=rg(n,U,N),{conclusionRemark:_e,setConclusionRemark:Fe,conclusionLoading:ze,conclusionSubmitting:Le,aiGenerated:Je,handleGenerateConclusion:Be,handleFinalizeConclusion:tt,generationAttempts:ws,generationFailed:Yt,maxAttemptsReached:rt}=ag(F,n,L,N,s,ea,ft);p.useEffect(()=>{(async()=>{var hs;try{const zs=await Js("SYSTEM_SETTINGS"),ir=await Js("WORKFLOW_SHARING"),lr=[...zs,...ir],da={};lr.forEach(vt=>{da[vt.configKey]=vt.configValue}),j({maxApprovalLevels:parseInt(da.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(da.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((hs=da.ALLOW_ADD_SPECTATOR)==null?void 0:hs.toLowerCase())==="true",maxSpectators:parseInt(da.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(zs){console.error("Failed to load system policy:",zs)}})()},[]),p.useEffect(()=>{const hs=new URLSearchParams(window.location.search).get("tab");hs&&c(hs)},[n]);const st=()=>{N()},bt=()=>{w(!0)},as=()=>{C(!0)},Ft=async()=>{await N()},fa=()=>{D(!0)},ya=async()=>{await N()},Oa=async()=>{await N()},Sa=async()=>{if(!(M!=null&&M.requestId)){K.error("Request ID not found");return}if(!u){K.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},At=((F==null?void 0:F.status)==="approved"||(F==null?void 0:F.status)==="rejected")&&L,Ta=(F==null?void 0:F.status)==="closed";p.useEffect(()=>{(async()=>{if(!Ta||!(M!=null&&M.requestId)){g(null),h(null);return}try{y(!0);const hs=await dg(M.requestId);if(hs!=null&&hs.summaryId){h(hs.summaryId);try{const zs=await Cc(hs.summaryId);g(zs)}catch(zs){console.error("Failed to fetch summary details:",zs),g(null),h(null)}}else g(null),h(null)}catch{g(null),h(null)}finally{y(!1)}})()},[Ta,M==null?void 0:M.requestId]);const er=((F==null?void 0:F.approvalFlow)||[]).filter(Mt=>Mt&&typeof Mt.step=="number").map(Mt=>({levelNumber:Mt.step||0,approverName:Mt.approver||"Unknown",status:Mt.status||"pending",tatHours:Mt.tatHours||24}));return B&&!F&&!M?e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(zt,{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(yx,{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(I,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ss,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(I,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):F?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"custom-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(ES,{request:F,refreshing:k,onBack:s||(()=>window.history.back()),onRefresh:st,onShareSummary:Sa,isInitiator:L,slaData:((tr=F==null?void 0:F.summary)==null?void 0:tr.sla)||(F==null?void 0:F.sla)||null,isPaused:((sr=F==null?void 0:F.pauseInfo)==null?void 0:sr.isPaused)||!1}),e.jsxs(Un,{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(Bn,{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(Dt,{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(bx,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Ta&&x&&e.jsxs(Dt,{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(So,{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(Dt,{value:"workflow",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-workflow",children:[e.jsx(Ys,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),e.jsxs(Dt,{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(De,{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(Dt,{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(Pt,{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(Dt,{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(Is,{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(ie,{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-red-500 text-white text-[10px] flex items-center justify-center p-0","data-testid":"worknotes-unread-badge",children: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(Tt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(NN,{request:F,isInitiator:L,needsClosure:At,conclusionRemark:_e,setConclusionRemark:Fe,conclusionLoading:ze,conclusionSubmitting:Le,aiGenerated:Je,handleGenerateConclusion:Be,handleFinalizeConclusion:tt,onPause:bt,onResume:as,onRetrigger:fa,currentUserIsApprover:!!U,pausedByUserId:(rr=(ar=F==null?void 0:F.pauseInfo)==null?void 0:ar.pausedBy)==null?void 0:rr.userId,currentUserId:O==null?void 0:O.userId,generationAttempts:ws,generationFailed:Yt,maxAttemptsReached:rt})}),Ta&&e.jsx(Tt,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(IS,{summary:x,loading:f,onShare:Sa,isInitiator:L})}),e.jsx(Tt,{value:"workflow",className:"mt-0",children:e.jsx(SN,{request:F,user:O,isInitiator:L,onSkipApprover:Mt=>{if(!Mt.levelId){alert("Level ID not available");return}nt(Mt),pe(!0)},onRefresh:N})}),e.jsx(Tt,{value:"documents",className:"mt-0",children:e.jsx(RS,{request:F,workNoteAttachments:E,uploadingDocument:H,documentPolicy:ce,triggerFileInput:Q,setPreviewDocument:W,downloadDocument:js})}),e.jsx(Tt,{value:"activity",className:"mt-0",children:e.jsx(DS,{request:F})}),e.jsx(Tt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(PS,{requestId:n,requestTitle:F.title,mergedMessages:oe,setWorkNoteAttachments:V,isInitiator:L,isSpectator:$,currentLevels:er,onAddApprover:ee,maxApprovalLevels:S.maxApprovalLevels,onPolicyViolation:Mt=>R({open:!0,violations:Mt})})})]}),o!=="worknotes"&&e.jsx(FS,{request:F,isInitiator:L,isSpectator:$,currentApprovalLevel:U,onAddApprover:()=>$e(!0),onAddSpectator:()=>Me(!0),onApprove:()=>ae(!0),onReject:()=>Ne(!0),onPause:bt,onResume:as,onRetrigger:fa,summaryId:u,refreshTrigger:b,pausedByUserId:($a=(nr=F==null?void 0:F.pauseInfo)==null?void 0:nr.pausedBy)==null?void 0:$a.userId,currentUserId:O==null?void 0:O.userId,apiRequest:M})]})]})]})}),d&&u&&e.jsx(pg,{isOpen:d,onClose:()=>m(!1),summaryId:u,requestTitle:(F==null?void 0:F.title)||"N/A",onSuccess:()=>{N(),v(Mt=>Mt+1)}}),A&&(M==null?void 0:M.requestId)&&e.jsx(gg,{isOpen:A,onClose:()=>w(!1),requestId:M.requestId,levelId:(U==null?void 0:U.levelId)||null,onSuccess:ya}),T&&(M==null?void 0:M.requestId)&&e.jsx(fg,{isOpen:T,onClose:()=>C(!1),requestId:M.requestId,onSuccess:Ft}),_&&(M==null?void 0:M.requestId)&&e.jsx(yg,{isOpen:_,onClose:()=>D(!1),requestId:M.requestId,approverName:(Ua=(ba=F==null?void 0:F.pauseInfo)==null?void 0:ba.pausedBy)==null?void 0:Ua.name,onSuccess:Oa}),e.jsx(MS,{showApproveModal:Ae,showRejectModal:ye,showAddApproverModal:ve,showAddSpectatorModal:re,showSkipApproverModal:ot,showActionStatusModal:Oe,previewDocument:Y,documentError:xe,request:F,skipApproverData:mt,actionStatus:_s,existingParticipants:se,currentLevels:er,maxApprovalLevels:S.maxApprovalLevels,onPolicyViolation:Mt=>R({open:!0,violations:Mt}),setShowApproveModal:ae,setShowRejectModal:Ne,setShowAddApproverModal:$e,setShowAddSpectatorModal:Me,setShowSkipApproverModal:pe,setShowActionStatusModal:ft,setPreviewDocument:W,setDocumentError:ke,setSkipApproverData:nt,setActionStatus:ea,handleApproveConfirm:Aa,handleRejectConfirm:qa,handleAddApprover:ee,handleAddSpectator:te,handleSkipApprover:we,downloadDocument:js,documentPolicy:ce}),e.jsx($n,{open:P.open,onClose:()=>R({open:!1,violations:[]}),violations:P.violations,policyDetails:{maxApprovalLevels:S.maxApprovalLevels,maxParticipants:S.maxParticipants,allowSpectators:S.allowSpectators,maxSpectators:S.maxSpectators}})]}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"not-found-state",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(De,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Custom Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The custom request you're looking for doesn't exist or may have been deleted."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(I,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ss,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(I,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function OS(t){return e.jsx(_S,{children:e.jsx(LS,{...t})})}function $S({searchTerm:t,statusFilter:s,priorityFilter:a,sortBy:r,sortOrder:n,onSearchChange:i,onStatusFilterChange:l,onPriorityFilterChange:o,onSortByChange:c,onSortOrderChange:d,onClearFilters:m,activeFiltersCount:u}){return e.jsxs(J,{className:"shadow-lg border-0",children:[e.jsx(me,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Te,{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(I,{variant:"ghost",size:"sm",onClick:m,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(gt,{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(q,{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(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(Ie,{placeholder:"Search requests, IDs...",value:t,onChange:h=>i(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"})]}),e.jsxs(He,{value:a,onValueChange:o,children:[e.jsx(Ge,{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(We,{placeholder:"All Priorities"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Priorities"}),e.jsx(X,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ga,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(X,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:s,onValueChange:l,children:[e.jsx(Ge,{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(We,{placeholder:"All Statuses"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Statuses"}),e.jsx(X,{value:"pending",children:"Pending (In Approval)"}),e.jsx(X,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:r,onValueChange:h=>c(h),children:[e.jsx(Ge,{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(We,{placeholder:"Sort by"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"due",children:"Due Date"}),e.jsx(X,{value:"created",children:"Date Created"}),e.jsx(X,{value:"priority",children:"Priority"}),e.jsx(X,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>d(n==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:n==="asc"?e.jsx(_i,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Li,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function US({searchTerm:t,priorityFilter:s,statusFilter:a,sortBy:r,sortOrder:n,activeFiltersCount:i,onSearchChange:l,onPriorityChange:o,onStatusChange:c,onSortByChange:d,onSortOrderChange:m,onClearFilters:u}){return e.jsxs(J,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(me,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:i>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[i," filter",i>1?"s":""," active"]})})]})]}),i>0&&e.jsxs(I,{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(gt,{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(q,{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(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(Ie,{placeholder:"Search requests, IDs...",value:t,onChange:h=>l(h.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white transition-colors","data-testid":"closed-requests-search"})]}),e.jsxs(He,{value:s,onValueChange:o,children:[e.jsx(Ge,{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(We,{placeholder:"All Priorities"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Priorities"}),e.jsx(X,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ga,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(X,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:a,onValueChange:c,children:[e.jsx(Ge,{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(We,{placeholder:"Closure Type"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Closures"}),e.jsx(X,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(X,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nt,{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(He,{value:r,onValueChange:h=>d(h),children:[e.jsx(Ge,{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(We,{placeholder:"Sort by"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"due",children:"Due Date"}),e.jsx(X,{value:"created",children:"Date Created"}),e.jsx(X,{value:"priority",children:"Priority"})]})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:m,className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11","data-testid":"closed-requests-sort-order",children:n==="asc"?e.jsx(_i,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Li,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function BS({searchTerm:t,statusFilter:s,priorityFilter:a,departmentFilter:r,slaComplianceFilter:n,initiatorFilter:i,approverFilter:l,approverFilterType:o,dateRange:c,customStartDate:d,customEndDate:m,showCustomDatePicker:u,departments:h,loadingDepartments:x,initiatorSearch:g,approverSearch:f,onSearchChange:y,onStatusChange:b,onPriorityChange:v,onDepartmentChange:A,onSlaComplianceChange:w,onInitiatorChange:T,onApproverChange:C,onApproverTypeChange:_,onDateRangeChange:D,onCustomStartDateChange:S,onCustomEndDateChange:j,onShowCustomDatePickerChange:P,onApplyCustomDate:R,onClearFilters:O,hasActiveFilters:F}){return e.jsx(J,{className:"border-gray-200 shadow-md","data-testid":"user-all-requests-filters",children:e.jsx(q,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),F&&e.jsx(ie,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),F&&e.jsxs(I,{variant:"ghost",size:"sm",onClick:O,className:"gap-2",children:[e.jsx(zt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx($t,{}),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(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ie,{placeholder:"Search requests...",value:t,onChange:M=>y(M.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:b,children:[e.jsx(Ge,{className:"h-10","data-testid":"status-filter",children:e.jsx(We,{placeholder:"All Status"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Status"}),e.jsx(X,{value:"pending",children:"Pending"}),e.jsx(X,{value:"paused",children:"Paused"}),e.jsx(X,{value:"approved",children:"Approved"}),e.jsx(X,{value:"rejected",children:"Rejected"}),e.jsx(X,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:v,children:[e.jsx(Ge,{className:"h-10","data-testid":"priority-filter",children:e.jsx(We,{placeholder:"All Priority"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Priority"}),e.jsx(X,{value:"express",children:"Express"}),e.jsx(X,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:A,disabled:x||h.length===0,children:[e.jsx(Ge,{className:"h-10","data-testid":"department-filter",children:e.jsx(We,{placeholder:x?"Loading...":"All Departments"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Departments"}),h.map(M=>e.jsx(X,{value:M,children:M},M))]})]}),e.jsxs(He,{value:n,onValueChange:w,children:[e.jsx(Ge,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(We,{placeholder:"All SLA Status"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All SLA Status"}),e.jsx(X,{value:"compliant",children:"Compliant"}),e.jsx(X,{value:"on-track",children:"On Track"}),e.jsx(X,{value:"approaching",children:"Approaching"}),e.jsx(X,{value:"critical",children:"Critical"}),e.jsx(X,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:g.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:g.selectedUser.displayName||g.selectedUser.email}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:g.handleClear,children:e.jsx(gt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{placeholder:"Search initiator...",value:g.searchQuery,onChange:M=>g.handleSearch(M.target.value),onFocus:()=>{g.searchResults.length>0&&g.setShowResults(!0)},onBlur:()=>setTimeout(()=>g.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),g.showResults&&g.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:g.searchResults.map(M=>e.jsx("button",{type:"button",onClick:()=>g.handleSelect(M),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:M.displayName||M.email}),M.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:M.email})]})},M.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Approver"}),l!=="all"&&_&&e.jsxs(He,{value:o,onValueChange:M=>_(M),children:[e.jsx(Ge,{className:"h-7 w-32 text-xs",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"current",children:"Current Only"}),e.jsx(X,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:f.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:f.selectedUser.displayName||f.selectedUser.email}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:f.handleClear,children:e.jsx(gt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{placeholder:"Search approver...",value:f.searchQuery,onChange:M=>f.handleSearch(M.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(M=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(M),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:M.displayName||M.email}),M.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:M.email})]})},M.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(lt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:c,onValueChange:M=>D(M),children:[e.jsx(Ge,{className:"w-[160px] h-10",children:e.jsx(We,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),c==="custom"&&e.jsxs(Zs,{open:u,onOpenChange:P,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),d&&m?`${Ye(d,"MMM d, yyyy")} - ${Ye(m,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Qs,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Bs,{value:d||null,onChange:M=>{const B=M?new Date(M):void 0;B?(S==null||S(B),m&&B>m&&(j==null||j(B))):S==null||S(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",children:"End Date"}),e.jsx(Bs,{value:m||null,onChange:M=>{const B=M?new Date(M):void 0;B?(j==null||j(B),d&&B<d&&(S==null||S(B))):j==null||j(void 0)},minDate:d||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(I,{size:"sm",onClick:R,disabled:!d||!m,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply Range"}),e.jsx(I,{size:"sm",variant:"outline",onClick:()=>{P==null||P(!1),S==null||S(void 0),j==null||j(void 0),D("month")},children:"Cancel"})]})]})})]})]})]})})})}function VS({request:t,apiRequest:s,currentUserId:a,isInitiator:r,onEditClaimAmount:n,className:i="",needsClosure:l=!1,conclusionRemark:o="",setConclusionRemark:c,conclusionLoading:d=!1,conclusionSubmitting:m=!1,aiGenerated:u=!1,handleGenerateConclusion:h,handleFinalizeConclusion:x,generationAttempts:g=0,generationFailed:f=!1,maxAttemptsReached:y=!1}){var T,C,_,D,S,j,P,R,O;if(!Qi(s))return e.jsx("div",{className:"text-center py-8 text-gray-500",children:e.jsx("p",{children:"This is not a claim management request."})});const b=mg(s);if(!b)return console.warn("[ClaimManagementOverviewTab] Failed to map claim data:",{apiRequest:s,hasClaimDetails:!!(s!=null&&s.claimDetails),hasProposalDetails:!!(s!=null&&s.proposalDetails),hasCompletionDetails:!!(s!=null&&s.completionDetails)}),e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx("p",{children:"Unable to load claim management data."}),e.jsx("p",{className:"text-xs mt-2",children:"Please ensure the request has been properly initialized."})]});const v=ug(s,a),A=xg(v),w={name:((T=s.initiator)==null?void 0:T.name)||((C=s.initiator)==null?void 0:C.displayName)||((_=s.initiator)==null?void 0:_.email)||"Unknown",role:((D=s.initiator)==null?void 0:D.role)||((S=s.initiator)==null?void 0:S.designation)||"Initiator",department:((j=s.initiator)==null?void 0:j.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(bS,{activityInfo:b.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(vS,{dealerInfo:b.dealerInfo}),A.showProposalDetails&&b.proposalDetails&&e.jsx(NS,{proposalDetails:b.proposalDetails}),e.jsx(wS,{initiatorInfo:w}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(J,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(Pe,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(Te,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(q,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(na,{content:s.conclusionRemark||"",className:"text-sm"})}),s.closureDate&&e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-gray-500 border-t border-gray-200 pt-3",children:[e.jsxs("span",{children:["Request closed on ",is(s.closureDate)]}),e.jsxs("span",{children:["By ",w.name]})]})]})]}),l&&e.jsxs(J,{"data-testid":"conclusion-remark-card",children:[e.jsx(me,{className:`bg-gradient-to-r border-b ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(ue,{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(Pe,{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(Te,{className:"mt-1 text-xs sm:text-sm",children:((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"This request was rejected. Please review the AI-generated closure remark and finalize it to close this request.":"All approvals are complete. Please review and finalize the conclusion to close this request."})]}),h&&e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(I,{variant:"outline",size:"sm",onClick:h,disabled:d||y,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(zt,{className:`w-3.5 h-3.5 ${d?"animate-spin":""}`}),u?"Regenerate":"Generate with AI"]}),u&&!y&&!f&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-g," attempts remaining"]})]})]})}),e.jsx(q,{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(Ze,{className:"w-8 h-8 text-blue-600 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Preparing conclusion remark..."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Conclusion Remark"}),u&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),c&&e.jsx(Fn,{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"})]})]}),x&&e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(I,{onClick:x,disabled:m||!o.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function zS({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(""),[u,h]=p.useState(!1),[x,g]=p.useState(null),f=async()=>{if(!d.trim()){K.error("Please provide approval comments");return}try{h(!0),g("approve"),await a(d),b(),s()}catch(A){console.error("Failed to approve request:",A),K.error("Failed to approve request. Please try again.")}finally{h(!1),g(null)}},y=async()=>{if(!d.trim()){K.error("Please provide rejection reason");return}try{h(!0),g("reject"),await r(d),b(),s()}catch(A){console.error("Failed to reject request:",A),K.error("Failed to reject request. Please try again.")}finally{h(!1),g(null)}},b=()=>{m(""),g(null)},v=()=>{u||(b(),s())};return t?e.jsx(ht,{open:t,onOpenChange:v,children:e.jsxs(ct,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(pt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(dt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(Pe,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(Et,{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(De,{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(Is,{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(na,{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(Ts,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:d,onChange:A=>m(A.target.value),className:"min-h-[80px] lg:min-h-[90px] text-xs lg:text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[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(Nt,{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(kt,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end px-6 pb-6 pt-3 lg:pt-4 flex-shrink-0 border-t bg-gray-50",children:[e.jsx(I,{variant:"outline",onClick:v,disabled:u,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(I,{onClick:y,disabled:!d.trim()||u,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:u&&x==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"Reject"]})}),e.jsx(I,{onClick:f,disabled:!d.trim()||u,className:"bg-green-600 hover:bg-green-700 text-white",children:u&&x==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function HS({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:c,dueDate:d}){const[m,u]=p.useState(!1),[h,x]=p.useState(!1),g=(n==null?void 0:n.creditNoteNumber)&&(n==null?void 0:n.creditNoteNumber)!=="",f=(n==null?void 0:n.creditNoteNumber)||"",y=n!=null&&n.creditNoteDate?is(n.creditNoteDate,{includeTime:!1,format:"short"}):"",b=(n==null?void 0:n.creditNoteAmount)||0,v=(n==null?void 0:n.status)||"PENDING",A=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",w=(i==null?void 0:i.dealerCode)||"RE-JP-009",T=l||"Activity",C=o||"RE-REQ-2024-CM-101",_=d?is(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",D=async()=>{if(a)try{u(!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{u(!1)}else K.info("Credit note will be automatically saved to Documents tab")},S=async()=>{if(r)try{x(!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{x(!1)}else K.info("Email notification will be sent to dealer with credit note attachment")},j=P=>`₹${P.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(pt,{children:[e.jsxs(dt,{className:"font-semibold flex items-center gap-2 text-2xl",children:[e.jsx(ls,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note from SAP"]}),e.jsx(Et,{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(ie,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(Pe,{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(ne,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(R0,{className:"w-3 h-3"}),"Credit Note Number"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1 text-lg",children:f})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(ne,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(lt,{className:"w-3 h-3"}),"Issue Date"]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:y})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-5",children:[e.jsxs(ne,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-3",children:[e.jsx(Ea,{className:"w-4 h-4"}),"Credit Note Amount"]}),e.jsx("p",{className:"text-4xl font-bold text-blue-700",children:j(b)})]})]}):e.jsx("div",{className:"bg-gray-50 border-2 border-gray-300 rounded-lg p-8 text-center",children:e.jsxs("div",{className:"flex flex-col items-center justify-center space-y-4",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center",children:e.jsx(ls,{className:"w-8 h-8 text-gray-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-700 mb-2",children:"No Credit Note Available"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Credit note has not been generated yet. Please wait for the credit note to be generated from DMS."})]})]})}),e.jsxs("div",{className:"bg-purple-50 border-2 border-purple-200 rounded-lg p-5",children:[e.jsxs("h3",{className:"font-semibold text-purple-900 mb-4 flex items-center gap-2",children:[e.jsx(Mi,{className:"w-5 h-5"}),"Dealer Information"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ne,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:A})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ne,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:w})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ne,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Activity"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:T})]})]})]}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:[e.jsxs("h3",{className:"font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4"}),"Reference Details"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Request ID"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:C})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Due Date"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:_})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(De,{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(kt,{className:"flex-col-reverse gap-2 sm:flex-row flex items-center justify-between sm:justify-between",children:[e.jsx(I,{variant:"outline",onClick:s,disabled:m||h,className:"border-2",children:"Close"}),e.jsx("div",{className:"flex gap-2",children:g&&e.jsxs(e.Fragment,{children:[e.jsxs(I,{variant:"outline",onClick:D,disabled:m||h,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),m?"Downloading...":"Download"]}),e.jsxs(I,{onClick:S,disabled:m||h,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(fx,{className:"w-4 h-4 mr-2"}),h?"Sending...":"Send to Dealer"]})]})})]})]})})}function WS({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",activityName:n="Activity",requestId:i,documentPolicy:l}){var ke,Ae;const[o,c]=p.useState(""),[d,m]=p.useState(""),[u,h]=p.useState([]),[x,g]=p.useState([]),[f,y]=p.useState([]),[b,v]=p.useState([]),[A,w]=p.useState(null),[T,C]=p.useState(""),[_,D]=p.useState(!1),[S,j]=p.useState(null),P=p.useRef(null),R=p.useRef(null),O=p.useRef(null),F=p.useRef(null),M=ae=>{const ye=ae.type.toLowerCase(),Ne=ae.name.toLowerCase();return ye.includes("image")||ye.includes("pdf")||Ne.endsWith(".pdf")||Ne.endsWith(".jpg")||Ne.endsWith(".jpeg")||Ne.endsWith(".png")||Ne.endsWith(".gif")||Ne.endsWith(".webp")};p.useEffect(()=>()=>{S!=null&&S.url&&URL.revokeObjectURL(S.url)},[S]);const B=ae=>{if(!M(ae)){K.error("Preview is only available for images and PDF files");return}S!=null&&S.url&&URL.revokeObjectURL(S.url);const ye=URL.createObjectURL(ae);j({file:ae,url:ye})},k=ae=>{const ye=URL.createObjectURL(ae),Ne=document.createElement("a");Ne.href=ye,Ne.download=ae.name,document.body.appendChild(Ne),Ne.click(),document.body.removeChild(Ne),URL.revokeObjectURL(ye)},N=p.useMemo(()=>u.reduce((ae,ye)=>ae+(ye.amount||0),0),[u]),U=p.useMemo(()=>{const ae=o!=="",ye=x.length>0,Ne=f.length>0,ve=T.trim().length>0;return ae&&ye&&Ne&&ve},[o,x,f,T]),$=new Date().toISOString().split("T")[0],L=()=>{h([...u,{id:Date.now().toString(),description:"",amount:0}])},se=(ae,ye,Ne)=>{h(u.map(ve=>ve.id===ae?{...ve,[ye]:Ne}:ve))},G=ae=>{h(u.filter(ye=>ye.id!==ae))},oe=ae=>{const ye=Array.from(ae.target.files||[]);if(ye.length>0){const Ne=[],ve=l.maxFileSizeMB*1024*1024,$e=[".pdf",".doc",".docx",".zip",".rar"];ye.forEach(re=>{var pe,Oe;const Me="."+((pe=re.name.split(".").pop())==null?void 0:pe.toLowerCase()),ot=((Oe=re.name.split(".").pop())==null?void 0:Oe.toLowerCase())||"";if(re.size>ve){K.error(`"${re.name}" exceeds ${l.maxFileSizeMB}MB limit and was not added.`);return}if(!$e.includes(Me)){K.error(`"${re.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!l.allowedFileTypes.includes(ot)){K.error(`"${re.name}" has an unallowed file type according to system policy.`);return}Ne.push(re)}),Ne.length>0&&g([...x,...Ne]),P.current&&(P.current.value="")}},Z=ae=>{g(x.filter((ye,Ne)=>Ne!==ae))},E=ae=>{const ye=Array.from(ae.target.files||[]);if(ye.length>0){const Ne=[],ve=l.maxFileSizeMB*1024*1024;ye.forEach($e=>{var Me;const re=((Me=$e.name.split(".").pop())==null?void 0:Me.toLowerCase())||"";if($e.size>ve){K.error(`Photo "${$e.name}" exceeds ${l.maxFileSizeMB}MB limit.`);return}if(!$e.type.startsWith("image/")){K.error(`"${$e.name}" is not an image file.`);return}if(!l.allowedFileTypes.includes(re)){K.error(`"${$e.name}" has an unsupported image format.`);return}Ne.push($e)}),Ne.length>0&&y([...f,...Ne]),R.current&&(R.current.value="")}},V=ae=>{y(f.filter((ye,Ne)=>Ne!==ae))},H=ae=>{const ye=Array.from(ae.target.files||[]);if(ye.length>0){const Ne=[],ve=l.maxFileSizeMB*1024*1024,$e=[".pdf",".jpg",".jpeg",".png"];ye.forEach(re=>{var pe,Oe;const Me="."+((pe=re.name.split(".").pop())==null?void 0:pe.toLowerCase()),ot=((Oe=re.name.split(".").pop())==null?void 0:Oe.toLowerCase())||"";if(re.size>ve){K.error(`Invoice "${re.name}" exceeds ${l.maxFileSizeMB}MB limit.`);return}if(!$e.includes(Me)){K.error(`"${re.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!l.allowedFileTypes.includes(ot)){K.error(`"${re.name}" format is not allowed by system policy.`);return}Ne.push(re)}),Ne.length>0&&v([...b,...Ne]),O.current&&(O.current.value="")}},Q=ae=>{v(b.filter((ye,Ne)=>Ne!==ae))},Y=ae=>{var Ne,ve,$e;const ye=(Ne=ae.target.files)==null?void 0:Ne[0];if(ye){const re=l.maxFileSizeMB*1024*1024,Me=[".pdf",".xlsx",".xls",".csv"],ot="."+((ve=ye.name.split(".").pop())==null?void 0:ve.toLowerCase()),pe=(($e=ye.name.split(".").pop())==null?void 0:$e.toLowerCase())||"";if(ye.size>re){K.error(`Attendance file exceeds ${l.maxFileSizeMB}MB limit.`),F.current&&(F.current.value="");return}if(!Me.includes(ot)){K.error("Please upload PDF, Excel, or CSV files only"),F.current&&(F.current.value="");return}if(!l.allowedFileTypes.includes(pe)){K.error(`"${ye.name}" format is not allowed by system policy.`),F.current&&(F.current.value="");return}w(ye)}},W=async()=>{if(!U){K.error("Please fill all required fields");return}const ae=u.filter(ye=>ye.description.trim()!==""&&ye.amount>0);try{D(!0),await a({activityCompletionDate:o,numberOfParticipants:d?parseInt(d):void 0,closedExpenses:ae,totalClosedExpenses:N,completionDocuments:x,activityPhotos:f,invoicesReceipts:b.length>0?b:void 0,attendanceSheet:A||void 0,completionDescription:T}),ce(),s()}catch(ye){console.error("Failed to submit completion documents:",ye),K.error("Failed to submit completion documents. Please try again.")}finally{D(!1)}},ce=()=>{S!=null&&S.url&&URL.revokeObjectURL(S.url),j(null),c(""),m(""),h([]),g([]),y([]),v([]),w(null),C(""),P.current&&(P.current.value=""),R.current&&(R.current.value=""),O.current&&(O.current.value=""),F.current&&(F.current.value="")},xe=()=>{_||(ce(),s())};return e.jsxs(ht,{open:t,onOpenChange:xe,children:[e.jsxs(ct,{className:"dealer-completion-documents-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs(dt,{className:"font-semibold flex items-center gap-2 text-xl sm:text-2xl",children:[e.jsx(Es,{className:"w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]"}),"Activity Completion Documents"]}),e.jsx(Et,{className:"text-sm sm:text-base",children:"Step 5: Upload completion proof and final documents"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs sm:text-sm text-gray-600",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",n]}),e.jsx("div",{className:"mt-2",children:"Please upload completion documents, photos, and provide details about the completed activity."})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-6 py-3",children:e.jsxs("div",{className:"space-y-5 sm:space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"space-y-1.5 sm:space-y-2",children:[e.jsxs(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(lt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Completion Date *"]}),e.jsx(Bs,{value:o||null,onChange:ae=>c(ae||""),maxDate:$,placeholderText:"dd/mm/yyyy",className:"w-full max-w-[280px]",wrapperClassName:"max-w-[280px]"})]}),e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base sm:text-lg",children:"Closed Expenses"}),e.jsx(ie,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs(I,{type:"button",onClick:L,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(us,{className:"w-4 h-4 mr-1"}),"Add Expense"]})]}),e.jsxs("div",{className:"space-y-2 sm:space-y-3",children:[u.map(ae=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx("div",{className:"flex-1",children:e.jsx(Ie,{placeholder:"Item name (e.g., Venue rental, Refreshments, Printing)",value:ae.description,onChange:ye=>se(ae.id,"description",ye.target.value),className:"text-sm"})}),e.jsx("div",{className:"w-32 sm:w-40",children:e.jsx(Ie,{type:"number",placeholder:"Amount",min:"0",step:"0.01",value:ae.amount||"",onChange:ye=>se(ae.id,"amount",parseFloat(ye.target.value)||0),className:"text-sm"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"mt-0.5 hover:bg-red-100 hover:text-red-700 h-9 w-9 p-0",onClick:()=>G(ae.id),children:e.jsx(gt,{className:"w-4 h-4"})})]},ae.id)),u.length===0&&e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 italic",children:'No expenses added. Click "Add Expense" to add expense items.'}),u.length>0&&N>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:["₹",N.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]})]}),e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base sm:text-lg",children:"Completion Evidence"}),e.jsx(ie,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(De,{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 ${x.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(ae=>l.allowedFileTypes.includes(ae.replace(".",""))).join(","),className:"hidden",id:"completionDocs",onChange:oe}),e.jsx("label",{htmlFor:"completionDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:x.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Rs,{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:[x.length," document",x.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(Es,{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"})]})})]}),x.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 (",x.length,"):"]}),x.map((ae,ye)=>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(De,{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:ae.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(ae)&&e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>B(ae),title:"Preview file",children:e.jsx(xt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>k(ae),title:"Download file",children:e.jsx(wt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>Z(ye),title:"Remove document",children:e.jsx(gt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},ye))]})]}),e.jsxs("div",{children:[e.jsxs(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Jn,{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 ${f.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(ae=>l.allowedFileTypes.includes(ae.replace(".",""))).join(","),className:"hidden",id:"completionPhotos",onChange:E}),e.jsx("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:f.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Rs,{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:[f.length," photo",f.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(Jn,{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)"})]})})]}),f.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 (",f.length,"):"]}),f.map((ae,ye)=>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(Jn,{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:ae.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(ae)&&e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>B(ae),title:"Preview photo",children:e.jsx(xt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>k(ae),title:"Download photo",children:e.jsx(wt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>V(ye),title:"Remove photo",children:e.jsx(gt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},ye))]})]})]})]}),e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base sm:text-lg",children:"Supporting Documents"}),e.jsx(ie,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(ls,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Invoices / Receipts"]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload invoices and receipts for expenses incurred"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${b.length>0?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:O,type:"file",multiple:!0,accept:[".pdf",".jpg",".jpeg",".png"].filter(ae=>l.allowedFileTypes.includes(ae.replace(".",""))).join(","),className:"hidden",id:"invoiceReceipts",onChange:H}),e.jsx("label",{htmlFor:"invoiceReceipts",className:"cursor-pointer flex flex-col items-center gap-2",children:b.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-blue-700",children:[b.length," document",b.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-blue-600",children:"Click to add more documents"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload invoices/receipts (PDF, JPG, PNG)"})]})})]}),b.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",b.length,"):"]}),b.map((ae,ye)=>e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-2 sm:p-3 rounded-lg text-xs sm:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(ls,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:ae.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(ae)&&e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>B(ae),title:"Preview file",children:e.jsx(xt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>k(ae),title:"Download file",children:e.jsx(wt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>Q(ye),title:"Remove document",children:e.jsx(gt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},ye))]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm sm:text-base font-semibold",children:"Attendance Sheet / Participant List"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload attendance records or participant lists (if applicable)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${A?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:F,type:"file",accept:[".pdf",".xlsx",".xls",".csv"].filter(ae=>l.allowedFileTypes.includes(ae.replace(".",""))).join(","),className:"hidden",id:"attendanceDoc",onChange:Y}),e.jsx("label",{htmlFor:"attendanceDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:A?e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1 w-full max-w-full px-2",children:[e.jsx("span",{className:"text-sm font-semibold text-blue-700 break-words text-center w-full max-w-full",children:A.name}),e.jsx("span",{className:"text-xs text-blue-600",children:"Document selected"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload attendance sheet (Excel, PDF, CSV)"})]})})]}),A&&e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"text-xs font-medium text-gray-600 mb-2",children:"Selected Document:"}),e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-2 sm:p-3 rounded-lg text-xs sm:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(De,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:A.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(A)&&e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>B(A),title:"Preview file",children:e.jsx(xt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>k(A),title:"Download file",children:e.jsx(wt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>{w(null),F.current&&(F.current.value="")},title:"Remove document",children:e.jsx(gt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5 sm:space-y-2 max-w-3xl",children:[e.jsx(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(Ts,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:T,onChange:ae=>C(ae.target.value),className:"min-h-[100px] sm:min-h-[120px] text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[T.length," characters"]})]}),!U&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 sm:p-4 flex items-start gap-2 sm:gap-3",children:[e.jsx(Ve,{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(kt,{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pt-3 pb-6 border-t flex-shrink-0",children:[e.jsx(I,{variant:"outline",onClick:xe,disabled:_,className:"border-2",children:"Cancel"}),e.jsx(I,{onClick:W,disabled:_||!U,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:_?"Submitting...":"Submit Documents"})]})]}),S&&e.jsx(ht,{open:!!S,onOpenChange:()=>{S!=null&&S.url&&URL.revokeObjectURL(S.url),j(null)},children:e.jsx(ct,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(pt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(xt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(dt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:S.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[S.file.type||"Unknown type"," • ",(S.file.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(I,{variant:"outline",size:"sm",onClick:()=>k(S.file),className:"gap-2 h-9",children:[e.jsx(wt,{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:(ke=S.file.type)!=null&&ke.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:S.url,alt:S.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(Ae=S.file.type)!=null&&Ae.includes("pdf")||S.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:S.url,className:"w-full h-full rounded-lg border-0",title:S.file.name,style:{minHeight:"70vh",height:"100%"}})}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(xt,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),e.jsxs(I,{onClick:()=>k(S.file),className:"gap-2",children:[e.jsx(wt,{className:"h-4 w-4"}),"Download ",S.file.name]})]})})]})})})]})}function GS({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,u]=p.useState([{id:"1",description:"",amount:0}]),[h,x]=p.useState("date"),[g,f]=p.useState(""),[y,b]=p.useState(""),[v,A]=p.useState([]),[w,T]=p.useState(""),[C,_]=p.useState(!1),[D,S]=p.useState(null),[j,P]=p.useState(!1),R=p.useRef(null),O=p.useRef(null),F=W=>{if(!W)return!1;const ce=W.toLowerCase();return ce.endsWith(".pdf")||!!ce.match(/\.(jpg|jpeg|png|gif|webp)$/i)},M=W=>F(W.name);p.useEffect(()=>()=>{D!=null&&D.fileUrl&&D.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(D.fileUrl)},[D]);const B=W=>{if(!M(W)){K.error("Preview is only available for images and PDF files");return}D!=null&&D.fileUrl&&D.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(D.fileUrl);const ce=URL.createObjectURL(W);S({fileName:W.name,fileType:W.type,documentId:"",fileUrl:ce,fileSize:W.size})},k=W=>{const ce=W.originalFileName||W.fileName||W.name||"Document",xe=W.documentId||W.id||"",ke=ce.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let Ae="";if(xe)Ae=Zr(xe);else if(Ae=W.storageUrl||W.documentUrl||"",Ae&&!Ae.startsWith("http")){const ae="https://re-workflow-nt-dev.siplsolutions.com",ye=ae.endsWith("/")?ae.slice(0,-1):ae,Ne=Ae.startsWith("/")?Ae:`/${Ae}`;Ae=`${ye}${Ne}`}S({fileName:ce,fileType:ke,documentId:xe,fileUrl:Ae})},N=W=>{const ce=URL.createObjectURL(W),xe=document.createElement("a");xe.href=ce,xe.download=W.name,document.body.appendChild(xe),xe.click(),document.body.removeChild(xe),URL.revokeObjectURL(ce)},U=p.useMemo(()=>m.reduce((W,ce)=>W+(ce.amount||0),0),[m]),$=p.useMemo(()=>{const W=c!==null,ce=m.length>0&&m.every(Ae=>Ae.description.trim()!==""&&Ae.amount>0),xe=h==="date"?g!=="":y!==""&&parseInt(y)>0,ke=w.trim().length>0;return W&&ce&&xe&&ke},[c,m,h,g,y,w]),L=W=>{var xe,ke,Ae;const ce=(xe=W.target.files)==null?void 0:xe[0];if(ce){const ae=o.maxFileSizeMB*1024*1024;if(ce.size>ae){K.error(`File size exceeds the maximum allowed size of ${o.maxFileSizeMB}MB. Current size: ${(ce.size/(1024*1024)).toFixed(2)}MB`),R.current&&(R.current.value="");return}const ye=[".pdf",".doc",".docx"],Ne="."+((ke=ce.name.split(".").pop())==null?void 0:ke.toLowerCase()),ve=((Ae=ce.name.split(".").pop())==null?void 0:Ae.toLowerCase())||"";if(!ye.includes(Ne)||!o.allowedFileTypes.includes(ve)){K.error("Please upload a valid PDF, DOC, or DOCX file as per system policy"),R.current&&(R.current.value="");return}d(ce)}},se=W=>{const ce=Array.from(W.target.files||[]),xe=[],ke=o.maxFileSizeMB*1024*1024;ce.forEach(Ae=>{var ye;if(Ae.size>ke){K.error(`"${Ae.name}" exceeds ${o.maxFileSizeMB}MB limit and was not added.`);return}const ae=((ye=Ae.name.split(".").pop())==null?void 0:ye.toLowerCase())||"";if(!o.allowedFileTypes.includes(ae)){K.error(`"${Ae.name}" has an unsupported file type and was not added.`);return}xe.push(Ae)}),xe.length>0&&A(Ae=>[...Ae,...xe]),O.current&&(O.current.value="")},G=()=>{u(W=>[...W,{id:Date.now().toString(),description:"",amount:0}])},oe=W=>{m.length>1&&u(ce=>ce.filter(xe=>xe.id!==W))},Z=(W,ce,xe)=>{u(ke=>ke.map(Ae=>Ae.id===W?{...Ae,[ce]:ce==="amount"?parseFloat(xe.toString())||0:xe}:Ae))},E=W=>{A(ce=>ce.filter((xe,ke)=>ke!==W))},V=async()=>{if(!$){K.error("Please fill all required fields");return}let W=g||"";if(h==="days"&&y){const ce=parseInt(y),xe=new Date;xe.setDate(xe.getDate()+ce),W=xe.toISOString().split("T")[0]}try{_(!0),await a({proposalDocument:c,costBreakup:m.filter(ce=>ce.description.trim()!==""&&ce.amount>0),expectedCompletionDate:W,otherDocuments:v,dealerComments:w}),H(),s()}catch(ce){console.error("Failed to submit proposal:",ce),K.error("Failed to submit proposal. Please try again.")}finally{_(!1)}},H=()=>{D!=null&&D.fileUrl&&D.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(D.fileUrl),S(null),d(null),u([{id:"1",description:"",amount:0}]),x("date"),f(""),b(""),A([]),T(""),R.current&&(R.current.value=""),O.current&&(O.current.value="")},Q=()=>{C||(H(),s())},Y=new Date().toISOString().split("T")[0];return e.jsxs(ht,{open:t,onOpenChange:Q,children:[e.jsxs(ct,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"flex-shrink-0 pb-3 lg:pb-4",children:[e.jsxs(dt,{className:"flex items-center gap-2 text-xl lg:text-2xl",children:[e.jsx(Es,{className:"w-5 h-5 lg:w-6 lg:h-6 text-[--re-green]"}),"Dealer Proposal Submission"]}),e.jsx(Et,{className:"text-sm lg:text-base",children:"Step 1: Upload proposal and planning details"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs lg:text-sm text-gray-600",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",n]})]}),e.jsx("div",{className:"mt-1",children:"Please upload proposal document, provide cost breakdown, timeline, and detailed comments."})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden min-h-0 py-3 lg:py-4",children:[l&&e.jsx("div",{className:"mb-6 mx-1",children:e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg overflow-hidden cursor-pointer hover:bg-amber-100/50 transition-colors",onClick:()=>P(!j),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(De,{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(ie,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(l.totalEstimatedBudget||l.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:j?e.jsx(Co,{className:"w-4 h-4"}):e.jsx(us,{className:"w-4 h-4"})})]}),j&&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(lt,{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:F(l.documentUrl)?e.jsxs(e.Fragment,{children:[e.jsx(xt,{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(wt,{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(De,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:l.otherDocuments.map((W,ce)=>e.jsx(zr,{document:{documentId:W.documentId||W.id||"",name:W.originalFileName||W.fileName||W.name||"Supporting Document",fileType:(W.originalFileName||W.fileName||W.name||"").split(".").pop()||"file",uploadedAt:W.uploadedAt||new Date().toISOString()},onPreview:F(W.originalFileName||W.fileName||W.name||"")?()=>k(W):void 0,onDownload:async xe=>{if(xe)await js(xe);else{let ke=W.storageUrl||W.documentUrl;if(ke&&!ke.startsWith("http")){const Ae="https://re-workflow-nt-dev.siplsolutions.com",ae=Ae.endsWith("/")?Ae.slice(0,-1):Ae,ye=ke.startsWith("/")?ke:`/${ke}`;ke=`${ae}${ye}`}ke&&window.open(ke,"_blank")}}},ce))})]})]}),(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((W,ce)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:W.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(W.amount).toLocaleString("en-IN")]})]},ce)),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(ie,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{children:[e.jsx(ne,{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:R,type:"file",accept:[".pdf",".doc",".docx"].filter(W=>o.allowedFileTypes.includes(W.replace(".",""))).join(","),className:"hidden",id:"proposalDoc",onChange:L}),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(Rs,{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:[M(c)&&e.jsxs(I,{type:"button",variant:"outline",size:"sm",onClick:()=>B(c),className:"h-8 text-xs",children:[e.jsx(xt,{className:"w-3.5 h-3.5 mr-1"}),"Preview"]}),e.jsxs(I,{type:"button",variant:"outline",size:"sm",onClick:()=>N(c),className:"h-8 text-xs",children:[e.jsx(wt,{className:"w-3.5 h-3.5 mr-1"}),"Download"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload proposal (PDF, DOC, DOCX)"})]})})]})]})]}),e.jsxs("div",{className:"space-y-2 lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Other Supporting Documents"}),e.jsx(ie,{variant:"outline",className:"text-xs border-gray-300 text-gray-600 bg-gray-50 font-medium",children:"Optional"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"flex items-center gap-2 text-sm lg:text-base font-semibold",children:"Additional Documents"}),e.jsx("p",{className:"text-xs lg:text-sm text-gray-600 mb-2",children:"Any other supporting documents (invoices, receipts, photos, etc.)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${v.length>0?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:O,type:"file",multiple:!0,accept:o.allowedFileTypes.map(W=>`.${W}`).join(","),className:"hidden",id:"otherDocs",onChange:se}),e.jsx("label",{htmlFor:"otherDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:v.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-blue-700",children:[v.length," document",v.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-blue-600",children:"Click to add more documents"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600 text-center",children:"Click to upload additional documents"}),e.jsxs("span",{className:"text-[10px] text-gray-400",children:["Max ",o.maxFileSizeMB,"MB | ",o.allowedFileTypes.join(", ").toUpperCase()]})]})})]}),v.length>0&&e.jsxs("div",{className:"mt-2 lg:mt-3 space-y-2 max-h-[150px] lg:max-h-[140px] overflow-y-auto",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",v.length,"):"]}),v.map((W,ce)=>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(De,{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:W.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(W)&&e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>B(W),title:"Preview file",children:e.jsx(xt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>N(W),title:"Download file",children:e.jsx(wt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>E(ce),title:"Remove document",children:e.jsx(gt,{className:"w-4 h-4"})})]})]},ce))]})]})]})]}),e.jsxs("div",{className:"space-y-4 lg:space-y-4 flex flex-col",children:[e.jsxs("div",{className:"space-y-2 lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Cost Breakup"}),e.jsx(ie,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs(I,{type:"button",onClick:G,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(us,{className:"w-3 h-3 lg:w-4 lg:h-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Add Item"}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})]}),e.jsx("div",{className:"space-y-2 lg:space-y-2 max-h-[200px] lg:max-h-[180px] overflow-y-auto",children:m.map(W=>e.jsxs("div",{className:"flex gap-2 items-start w-full",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Ie,{placeholder:"Item description (e.g., Banner printing, Event setup)",value:W.description,onChange:ce=>Z(W.id,"description",ce.target.value),className:"w-full"})}),e.jsx("div",{className:"w-32 lg:w-36 flex-shrink-0",children:e.jsx(Ie,{type:"number",placeholder:"Amount",min:"0",step:"0.01",value:W.amount||"",onChange:ce=>Z(W.id,"amount",ce.target.value),className:"w-full"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"mt-0.5 hover:bg-red-100 hover:text-red-700 flex-shrink-0",onClick:()=>oe(W.id),disabled:m.length===1,children:e.jsx(gt,{className:"w-4 h-4"})})]},W.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(qn,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-700"}),e.jsx("span",{className:"font-semibold text-sm lg:text-base text-gray-900",children:"Estimated Budget"})]}),e.jsxs("div",{className:"text-xl lg:text-2xl font-bold text-gray-900",children:["₹",U.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs("div",{className:"space-y-2 lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Timeline for Closure"}),e.jsx(ie,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(I,{type:"button",onClick:()=>x("date"),className:h==="date"?"bg-[#2d4a3e] hover:bg-[#1f3329] text-white":"border-2 hover:bg-gray-50",size:"sm",children:[e.jsx(lt,{className:"w-4 h-4 mr-1"}),"Specific Date"]}),e.jsx(I,{type:"button",onClick:()=>x("days"),className:h==="days"?"bg-[#2d4a3e] hover:bg-[#1f3329] text-white":"border-2 hover:bg-gray-50",size:"sm",children:"Number of Days"})]}),h==="date"?e.jsxs("div",{className:"w-full",children:[e.jsx(ne,{className:"text-xs lg:text-sm font-medium mb-1.5 lg:mb-2 block",children:"Expected Completion Date"}),e.jsx(Bs,{value:g||null,onChange:W=>f(W||""),minDate:Y,placeholderText:"dd/mm/yyyy",className:"w-full"})]}):e.jsxs("div",{className:"w-full",children:[e.jsx(ne,{className:"text-xs lg:text-sm font-medium mb-1.5 lg:mb-2 block",children:"Number of Days"}),e.jsx(Ie,{type:"number",placeholder:"Enter number of days",min:"1",value:y,onChange:W=>b(W.target.value),className:"h-9 lg:h-10 w-full"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"dealerComments",className:"text-sm lg:text-base font-semibold flex items-center gap-2",children:"Dealer Comments / Details *"}),e.jsx(Ts,{id:"dealerComments",placeholder:"Provide detailed comments about this claim request, including any special considerations, execution details, or additional information...",value:w,onChange:W=>T(W.target.value),className:"min-h-[80px] lg:min-h-[100px] text-sm w-full"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[w.length," characters"]})]})]}),!$&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 lg:p-4 flex items-start gap-2 lg:gap-3 lg:col-span-2",children:[e.jsx(Ve,{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(kt,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end flex-shrink-0 pt-3 lg:pt-4 border-t",children:[e.jsx(I,{variant:"outline",onClick:Q,disabled:C,className:"border-2",children:"Cancel"}),e.jsx(I,{onClick:V,disabled:!$||C,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:C?"Submitting...":"Submit Documents"})]})]}),D&&e.jsx(Cr,{fileName:D.fileName,fileType:D.fileType,fileUrl:D.fileUrl,fileSize:D.fileSize,attachmentId:D.documentId,onDownload:js,open:!!D,onClose:()=>S(null)})]})}function KS({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n,requestId:i,preFilledIONumber:l,preFilledBlockedAmount:o,preFilledRemainingBalance:c}){const[d,m]=p.useState("approve"),[u,h]=p.useState(""),[x,g]=p.useState(!1),f=l||"";p.useEffect(()=>{t&&(h(""),m("approve"))},[t]);const y=u.length,b=500,v=p.useMemo(()=>(d==="reject"||f.trim().length>0)&&u.trim().length>0,[d,f,u]),A=async()=>{if(!v){if(d==="approve"&&!f.trim()){K.error("IO number is required. Please block amount from IO tab first.");return}if(!u.trim()){K.error("Please provide comments");return}return}try{g(!0),d==="approve"?await a({ioNumber:f.trim(),comments:u.trim()}):await r(u.trim()),w(),s()}catch(C){console.error(`Failed to ${d} request:`,C),K.error(`Failed to ${d} request. Please try again.`)}finally{g(!1)}},w=()=>{m("approve"),h("")},T=()=>{x||(w(),s())};return e.jsx(ht,{open:t,onOpenChange:T,children:e.jsxs(ct,{className:"dept-lead-io-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"flex-shrink-0 px-6 pt-6 pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 mb-2",children:[e.jsx("div",{className:"p-1.5 lg:p-2 rounded-lg bg-green-100",children:e.jsx(Pe,{className:"w-5 h-5 lg:w-6 lg:h-6 text-green-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(dt,{className:"font-semibold text-lg lg:text-xl",children:"Review and Approve"}),e.jsx(Et,{className:"text-xs lg:text-sm mt-1",children:"Review IO details and provide your approval comments"})]})]}),e.jsxs("div",{className:"space-y-2 lg:space-y-3 p-3 lg:p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-sm lg:text-base text-gray-900",children:"Workflow Step:"}),e.jsx(ie,{variant:"outline",className:"font-mono text-xs",children:"Step 3"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-sm lg:text-base text-gray-900",children:"Title:"}),e.jsx("p",{className:"text-xs lg:text-sm text-gray-700 mt-1",children:n||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm lg:text-base text-gray-900",children:"Action:"}),e.jsxs(ie,{className:"bg-green-100 text-green-800 border-green-200 text-xs",children:[e.jsx(Pe,{className:"w-3 h-3 mr-1"}),"APPROVE"]})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden py-3 lg:py-4 px-6",children:e.jsxs("div",{className:"space-y-3 lg:space-y-4",children:[e.jsxs("div",{className:"flex gap-2 p-1 bg-gray-100 rounded-lg",children:[e.jsxs(I,{type:"button",onClick:()=>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(Pe,{className:"w-4 h-4 mr-1"}),"Approve"]}),e.jsxs(I,{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(Nt,{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(ls,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),e.jsx("h4",{className:"font-semibold text-sm lg:text-base text-blue-900",children:"IO Organisation Details"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(ne,{htmlFor:"ioNumber",className:"text-xs lg:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["IO Number ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ie,{id:"ioNumber",value:f||"—",disabled:!0,readOnly:!0,className:"bg-gray-100 h-8 lg:h-9 cursor-not-allowed text-xs lg:text-sm"}),!f&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:"⚠️ IO number not found. Please block amount from IO tab first."}),f&&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(ne,{htmlFor:"comment",className:"text-xs lg:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Comments & Remarks ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ts,{id:"comment",placeholder:d==="approve"?"Enter your approval comments and any conditions or notes...":"Enter detailed reasons for rejection...",value:u,onChange:C=>{const _=C.target.value;_.length<=b&&h(_)},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(ss,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[y,"/",b]})]})]})]})]})}),e.jsxs(kt,{className:"flex-shrink-0 flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pb-6 pt-3 border-t",children:[e.jsx(I,{variant:"outline",onClick:T,disabled:x,className:"text-sm lg:text-base",children:"Cancel"}),e.jsx(I,{onClick:A,disabled:!v||x,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:x?`${d==="approve"?"Approving":"Rejecting"}...`:e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),d==="approve"?"Approve Request":"Reject Request"]})})]})]})})}function YS({isOpen:t,onClose:s,onPush:a,completionDetails:r,ioDetails:n,completionDocuments:i,requestTitle:l,requestNumber:o}){var j,P;const[c,d]=p.useState(""),[m,u]=p.useState(!1),[h,x]=p.useState(null),[g,f]=p.useState(!1),y=c.length,b=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]),A=R=>{if(!R)return"—";try{return new Date(R).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return R}},w=R=>`₹${R.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,T=R=>{if(!R.name)return!1;const O=R.name.toLowerCase();return O.endsWith(".pdf")||O.endsWith(".jpg")||O.endsWith(".jpeg")||O.endsWith(".png")||O.endsWith(".gif")||O.endsWith(".webp")},C=async R=>{if(!R.id){K.error("Document preview not available - document ID missing");return}f(!0);try{const O=Zr(R.id),F=R.name.toLowerCase(),M=F.endsWith(".pdf"),B=F.match(/\.(jpg|jpeg|png|gif|webp)$/i),k=!0,N=k?null:localStorage.getItem("accessToken"),$=await fetch(O,{headers:{Accept:M?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!$.ok)throw new Error(`Failed to load file: ${$.status} ${$.statusText}`);const L=await $.blob();if(L.size===0)throw new Error("File is empty or could not be loaded");const se=window.URL.createObjectURL(L);x({name:R.name,url:se,type:L.type||(M?"application/pdf":B?"image":void 0),size:L.size})}catch(O){console.error("Failed to load document preview:",O),K.error("Failed to load document preview")}finally{f(!1)}};p.useEffect(()=>()=>{h!=null&&h.url&&h.url.startsWith("blob:")&&window.URL.revokeObjectURL(h.url)},[h]);const _=async()=>{if(!c.trim()){K.error("Please provide comments before pushing to DMS");return}try{u(!0),await a(c.trim()),D(),s()}catch(R){console.error("Failed to push to DMS:",R),K.error("Failed to push to DMS. Please try again.")}finally{u(!1)}},D=()=>{d("")},S=()=>{m||(D(),s())};return e.jsxs(ht,{open:t,onOpenChange:S,children:[e.jsxs(ct,{className:"dms-push-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 mb-2",children:[e.jsx("div",{className:"p-1.5 sm:p-2 rounded-lg bg-indigo-100",children:e.jsx(Pt,{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(dt,{className:"font-semibold text-lg sm:text-xl",children:"Push to DMS - Verification"}),e.jsx(Et,{className:"text-xs sm:text-sm mt-1",children:"Review completion details and expenses before pushing to DMS for e-invoice generation"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 p-3 sm:p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between sm:flex-col sm:items-start sm:gap-1",children:[e.jsx("span",{className:"font-medium text-xs sm:text-sm text-gray-600",children:"Workflow Step:"}),e.jsx(ie,{variant:"outline",className:"font-mono text-xs",children:"Requestor Claim Approval"})]}),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(ie,{className:"bg-indigo-100 text-indigo-800 border-indigo-200 text-xs",children:[e.jsx(Pt,{className:"w-3 h-3 mr-1"}),"PUSH TO DMS"]})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-6 py-3",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6",children:[r&&e.jsxs(J,{children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Rs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Details"]}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Review activity completion information"})]}),e.jsxs(q,{className:"space-y-2 sm:space-y-3",children:[r.activityCompletionDate&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Activity Completion Date:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:A(r.activityCompletionDate)})]}),r.numberOfParticipants!==void 0&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Number of Participants:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:r.numberOfParticipants})]}),r.completionDescription&&e.jsxs("div",{className:"pt-2",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Completion Description:"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-900 line-clamp-3",children:r.completionDescription})]})]})]}),n&&n.ioNumber&&e.jsxs(J,{children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(ls,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"IO Details"]}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Internal Order information for budget reference"})]}),e.jsxs(q,{className:"space-y-2 sm:space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"IO Number:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900 font-mono",children:n.ioNumber})]}),n.blockedAmount!==void 0&&n.blockedAmount>0&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Blocked Amount:"}),e.jsx("span",{className:"text-xs sm:text-sm font-bold text-green-700",children:w(n.blockedAmount)})]}),n.remainingBalance!==void 0&&n.remainingBalance!==null&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Remaining Balance:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:w(n.remainingBalance)})]})]})]}),(r==null?void 0:r.closedExpenses)&&r.closedExpenses.length>0&&e.jsxs(J,{children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Ea,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Expense Breakdown"]}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Review closed expenses before pushing to DMS"})]}),e.jsxs(q,{children:[e.jsx("div",{className:"space-y-1.5 sm:space-y-2 max-h-[200px] overflow-y-auto",children:r.closedExpenses.map((R,O)=>e.jsxs("div",{className:"flex items-center justify-between py-1.5 sm:py-2 px-2 sm:px-3 bg-gray-50 rounded border",children:[e.jsx("div",{className:"flex-1 min-w-0 pr-2",children:e.jsx("p",{className:"text-xs sm:text-sm font-medium text-gray-900 truncate",children:R.description||`Expense ${O+1}`})}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:w(typeof R=="object"&&R.amount||0)})})]},O))}),e.jsxs("div",{className:"flex items-center justify-between py-2 sm:py-3 px-2 sm:px-3 bg-blue-50 rounded border-2 border-blue-200 mt-2 sm:mt-3",children:[e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:"Total:"}),e.jsx("span",{className:"text-sm sm:text-base font-bold text-blue-700",children:w(v)})]})]})]})]}),i&&e.jsxs("div",{className:"space-y-4",children:[i.completionDocuments&&i.completionDocuments.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"font-semibold text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Rs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Documents"]}),e.jsxs(ie,{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(Rs,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600 flex-shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:R.name,children:R.name})})]}),R.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[T(R)&&e.jsx("button",{type:"button",onClick:()=>C(R),disabled:g,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:g?e.jsx(Ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(xt,{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 js(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(wt,{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(Pt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Activity Photos"]}),e.jsxs(ie,{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(Pt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 flex-shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:R.name,children:R.name})})]}),R.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[T(R)&&e.jsx("button",{type:"button",onClick:()=>C(R),disabled:g,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview photo",children:g?e.jsx(Ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(xt,{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 js(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(wt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},O))})]}),i.invoicesReceipts&&i.invoicesReceipts.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"font-semibold text-sm sm:text-base flex items-center gap-2",children:[e.jsx(ls,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Invoices / Receipts"]}),e.jsxs(ie,{variant:"secondary",className:"text-xs",children:[i.invoicesReceipts.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:i.invoicesReceipts.map((R,O)=>e.jsxs("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 min-w-0 flex-1",children:[e.jsx(ls,{className:"w-4 h-4 lg:w-5 lg:h-5 text-purple-600 flex-shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:R.name,children:R.name})})]}),R.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[T(R)&&e.jsx("button",{type:"button",onClick:()=>C(R),disabled:g,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:g?e.jsx(Ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(xt,{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 js(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(wt,{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(Pt,{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(Pt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-indigo-600 flex-shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:i.attendanceSheet.name,children:i.attendanceSheet.name})})]}),i.attendanceSheet.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[T(i.attendanceSheet)&&e.jsx("button",{type:"button",onClick:()=>C(i.attendanceSheet),disabled:g,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:g?e.jsx(Ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(xt,{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 js(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(wt,{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(ss,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-yellow-900",children:"Please verify all details before pushing to DMS"}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1",children:"Once pushed, the system will automatically generate an e-invoice and log it as an activity."})]})]})}),e.jsxs("div",{className:"space-y-1.5 max-w-2xl",children:[e.jsxs(ne,{htmlFor:"comment",className:"text-xs sm:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Comments & Remarks ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ts,{id:"comment",placeholder:"Enter your comments about pushing to DMS (e.g., verified expenses, ready for invoice generation)...",value:c,onChange:R=>{const O=R.target.value;O.length<=b&&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(ss,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[y,"/",b]})]})]})]})}),e.jsxs(kt,{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pt-3 pb-6 border-t flex-shrink-0",children:[e.jsx(I,{variant:"outline",onClick:S,disabled:m,children:"Cancel"}),e.jsx(I,{onClick:_,disabled:!c.trim()||m,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:m?"Pushing to DMS...":e.jsxs(e.Fragment,{children:[e.jsx(Pt,{className:"w-4 h-4 mr-2"}),"Push to DMS"]})})]})]}),h&&e.jsx(ht,{open:!!h,onOpenChange:()=>x(null),children:e.jsx(ct,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(pt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(xt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(dt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:h.name}),h.type&&e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[h.type," ",h.size&&`• ${(h.size/1024).toFixed(1)} KB`]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(I,{variant:"outline",size:"sm",onClick:()=>{const R=document.createElement("a");R.href=h.url,R.download=h.name,R.click()},className:"gap-2 h-9",children:[e.jsx(wt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:g?e.jsx("div",{className:"flex items-center justify-center h-full min-h-[70vh]",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ze,{className:"w-8 h-8 animate-spin text-blue-600 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]})}):h.name.toLowerCase().endsWith(".pdf")||(j=h.type)!=null&&j.includes("pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:h.url,className:"w-full h-full rounded-lg border-0",title:h.name,style:{minHeight:"70vh",height:"100%"}})}):h.name.match(/\.(jpg|jpeg|png|gif|webp)$/i)||(P=h.type)!=null&&P.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:h.url,alt:h.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(xt,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),e.jsxs(I,{onClick:()=>{const R=document.createElement("a");R.href=h.url,R.download=h.name,R.click()},className:"gap-2",children:[e.jsx(wt,{className:"h-4 w-4"}),"Download ",h.name]})]})})]})})})]})}function ZS({isOpen:t,onClose:s,stepNumber:a,stepName:r,requestNumber:n="RE-REQ-2024-CM-101",recipientEmail:i="system@royalenfield.com",subject:l,emailBody:o}){const c=`System Notification: Activity Created - ${n}`,d=l||c,m=`System Notification
Activity has been automatically created for claim ${n}.
All stakeholders have been notified.
This is an automated message.`,u=o||m;return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(pt,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center",children:e.jsx(Ia,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(dt,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(Et,{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(Lt,{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(Ia,{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(Mi,{className:"w-5 h-5 text-purple-600"}),e.jsx("span",{className:"font-semibold text-gray-900",children:"Royal Enfield"})]}),e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans text-sm text-gray-700 leading-relaxed bg-transparent p-0 border-0",children:u})}),e.jsx("div",{className:"pt-3 border-t border-gray-200",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx(lt,{className:"w-3 h-3"}),e.jsx("span",{children:"Automated email • Royal Enfield Claims Portal"})]})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ie,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(ie,{className:"bg-purple-50 text-purple-700 border-purple-200",children:"Auto-triggered"})]})]}),e.jsx("div",{className:"flex justify-end gap-2 pt-2",children:e.jsxs(I,{variant:"outline",onClick:s,className:"h-9",children:[e.jsx(gt,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function XS({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[u,h]=p.useState(""),[x,g]=p.useState(!1),[f,y]=p.useState(null),[b,v]=p.useState(!1),A=(d==null?void 0:d.internalOrder)||(d==null?void 0:d.internal_order),T=((A==null?void 0:A.ioBlockedAmount)||(A==null?void 0:A.io_blocked_amount)||0)>0,[C,_]=p.useState(null),D=p.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const k=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(k)?k.reduce((N,U)=>{const $=typeof U=="object"&&U.amount||0;return N+(Number($)||0)},0):0},[i]),S=k=>{if(!k)return"—";try{return new Date(k).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return k}},j=k=>{if(!k.name)return!1;const N=k.name.toLowerCase();return N.endsWith(".pdf")||N.endsWith(".jpg")||N.endsWith(".jpeg")||N.endsWith(".png")||N.endsWith(".gif")||N.endsWith(".webp")},P=k=>{let N=k.url||k.storageUrl||"";const U=k.id||k.documentId||"";if(!U&&!N){K.error("Document preview not available");return}if(N&&!N.startsWith("http")&&!N.startsWith("blob:")){const $="https://re-workflow-nt-dev.siplsolutions.com",L=$.endsWith("/")?$.slice(0,-1):$,se=N.startsWith("/")?N:`/${N}`;N=`${L}${se}`}_({name:k.name||"Document",url:N||(U?Zr(U):""),type:(k.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:U})};p.useEffect(()=>()=>{C!=null&&C.url&&C.url.startsWith("blob:")&&window.URL.revokeObjectURL(C.url)},[C]);const R=async()=>{if(!u.trim()){K.error("Please provide approval comments");return}try{g(!0),y("approve"),await a(u),M(),s()}catch(k){console.error("Failed to approve proposal:",k),K.error("Failed to approve proposal. Please try again.")}finally{g(!1),y(null)}},O=async()=>{if(!u.trim()){K.error("Please provide rejection reason");return}try{g(!0),y("reject"),await r(u),M(),s()}catch(k){console.error("Failed to reject proposal:",k),K.error("Failed to reject proposal. Please try again.")}finally{g(!1),y(null)}},F=async()=>{if(!u.trim()){K.error("Please provide reasons for requesting a revision");return}if(!n){K.error("Revision feature is not available");return}try{g(!0),y("revision"),await n(u),M(),s()}catch(k){console.error("Failed to request revision:",k),K.error("Failed to request revision. Please try again.")}finally{g(!1),y(null)}},M=()=>{h(""),y(null)},B=()=>{x||(M(),s())};return t?e.jsxs(ht,{open:t,onOpenChange:B,children:[e.jsxs(ct,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(dt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(Pe,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),e.jsx(Et,{className:"text-xs lg:text-sm",children:"Step 2: Review dealer proposal and make a decision"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",l]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",o]})]}),e.jsxs("div",{className:"mt-1 text-amber-600 font-medium",children:["Decision: ",e.jsx("strong",{children:"Confirms?"})," (YES → Continue to Dept Lead / NO → Request is cancelled)"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden min-h-0 py-3 lg:py-4 px-6",children:[m&&e.jsx("div",{className:"mb-6",children:e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg overflow-hidden cursor-pointer hover:bg-amber-100/50 transition-colors",onClick:()=>v(!b),children:[e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{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(ie,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(m.totalEstimatedBudget||m.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:b?e.jsx(Co,{className:"w-4 h-4"}):e.jsx(us,{className:"w-4 h-4"})})]}),b&&e.jsxs("div",{className:"px-4 pb-4 border-t border-amber-200 space-y-4 bg-white/50",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-xs mt-3",children:[m.expectedCompletionDate&&e.jsxs("div",{className:"flex items-center gap-1.5 text-gray-700",children:[e.jsx(lt,{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:j({name:m.documentUrl})?e.jsxs(e.Fragment,{children:[e.jsx(xt,{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(wt,{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(qn,{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((k,N)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:k.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(k.amount).toLocaleString("en-IN")]})]},N)),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(De,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:m.otherDocuments.map((k,N)=>e.jsx(zr,{document:{documentId:k.documentId||k.id||"",name:k.originalFileName||k.fileName||k.name||"Supporting Document",fileType:(k.originalFileName||k.fileName||k.name||"").split(".").pop()||"file",uploadedAt:k.uploadedAt||new Date().toISOString()},onPreview:j({name:k.originalFileName||k.fileName||k.name||""})?()=>P(k):void 0,onDownload:async U=>{if(U)await js(U);else{let $=k.storageUrl||k.documentUrl;if($&&!$.startsWith("http")){const L="https://re-workflow-nt-dev.siplsolutions.com",se=L.endsWith("/")?L.slice(0,-1):L,G=$.startsWith("/")?$:`/${$}`;$=`${se}${G}`}$&&window.open($,"_blank")}}},N))})]}),(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(Is,{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(De,{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(De,{className:"w-5 h-5 lg:w-6 lg:h-6 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:i.proposalDocument.name,children:i.proposalDocument.name}),(i==null?void 0:i.submittedAt)&&e.jsxs("p",{className:"text-xs text-gray-500 truncate",children:["Submitted on ",S(i.submittedAt)]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:i.proposalDocument.id&&e.jsxs(e.Fragment,{children:[j(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(xt,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var k;try{(k=i.proposalDocument)!=null&&k.id&&await js(i.proposalDocument.id)}catch(N){console.error("Failed to download document:",N),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(wt,{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(De,{className:"w-4 h-4 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(ie,{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((k,N)=>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(De,{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:k.name,children:k.name})]}),k.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[j(k)&&e.jsx("button",{type:"button",onClick:()=>P(k),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(xt,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{k.id&&await js(k.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(wt,{className:"w-5 h-5 text-gray-600"})})]})]},N))})]})]}),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(qn,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const k=i!=null&&i.costBreakup?Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[]:[];return k&&Array.isArray(k)&&k.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:k.map((N,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:(N==null?void 0:N.description)||"N/A"}),e.jsxs("div",{className:"text-xs lg:text-sm font-semibold text-gray-900 text-right",children:["₹",(Number(N==null?void 0:N.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(N==null?void 0:N.id)||(N==null?void 0:N.description)||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(qn,{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(lt,{className:"w-4 h-4 text-purple-600"}),"Expected Completion Date"]})}),e.jsx("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50",children:e.jsx("p",{className:"text-sm lg:text-base font-semibold text-gray-900",children:i!=null&&i.expectedCompletionDate?S(i.expectedCompletionDate):"Not specified"})})]})]}),e.jsx("div",{className:"space-y-2 border-t pt-3 lg:pt-3 lg:col-span-2 mt-2",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 lg:gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(Is,{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(Ts,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:u,onChange:k=>h(k.target.value),className:"min-h-[150px] lg:min-h-[140px] text-xs lg:text-sm w-full"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[u.length," characters"]})]})]})}),!u.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2 lg:col-span-2",children:[e.jsx(Nt,{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(kt,{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(I,{variant:"outline",onClick:B,disabled:x,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(I,{onClick:F,disabled:!u.trim()||x,variant:"secondary",className:"bg-amber-100 hover:bg-amber-200 text-amber-900 border border-amber-200 w-full sm:w-auto",children:x&&f==="revision"?"Requesting...":e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Request Revised Quotation"]})}),e.jsx(I,{onClick:O,disabled:!u.trim()||x,variant:"destructive",className:"bg-red-600 hover:bg-red-700 w-full sm:w-auto",children:x&&f==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(I,{onClick:R,disabled:!u.trim()||!T||x,className:"bg-green-600 hover:bg-green-700 text-white disabled:opacity-50 disabled:cursor-not-allowed w-full sm:w-auto",title:T?"":"Please block IO budget before approving",children:x&&f==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Approve (Continue to Dept Lead)"]})})]}),!T&&e.jsx("p",{className:"text-xs text-red-600 text-center sm:text-left",children:"Please block IO budget in the IO Tab before approving"})]})]})]}),C&&e.jsx(Cr,{fileName:C.name,fileType:C.type||"",fileUrl:C.url,fileSize:C.size,attachmentId:C.id,onDownload:js,open:!!C,onClose:()=>_(null)})]}):null}function QS({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=x=>Number(x||0).toLocaleString("en-IN",{maximumFractionDigits:2,style:"currency",currency:"INR"}),d=x=>{if(!x)return null;try{return new Date(x).toLocaleDateString("en-IN",{day:"numeric",month:"short",year:"numeric"})}catch{return x}},m=x=>{if(!x)return!1;const g=x.toLowerCase();return g.endsWith(".pdf")||!!g.match(/\.(jpg|jpeg|png|gif|webp)$/i)},u=x=>{var f;const g=(f=(x||"").split(".").pop())==null?void 0:f.toLowerCase();return g==="pdf"?"pdf":["jpg","jpeg","png","gif","webp"].includes(g||"")?"image":"file"},h=x=>{const g=x.fileName||x.originalFileName||(o?"Proposal Document":"Completion Document"),f=x.documentId||"",y=g.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let b="";if(f)b=Zr(f);else if(b=x.storageUrl||x.documentUrl||"",b&&!b.startsWith("http")){const v="https://re-workflow-nt-dev.siplsolutions.com",A=v.endsWith("/")?v.slice(0,-1):v,w=b.startsWith("/")?b:`/${b}`;b=`${A}${w}`}l({fileName:g,fileType:y,documentId:f,fileUrl:b,fileSize:x.sizeBytes})};return e.jsxs(e.Fragment,{children:[e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs(pt,{className:"px-6 py-4 border-b",children:[e.jsxs(dt,{className:"flex items-center gap-2",children:[o?e.jsx(De,{className:"w-5 h-5 text-blue-600"}):e.jsx(ls,{className:"w-5 h-5 text-green-600"}),n||(o?"Proposal Snapshot Details":"Completion Snapshot Details")]}),e.jsxs(Et,{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(lt,{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(zr,{document:{documentId:"",name:o?"Proposal Document":"Completion Document",fileType:u(a.documentUrl),uploadedAt:new Date().toISOString()},onPreview:m(a.documentUrl)?()=>h({fileName:o?"Proposal Document":"Completion Document",documentUrl:a.documentUrl}):void 0,onDownload:async()=>{let x=a.documentUrl;if(!x.startsWith("http")){const g="https://re-workflow-nt-dev.siplsolutions.com",f=g.endsWith("/")?g.slice(0,-1):g,y=x.startsWith("/")?x:`/${x}`;x=`${f}${y}`}window.open(x,"_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(ie,{variant:"secondary",className:"text-[10px] h-5",children:[a.otherDocuments.length," Files"]})]}),e.jsx("div",{className:"space-y-2",children:a.otherDocuments.map((x,g)=>e.jsx(zr,{document:{documentId:x.documentId||"",name:x.originalFileName||x.fileName||"Supporting Document",fileType:u(x.originalFileName||x.fileName||""),uploadedAt:x.uploadedAt||new Date().toISOString()},onPreview:m(x.originalFileName||x.fileName||"")?()=>h(x):void 0,onDownload:x.documentId?js:async()=>{let f=x.storageUrl||x.documentUrl;if(f&&!f.startsWith("http")){const y="https://re-workflow-nt-dev.siplsolutions.com",b=y.endsWith("/")?y.slice(0,-1):y,v=f.startsWith("/")?f:`/${f}`;f=`${b}${v}`}f&&window.open(f,"_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((x,g)=>e.jsxs("tr",{className:"bg-white hover:bg-gray-50/50",children:[e.jsx("td",{className:"p-3 text-gray-800",children:x.description}),e.jsx("td",{className:"p-3 text-right text-gray-900 font-medium tabular-nums",children:c(x.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(ux,{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(I,{onClick:s,children:"Close"})})]})}),i&&e.jsx(Cr,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:js,open:!!i,onClose:()=>l(null)})]})}async function JS(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 qS(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 eT(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 tT(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 sT(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 bg(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 aT(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 rT(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 nT(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 Tr=t=>{if(!t)return"";try{return is(t)}catch{try{return new Date(t).toLocaleString("en-IN",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}catch{return t}}},iT=t=>{switch(t){case"approved":return e.jsx(Pe,{className:"w-5 h-5 text-green-600"});case"pending":return e.jsx(Xe,{className:"w-5 h-5 text-blue-600"});case"rejected":return e.jsx(Pe,{className:"w-5 h-5 text-red-600"});default:return e.jsx(Xe,{className:"w-5 h-5 text-gray-400"})}},lT=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"}},oT=(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",cT=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 dT({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i}){var fa,ya,Oa,Sa,At,Ta,er,tr,sr,ar,rr,nr,$a,ba,Ua,Mt,hs,zs,ir,lr,da,vt,ps,Ls,ta,Ar,ma,Ba,qr,en,tn,Pc,Ic,Ec,Fc,Mc,_c,Lc,Oc,$c,Uc,Bc,Vc,zc,Hc,Wc,Gc,Kc,Yc,Zc,Xc,Qc,Jc,qc,ed,td,sd,ad,rd,nd,id,ld,od,cd,dd,md,ud,xd,hd,pd,gd,fd,yd,bd,vd,jd,Nd,wd,Cd,Ad,Sd,Td,kd,Rd,Dd,Pd,Id,Ed,Fd,Md,_d,Ld;const[l,o]=p.useState(!1),[c,d]=p.useState(!1),[m,u]=p.useState(!1),[h,x]=p.useState(!1),[g,f]=p.useState(!1),[y,b]=p.useState(!1),[v,A]=p.useState(!1),[w,T]=p.useState(null),[C,_]=p.useState(!1),[D,S]=p.useState(null),[j,P]=p.useState([]),[R,O]=p.useState(!1),[F,M]=p.useState(new Set),[B,k]=p.useState(null),[N,U]=p.useState([]),[$,L]=p.useState(0);p.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Ee=t.id||t.requestId;try{const ge=await Cs(Ee),le=(ge==null?void 0:ge.approvalLevels)||(ge==null?void 0:ge.approvals)||[];if(le&&le.length>0){const fe=le.map(he=>{var Ce;return{step:he.levelNumber||he.level_number||0,levelNumber:he.levelNumber||he.level_number||0,levelName:he.levelName||he.level_name,approver:he.approverName||he.approver_name||"",approverEmail:(he.approverEmail||he.approver_email||"").toLowerCase(),status:((Ce=he.status)==null?void 0:Ce.toLowerCase())||"waiting",tatHours:he.tatHours||he.tat_hours||24,elapsedHours:he.elapsedHours||he.elapsed_hours,approvedAt:he.actionDate||he.action_date,comment:he.comments||he.comment,levelId:he.levelId||he.level_id}}).sort((he,Ce)=>(he.levelNumber||0)-(Ce.levelNumber||0));U(he=>he.length!==fe.length||he.some((Ue,be)=>{const yt=fe[be];return!yt||Ue.levelNumber!==yt.levelNumber||Ue.levelName!==yt.levelName||Ue.approverEmail!==yt.approverEmail||Ue.status!==yt.status})?fe:he)}else U([])}catch(ge){console.warn("Failed to load approval flows from API:",ge),t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&U(t.approvalFlow)}}else t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&U(t.approvalFlow)})()},[t==null?void 0:t.id,t==null?void 0:t.requestId,t==null?void 0:t.totalLevels,$]),p.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const z=t.id||t.requestId;(async()=>{try{const ge=await Cs(z),le=(ge==null?void 0:ge.approvalLevels)||(ge==null?void 0:ge.approvals)||[];if(le&&le.length>0){const fe=le.map(he=>{var Ce;return{step:he.levelNumber||he.level_number||0,levelNumber:he.levelNumber||he.level_number||0,levelName:he.levelName||he.level_name,approver:he.approverName||he.approver_name||"",approverEmail:(he.approverEmail||he.approver_email||"").toLowerCase(),status:((Ce=he.status)==null?void 0:Ce.toLowerCase())||"waiting",tatHours:he.tatHours||he.tat_hours||24,elapsedHours:he.elapsedHours||he.elapsed_hours,approvedAt:he.actionDate||he.action_date,comment:he.comments||he.comment,levelId:he.levelId||he.level_id}}).sort((he,Ce)=>(he.levelNumber||0)-(Ce.levelNumber||0));U(fe)}}catch(ge){console.warn("Failed to load approval flows from API:",ge)}})()}},[t==null?void 0:t.currentStep,t==null?void 0:t.totalLevels]);const se=async()=>{L(z=>z+1),await new Promise(z=>setTimeout(z,500)),n==null||n(),G()},G=async()=>{if(t!=null&&t.id||t!=null&&t.requestId)try{const Ee=[...await fN(t.id||t.requestId)||[]].sort((ge,le)=>new Date(le.createdAt).getTime()-new Date(ge.createdAt).getTime());P(Ee)}catch(z){console.warn("Failed to load version history:",z)}};p.useEffect(()=>{G()},[t==null?void 0:t.id,t==null?void 0:t.requestId,$]);const oe=(z,Ee,ge)=>{if(Ee&&Ee.trim())return Ee.toLowerCase().includes("additional approver"),Ee;const le={1:"Dealer - Proposal Submission",2:"Requestor Evaluation & Confirmation",3:"Department Lead Approval",4:"Activity Creation",5:"Dealer - Completion Documents",6:"Requestor - Claim Approval",7:"E-Invoice Generation",8:"Credit Note from SAP"};return le[z]?le[z]:ge&&ge!=="Unknown"&&ge!=="System"?`Additional Approver - ${ge}`:`Additional Approver - Step ${z}`},Z=(z,Ee,ge)=>{if(Ee&&Ee.toLowerCase().includes("additional approver"))return ge&&ge!=="Unknown"&&ge!=="System"?`${ge} will review and approve this request as an additional approver.`:"Additional approver will review and approve this request.";if(Ee&&Ee.trim()){const he=Ee.toLowerCase();if(he.includes("dealer")&&he.includes("proposal"))return"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests";if(he.includes("requestor")&&(he.includes("evaluation")||he.includes("confirmation")))return"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)";if(he.includes("department lead"))return"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)";if(he.includes("activity creation"))return"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.";if(he.includes("dealer")&&(he.includes("completion")||he.includes("documents")))return"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description";if(he.includes("requestor")&&(he.includes("claim")||he.includes("approval")))return"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.";if(he.includes("e-invoice")||he.includes("invoice generation"))return"E-invoice will be generated through DMS.";if(he.includes("credit note")||he.includes("sap"))return"Got credit note from SAP. Review and send to dealer to complete the claim management process."}const fe={1:"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests",2:"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)",3:"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)",4:"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.",5:"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description",6:"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.",7:"E-invoice will be generated through DMS.",8:"Got credit note from SAP. Review and send to dealer to complete the claim management process."};return fe[z]?fe[z]:ge&&ge!=="Unknown"&&ge!=="System"?`${ge} will review and approve this request.`:`Step ${z} approval required.`},E=z=>{if(!j||j.length===0||!z)return{current:null,previous:null};const le=[...j.filter(Ce=>{var Ue;return!!(Ce.levelName&&Ce.levelName.trim()===z.trim()||(Ue=Ce.snapshotData)!=null&&Ue.levelName&&Ce.snapshotData.levelName.trim()===z.trim())})].sort((Ce,Ue)=>{if(Ue.version!==Ce.version)return Ue.version-Ce.version;const be=Ce.snapshotType==="APPROVE"?1:Ce.snapshotType==="PROPOSAL"||Ce.snapshotType==="COMPLETION"?2:3,yt=Ue.snapshotType==="APPROVE"?1:Ue.snapshotType==="PROPOSAL"||Ue.snapshotType==="COMPLETION"?2:3;return be-yt}).filter((Ce,Ue,be)=>Ce.snapshotType==="WORKFLOW"?!be.some(ut=>ut.snapshotType==="APPROVE"&&ut.levelName===Ce.levelName&&ut.version>=Ce.version):!0),fe=le.length>0?le[0]:null,he=le.length>1?le[1]:null;return{current:fe,previous:he,all:le}},V=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),H=V!=null?Number(V):null,Q=((t==null?void 0:t.status)||"").toUpperCase(),Y=Q==="REJECTED",W=Q==="CLOSED",ce=!Y&&!W&&(Q==="PENDING"||Q==="IN_PROGRESS"||Q==="IN-PROGRESS"),xe=N.find(z=>{var le,fe;const Ee=z.levelId||z.level_id,ge=(le=t==null?void 0:t.approvals)==null?void 0:le.find(he=>he.levelId===Ee);return((fe=ge==null?void 0:ge.status)==null?void 0:fe.toLowerCase())==="rejected"}),ke=xe?Number(xe.levelNumber||xe.level_number||xe.step||0):null,Ae=N.map((z,Ee)=>{var ua,bs,de,Ut,Zt,fs,Qe;const ge=Number(z.levelNumber||z.level_number||z.step||Ee+1),le=z.levelName||z.level_name,fe=(ua=t==null?void 0:t.approvals)==null?void 0:ua.find(Se=>Se.levelId===z.levelId);let he;if(le&&le.toLowerCase().includes("department lead")||ge===3){const Se=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);(Se!=null&&Se.ioNumber||Se!=null&&Se.io_number)&&(he={ioNumber:Se.ioNumber||Se.io_number||"",blockedAmount:Se.ioBlockedAmount||Se.io_blocked_amount||0,availableBalance:Se.ioAvailableBalance||Se.io_available_balance||0,remainingBalance:Se.ioRemainingBalance||Se.io_remaining_balance||0,organizedBy:((bs=Se.organizer)==null?void 0:bs.displayName)||((de=Se.organizer)==null?void 0:de.name)||Se.organizedBy||z.approver||"N/A",organizedAt:Se.organizedAt||Se.organized_at||z.approvedAt||(t==null?void 0:t.updatedAt)||""})}let Ue;ge===6&&(fe!=null&&fe.dmsDetails?Ue={dmsNumber:fe.dmsDetails.dmsNumber||"",dmsRemarks:fe.dmsDetails.dmsRemarks||"",pushedBy:fe.dmsDetails.pushedBy||z.approver,pushedAt:fe.dmsDetails.pushedAt||z.approvedAt||""}:t!=null&&t.dmsNumber&&(Ue={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((Ut=t.dmsDetails)==null?void 0:Ut.dmsRemarks)||"",pushedBy:z.approver,pushedAt:z.approvedAt||t.updatedAt||""}));let be;if(Y||W)((Zt=fe==null?void 0:fe.status)==null?void 0:Zt.toLowerCase())==="rejected"?be="rejected":ke!==null&&ge>ke?be="waiting":((fs=fe==null?void 0:fe.status)==null?void 0:fs.toLowerCase())==="approved"?be="approved":ke!==null&&ge<ke?((Qe=fe==null?void 0:fe.status)==null?void 0:Qe.toLowerCase())==="approved"?be="approved":be="waiting":(H!==null&&ge>H,be="waiting");else if(ce&&H!==null&&H>0)if(ge>H)be="waiting";else if(ge<H)if(fe!=null&&fe.status){const Se=fe.status.toLowerCase();Se==="approved"?be="approved":Se==="rejected"?be="rejected":be="waiting"}else be="waiting";else if(fe!=null&&fe.status){const Se=fe.status.toLowerCase();Se==="approved"?be="approved":Se==="rejected"?be="rejected":be="in_progress"}else{const Se=(z.status||"pending").toLowerCase();Se==="in-review"||Se==="in_review"||Se==="in review"||Se==="pending"?be="in_progress":be=Se}else if(fe!=null&&fe.status){const Se=fe.status.toLowerCase();Se==="approved"?be="approved":Se==="rejected"?be="rejected":Se==="pending"||Se==="in_progress"||Se==="in-progress"?be="in_progress":be=(z.status||"waiting").toLowerCase()}else{const Se=(z.status||"waiting").toLowerCase();Se==="in-review"||Se==="in_review"||Se==="in review"||Se==="pending"?be="in_progress":be=Se}const ut=be==="waiting"?0:z.elapsedHours||0,gs=z.approver||z.approverName||"Unknown",jt=le?E(le):{current:null,previous:null};return{step:ge,title:oe(ge,le,gs),approver:gs,description:Z(ge,le,gs)||z.description||"",tatHours:z.tatHours||24,status:be,comment:z.comment||(fe==null?void 0:fe.comment),approvedAt:z.approvedAt||(fe==null?void 0:fe.timestamp),elapsedHours:ut,ioDetails:he,dmsDetails:Ue,einvoiceUrl:ge===7?fe==null?void 0:fe.einvoiceUrl:void 0,emailTemplateUrl:(fe==null?void 0:fe.emailTemplateUrl)||void 0,versionHistory:jt}});let ae=null,ye=1;if(Y||W)ke!==null?ye=ke:H!==null?ye=H:ye=(t==null?void 0:t.currentStep)||1;else if(ce){const z=H!==null?Ae.find(Ee=>Ee.step===H):null;ae=z&&(z.status==="pending"||z.status==="in_progress")?z:Ae.find(Ee=>{var le;const ge=((le=Ee.status)==null?void 0:le.toLowerCase())||"";return ge==="pending"||ge==="in_progress"||ge==="in-review"||ge==="in_review"}),ye=ae?ae.step:H||(t==null?void 0:t.currentStep)||1}else ye=H||(t==null?void 0:t.currentStep)||1;const Ne=((fa=s==null?void 0:s.email)==null?void 0:fa.toLowerCase())||"",ve=((ya=t==null?void 0:t.dealerEmail)==null?void 0:ya.toLowerCase())||((Sa=(Oa=t==null?void 0:t.dealer)==null?void 0:Oa.email)==null?void 0:Sa.toLowerCase())||((Ta=(At=t==null?void 0:t.claimDetails)==null?void 0:At.dealerEmail)==null?void 0:Ta.toLowerCase())||((tr=(er=t==null?void 0:t.claimDetails)==null?void 0:er.dealer_email)==null?void 0:tr.toLowerCase())||"",$e=ve&&Ne===ve,re=N.find(z=>(z.step||z.levelNumber||z.level_number)===ye),Me=((re==null?void 0:re.approverEmail)||"").toLowerCase(),ot=Me&&Ne===Me,pe=((ar=(sr=t==null?void 0:t.initiator)==null?void 0:sr.email)==null?void 0:ar.toLowerCase())||((rr=t==null?void 0:t.initiatorEmail)==null?void 0:rr.toLowerCase())||"",Oe=N.find(z=>{const Ee=(z.approverEmail||"").toLowerCase(),ge=(z.levelName||"").toLowerCase();return pe&&Ee===pe||ge.includes("requestor evaluation")||ge.includes("requestor")&&ge.includes("confirmation")}),ft=Oe&&(Oe.step||Oe.levelNumber||Oe.level_number)||2,mt=Oe||N.find(z=>(z.step||z.levelNumber||z.level_number)===2),nt=((mt==null?void 0:mt.approverEmail)||"").toLowerCase(),_s=nt&&Ne===nt,ea=N.find(z=>(z.step||z.levelNumber||z.level_number)===1),Aa=((ea==null?void 0:ea.approverEmail)||"").toLowerCase(),qa=Aa&&Ne===Aa,ee=N.find(z=>(z.levelName||"").toLowerCase().includes("department lead")),we=((ee==null?void 0:ee.approverEmail)||"").toLowerCase(),te=we&&Ne===we,_e=async z=>{var Ee,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const le=t.id||t.requestId;z.proposalDocument&&await xn(z.proposalDocument,le,"APPROVAL");for(const he of z.otherDocuments)await xn(he,le,"SUPPORTING");const fe=z.costBreakup.reduce((he,Ce)=>he+Ce.amount,0);await eT(le,{proposalDocument:z.proposalDocument||void 0,costBreakup:z.costBreakup.map(he=>({description:he.description,amount:he.amount})),totalEstimatedBudget:fe,expectedCompletionDate:z.expectedCompletionDate,dealerComments:z.dealerComments}),K.success("Proposal submitted successfully"),se()}catch(le){console.error("Failed to submit proposal:",le);const fe=((ge=(Ee=le==null?void 0:le.response)==null?void 0:Ee.data)==null?void 0:ge.message)||(le==null?void 0:le.message)||"Failed to submit proposal. Please try again.";throw K.error(fe),le}},Fe=async z=>{var Ee,ge,le,fe,he;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Ce=t.id||t.requestId,Ue=await Cs(Ce),be=(Ue==null?void 0:Ue.approvalLevels)||(Ue==null?void 0:Ue.approvals)||[],yt=((ge=(Ee=t==null?void 0:t.initiator)==null?void 0:Ee.email)==null?void 0:ge.toLowerCase())||((le=t==null?void 0:t.initiatorEmail)==null?void 0:le.toLowerCase())||"",ut=be.find(jt=>{const ua=(jt.approverEmail||jt.approver_email||"").toLowerCase(),bs=(jt.levelName||jt.level_name||"").toLowerCase(),de=jt.levelNumber||jt.level_number;return yt&&ua===yt||bs.includes("requestor evaluation")||bs.includes("requestor")&&bs.includes("confirmation")||de===ft})||be.find(jt=>(jt.levelNumber||jt.level_number)===2);if(!(ut!=null&&ut.levelId)&&!(ut!=null&&ut.level_id))throw new Error("Initiator approval level not found");const gs=ut.levelId||ut.level_id;await mn(Ce,gs,z),K.success("Proposal approved successfully"),se()}catch(Ce){console.error("Failed to approve proposal:",Ce);const Ue=((he=(fe=Ce==null?void 0:Ce.response)==null?void 0:fe.data)==null?void 0:he.message)||(Ce==null?void 0:Ce.message)||"Failed to approve proposal. Please try again.";throw K.error(Ue),Ce}},ze=async z=>{var Ee,ge,le,fe,he;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Ce=t.id||t.requestId,Ue=await Cs(Ce),be=(Ue==null?void 0:Ue.approvalLevels)||(Ue==null?void 0:Ue.approvals)||[],yt=((ge=(Ee=t==null?void 0:t.initiator)==null?void 0:Ee.email)==null?void 0:ge.toLowerCase())||((le=t==null?void 0:t.initiatorEmail)==null?void 0:le.toLowerCase())||"",ut=be.find(jt=>{const ua=(jt.approverEmail||jt.approver_email||"").toLowerCase(),bs=(jt.levelName||jt.level_name||"").toLowerCase(),de=jt.levelNumber||jt.level_number;return yt&&ua===yt||bs.includes("requestor evaluation")||bs.includes("requestor")&&bs.includes("confirmation")||de===ft})||be.find(jt=>(jt.levelNumber||jt.level_number)===2);if(!(ut!=null&&ut.levelId)&&!(ut!=null&&ut.level_id))throw new Error("Initiator approval level not found");const gs=ut.levelId||ut.level_id;await kr(Ce,gs,"Proposal rejected by requestor",z),K.success("Proposal rejected. Request has been cancelled."),se()}catch(Ce){console.error("Failed to reject proposal:",Ce);const Ue=((he=(fe=Ce==null?void 0:Ce.response)==null?void 0:fe.data)==null?void 0:he.message)||(Ce==null?void 0:Ce.message)||"Failed to reject proposal. Please try again.";throw K.error(Ue),Ce}},Le=async z=>{var Ee,ge,le,fe,he;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Ce=t.id||t.requestId,Ue=await Cs(Ce),be=(Ue==null?void 0:Ue.approvalLevels)||(Ue==null?void 0:Ue.approvals)||[],yt=((ge=(Ee=t==null?void 0:t.initiator)==null?void 0:Ee.email)==null?void 0:ge.toLowerCase())||((le=t==null?void 0:t.initiatorEmail)==null?void 0:le.toLowerCase())||"",ut=be.find(jt=>{const ua=(jt.approverEmail||jt.approver_email||"").toLowerCase(),bs=(jt.levelName||jt.level_name||"").toLowerCase(),de=jt.levelNumber||jt.level_number;return yt&&ua===yt||bs.includes("requestor evaluation")||bs.includes("requestor")&&bs.includes("confirmation")||de===ft})||be.find(jt=>(jt.levelNumber||jt.level_number)===2);if(!(ut!=null&&ut.levelId)&&!(ut!=null&&ut.level_id))throw new Error("Initiator approval level not found");const gs=ut.levelId||ut.level_id;await kr(Ce,gs,"Revised Quotation Requested",z),K.success("Revision requested. Request returned to dealer."),se()}catch(Ce){console.error("Failed to request revision:",Ce);const Ue=((he=(fe=Ce==null?void 0:Ce.response)==null?void 0:fe.data)==null?void 0:he.message)||(Ce==null?void 0:Ce.message)||"Failed to request revision. Please try again.";throw K.error(Ue),Ce}},Je=async z=>{var Ee,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const le=t.id||t.requestId,fe=await Cs(le),he=(fe==null?void 0:fe.approvalLevels)||(fe==null?void 0:fe.approvals)||[],Ce=he.find(be=>(be.levelName||be.level_name||"").toLowerCase().includes("department lead"))||he.find(be=>(be.levelNumber||be.level_number)===3);if(!(Ce!=null&&Ce.levelId)&&!(Ce!=null&&Ce.level_id))throw new Error("Department Lead approval level not found");const Ue=Ce.levelId||Ce.level_id;await bg(le,{ioNumber:z.ioNumber}),await mn(le,Ue,z.comments),K.success("Request approved and IO organized successfully"),se()}catch(le){console.error("Failed to approve and organize IO:",le);const fe=((ge=(Ee=le==null?void 0:le.response)==null?void 0:Ee.data)==null?void 0:ge.message)||(le==null?void 0:le.message)||"Failed to approve request. Please try again.";throw K.error(fe),le}},Be=async z=>{var Ee,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const le=t.id||t.requestId,fe=z.closedExpenses.map(he=>({description:he.description,amount:he.amount}));if(await tT(le,{activityCompletionDate:z.activityCompletionDate,numberOfParticipants:z.numberOfParticipants,closedExpenses:fe,totalClosedExpenses:z.totalClosedExpenses,completionDocuments:z.completionDocuments,activityPhotos:z.activityPhotos,completionDescription:z.completionDescription}),z.invoicesReceipts&&z.invoicesReceipts.length>0)for(const he of z.invoicesReceipts)await xn(he,le,"SUPPORTING");z.attendanceSheet&&await xn(z.attendanceSheet,le,"SUPPORTING"),K.success("Completion documents submitted successfully"),se()}catch(le){console.error("Failed to submit completion documents:",le);const fe=((ge=(Ee=le==null?void 0:le.response)==null?void 0:Ee.data)==null?void 0:ge.message)||(le==null?void 0:le.message)||"Failed to submit completion documents. Please try again.";throw K.error(fe),le}},tt=async z=>{var Ee,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const le=t.id||t.requestId,fe=new Date().toISOString().slice(0,10);await aT(le,{eInvoiceDate:fe}),K.success("Pushed to DMS successfully. E-invoice will be generated automatically."),se()}catch(le){console.error("[DealerClaimWorkflowTab] Error pushing to DMS:",le);const fe=((ge=(Ee=le==null?void 0:le.response)==null?void 0:Ee.data)==null?void 0:ge.message)||(le==null?void 0:le.message)||"Failed to push to DMS. Please try again.";throw K.error(fe),le}},ws=async z=>{var Ee,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const le=t.id||t.requestId,fe=await Cs(le),he=(fe==null?void 0:fe.approvalLevels)||(fe==null?void 0:fe.approvals)||[],Ce=he.find(be=>(be.levelName||be.level_name||"").toLowerCase().includes("department lead"))||he.find(be=>(be.levelNumber||be.level_number)===3);if(!(Ce!=null&&Ce.levelId)&&!(Ce!=null&&Ce.level_id))throw new Error("Department Lead approval level not found");const Ue=Ce.levelId||Ce.level_id;await kr(le,Ue,"Dept Lead rejected - More clarification required",z),K.success("Request rejected. Request has been cancelled."),se()}catch(le){console.error("Failed to reject request:",le);const fe=((ge=(Ee=le==null?void 0:le.response)==null?void 0:Ee.data)==null?void 0:ge.message)||(le==null?void 0:le.message)||"Failed to reject request. Please try again.";throw K.error(fe),le}},[Yt,rt]=p.useState(null);p.useEffect(()=>{if(!t){rt(null);return}(async()=>{try{const Ee=t.id||t.requestId;if(!Ee){rt(null);return}const ge=await Cs(Ee),le=(ge==null?void 0:ge.documents)||[],fe=t.proposalDetails||(ge==null?void 0:ge.proposalDetails)||{},he=le.find(be=>be.category==="APPROVAL"||be.type==="proposal"||be.documentCategory==="APPROVAL"),Ce=le.filter(be=>be.category==="SUPPORTING"||be.type==="supporting"||be.documentCategory==="SUPPORTING");let Ue=fe.costBreakup||[];if(typeof Ue=="string")try{Ue=JSON.parse(Ue)}catch(be){console.warn("Failed to parse costBreakup JSON:",be),Ue=[]}Array.isArray(Ue)||(Ue=[]),rt({proposalDocument:he?{name:he.fileName||he.file_name||he.name,id:he.documentId||he.document_id||he.id}:void 0,costBreakup:Ue,expectedCompletionDate:fe.expectedCompletionDate||"",otherDocuments:Ce.map(be=>({name:be.fileName||be.file_name||be.name,id:be.documentId||be.document_id||be.id})),dealerComments:fe.dealerComments||"",submittedAt:fe.submittedAt})}catch(Ee){console.warn("Failed to load proposal data:",Ee);const ge=t.proposalDetails||{};let le=ge.costBreakup||[];if(typeof le=="string")try{le=JSON.parse(le)}catch(fe){console.warn("Failed to parse costBreakup JSON:",fe),le=[]}Array.isArray(le)||(le=[]),rt({proposalDocument:void 0,costBreakup:le,expectedCompletionDate:ge.expectedCompletionDate||"",otherDocuments:[],dealerComments:ge.dealerComments||"",submittedAt:ge.submittedAt})}})()},[t]);const[st,bt]=p.useState(null);p.useEffect(()=>{if(!t){bt(null);return}(async()=>{try{const Ee=t.id||t.requestId;if(!Ee){bt(null);return}const ge=await Cs(Ee),le=(ge==null?void 0:ge.documents)||[],fe=[],he=[],Ce=[];let Ue=null;le.forEach(be=>{const yt=(be.category||be.documentCategory||be.type||"").toUpperCase(),ut=(be.fileName||be.file_name||be.name||"").toLowerCase(),gs={name:be.fileName||be.file_name||be.name,id:be.documentId||be.document_id||be.id,url:be.url||be.storageUrl||be.storage_url};yt==="COMPLETION"||yt==="COMPLETION_DOCUMENT"?fe.push(gs):yt==="ACTIVITY_PHOTO"||yt==="PHOTO"||yt==="IMAGE"?he.push(gs):yt==="ATTENDANCE"||yt==="ATTENDANCE_SHEET"?Ue=gs:(yt==="SUPPORTING"||yt==="INVOICE"||yt==="RECEIPT")&&(!Ue&&(ut.includes("attendance")||ut.includes("participant"))?Ue=gs:Ce.push(gs))}),fe.length===0&&he.length===0&&t.completionDetails,bt({completionDocuments:fe,activityPhotos:he,invoicesReceipts:Ce,attendanceSheet:Ue})}catch(Ee){console.warn("Failed to load completion documents:",Ee),bt(null)}})()},[t]);const as=((nr=t==null?void 0:t.claimDetails)==null?void 0:nr.dealerName)||(($a=t==null?void 0:t.dealerInfo)==null?void 0:$a.name)||"Dealer",Ft=((ba=t==null?void 0:t.claimDetails)==null?void 0:ba.activityName)||((Ua=t==null?void 0:t.activityInfo)==null?void 0:Ua.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(J,{children:[e.jsx(me,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(Te,{className:"mt-2",children:"Approval process for dealer claim management"})]})})}),e.jsxs(q,{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(ss,{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:Ae.map((z,Ee)=>{var ut,gs,jt,ua,bs;const le=(((ut=z.status)==null?void 0:ut.toLowerCase())||"")==="in_progress",fe=z.step===ye,he=ce&&le&&fe,Ce=z.status==="approved",Ue=N.find(de=>(de.step||de.levelNumber||de.level_number)===z.step),be=Ue!=null&&Ue.levelId?(gs=t==null?void 0:t.approvals)==null?void 0:gs.find(de=>de.levelId===Ue.levelId||de.level_id===Ue.levelId):null,yt=(be==null?void 0:be.status)==="PAUSED"||((jt=t==null?void 0:t.pauseInfo)==null?void 0:jt.isPaused)&&(((ua=t==null?void 0:t.pauseInfo)==null?void 0:ua.levelId)===(be==null?void 0:be.levelId)||((bs=t==null?void 0:t.pauseInfo)==null?void 0:bs.level_id)===(be==null?void 0:be.levelId));return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${oT(z.status,he)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${cT(z.status)}`,children:iT(z.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:z.title}),e.jsx(ie,{className:lT(z.status),children:z.status.toLowerCase()}),z.emailTemplateUrl&&z.status==="approved"&&e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>{T({stepNumber:z.step,stepName:z.title}),A(!0)},children:e.jsx(Ia,{className:"w-3.5 h-3.5 text-blue-600"})}),z.step===7&&z.einvoiceUrl&&Ce&&e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",title:"Download E-Invoice",onClick:()=>window.open(z.einvoiceUrl,"_blank"),children:e.jsx(wt,{className:"w-3.5 h-3.5 text-green-600"})})]}),e.jsx("p",{className:"text-sm text-gray-600",children:z.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:z.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",Ot(z.tatHours)]}),z.elapsedHours&&(he||Ce)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",Ot(z.elapsedHours)]})]})]}),z.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:z.comment})}),z.versionHistory&&z.versionHistory.all&&z.versionHistory.all.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsxs(I,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs text-amber-700 hover:text-amber-800 hover:bg-amber-50",onClick:()=>{const de=new Set(F);de.has(z.step)?de.delete(z.step):de.add(z.step),M(de)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vx,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"font-medium",children:"Version History"}),z.versionHistory.all&&z.versionHistory.all.length>0&&e.jsxs(ie,{className:"bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0",children:[z.versionHistory.all.length," Versions"]})]}),F.has(z.step)?e.jsx(dx,{className:"w-4 h-4"}):e.jsx(wo,{className:"w-4 h-4"})]}),F.has(z.step)&&z.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:z.versionHistory.all.map((de,Ut)=>{var Zt,fs,Qe,Se;return e.jsxs("div",{className:`space-y-2 ${Ut>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(ie,{className:`${Ut===0?"bg-amber-500":"bg-gray-400"} text-white text-[10px] px-2 py-0.5`,children:[Ut===0?"Current":"Previous",": v",de.version]}),e.jsx("span",{className:"text-[10px] text-gray-600 font-medium",children:Tr(de.createdAt)})]})}),e.jsx("p",{className:"text-xs text-gray-700 font-medium",children:de.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${Ut===0?"bg-blue-100":"bg-gray-100"} flex items-center justify-center`,children:e.jsx("span",{className:`text-[8px] font-bold ${Ut===0?"text-blue-600":"text-gray-600"}`,children:((fs=(Zt=de.changer)==null?void 0:Zt.displayName)==null?void 0:fs.charAt(0))||"U"})}),e.jsxs("span",{className:"text-[10px] text-gray-600",children:["By ",((Qe=de.changer)==null?void 0:Qe.displayName)||((Se=de.changer)==null?void 0:Se.email)||"Unknown User"]})]}),de.snapshotType==="PROPOSAL"&&de.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700",children:"Proposal Snapshot"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Budget: ₹",Number(de.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>k({data:de.snapshotData,type:"PROPOSAL",title:`Proposal (v${de.version})`}),children:[e.jsx(xt,{className:"w-3 h-3"}),"View Details"]})]}),de.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",de.snapshotData.comments]})]}),de.snapshotType==="INTERNAL_ORDER"&&de.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700 mb-1",children:"IO Block Snapshot:"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["IO Number: ",de.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Blocked Amount: ₹",Number(de.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),de.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-[10px] text-gray-600",children:["SAP Doc: ",de.snapshotData.sapDocumentNumber]})]}),de.snapshotType==="COMPLETION"&&de.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700",children:"Completion Snapshot"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Total: ₹",Number(de.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>k({data:de.snapshotData,type:"COMPLETION",title:`Completion (v${de.version})`}),children:[e.jsx(xt,{className:"w-3 h-3"}),"View Details"]})]}),de.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",de.snapshotData.comments]})]}),de.snapshotType==="APPROVE"&&de.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1",children:[de.snapshotData.action==="APPROVE"?"Approval":"Rejection"," Snapshot:"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["By: ",de.snapshotData.approverName||de.snapshotData.approverEmail||"Unknown"]}),de.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1",children:["Comments: ",de.snapshotData.comments.substring(0,100),de.snapshotData.comments.length>100?"...":""]}),de.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-[10px] text-red-600 mt-1",children:["Rejection Reason: ",de.snapshotData.rejectionReason.substring(0,100),de.snapshotData.rejectionReason.length>100?"...":""]})]}),de.snapshotType==="WORKFLOW"&&de.snapshotData&&de.snapshotData.comments&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700 mb-1",children:"Approval Comment:"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:[de.snapshotData.comments.substring(0,100),de.snapshotData.comments.length>100?"...":""]})]})]},Ut)})})]}),he&&(be==null?void 0:be.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:be.sla.deadline?pa(be.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${yt?"bg-gray-100 border-gray-300":(be.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(be.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(be.sla.percentageUsed||0)>=50?"bg-amber-50 border-amber-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",yt&&"(Paused)"]}),e.jsxs("div",{className:"space-y-2 text-xs mb-3",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time elapsed since assigned:"}),e.jsx("span",{className:"font-medium text-gray-900",children:be.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:[be.sla.elapsedText||"0 hours"," / ",Ot(z.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const de=be.sla.percentageUsed||0,Ut=()=>yt?"bg-gray-500":de>=100?"bg-red-600":de>=75?"bg-orange-500":de>=50?"bg-amber-500":"bg-green-600",Zt=()=>yt?"text-gray-600":de>=100?"text-red-600":de>=75?"text-orange-600":de>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(oa,{value:de,className:"h-3",indicatorClassName:Ut()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${Zt()}`,children:["Progress: ",Math.min(100,de),"% of TAT used"]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[be.sla.remainingText||"0 hours"," remaining"]})]})]})})(),be.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(xi,{className:"w-4 h-4"}),"Deadline Breached"]}),be.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(ss,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),(()=>{const de=z.levelName||z.level_name;return(de&&de.toLowerCase().includes("department lead")||z.title&&z.title.toLowerCase().includes("department lead"))&&z.status==="approved"&&z.ioDetails&&z.ioDetails.ioNumber&&e.jsxs("div",{className:"mt-3 p-3 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ls,{className:"w-4 h-4 text-blue-600"}),e.jsx("p",{className:"text-xs font-semibold text-blue-900 uppercase tracking-wide",children:"IO Organisation Details"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"IO Number:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:z.ioDetails.ioNumber})]}),z.ioDetails.blockedAmount!==void 0&&z.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:["₹",z.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),z.ioDetails.remainingBalance!==void 0&&z.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:["₹",z.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 ",z.ioDetails.organizedBy||z.approver||"N/A"," on"," ",z.ioDetails.organizedAt?Tr(z.ioDetails.organizedAt):z.approvedAt?Tr(z.approvedAt):"N/A"]})]})]})})(),z.step===6&&z.dmsDetails&&z.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(Pt,{className:"w-4 h-4 text-purple-600"}),e.jsx("p",{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"DMS Processing Details"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"DMS Number:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:z.dmsDetails.dmsNumber})]}),z.dmsDetails.dmsRemarks&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"DMS Remarks:"}),e.jsx("p",{className:"text-sm text-gray-900",children:z.dmsDetails.dmsRemarks})]}),z.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Pushed by ",z.dmsDetails.pushedBy," on"," ",Tr(z.dmsDetails.pushedAt)]})]})]}),(()=>{const de=N.find(Se=>(Se.step||Se.levelNumber||Se.level_number)===z.step),Ut=((de==null?void 0:de.approverEmail)||"").toLowerCase(),Zt=Ut&&Ne===Ut,fs=z.step===1||(de==null?void 0:de.levelName)&&de.levelName.toLowerCase().includes("dealer");return he&&(Zt||fs&&$e)})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[z.step===1&&($e||qa)&&e.jsxs(I,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{o(!0)},children:[e.jsx(Es,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),z.step===ft&&(a||_s)&&e.jsxs(I,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{d(!0)},children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const de=N.find(Se=>(Se.step||Se.levelNumber||Se.level_number)===z.step);if(!((de==null?void 0:de.levelName)||z.title||"").toLowerCase().includes("initiator action")||!(a||Ne===pe))return null;const Qe=async Se=>{var Wt,Rt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const os=t.requestId||t.id;await mh(os,Se,{reason:""}),K.success(`Action "${Se==="REVISE"?"Revision Requested":"Request Reopened"}" performed successfully`),se()}catch(os){console.error("Failed to perform initiator action:",os);const sn=((Rt=(Wt=os==null?void 0:os.response)==null?void 0:Wt.data)==null?void 0:Rt.message)||(os==null?void 0:os.message)||"Failed to perform action";K.error(sn)}};return e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:()=>Qe("REVISE"),children:[e.jsx(zt,{className:"w-4 h-4 mr-2"}),"Request Re-quotation"]}),e.jsxs(I,{variant:"outline",className:"border-blue-500 text-blue-600 hover:bg-blue-50",onClick:()=>Qe("REOPEN"),children:[e.jsx(px,{className:"w-4 h-4 mr-2"}),"Reopen"]})]})})(),(()=>{const de=N.find(Rt=>(Rt.levelName||"").toLowerCase().includes("department lead"));if(!(de&&z.step===(de.step||de.levelNumber||de.level_number)))return null;const Zt=((de==null?void 0:de.approverEmail)||"").toLowerCase();if(!(Zt&&Ne===Zt||te||ot))return null;const Qe=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),Se=(Qe==null?void 0:Qe.ioNumber)||(Qe==null?void 0:Qe.io_number)||(t==null?void 0:t.ioNumber)||"",Wt=Se&&Se.trim()!=="";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(I,{className:"bg-green-600 hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>{u(!0)},disabled:!Wt,children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Review and Approve"]}),!Wt&&e.jsx("p",{className:"text-xs text-amber-600",children:"Please add an IO number in the IO tab before approving this step."})]})})(),(()=>{const de=N.find(Se=>(Se.step||Se.levelNumber||Se.level_number)===z.step),Ut=((de==null?void 0:de.approverEmail)||"").toLowerCase(),Zt=$e&&Ut===ve,fs=((de==null?void 0:de.levelName)||z.title||"").toLowerCase(),Qe=fs.includes("dealer completion")||fs.includes("completion documents");return Zt&&Qe})()&&e.jsxs(I,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{x(!0)},children:[e.jsx(Es,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const de=N.find(Qe=>{const Se=(Qe.levelName||"").toLowerCase();return Se.includes("requestor claim")||Se.includes("requestor - claim")});if(!(de&&z.step===(de.step||de.levelNumber||de.level_number)))return null;const Zt=((de==null?void 0:de.approverEmail)||"").toLowerCase();return a||Zt&&Ne===Zt?e.jsxs(I,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{f(!0)},children:[e.jsx(Pt,{className:"w-4 h-4 mr-2"}),"Push to DMS"]}):null})(),z.step===8&&(()=>{var Se;const de=N.find(Wt=>(Wt.step||Wt.levelNumber||Wt.level_number)===8),Ut=((de==null?void 0:de.approverEmail)||"").toLowerCase(),Zt=Ut&&Ne===Ut,fs=((Se=s==null?void 0:s.role)==null?void 0:Se.toUpperCase())||"";return Zt||(fs==="FINANCE"||fs==="ADMIN")})()&&e.jsxs(I,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{b(!0)},children:[e.jsx(ls,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]}),(()=>{const de=N.find(Qe=>(Qe.step||Qe.levelNumber||Qe.level_number)===z.step),Zt=((de==null?void 0:de.levelName)||z.title||"").toLowerCase().includes("additional approver"),fs=z.step===1||z.step===ft||(()=>{const Qe=N.find(Se=>(Se.levelName||"").toLowerCase().includes("department lead"));return Qe&&z.step===(Qe.step||Qe.levelNumber||Qe.level_number)})()||(()=>{const Qe=N.find(sn=>(sn.step||sn.levelNumber||sn.level_number)===z.step),Se=((Qe==null?void 0:Qe.approverEmail)||"").toLowerCase(),Wt=$e&&Se===ve,Rt=((Qe==null?void 0:Qe.levelName)||z.title||"").toLowerCase(),os=Rt.includes("dealer completion")||Rt.includes("completion documents");return Wt&&os})()||(()=>{const Qe=N.find(Se=>{const Wt=(Se.levelName||"").toLowerCase();return Wt.includes("requestor claim")||Wt.includes("requestor - claim")});return Qe&&z.step===(Qe.step||Qe.levelNumber||Qe.level_number)})()||z.step===8;if(Zt||!fs){const Qe=(de==null?void 0:de.levelId)||(de==null?void 0:de.level_id);if(Qe){const Se=(de==null?void 0:de.levelName)||(de==null?void 0:de.level_name)||z.title||"Approval Level",Wt=(de==null?void 0:de.approverName)||(de==null?void 0:de.approver_name)||z.approver||"Approver";return e.jsxs(I,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{S({levelId:Qe,levelName:Se,approverName:Wt}),_(!0)},children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Review Request"]})}return e.jsxs(e.Fragment,{children:[e.jsxs(I,{className:"bg-green-600 hover:bg-green-700",onClick:async()=>{var Se,Wt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Rt=t.id||t.requestId;if(!Qe){K.error("Approval level not found");return}await mn(Rt,Qe,""),K.success("Request approved successfully"),se()}catch(Rt){console.error("Failed to approve:",Rt);const os=((Wt=(Se=Rt==null?void 0:Rt.response)==null?void 0:Se.data)==null?void 0:Wt.message)||(Rt==null?void 0:Rt.message)||"Failed to approve request. Please try again.";K.error(os)}},children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(I,{variant:"destructive",onClick:async()=>{var Se,Wt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Rt=t.id||t.requestId;if(!Qe){K.error("Approval level not found");return}const os=prompt("Please provide a reason for rejection:");if(os===null)return;await kr(Rt,Qe,"Request rejected",os),K.success("Request rejected successfully"),se()}catch(Rt){console.error("Failed to reject:",Rt);const os=((Wt=(Se=Rt==null?void 0:Rt.response)==null?void 0:Se.data)==null?void 0:Wt.message)||(Rt==null?void 0:Rt.message)||"Failed to reject request. Please try again.";K.error(os)}},children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),z.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",Tr(z.approvedAt)]})]})]})},Ee)})})]})]}),e.jsx(GS,{isOpen:l,onClose:()=>o(!1),onSubmit:_e,dealerName:as,activityName:Ft,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),previousProposalData:(Mt=j==null?void 0:j.find(z=>z.snapshotType==="PROPOSAL"))==null?void 0:Mt.snapshotData,documentPolicy:i}),e.jsx(XS,{isOpen:c,onClose:()=>{d(!1)},onApprove:Fe,onReject:ze,onRequestRevision:Le,proposalData:Yt,dealerName:as,activityName:Ft,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const z=(j==null?void 0:j.filter(Ee=>Ee.snapshotType==="PROPOSAL"))||[];return z.length>1?z[1].snapshotData:null})()}),e.jsx(KS,{isOpen:m,onClose:()=>u(!1),onApprove:Je,onReject:ws,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((hs=t==null?void 0:t.internalOrder)==null?void 0:hs.ioNumber)||((zs=t==null?void 0:t.internalOrder)==null?void 0:zs.io_number)||((ir=t==null?void 0:t.internal_order)==null?void 0:ir.ioNumber)||((lr=t==null?void 0:t.internal_order)==null?void 0:lr.io_number)||void 0,preFilledBlockedAmount:((da=t==null?void 0:t.internalOrder)==null?void 0:da.ioBlockedAmount)||((vt=t==null?void 0:t.internalOrder)==null?void 0:vt.io_blocked_amount)||((ps=t==null?void 0:t.internal_order)==null?void 0:ps.ioBlockedAmount)||((Ls=t==null?void 0:t.internal_order)==null?void 0:Ls.io_blocked_amount)||void 0,preFilledRemainingBalance:((ta=t==null?void 0:t.internalOrder)==null?void 0:ta.ioRemainingBalance)||((Ar=t==null?void 0:t.internalOrder)==null?void 0:Ar.io_remaining_balance)||((ma=t==null?void 0:t.internal_order)==null?void 0:ma.ioRemainingBalance)||((Ba=t==null?void 0:t.internal_order)==null?void 0:Ba.io_remaining_balance)||void 0}),e.jsx(WS,{isOpen:h,onClose:()=>x(!1),onSubmit:Be,dealerName:as,activityName:Ft,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i}),e.jsx(YS,{isOpen:g,onClose:()=>f(!1),onPush:tt,completionDetails:{activityCompletionDate:((qr=t==null?void 0:t.completionDetails)==null?void 0:qr.activityCompletionDate)||((en=t==null?void 0:t.completionDetails)==null?void 0:en.activity_completion_date),numberOfParticipants:((tn=t==null?void 0:t.completionDetails)==null?void 0:tn.numberOfParticipants)||((Pc=t==null?void 0:t.completionDetails)==null?void 0:Pc.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((Ic=t==null?void 0:t.completionDetails)==null?void 0:Ic.closedExpenses)||((Ec=t==null?void 0:t.completionDetails)==null?void 0:Ec.closed_expenses),totalClosedExpenses:((Fc=t==null?void 0:t.budgetTracking)==null?void 0:Fc.closedExpenses)||((Mc=t==null?void 0:t.budgetTracking)==null?void 0:Mc.closed_expenses)||((_c=t==null?void 0:t.completionDetails)==null?void 0:_c.totalClosedExpenses)||((Lc=t==null?void 0:t.completionDetails)==null?void 0:Lc.total_closed_expenses),completionDescription:((Oc=t==null?void 0:t.completionDetails)==null?void 0:Oc.completionDescription)||(($c=t==null?void 0:t.completionDetails)==null?void 0:$c.completion_description)},ioDetails:{ioNumber:((Uc=t==null?void 0:t.internalOrder)==null?void 0:Uc.ioNumber)||((Bc=t==null?void 0:t.internalOrder)==null?void 0:Bc.io_number)||((Vc=t==null?void 0:t.internal_order)==null?void 0:Vc.ioNumber)||((zc=t==null?void 0:t.internal_order)==null?void 0:zc.io_number),blockedAmount:((Hc=t==null?void 0:t.internalOrder)==null?void 0:Hc.ioBlockedAmount)||((Wc=t==null?void 0:t.internalOrder)==null?void 0:Wc.io_blocked_amount)||((Gc=t==null?void 0:t.internal_order)==null?void 0:Gc.ioBlockedAmount)||((Kc=t==null?void 0:t.internal_order)==null?void 0:Kc.io_blocked_amount),availableBalance:((Yc=t==null?void 0:t.internalOrder)==null?void 0:Yc.ioAvailableBalance)||((Zc=t==null?void 0:t.internalOrder)==null?void 0:Zc.io_available_balance)||((Xc=t==null?void 0:t.internal_order)==null?void 0:Xc.ioAvailableBalance)||((Qc=t==null?void 0:t.internal_order)==null?void 0:Qc.io_available_balance),remainingBalance:((Jc=t==null?void 0:t.internalOrder)==null?void 0:Jc.ioRemainingBalance)||((qc=t==null?void 0:t.internalOrder)==null?void 0:qc.io_remaining_balance)||((ed=t==null?void 0:t.internal_order)==null?void 0:ed.ioRemainingBalance)||((td=t==null?void 0:t.internal_order)==null?void 0:td.io_remaining_balance)},completionDocuments:st,requestTitle:t==null?void 0:t.title,requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.request_number)||(t==null?void 0:t.id)}),e.jsx(HS,{isOpen:y,onClose:()=>b(!1),onDownload:async()=>{K.info("Download functionality will be implemented")},onSendToDealer:async()=>{var z,Ee;try{const ge=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!ge){K.error("Request ID not found");return}await rT(ge),K.success("Credit note sent to dealer successfully. Step 8 has been approved."),n&&n()}catch(ge){console.error("Failed to send credit note to dealer:",ge);const le=((Ee=(z=ge==null?void 0:ge.response)==null?void 0:z.data)==null?void 0:Ee.message)||(ge==null?void 0:ge.message)||"Failed to send credit note to dealer";K.error(le)}},creditNoteData:{creditNoteNumber:((sd=t==null?void 0:t.creditNote)==null?void 0:sd.creditNoteNumber)||((ad=t==null?void 0:t.creditNote)==null?void 0:ad.credit_note_number)||((nd=(rd=t==null?void 0:t.claimDetails)==null?void 0:rd.creditNote)==null?void 0:nd.creditNoteNumber)||((id=t==null?void 0:t.claimDetails)==null?void 0:id.creditNoteNumber)||((ld=t==null?void 0:t.claimDetails)==null?void 0:ld.credit_note_number),creditNoteDate:((od=t==null?void 0:t.creditNote)==null?void 0:od.creditNoteDate)||((cd=t==null?void 0:t.creditNote)==null?void 0:cd.credit_note_date)||((md=(dd=t==null?void 0:t.claimDetails)==null?void 0:dd.creditNote)==null?void 0:md.creditNoteDate)||((ud=t==null?void 0:t.claimDetails)==null?void 0:ud.creditNoteDate)||((xd=t==null?void 0:t.claimDetails)==null?void 0:xd.credit_note_date),creditNoteAmount:(hd=t==null?void 0:t.creditNote)!=null&&hd.creditNoteAmount?Number((pd=t==null?void 0:t.creditNote)==null?void 0:pd.creditNoteAmount):(gd=t==null?void 0:t.creditNote)!=null&&gd.credit_note_amount?Number((fd=t==null?void 0:t.creditNote)==null?void 0:fd.credit_note_amount):(bd=(yd=t==null?void 0:t.claimDetails)==null?void 0:yd.creditNote)!=null&&bd.creditNoteAmount?Number((jd=(vd=t==null?void 0:t.claimDetails)==null?void 0:vd.creditNote)==null?void 0:jd.creditNoteAmount):(Nd=t==null?void 0:t.claimDetails)!=null&&Nd.creditNoteAmount?Number((wd=t==null?void 0:t.claimDetails)==null?void 0:wd.creditNoteAmount):(Cd=t==null?void 0:t.claimDetails)!=null&&Cd.credit_note_amount?Number((Ad=t==null?void 0:t.claimDetails)==null?void 0:Ad.credit_note_amount):void 0,status:((Sd=t==null?void 0:t.creditNote)==null?void 0:Sd.status)||((kd=(Td=t==null?void 0:t.claimDetails)==null?void 0:Td.creditNote)==null?void 0:kd.status)||((Rd=t==null?void 0:t.creditNote)!=null&&Rd.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((Dd=t==null?void 0:t.claimDetails)==null?void 0:Dd.dealerName)||((Pd=t==null?void 0:t.claimDetails)==null?void 0:Pd.dealer_name),dealerCode:((Id=t==null?void 0:t.claimDetails)==null?void 0:Id.dealerCode)||((Ed=t==null?void 0:t.claimDetails)==null?void 0:Ed.dealer_code),dealerEmail:((Fd=t==null?void 0:t.claimDetails)==null?void 0:Fd.dealerEmail)||((Md=t==null?void 0:t.claimDetails)==null?void 0:Md.dealer_email)},activityName:((_d=t==null?void 0:t.claimDetails)==null?void 0:_d.activityName)||((Ld=t==null?void 0:t.claimDetails)==null?void 0:Ld.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(ZS,{isOpen:v,onClose:()=>{A(!1),T(null)},stepNumber:(w==null?void 0:w.stepNumber)||4,stepName:(w==null?void 0:w.stepName)||"Activity Creation",requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.id)||(t==null?void 0:t.request_number),recipientEmail:"system@royalenfield.com"}),D&&e.jsx(zS,{isOpen:C,onClose:()=>{_(!1),S(null)},onApprove:async z=>{var Ee,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const le=t.id||t.requestId,fe=D.levelId;if(!fe){K.error("Approval level not found");return}await mn(le,fe,z),K.success("Request approved successfully"),se(),_(!1),S(null)}catch(le){console.error("Failed to approve:",le);const fe=((ge=(Ee=le==null?void 0:le.response)==null?void 0:Ee.data)==null?void 0:ge.message)||(le==null?void 0:le.message)||"Failed to approve request. Please try again.";throw K.error(fe),le}},onReject:async z=>{var Ee,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const le=t.id||t.requestId,fe=D.levelId;if(!fe){K.error("Approval level not found");return}await kr(le,fe,"Request rejected",z),K.success("Request rejected successfully"),se(),_(!1),S(null)}catch(le){console.error("Failed to reject:",le);const fe=((ge=(Ee=le==null?void 0:le.response)==null?void 0:Ee.data)==null?void 0:ge.message)||(le==null?void 0:le.message)||"Failed to reject request. Please try again.";throw K.error(fe),le}},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}),j&&j.length>0&&e.jsxs(J,{className:"mt-6 border-amber-100 bg-amber-50/30",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ue,{className:"text-sm font-bold flex items-center gap-2 text-amber-900",children:[e.jsx(Pt,{className:"w-4 h-4"}),"Revision History & Audit Trail"]}),e.jsx(I,{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(Te,{className:"text-xs text-amber-700",children:"Records of all revisions and actions taken on this request"})]}),R&&e.jsx(q,{children:e.jsx("div",{className:"space-y-4",children:j.map((z,Ee)=>{var ge,le,fe,he;return e.jsxs("div",{className:"relative pl-6 pb-4 border-l-2 border-amber-200 last:border-0 last:pb-0",children:[e.jsx("div",{className:"absolute left-[-9px] top-0 w-4 h-4 rounded-full bg-amber-500 border-2 border-white shadow-sm"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs font-bold text-amber-900",children:["Version ",z.version]}),z.snapshotType&&e.jsx(ie,{className:"bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0",children:z.snapshotType}),z.levelNumber&&e.jsxs(ie,{className:"bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0",children:["Step ",z.levelNumber]})]}),e.jsx("span",{className:"text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full",children:Tr(z.createdAt)})]}),e.jsx("p",{className:"text-xs font-medium text-gray-800",children:z.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:((le=(ge=z.changer)==null?void 0:ge.displayName)==null?void 0:le.charAt(0))||"U"})}),e.jsxs("span",{className:"text-xs text-gray-500",children:["By ",((fe=z.changer)==null?void 0:fe.displayName)||((he=z.changer)==null?void 0:he.email)||"Unknown User"]})]}),z.snapshotType==="PROPOSAL"&&z.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:"}),z.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(I,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-small flex items-center gap-1",onClick:()=>k({data:z.snapshotData,type:"PROPOSAL",title:`Historical Proposal (Version ${z.version})`}),children:["View Details",e.jsx(xt,{className:"w-2 h-2"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Budget: ₹",Number(z.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),z.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",z.snapshotData.comments.substring(0,80),z.snapshotData.comments.length>80?"...":""]})]}),z.snapshotType==="COMPLETION"&&z.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:"}),z.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(I,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-medium flex items-center gap-1",onClick:()=>k({data:z.snapshotData,type:"COMPLETION",title:`Historical Completion (Version ${z.version})`}),children:["View Details",e.jsx(xt,{className:"w-3 h-3"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Total Expenses: ₹",Number(z.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),z.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",z.snapshotData.comments.substring(0,80),z.snapshotData.comments.length>80?"...":""]})]}),z.snapshotType==="INTERNAL_ORDER"&&z.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: ",z.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-gray-600",children:["Blocked: ₹",Number(z.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),z.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-gray-600",children:["SAP Doc: ",z.snapshotData.sapDocumentNumber]})]}),z.snapshotType==="APPROVE"&&z.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:[z.snapshotData.action==="APPROVE"?"Approval":"Rejection",":"]}),e.jsxs("p",{className:"text-gray-600",children:["By: ",z.snapshotData.approverName||z.snapshotData.approverEmail||"Unknown"]}),z.snapshotData.levelName&&e.jsxs("p",{className:"text-gray-600",children:["Level: ",z.snapshotData.levelName]}),z.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",z.snapshotData.comments.substring(0,80),z.snapshotData.comments.length>80?"...":""]}),z.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-red-600 mt-1",children:["Rejection Reason: ",z.snapshotData.rejectionReason.substring(0,80),z.snapshotData.rejectionReason.length>80?"...":""]})]}),z.snapshotType==="WORKFLOW"&&z.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: ",z.snapshotData.status||"N/A"]}),z.snapshotData.currentLevel&&e.jsxs("p",{className:"text-gray-600",children:["Current Level: ",z.snapshotData.currentLevel]})]})]})]},z.historyId||Ee)})})})]}),e.jsx(QS,{isOpen:!!B,onClose:()=>k(null),snapshot:B==null?void 0:B.data,type:(B==null?void 0:B.type)||"PROPOSAL",title:B==null?void 0:B.title})]})}function mT({request:t,apiRequest:s,onRefresh:a}){const{user:r}=Qt(),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)||"",u=(i==null?void 0:i.organizer)||null,h=(s==null?void 0:s.proposalDetails)||{},x=Number((h==null?void 0:h.totalEstimatedBudget)||(h==null?void 0:h.total_estimated_budget)||0),[g,f]=p.useState(l),[y,b]=p.useState(!1),[v,A]=p.useState(null),[w,T]=p.useState(""),[C,_]=p.useState(null),[D,S]=p.useState(!1);p.useEffect(()=>{if(i&&l){const R=Number(c)||0,O=(u==null?void 0:u.displayName)||(u==null?void 0:u.display_name)||(u==null?void 0:u.name)||(u!=null&&u.firstName&&(u!=null&&u.lastName)?`${u.firstName} ${u.lastName}`.trim():null)||(u==null?void 0:u.email)||"Unknown User";if(f(l),o>0){const F=Number(o)||0,M=Number(d)||0,B=R-F;Math.abs(M-B)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:R,blockedAmount:F,expectedRemaining:B,backendRemaining:M,difference:M-B}),_({ioNumber:l,blockedAmount:F,availableBalance:R,remainingBalance:M,blockedDate:i.organizedAt||i.organized_at||new Date().toISOString(),blockedBy:O,sapDocumentNumber:m,status:i.status==="BLOCKED"?"blocked":i.status==="RELEASED"?"released":"blocked"}),R>0&&A(R)}}},[i,l,o,c,d,m,u]);const j=async()=>{var R,O;if(!g.trim()){K.error("Please enter an IO number");return}if(!n){K.error("Request ID not found");return}b(!0);try{const F=await sT(n,g.trim());F.isValid&&F.availableBalance>0?(A(F.availableBalance),x>0?T(String(x)):T(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"),A(null),T(""))}catch(F){console.error("Failed to fetch IO budget:",F);const M=((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(M),A(null)}finally{b(!1)}},P=async()=>{var F,M;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(w);if(!w||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(x>0){const B=parseFloat(x.toFixed(2));if(Math.abs(O-B)>.01){K.error(`Amount to block must be exactly equal to the estimated budget (₹${B.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})})`);return}}S(!0);try{const B=parseFloat(v.toFixed(2)),k=parseFloat((B-O).toFixed(2)),N={ioNumber:g.trim(),ioAvailableBalance:B,ioBlockedAmount:O,ioRemainingBalance:k};await bg(n,N);const U=await qS(n),$=(U==null?void 0:U.internalOrder)||(U==null?void 0:U.internal_order);if($){const L=Number($.ioBlockedAmount||$.io_blocked_amount||O),se=Number($.ioRemainingBalance||$.io_remaining_balance||0),G=v-L;Math.abs(L-O)>.01&&console.warn("[IOTab] ⚠️ Amount mismatch! Sent:",O,"Saved:",L),Math.abs(se-G)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:v,blockedAmount:L,expectedRemaining:G,backendRemaining:se,difference:se-G});const oe=r,Z=(oe==null?void 0:oe.displayName)||(oe==null?void 0:oe.display_name)||(oe==null?void 0:oe.name)||(oe!=null&&oe.firstName&&(oe!=null&&oe.lastName)?`${oe.firstName} ${oe.lastName}`.trim():null)||(oe==null?void 0:oe.email)||"Current User",E={ioNumber:$.ioNumber||$.io_number||g,blockedAmount:L,availableBalance:v,remainingBalance:se,blockedDate:$.organizedAt||$.organized_at||new Date().toISOString(),blockedBy:Z,sapDocumentNumber:$.sapDocumentNumber||$.sap_document_number||"",status:"blocked"};_(E),T(""),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(B){console.error("Failed to block IO budget:",B);const k=((M=(F=B==null?void 0:B.response)==null?void 0:F.data)==null?void 0:M.message)||(B==null?void 0:B.message)||"Failed to block IO budget in SAP";K.error(k)}finally{S(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(J,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Ea,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(Te,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(q,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ie,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:g,onChange:R=>f(R.target.value),disabled:y||!!C,className:"flex-1"}),e.jsxs(I,{onClick:j,disabled:!g.trim()||y||!!C,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),y?"Fetching...":"Fetch Amount"]})]})]}),!v&&!C&&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&&!C&&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(Pe,{className:"w-8 h-8 text-green-600"})]}),e.jsxs("div",{className:"mt-3 pt-3 border-t border-green-200",children:[e.jsxs("p",{className:"text-xs text-gray-600",children:[e.jsx("strong",{children:"IO Number:"})," ",g]}),e.jsxs("p",{className:"text-xs text-gray-600 mt-1",children:[e.jsx("strong",{children:"Fetched from:"})," SAP System"]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{htmlFor:"blockAmount",children:"Amount to Block *"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",children:"₹"}),e.jsx(Ie,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:w,onChange:R=>T(R.target.value),className:"pl-8"})]}),x>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:["₹",x.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs(I,{onClick:P,disabled:D||!w||parseFloat(w)<=0||parseFloat(w)>v||x>0&&Math.abs(parseFloat(w)-x)>.01,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Ht,{className:"w-4 h-4 mr-2"}),D?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(J,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(Te,{children:"Details of IO blocked in SAP system"})]}),e.jsx(q,{children:C?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(Pe,{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:C.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:C.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:["₹",C.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:["₹",C.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:["₹",C.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:C.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(C.blockedDate).toLocaleString("en-IN",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",hour12:!0})})]}),e.jsxs("div",{className:"p-4 bg-gray-50",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Status"}),e.jsxs(ie,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Pe,{className:"w-3 h-3 mr-1"}),"Blocked"]})]})]})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ea,{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 uT(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 xT(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 $s=[{level:1,name:"Dealer Proposal Submission",description:"Dealer submits proposal documents",defaultTat:72,isAuto:!1,approverType:"dealer"},{level:2,name:"Requestor Evaluation",description:"Initiator evaluates dealer proposal",defaultTat:48,isAuto:!1,approverType:"initiator"},{level:3,name:"Department Lead Approval",description:"Department lead approves and blocks IO budget",defaultTat:72,isAuto:!1,approverType:"manual"},{level:4,name:"Dealer Completion Documents",description:"Dealer submits completion documents",defaultTat:120,isAuto:!1,approverType:"dealer"},{level:5,name:"Requestor Claim Approval",description:"Initiator approves completion",defaultTat:48,isAuto:!1,approverType:"initiator"}];function hT({formData:t,updateFormData:s,onValidationError:a,currentUserEmail:r="",currentUserId:n="",currentUserName:i="",onValidate:l,maxApprovalLevels:o,onPolicyViolation:c}){const{userSearchResults:d,userSearchLoading:m,searchUsersForIndex:u,clearSearchForIndex:h}=qp(),[x,g]=p.useState(!1),[f,y]=p.useState(""),[b,v]=p.useState(24),[A,w]=p.useState("hours"),[T,C]=p.useState(3),[_,D]=p.useState([]),[S,j]=p.useState(!1),[P,R]=p.useState(null),O=p.useRef(null),F=()=>{const E=t.approvers||[],V=[];return $s.forEach(H=>{if(H.isAuto||H.approverType==="dealer"||H.approverType==="initiator")return;const Q=E.find(Y=>Y.level===H.level);(!Q||!Q.email||!Q.userId||!Q.tat)&&V.push(`${H.name}`)}),{isValid:V.length===0,missingSteps:V}};p.useEffect(()=>{if(l){const E=F();l(E.isValid)}},[t.approvers]),p.useEffect(()=>{const E=t.approvers||[];if(E.length>0){const V=[],H=E.filter(Y=>Y.isAdditional);$s.forEach(Y=>{const W=E.find(ce=>ce.originalStepLevel===Y.level||!ce.originalStepLevel&&!ce.isAdditional&&ce.level===Y.level);if(W)V.push(W);else if(Y.isAuto){const ce=Y.level===8?"finance@royalenfield.com":"system@royalenfield.com",xe=Y.level===8?"System/Finance":"System";V.push({email:ce,name:xe,level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level})}else Y.approverType==="dealer"?V.push({email:t.dealerEmail||"",name:t.dealerName||"",level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level}):Y.approverType==="initiator"?V.push({email:r||"",name:i||r||"User",userId:n,level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level}):V.push({email:"",name:"",level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level})}),H.forEach(Y=>{V.push(Y)}),V.sort((Y,W)=>Y.level-W.level),JSON.stringify(E.map(Y=>({level:Y.level,originalStepLevel:Y.originalStepLevel})))!==JSON.stringify(V.map(Y=>({level:Y.level,originalStepLevel:Y.originalStepLevel})))&&s("approvers",V)}else{const V=[];$s.forEach(H=>{H.isAuto||(H.approverType==="dealer"?V.push({email:t.dealerEmail||"",name:t.dealerName||"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}):H.approverType==="initiator"?V.push({email:r||"",name:i||r||"User",userId:n,level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}):V.push({email:"",name:"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}))}),s("approvers",V)}},[t.dealerEmail,t.dealerName,r,n,i]);const M=(E,V)=>{const H=[...t.approvers||[]],Q=H.findIndex(Y=>Y.originalStepLevel===E||!Y.originalStepLevel&&Y.level===E&&!Y.isAdditional);if(Q===-1){const Y=$s.find(W=>W.level===E);H.push({email:V,name:"",level:E,tat:(Y==null?void 0:Y.defaultTat)||48,tatType:"hours",originalStepLevel:E})}else{const Y=H[Q];if(Y){const W=Y.email;H[Q]={...Y,email:V,name:V!==W?"":Y.name,userId:V!==W?void 0:Y.userId}}}if(s("approvers",H),!V||!V.startsWith("@")||V.length<2){h(E-1);return}u(E-1,V,10)},B=async(E,V)=>{var H,Q;try{const Y=$s.find(ae=>ae.level===E);if(Y&&!Y.isAuto&&Y.approverType!=="initiator"&&((H=V.email)==null?void 0:H.toLowerCase())===(r==null?void 0:r.toLowerCase())){K.error(`You cannot assign yourself as ${Y.name} approver.`),a&&a({type:"self-assign",email:V.email,message:`You cannot assign yourself as ${Y.name} approver.`});return}if((t.approvers||[]).some(ae=>{var ye,Ne;return ae.level!==E&&(ae.userId===V.userId||((ye=ae.email)==null?void 0:ye.toLowerCase())===((Ne=V.email)==null?void 0:Ne.toLowerCase()))})){K.error("This user is already assigned to another step."),a&&a({type:"error",email:V.email,message:"This user is already assigned to another step."});return}const xe=await la({userId:V.userId,email:V.email,displayName:V.displayName,firstName:V.firstName,lastName:V.lastName,department:V.department,phone:V.phone,mobilePhone:V.mobilePhone,designation:V.designation,jobTitle:V.jobTitle,manager:V.manager,employeeId:V.employeeId,employeeNumber:V.employeeNumber,secondEmail:V.secondEmail,location:V.location}),ke=[...t.approvers||[]],Ae=ke.findIndex(ae=>ae.originalStepLevel===E||!ae.originalStepLevel&&ae.level===E&&!ae.isAdditional);if(Ae===-1){const ae=$s.find(ye=>ye.level===E);ke.push({email:V.email,name:V.displayName||[V.firstName,V.lastName].filter(Boolean).join(" "),userId:xe.userId,level:E,tat:(ae==null?void 0:ae.defaultTat)||48,tatType:"hours",originalStepLevel:E})}else{const ae=ke[Ae];ae&&(ke[Ae]={...ae,email:V.email,name:V.displayName||[V.firstName,V.lastName].filter(Boolean).join(" "),userId:xe.userId,originalStepLevel:ae.originalStepLevel||E})}s("approvers",ke),h(E-1),K.success(`Approver for ${(Q=$s.find(ae=>ae.level===E))==null?void 0:Q.name} selected successfully.`)}catch(Y){console.error("Failed to ensure user exists:",Y),K.error("Failed to validate user. Please try again."),a&&a({type:"error",email:V.email,message:"Failed to validate user. Please try again."})}},k=(E,V)=>{const H=[...t.approvers||[]],Q=H.findIndex(Y=>Y.originalStepLevel===E||!Y.originalStepLevel&&Y.level===E&&!Y.isAdditional);if(Q!==-1){const Y=H[Q];Y&&(H[Q]={...Y,tat:V},s("approvers",H))}},N=(E,V)=>{const H=[...t.approvers||[]],Q=H.findIndex(Y=>Y.originalStepLevel===E||!Y.originalStepLevel&&Y.level===E&&!Y.isAdditional);if(Q!==-1){const Y=H[Q];Y&&(H[Q]={...Y,tatType:V,tat:""},s("approvers",H))}},U=E=>{if(y(E),P&&P.email.toLowerCase()!==E.toLowerCase()&&R(null),O.current&&clearTimeout(O.current),!E||!E.startsWith("@")||E.length<2){D([]),j(!1);return}j(!0),O.current=setTimeout(async()=>{var V;try{const H=E.slice(1),Y=((V=(await ca(H,10)).data)==null?void 0:V.data)||[];D(Y)}catch(H){console.error("Search failed:",H),D([])}finally{j(!1)}},300)},$=async E=>{try{await la({userId:E.userId,email:E.email,displayName:E.displayName,firstName:E.firstName,lastName:E.lastName,department:E.department,phone:E.phone,mobilePhone:E.mobilePhone,designation:E.designation,jobTitle:E.jobTitle,manager:E.manager,employeeId:E.employeeId,employeeNumber:E.employeeNumber,secondEmail:E.secondEmail,location:E.location}),y(E.email),R(E),D([]),j(!1)}catch(V){console.error("Failed to ensure user exists:",V),K.error("Failed to verify user. Please try again.")}},L=async()=>{var ye,Ne;const E=f.trim().toLowerCase();if(!E){K.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)){K.error("Please enter a valid email address");return}const H=typeof b=="string"?Number(b):b;if(!H||H<=0||isNaN(H)){K.error("Please enter valid TAT (minimum 1)");return}const Q=A==="days"?30:720;if((A==="days"?H*24:H)>720){K.error(`TAT cannot exceed ${Q} ${A==="days"?"days":"hours"}`);return}const W=$s.find(ve=>ve.name==="Requestor Claim Approval");if(W&&T>=W.level){K.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if(E===(r==null?void 0:r.toLowerCase())){K.error("You cannot add yourself as an additional approver.");return}const ce=t.approvers||[];if(ce.some(ve=>{var $e;return ve.userId&&(P==null?void 0:P.userId)&&ve.userId===P.userId||(($e=ve.email)==null?void 0:$e.toLowerCase())===E})){K.error("This user is already assigned as an approver.");return}const ke=ce.find(ve=>ve.originalStepLevel===T||!ve.originalStepLevel&&!ve.isAdditional&&ve.level===T),ae=(ke?ke.level:T)+1;if(o){const $e=new Set(ce.map(re=>re.level)).size+1;if($e>o){const re=[{type:"max_approval_levels",message:`Adding this approver would create ${$e} approval levels, which exceeds the maximum allowed (${o}). Please remove some approvers before adding a new one.`,currentValue:$e,maxValue:o}];c?c(re):K.error(((ye=re[0])==null?void 0:ye.message)||"Maximum approval levels exceeded");return}}if(!P||P.email.toLowerCase()!==E)try{const $e=((Ne=(await ca(E,1)).data)==null?void 0:Ne.data)||[];if($e.length===0){K.error("User not found in organization directory. Please use @ to search for users.");return}const re=$e[0];await la({userId:re.userId,email:re.email,displayName:re.displayName,firstName:re.firstName,lastName:re.lastName,department:re.department,phone:re.phone,mobilePhone:re.mobilePhone,designation:re.designation,jobTitle:re.jobTitle,manager:re.manager,employeeId:re.employeeId,employeeNumber:re.employeeNumber,secondEmail:re.secondEmail,location:re.location});const Me={email:re.email,name:re.displayName||[re.firstName,re.lastName].filter(Boolean).join(" "),userId:re.userId,level:ae,tat:typeof b=="string"?Number(b):b,tatType:A,isAdditional:!0,insertAfterLevel:T,stepName:`Additional Approver - ${re.displayName||re.email}`},ot=ce.map(pe=>pe.level>=ae?{...pe,level:pe.level+1}:pe);ot.push(Me),ot.sort((pe,Oe)=>pe.level-Oe.level),s("approvers",ot),K.success("Additional approver added and subsequent steps shifted")}catch(ve){console.error("Failed to validate approver:",ve),K.error("Failed to validate user. Please try again.");return}else{const ve={email:P.email,name:P.displayName||[P.firstName,P.lastName].filter(Boolean).join(" "),userId:P.userId,level:ae,tat:b,tatType:A,isAdditional:!0,insertAfterLevel:T,stepName:`Additional Approver - ${P.displayName||P.email}`},$e=ce.map(re=>re.level>=ae?{...re,level:re.level+1}:re);$e.push(ve),$e.sort((re,Me)=>re.level-Me.level),s("approvers",$e),K.success("Additional approver added and subsequent steps shifted")}y(""),v(24),w("hours"),C(3),R(null),D([]),g(!1)},se=E=>{const V=[...t.approvers||[]];if(!V.find(W=>W.level===E))return;const Y=V.filter(W=>W.level!==E).map(W=>W.level>E&&!W.isAdditional?{...W,level:W.level-1}:W);Y.sort((W,ce)=>W.level-ce.level),s("approvers",Y),K.success("Additional approver removed and subsequent steps shifted back")},G=()=>[...t.approvers||[]].sort((V,H)=>V.level-H.level),oe=t.approvers||[],Z=G();return e.jsxs(ms.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(Bt,{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(J,{className:"border-2 border-blue-200 bg-blue-50",children:e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(Wr,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsxs(Te,{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 E=t.approvers||[],H=new Set(E.map(Q=>Q.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]})]})]})}),e.jsxs(J,{className:"border-2",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(ds,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx(Te,{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(q,{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 E=t.approvers||[],H=new Set(E.map(Q=>Q.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]}),e.jsxs(I,{type:"button",variant:"outline",onClick:()=>g(!0),className:"flex items-center gap-2",children:[e.jsx(us,{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(Lt,{className:"w-4 h-4 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-blue-900 text-sm",children:"Request Initiator"}),e.jsx(ie,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-xs text-blue-700",children:"Creates and submits the request"})]})]})}),(()=>{const E=Z.filter(H=>H.isAdditional&&H.insertAfterLevel===0);let V=E.length;return $s.filter(H=>!H.isAuto).map((H,Q,Y)=>{var ye,Ne;const W=oe.find(ve=>ve.originalStepLevel===H.level||!ve.originalStepLevel&&ve.level===H.level&&!ve.isAdditional)||{email:"",name:"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level},ce=Q===Y.length-1,xe=H.isAuto||H.approverType==="dealer"||H.approverType==="initiator",ke=!H.isAuto,Ae=Z.filter(ve=>ve.isAdditional&&ve.insertAfterLevel===H.level).sort((ve,$e)=>ve.level-$e.level),ae=V+1;return V++,V+=Ae.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"})}),Q===0&&E.map((ve,$e)=>{const re=$e+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:re})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:"Additional Approver"}),e.jsx(ie,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:()=>se(ve.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(gt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:ve.name||ve.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",ve.email]}),e.jsxs("div",{children:["TAT: ",ve.tat," ",ve.tatType]})]})]})]})})]},`additional-${ve.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${W.email&&W.userId?"border-green-200 bg-green-50":xe?"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 ${W.email&&W.userId?"bg-green-600":xe?"bg-blue-600":"bg-gray-400"}`,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:H.name}),ce&&e.jsx(ie,{variant:"destructive",className:"text-xs",children:"FINAL"}),xe&&e.jsx(ie,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:H.description}),ke&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs(ne,{htmlFor:`approver-${H.level}`,className:"text-xs font-medium",children:["Email Address ",!xe&&"*"]}),W.email&&W.userId&&e.jsxs(ie,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Pe,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ie,{id:`approver-${H.level}`,type:"text",placeholder:xe?W.email:"@approver@royalenfield.com",value:W.email||"",onChange:ve=>{const $e=ve.target.value;xe||M(H.level,$e)},disabled:xe||H.isAuto,className:"h-9 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full text-sm"}),!xe&&!H.isAuto&&(m[H.level-1]||(((ye=d[H.level-1])==null?void 0:ye.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:(Ne=d[H.level-1])==null?void 0:Ne.map(ve=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>B(H.level,ve),children:[e.jsx("div",{className:"font-medium text-gray-900",children:ve.displayName||ve.email}),e.jsx("div",{className:"text-xs text-gray-600",children:ve.email}),ve.department&&e.jsx("div",{className:"text-xs text-gray-500",children:ve.department})]},ve.userId))})})]}),W.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:W.name})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:`tat-${H.level}`,className:"text-xs font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ie,{id:`tat-${H.level}`,type:"number",placeholder:W.tatType==="days"?"7":"24",min:"1",max:W.tatType==="days"?"30":"720",value:W.tat||"",onChange:ve=>k(H.level,parseInt(ve.target.value)||""),disabled:H.isAuto,className:"h-9 border-2 border-gray-300 focus:border-blue-500 flex-1 text-sm"}),e.jsxs(He,{value:W.tatType||"hours",onValueChange:ve=>N(H.level,ve),disabled:H.isAuto,children:[e.jsx(Ge,{className:"w-20 h-9 border-2 border-gray-300 text-sm",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"hours",children:"Hours"}),e.jsx(X,{value:"days",children:"Days"})]})]})]})]})]})]})]})}),Ae.map((ve,$e)=>{const re=ae+$e+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:re})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:ve.stepName||"Additional Approver"}),e.jsx(ie,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),ve.email&&ve.userId&&e.jsxs(ie,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Pe,{className:"w-3 h-3 mr-1"}),"Verified"]}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:()=>se(ve.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(gt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:ve.name||ve.email||"No approver assigned"}),ve.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",ve.email]}),ve.tat&&e.jsxs("div",{children:["TAT: ",ve.tat," ",ve.tatType]})]})]})]})})]},`additional-${ve.level}`)})]},H.level)})})()]})]}),e.jsxs(J,{className:"border-2",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(q,{children:e.jsx("div",{className:"space-y-3",children:Z.map(E=>{const V=E.originalStepLevel?$s.find(W=>W.level===E.originalStepLevel):$s.find(W=>W.level===E.level&&!E.isAdditional);if(V!=null&&V.isAuto)return null;const H=Number(E.tat||0),Y=(E.tatType||"hours")==="days"?H*24:H;if(!H)return null;if(E.isAdditional){const W=$s.find(ce=>ce.level===E.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:E.stepName||`Additional Approver (after "${(W==null?void 0:W.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[Y," hours"]})]},E.level)}return e.jsxs("div",{className:"flex items-center justify-between p-2 bg-gray-50 rounded",children:[e.jsx("span",{className:"text-sm font-medium",children:(V==null?void 0:V.name)||"Unknown"}),e.jsxs("span",{className:"text-sm text-gray-600",children:[Y," hours"]})]},E.level)})})})]})]}),e.jsx(ht,{open:x,onOpenChange:g,children:e.jsxs(ct,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(dt,{className:"flex items-center gap-2",children:[e.jsx(us,{className:"w-5 h-5 text-blue-600"}),"Add Additional Approver"]}),e.jsx(Et,{children:'Add an additional approver between workflow steps. The approver will be inserted after the selected step. Additional approvers cannot be added after "Requestor Claim Approval".'})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(He,{value:T.toString(),onValueChange:E=>C(Number(E)),children:[e.jsx(Ge,{className:"h-11 border-gray-300",children:e.jsx(We,{placeholder:"Select step"})}),e.jsx(Ke,{children:$s.filter(E=>{if(E.isAuto)return!1;const V=$s.find(H=>H.name==="Requestor Claim Approval");return!(V&&E.level>=V.level)}).map(E=>e.jsx(X,{value:E.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ds,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:E.name})]})},E.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 E=t.approvers||[],H=new Set(E.map(Q=>Q.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{type:"number",min:"1",max:A==="days"?"30":"720",value:b,onChange:E=>{const V=E.target.value;if(V==="")v("");else{const H=Number(V);!isNaN(H)&&H>=0&&v(H)}},onBlur:E=>{const V=E.target.value;(!V||V===""||Number(V)<=0)&&v(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(He,{value:A,onValueChange:E=>w(E),children:[e.jsx(Ge,{className:"w-24 h-11 border-gray-300",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"hours",children:"Hours"}),e.jsx(X,{value:"days",children:"Days"})]})]})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum time for this approver to respond (1-",A==="days"?"30 days":"720 hours",")"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ie,{type:"text",placeholder:"@username or user@example.com",value:f,onChange:E=>U(E.target.value),className:"pl-10 h-11 border-gray-300",autoFocus:!0}),(S||_.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:S?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):_.length>0?e.jsx("ul",{className:"divide-y",children:_.map(E=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>$(E),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:E.displayName||[E.firstName,E.lastName].filter(Boolean).join(" ")||E.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:E.email}),E.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:E.designation})]})})},E.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(kt,{children:[e.jsx(I,{type:"button",variant:"outline",onClick:()=>{g(!1),y(""),v(24),w("hours"),C(3),R(null),D([])},className:"flex-1",children:"Cancel"}),e.jsxs(I,{type:"button",onClick:L,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!f.trim()||!b,children:[e.jsx(us,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const Fl=[{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"}],Ml=["Claim Details","Approver Selection","Review & Submit"];function pT({onBack:t,onSubmit:s}){const{user:a}=Qt(),[r,n]=p.useState(1),[i,l]=p.useState(!1),[o,c]=p.useState([]),[d,m]=p.useState(!1),[u,h]=p.useState(""),x=p.useRef(null),[g,f]=p.useState(!1),y=p.useRef(null),[b,v]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[A,w]=p.useState({open:!1,violations:[]}),[T,C]=p.useState([]),[_,D]=p.useState(!0);p.useEffect(()=>{(async()=>{try{D(!0);const L=await xA();C(L)}catch(L){console.error("Failed to load activity types:",L),K.error("Failed to load activity types. Please refresh the page.")}finally{D(!1)}})()},[]),p.useEffect(()=>{(async()=>{var L;try{const se=await Js("SYSTEM_SETTINGS"),G=await Js("WORKFLOW_SHARING"),oe=[...se,...G],Z={};oe.forEach(E=>{Z[E.configKey]=E.configValue}),v({maxApprovalLevels:parseInt(Z.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Z.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((L=Z.ALLOW_ADD_SPECTATOR)==null?void 0:L.toLowerCase())==="true",maxSpectators:parseInt(Z.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(se){console.error("Failed to load system policy:",se)}})()},[]),p.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]);const[S,j]=p.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),P=Ml.length,R=$=>{if(h($),x.current&&clearTimeout(x.current),!$||$.trim().length<2){c([]),m(!1);return}m(!0),x.current=setTimeout(async()=>{try{const L=await uT($,10);c(L)}catch(L){console.error("Error searching dealers:",L),c([])}finally{m(!1)}},300)},O=($,L)=>{j(se=>{const G={...se,[$]:L};if($==="periodStartDate")L&&G.periodEndDate&&L>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($==="periodEndDate"&&L&&G.periodStartDate&&L<G.periodStartDate)return K.error("End date must be on or after the start date."),se;return G})},F=()=>{switch(r){case 1:return S.activityName&&S.activityType&&S.dealerCode&&S.dealerName&&S.activityDate&&S.location&&S.requestDescription;case 2:const L=(S.approvers||[]).find(se=>se.originalStepLevel===3||!se.originalStepLevel&&se.level===3&&!se.isAdditional);return(L==null?void 0:L.email)&&(L==null?void 0:L.userId)&&(L==null?void 0:L.tat);case 3:return!0;default:return!1}},M=()=>{if(r<P){if(!F()){if(r===2){const L=(S.approvers||[]).find(G=>G.originalStepLevel===3||!G.originalStepLevel&&G.level===3&&!G.isAdditional),se=[];(!(L!=null&&L.email)||!(L!=null&&L.userId)||!(L!=null&&L.tat))&&se.push("Department Lead Approval"),se.length>0?K.error(`Please add missing approvers: ${se.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)}},B=()=>{r>1&&n(r-1)},k=async $=>{l(!0);try{const L=await xT($.dealerCode);if(!L.isLoggedIn){K.error(`Dealer "${L.dealerName||L.displayName}" (${L.dealerCode}) is not mapped to the system.`,{duration:5e3}),h(""),c([]),O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress",""),l(!1);return}O("dealerCode",L.dealerCode),O("dealerName",L.dealerName||L.displayName),O("dealerEmail",L.email||""),O("dealerPhone",L.phone||""),O("dealerAddress",""),h(L.dealerName||L.displayName),c([]),K.success(`Dealer "${L.dealerName||L.displayName}" verified and mapped to the System`)}catch{K.error("Dealer is not mapped to the system",{duration:5e3}),h(""),c([]),O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress","")}finally{l(!1)}},N=()=>{if(g)return;const L=[...S.approvers||[]].sort((E,V)=>E.level-V.level),se=new Map,G=[];if(L.forEach(E=>{se.has(E.level)?G.push(E.level):se.set(E.level,E)}),G.length>0){K.error(`Duplicate approver levels detected: ${G.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",G,L);return}const oe=L.map(E=>{const V={email:E.email,name:E.name,userId:E.userId,level:E.level,tat:E.tat,tatType:E.tatType};return E.isAdditional&&E.stepName&&(V.stepName=E.stepName,V.isAdditional=!0),E.originalStepLevel&&(V.originalStepLevel=E.originalStepLevel),V}),Z={...S,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:oe};if(f(!0),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{f(!1),y.current=null},3e4),s)try{s(Z)}catch(E){y.current&&(clearTimeout(y.current),y.current=null),f(!1),console.error("Error submitting claim:",E)}else y.current&&(clearTimeout(y.current),y.current=null),f(!1)},U=()=>{switch(r){case 1:return e.jsxs(ms.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(ls,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Claim Details"}),e.jsx("p",{className:"text-gray-600",children:"Provide comprehensive information about your claim request"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(Ie,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:S.activityName,onChange:$=>O("activityName",$.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(He,{value:S.activityType,onValueChange:$=>O("activityType",$),disabled:_,children:[e.jsx(Ge,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(We,{placeholder:_?"Loading activity types...":"Select activity type"})}),e.jsx(Ke,{children:T.length>0?T.map($=>e.jsx(X,{value:$.title,children:$.title},$.activityTypeId)):e.jsx("div",{className:"px-2 py-1.5 text-sm text-gray-500 text-center",children:"No activity types available"})})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsx("div",{className:"mt-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ie,{placeholder:"Type dealer code, name, or email to search...",value:S.dealerCode?`${S.dealerName} (${S.dealerCode})`:u,onChange:$=>{S.dealerCode?(O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress",""),h($.target.value)):R($.target.value)},onFocus:()=>{u&&u.length>=2&&R(u)},className:"h-12 border-2 border-gray-300 focus:border-blue-500",disabled:i}),S.dealerCode&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsxs(ie,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Pe,{className:"w-3 h-3 mr-1"}),"Verified"]})}),(d||o.length>0)&&!S.dealerCode&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children: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($=>e.jsx("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>k($),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:$.dealerName||$.displayName}),e.jsxs("div",{className:"text-xs text-gray-600",children:[e.jsx("span",{className:"font-mono",children:$.dealerCode}),$.email&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1",children:"•"}),e.jsx("span",{children:$.email})]})]}),$.city&&$.state&&e.jsxs("div",{className:"text-xs text-gray-500",children:[$.city,", ",$.state]})]}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:$.isLoggedIn?e.jsx(Pe,{className:"w-4 h-4 text-green-600"}):e.jsx(Nt,{className:"w-4 h-4 text-red-500"})})]})},$.dealerId))})})]})}),S.dealerCode&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:S.dealerName})," (",S.dealerCode,")"]}),S.dealerEmail&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Email: ",S.dealerEmail]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(Zs,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(lt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:S.activityDate?Ye(S.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(Qs,{className:"w-auto p-0",align:"start",children:e.jsx(ti,{mode:"single",selected:S.activityDate,onSelect:$=>O("activityDate",$),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(Ie,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:S.location,onChange:$=>O("location",$.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Fn,{value:S.requestDescription||"",onChange:$=>O("requestDescription",$),placeholder:"Provide comprehensive details about your claim requirement including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ne,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(ie,{variant:"secondary",className:"text-xs",children:"Optional"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(Zs,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(lt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:S.periodStartDate?Ye(S.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(Qs,{className:"w-auto p-0",align:"start",children:e.jsx(ti,{mode:"single",selected:S.periodStartDate,onSelect:$=>O("periodStartDate",$),initialFocus:!0,toDate:S.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(Zs,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",disabled:!S.periodStartDate,children:[e.jsx(lt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:S.periodEndDate?Ye(S.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(Qs,{className:"w-auto p-0",align:"start",children:e.jsx(ti,{mode:"single",selected:S.periodEndDate,onSelect:$=>O("periodEndDate",$),initialFocus:!0,fromDate:S.periodStartDate||void 0})})]}),!S.periodStartDate&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Please select start date first"})]})]}),(S.periodStartDate||S.periodEndDate)&&e.jsx("div",{className:"mt-2",children:S.periodStartDate&&S.periodEndDate?e.jsxs("p",{className:"text-xs text-gray-600",children:["Period: ",Ye(S.periodStartDate,"d MMM yyyy")," - ",Ye(S.periodEndDate,"d MMM yyyy")]}):e.jsx("p",{className:"text-xs text-gray-500",children:S.periodStartDate?"Please select end date for the period":"Please select start date first"})})]})]})]});case 2:return e.jsx(hT,{formData:S,updateFormData:O,currentUserEmail:(a==null?void 0:a.email)||"",currentUserId:(a==null?void 0:a.userId)||"",currentUserName:(a==null?void 0:a.displayName)||(a==null?void 0:a.name)||(a!=null&&a.firstName&&(a!=null&&a.lastName)?`${a.firstName} ${a.lastName}`.trim():(a==null?void 0:a.email)||"User"),maxApprovalLevels:b.maxApprovalLevels,onPolicyViolation:$=>w({open:!0,violations:$})});case 3:return e.jsxs(ms.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(Pe,{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(J,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(q,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S.activityName})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(ie,{variant:"secondary",className:"mt-1",children:S.activityType})]})]})})]}),e.jsxs(J,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Mi,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(q,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1 font-mono",children:S.dealerCode})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S.dealerName})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:S.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:S.dealerPhone})]}),S.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:S.dealerAddress})]})]})})]}),e.jsxs(J,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-5 h-5 text-purple-600"}),"Selected Approvers"]})}),e.jsx(q,{className:"pt-6 space-y-4",children:e.jsx("div",{className:"space-y-3",children:[...S.approvers||[]].filter(L=>{var se,G;return!((se=L.email)!=null&&se.includes("system@"))&&!((G=L.email)!=null&&G.includes("finance@"))}).sort((L,se)=>L.level-se.level).map(L=>{const se=Number(L.tat||0),oe=(L.tatType||"hours")==="days"?se*24:se;let Z="Unknown",E="";if(L.isAdditional){Z=L.stepName||"Additional Approver";const V=Fl.find(H=>H.level===L.insertAfterLevel);E=L.stepName||`Additional Approver (after "${(V==null?void 0:V.name)||"Unknown"}")`}else{const V=L.originalStepLevel?Fl.find(H=>H.level===L.originalStepLevel):Fl.find(H=>H.level===L.level&&!H.isAuto);Z=(V==null?void 0:V.name)||"Unknown",E=Z}return e.jsx("div",{className:`p-3 rounded-lg border ${L.isAdditional?"bg-purple-50 border-purple-200":"bg-gray-50 border-gray-200"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:E}),L.isAdditional&&e.jsx(ie,{variant:"outline",className:"text-xs bg-purple-100 text-purple-700 border-purple-300",children:"ADDITIONAL"})]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:L.name||L.email||"Not selected"}),L.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:L.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[oe," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${L.level}-${L.email}`)})})})]}),e.jsxs(J,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(q,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S.activityDate?Ye(S.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Location"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ao,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:S.location})]})]}),S.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Estimated Budget"}),e.jsx("p",{className:"text-xl font-bold text-blue-900 mt-1",children:S.estimatedBudget})]})]})})]}),e.jsxs(J,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(q,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Brief Requirement"}),e.jsx("div",{className:"mt-2 p-4 bg-gray-50 rounded-lg border",children:e.jsx(na,{content:S.requestDescription||"",className:"text-sm"})})]})})]}),(S.periodStartDate||S.periodEndDate)&&e.jsxs(J,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(q,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S.periodStartDate?Ye(S.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S.periodEndDate?Ye(S.periodEndDate,"PPP"):"Not specified"})]})]})})]}),e.jsx("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-6",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Wr,{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(I,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Ss,{className:"w-3 h-3 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Back to Templates"}),e.jsx("span",{className:"sm:hidden",children:"Back"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-0",children:e.jsxs("div",{children:[e.jsx(ie,{variant:"secondary",className:"mb-2 text-xs",children:"Claim Management Template"}),e.jsx("h1",{className:"text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900",children:"New Claim Request"}),e.jsxs("p",{className:"text-sm sm:text-base text-gray-600 mt-1",children:["Step ",r," of ",P,": ",e.jsx("span",{className:"hidden sm:inline",children:Ml[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(oa,{value:r/P*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:Ml.map(($,L)=>e.jsx("span",{className:`text-xs sm:text-sm ${L+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:L+1},L))})]})]}),e.jsx(J,{className:"mb-6 sm:mb-8",children:e.jsx(q,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(Wi,{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(I,{variant:"outline",onClick:B,disabled:r===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Ss,{className:"w-4 h-4"}),"Previous"]}),r<P?e.jsxs(I,{onClick:M,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(xs,{className:"w-4 h-4"})]}):e.jsx(I,{onClick:N,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(Ze,{className:"w-4 h-4 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Nr,{className:"w-4 h-4"}),"Submit Claim Request"]})})]})]}),e.jsx($n,{open:A.open,onClose:()=>w({open:!1,violations:[]}),violations:A.violations,policyDetails:{maxApprovalLevels:b.maxApprovalLevels,maxParticipants:b.maxParticipants,allowSpectators:b.allowSpectators,maxSpectators:b.maxSpectators}})]})}const{DocumentsTab:gT,ActivityTab:fT,WorkNotesTab:yT,SummaryTab:bT,RequestDetailHeader:vT,QuickActionsSidebar:jT,RequestDetailModals:NT}=hg;let wT=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(ss,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(I,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(I,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function CT({requestId:t,onBack:s,dynamicRequests:a=[]}){var Mt,hs,zs,ir,lr,da;const n=La().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=p.useState(l),[d,m]=p.useState(!1),[u,h]=p.useState(null),[x,g]=p.useState(null),[f,y]=p.useState(!1),[b,v]=p.useState(0),[A,w]=p.useState(!1),[T,C]=p.useState(!1),[_,D]=p.useState(!1),[S,j]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[P,R]=p.useState({open:!1,violations:[]}),{user:O}=Qt(),{request:F,apiRequest:M,loading:B,refreshing:k,refreshDetails:N,currentApprovalLevel:U,isSpectator:$,isInitiator:L,existingParticipants:se,accessDenied:G}=wc(n,a,O),oe=(O==null?void 0:O.userId)||"",Z=L,{mergedMessages:E,unreadWorkNotes:V,workNoteAttachments:H,setWorkNoteAttachments:Q}=tg(n,M,o,O),{uploadingDocument:Y,triggerFileInput:W,previewDocument:ce,setPreviewDocument:xe,documentPolicy:ke,documentError:Ae,setDocumentError:ae}=sg(M,N),[ye,Ne]=p.useState(null),ve=ye||U,{showApproveModal:$e,setShowApproveModal:re,showRejectModal:Me,setShowRejectModal:ot,showAddApproverModal:pe,setShowAddApproverModal:Oe,showAddSpectatorModal:ft,setShowAddSpectatorModal:mt,showSkipApproverModal:nt,setShowSkipApproverModal:_s,showActionStatusModal:ea,setShowActionStatusModal:Aa,skipApproverData:qa,setSkipApproverData:ee,actionStatus:we,setActionStatus:te,handleApproveConfirm:_e,handleRejectConfirm:Fe,handleAddApprover:ze,handleSkipApprover:Le,handleAddSpectator:Je}=rg(n,ve,N),Be=async vt=>{await _e(vt),Ne(null)},tt=async vt=>{await Fe(vt),Ne(null)},ws=((F==null?void 0:F.status)||(M==null?void 0:M.status)||"").toLowerCase(),Yt=(ws==="approved"||ws==="rejected")&&L,{conclusionRemark:rt,setConclusionRemark:st,conclusionLoading:bt,conclusionSubmitting:as,aiGenerated:Ft,handleGenerateConclusion:fa,handleFinalizeConclusion:ya,generationAttempts:Oa,generationFailed:Sa,maxAttemptsReached:At}=ag(F,n,L,N,s,te,Aa);p.useEffect(()=>{(async()=>{var ps;try{const Ls=await Js("SYSTEM_SETTINGS"),ta=await Js("WORKFLOW_SHARING"),Ar=[...Ls,...ta],ma={};Ar.forEach(Ba=>{ma[Ba.configKey]=Ba.configValue}),j({maxApprovalLevels:parseInt(ma.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(ma.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((ps=ma.ALLOW_ADD_SPECTATOR)==null?void 0:ps.toLowerCase())==="true",maxSpectators:parseInt(ma.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Ls){console.error("Failed to load system policy:",Ls)}})()},[]),p.useEffect(()=>{const ps=new URLSearchParams(window.location.search).get("tab");ps&&c(ps)},[n]);const Ta=()=>{N()},er=()=>{w(!0)},tr=()=>{C(!0)},sr=async()=>{await N()},ar=()=>{D(!0)},rr=async()=>{await N()},nr=async()=>{await N()},$a=async()=>{if(!(M!=null&&M.requestId)){K.error("Request ID not found");return}if(!u){K.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},ba=(F==null?void 0:F.status)==="closed";p.useEffect(()=>{(async()=>{if(!ba||!(M!=null&&M.requestId)){g(null),h(null);return}try{y(!0);const ps=await dg(M.requestId);if(ps!=null&&ps.summaryId){h(ps.summaryId);try{const Ls=await Cc(ps.summaryId);g(Ls)}catch(Ls){console.error("Failed to fetch summary details:",Ls),g(null),h(null)}}else g(null),h(null)}catch{g(null),h(null)}finally{y(!1)}})()},[ba,M==null?void 0:M.requestId]),p.useEffect(()=>{if(!oe||!(M!=null&&M.requestId))return;const vt=Ur();if(!vt)return;Kx(vt,oe);const ps=Ls=>{var Ba,qr,en,tn;const ta=Ls==null?void 0:Ls.notification;if(!ta)return;const Ar=ta.requestId||ta.request_id,ma=((Ba=ta.metadata)==null?void 0:Ba.requestNumber)||((qr=ta.metadata)==null?void 0:qr.request_number);Ar!==M.requestId&&ma!==n&&ma!==M.requestNumber||((en=ta.metadata)!=null&&en.creditNoteNumber||(tn=ta.metadata)!=null&&tn.credit_note_number)&&N()};return vt.on("notification:new",ps),()=>{vt.off("notification:new",ps)}},[oe,M==null?void 0:M.requestId,n,N]);const Ua=((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 B&&!F&&!M?e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(zt,{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(yx,{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(I,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ss,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(I,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):F?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"dealer-claim-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(vT,{request:F,refreshing:k,onBack:s||(()=>window.history.back()),onRefresh:Ta,onShareSummary:$a,isInitiator:L,slaData:((Mt=F==null?void 0:F.summary)==null?void 0:Mt.sla)||(F==null?void 0:F.sla)||null,isPaused:((hs=F==null?void 0:F.pauseInfo)==null?void 0:hs.isPaused)||!1}),e.jsxs(Un,{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(Bn,{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(Dt,{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(bx,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),ba&&x&&e.jsxs(Dt,{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(So,{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(Dt,{value:"workflow",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-workflow",children:[e.jsx(Ys,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),Z&&e.jsxs(Dt,{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(Ea,{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(Dt,{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(De,{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(Dt,{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(Pt,{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(Dt,{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(Is,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),V>0&&e.jsx(ie,{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-red-500 text-white text-[10px] flex items-center justify-center p-0","data-testid":"worknotes-unread-badge",children:V>9?"9+":V})]})]})}),e.jsxs("div",{className:o==="worknotes"?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:o==="worknotes"?"":"lg:col-span-2",children:[e.jsx(Tt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(VS,{request:F,apiRequest:M,currentUserId:oe,isInitiator:L,needsClosure:Yt,conclusionRemark:rt,setConclusionRemark:st,conclusionLoading:bt,conclusionSubmitting:as,aiGenerated:Ft,handleGenerateConclusion:fa,handleFinalizeConclusion:ya,generationAttempts:Oa,generationFailed:Sa,maxAttemptsReached:At})}),ba&&e.jsx(Tt,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(bT,{summary:x,loading:f,onShare:$a,isInitiator:L})}),e.jsx(Tt,{value:"workflow",className:"mt-0",children:e.jsx(dT,{request:F,user:O,isInitiator:L,onSkipApprover:vt=>{if(!vt.levelId){alert("Level ID not available");return}ee(vt),_s(!0)},onRefresh:N,documentPolicy:ke})}),Z&&e.jsx(Tt,{value:"io",className:"mt-0",children:e.jsx(mT,{request:F,apiRequest:M,onRefresh:N})}),e.jsx(Tt,{value:"documents",className:"mt-0",children:e.jsx(gT,{request:F,workNoteAttachments:H,uploadingDocument:Y,documentPolicy:ke,triggerFileInput:W,setPreviewDocument:xe,downloadDocument:js})}),e.jsx(Tt,{value:"activity",className:"mt-0",children:e.jsx(fT,{request:F})}),e.jsx(Tt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(yT,{requestId:n,requestTitle:F.title,mergedMessages:E,setWorkNoteAttachments:Q,isInitiator:L,isSpectator:$,currentLevels:Ua,onAddApprover:ze,maxApprovalLevels:S.maxApprovalLevels,onPolicyViolation:vt=>R({open:!0,violations:vt})})})]}),o!=="worknotes"&&e.jsx(jT,{request:F,isInitiator:L,isSpectator:$,currentApprovalLevel:Qi(M)?null:U,onAddApprover:()=>Oe(!0),onAddSpectator:()=>mt(!0),onApprove:()=>re(!0),onReject:()=>ot(!0),onPause:er,onResume:tr,onRetrigger:ar,summaryId:u,refreshTrigger:b,pausedByUserId:(ir=(zs=F==null?void 0:F.pauseInfo)==null?void 0:zs.pausedBy)==null?void 0:ir.userId,currentUserId:oe,apiRequest:M})]})]})]})}),d&&u&&e.jsx(pg,{isOpen:d,onClose:()=>m(!1),summaryId:u,requestTitle:(F==null?void 0:F.title)||"N/A",onSuccess:()=>{N(),v(vt=>vt+1)}}),A&&(M==null?void 0:M.requestId)&&e.jsx(gg,{isOpen:A,onClose:()=>w(!1),requestId:M.requestId,levelId:(U==null?void 0:U.levelId)||null,onSuccess:rr}),T&&(M==null?void 0:M.requestId)&&e.jsx(fg,{isOpen:T,onClose:()=>C(!1),requestId:M.requestId,onSuccess:sr}),_&&(M==null?void 0:M.requestId)&&e.jsx(yg,{isOpen:_,onClose:()=>D(!1),requestId:M.requestId,approverName:(da=(lr=F==null?void 0:F.pauseInfo)==null?void 0:lr.pausedBy)==null?void 0:da.name,onSuccess:nr}),e.jsx(NT,{showApproveModal:$e,showRejectModal:Me,showAddApproverModal:pe,showAddSpectatorModal:ft,showSkipApproverModal:nt,showActionStatusModal:ea,previewDocument:ce,documentError:Ae,request:F,skipApproverData:qa,actionStatus:we,existingParticipants:se,currentLevels:Ua,maxApprovalLevels:S.maxApprovalLevels,onPolicyViolation:vt=>R({open:!0,violations:vt}),setShowApproveModal:re,setShowRejectModal:ot,setShowAddApproverModal:Oe,setShowAddSpectatorModal:mt,setShowSkipApproverModal:_s,setShowActionStatusModal:Aa,setPreviewDocument:xe,setDocumentError:ae,setSkipApproverData:ee,setActionStatus:te,handleApproveConfirm:Be,handleRejectConfirm:tt,handleAddApprover:ze,handleAddSpectator:Je,handleSkipApprover:Le,downloadDocument:js,documentPolicy:ke}),e.jsx($n,{open:P.open,onClose:()=>R({open:!1,violations:[]}),violations:P.violations,policyDetails:{maxApprovalLevels:S.maxApprovalLevels,maxParticipants:S.maxParticipants,allowSpectators:S.allowSpectators,maxSpectators:S.maxSpectators}})]}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"not-found-state",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(De,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Dealer Claim Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The dealer claim request you're looking for doesn't exist or may have been deleted."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(I,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ss,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(I,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function AT(t){return e.jsx(wT,{children:e.jsx(CT,{...t})})}function ST({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,u]=p.useState("all"),[h,x]=p.useState(),[g,f]=p.useState(),y=async(R=!1)=>{try{R?i(!0):r(!0);const O=await nT(m||"all",h,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(()=>{y()},[]);const b=(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"),A=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),w=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),T=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]),C=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"],S=p.useMemo(()=>c.length===0?null:c.reduce((R,O)=>O.approvalRate>((R==null?void 0:R.approvalRate)||0)?O:R),[c]),j=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(zt,{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(J,{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(q,{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(ds,{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(I,{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(De,{className:"w-5 h-5 mr-2"}),"Create New Claim"]}),e.jsxs(I,{onClick:()=>{i(!0),y(!0)},disabled:n,variant:"outline",className:"bg-white/10 hover:bg-white/20 text-white border-white/20",children:[e.jsx(zt,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh"]})]})]})})})]}),e.jsx(J,{className:"shadow-lg",children:e.jsxs(q,{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(zl,{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(I,{onClick:()=>t==null?void 0:t("/new-request"),className:"bg-blue-600 hover:bg-blue-700 text-white",children:[e.jsx(De,{className:"w-5 h-5 mr-2"}),"Create Your First Claim"]}),e.jsxs(I,{onClick:()=>{i(!0),y(!0)},disabled:n,variant:"outline",children:[e.jsx(zt,{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(J,{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(q,{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(ds,{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(I,{onClick:()=>t==null?void 0:t("/requests?status=pending"),className:"bg-blue-600 hover:bg-blue-700 text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200",children:[e.jsx(Xe,{className:"w-5 h-5 mr-2"}),"View Pending Claims"]}),e.jsxs(I,{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(De,{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(pi,{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(J,{className:"border-l-4 border-l-blue-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Raised Claims"}),e.jsx("div",{className:"p-2 rounded-lg bg-blue-50",children:e.jsx(De,{className:"h-4 w-4 text-blue-600"})})]})}),e.jsxs(q,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.totalClaims)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:b(l.totalValue,!0)})]})]}),e.jsxs(J,{className:"border-l-4 border-l-green-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Approved"}),e.jsx("div",{className:"p-2 rounded-lg bg-green-50",children:e.jsx(Pe,{className:"h-4 w-4 text-green-600"})})]})}),e.jsxs(q,{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(Ys,{className:"h-3 w-3 text-green-600"}),e.jsxs("p",{className:"text-xs text-green-600",children:[A(),"% approval rate"]})]})]})]}),e.jsxs(J,{className:"border-l-4 border-l-red-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Rejected"}),e.jsx("div",{className:"p-2 rounded-lg bg-red-50",children:e.jsx(Nt,{className:"h-4 w-4 text-red-600"})})]})}),e.jsxs(q,{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(D0,{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(J,{className:"border-l-4 border-l-orange-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Pending"}),e.jsx("div",{className:"p-2 rounded-lg bg-orange-50",children:e.jsx(Xe,{className:"h-4 w-4 text-orange-600"})})]})}),e.jsxs(q,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.pending)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:b(l.pendingValue)})]})]}),e.jsxs(J,{className:"border-l-4 border-l-emerald-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Credited"}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-50",children:e.jsx(P0,{className:"h-4 w-4 text-emerald-600"})})]})}),e.jsxs(q,{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(Ys,{className:"h-3 w-3 text-emerald-600"}),e.jsxs("p",{className:"text-xs text-emerald-600",children:[w(),"% credit rate"]})]})]})]}),e.jsxs(J,{className:"border-l-4 border-l-amber-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Pending Credit"}),e.jsx("div",{className:"p-2 rounded-lg bg-amber-50",children:e.jsx(ss,{className:"h-4 w-4 text-amber-600"})})]})}),e.jsxs(q,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.pendingCredit)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:b(l.pendingCreditValue)})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(J,{className:"shadow-lg",children:[e.jsx(me,{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(zl,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Claims Distribution by Activity Type"}),e.jsx(Te,{children:"Total claims raised across activity types"})]})]})}),e.jsxs(q,{children:[e.jsx(Mr,{width:"100%",height:300,children:e.jsxs(tx,{children:[e.jsx(sx,{data:T,cx:"50%",cy:"50%",labelLine:!1,label:({name:R,percentage:O})=>`${R}: ${O}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:T.map((R,O)=>e.jsx(ax,{fill:D[O%D.length]},`cell-${O}`))}),e.jsx(_r,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:T.slice(0,3).map((R,O)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-gray-50",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:D[O%D.length]}}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600",children:R.name}),e.jsx("p",{className:"text-sm text-gray-900",children:v(R.value)})]})]},O))})]})]}),e.jsxs(J,{className:"shadow-lg",children:[e.jsx(me,{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(pi,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Claims Status by Activity Type"}),e.jsx(Te,{children:"Count comparison across workflow stages"})]})]})}),e.jsx(q,{children:e.jsx(Mr,{width:"100%",height:300,children:e.jsxs(Ul,{data:C,children:[e.jsx(oi,{strokeDasharray:"3 3"}),e.jsx(ci,{dataKey:"name"}),e.jsx(di,{}),e.jsx(_r,{}),e.jsx(mi,{}),e.jsx(va,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(va,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(va,{dataKey:"Rejected",fill:"#ef4444"}),e.jsx(va,{dataKey:"Pending",fill:"#f59e0b"})]})})})]})]}),e.jsxs(J,{className:"shadow-lg",children:[e.jsx(me,{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(Pt,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Detailed Activity Type Breakdown"}),e.jsx(Te,{children:"In-depth analysis of claims by type and status"})]})]})}),e.jsx(q,{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(Mr,{width:"100%",height:350,children:e.jsxs(Ul,{data:_,children:[e.jsx(oi,{strokeDasharray:"3 3"}),e.jsx(ci,{dataKey:"name"}),e.jsx(di,{tickFormatter:R=>b(R)}),e.jsx(_r,{formatter:R=>b(R),labelFormatter:R=>R}),e.jsx(mi,{}),e.jsx(va,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(va,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(va,{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(J,{className:"shadow-md hover:shadow-lg transition-shadow",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-base",children:R.activityType}),e.jsxs(ie,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[R.approvalRate.toFixed(1),"% approved"]})]})}),e.jsxs(q,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Raised:"}),e.jsxs("span",{className:"text-gray-900",children:[v(R.raised)," (",b(R.raisedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Approved:"}),e.jsxs("span",{className:"text-green-600",children:[v(R.approved)," (",b(R.approvedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Rejected:"}),e.jsxs("span",{className:"text-red-600",children:[v(R.rejected)," (",b(R.rejectedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Pending:"}),e.jsxs("span",{className:"text-orange-600",children:[v(R.pending)," (",b(R.pendingValue),")"]})]}),e.jsx("div",{className:"h-px bg-gray-200 my-2"}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Credited:"}),e.jsxs("span",{className:"text-emerald-600",children:[v(R.credited)," (",b(R.creditedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Pending Credit:"}),e.jsxs("span",{className:"text-amber-600",children:[v(R.pendingCredit)," (",b(R.pendingCreditValue),")"]})]})]}),e.jsxs("div",{className:"pt-2",children:[e.jsxs("div",{className:"flex justify-between text-xs text-gray-600 mb-1",children:[e.jsx("span",{children:"Credit Rate"}),e.jsxs("span",{children:[R.creditRate.toFixed(1),"%"]})]}),e.jsx(oa,{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(J,{className:"border-t-4 border-t-green-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(q,{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(Ht,{className:"h-6 w-6 text-green-600"})}),e.jsx(Ys,{className:"h-5 w-5 text-green-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Best Performing"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:(S==null?void 0:S.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-green-600",children:[(S==null?void 0:S.approvalRate.toFixed(2))||0,"% approval rate"]})]})}),e.jsx(J,{className:"border-t-4 border-t-blue-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(q,{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(Ea,{className:"h-6 w-6 text-blue-600"})}),e.jsx(Pt,{className:"h-5 w-5 text-blue-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Top Activity Type"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:(j==null?void 0:j.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-blue-600",children:[j?b(j.raisedValue,!0):"₹0"," raised"]})]})}),e.jsx(J,{className:"border-t-4 border-t-emerald-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(q,{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(Ri,{className:"h-6 w-6 text-emerald-600"})}),e.jsx(Pe,{className:"h-5 w-5 text-emerald-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Overall Credit Rate"}),e.jsxs("p",{className:"text-xl text-gray-900 mb-1",children:[w(),"%"]}),e.jsxs("p",{className:"text-sm text-emerald-600",children:[v(l.credited)," claims credited"]})]})}),e.jsx(J,{className:"border-t-4 border-t-amber-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(q,{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(hx,{className:"h-6 w-6 text-amber-600"})}),e.jsx(ss,{className:"h-5 w-5 text-amber-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Pending Action"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:v(l.pendingCredit)}),e.jsxs("p",{className:"text-sm text-amber-600",children:[b(l.pendingCreditValue)," awaiting credit"]})]})})]})]})}function TT({searchTerm:t,sortBy:s,sortOrder:a,onSearchChange:r,onSortByChange:n,onSortOrderChange:i,onClearFilters:l,activeFiltersCount:o,...c}){return e.jsxs(J,{className:"shadow-lg border-0",children:[e.jsx(me,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Te,{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(I,{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(gt,{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(q,{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(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(Ie,{placeholder:"Search requests, IDs...",value:t,onChange:d=>r(d.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:s,onValueChange:d=>n(d),children:[e.jsx(Ge,{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(We,{placeholder:"Sort by"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"due",children:"Due Date"}),e.jsx(X,{value:"created",children:"Date Created"}),e.jsx(X,{value:"priority",children:"Priority"}),e.jsx(X,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(I,{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(_i,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Li,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function kT({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(J,{className:"shadow-lg border-0","data-testid":"dealer-closed-requests-filters",children:[e.jsx(me,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Te,{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(I,{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(gt,{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(q,{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(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(Ie,{placeholder:"Search requests, IDs...",value:t,onChange:u=>n(u.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors","data-testid":"dealer-closed-requests-search"})]}),i&&e.jsxs(He,{value:s,onValueChange:i,children:[e.jsx(Ge,{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(We,{placeholder:"Closure Type"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Closures"}),e.jsx(X,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(X,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nt,{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(He,{value:a,onValueChange:u=>l(u),children:[e.jsx(Ge,{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(We,{placeholder:"Sort by"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"due",children:"Due Date"}),e.jsx(X,{value:"created",children:"Date Created"}),e.jsx(X,{value:"priority",children:"Priority"})]})]}),e.jsx(I,{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(_i,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Li,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function RT({searchTerm:t,statusFilter:s,initiatorFilter:a,approverFilter:r,approverFilterType:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,initiatorSearch:d,approverSearch:m,onSearchChange:u,onStatusChange:h,onInitiatorChange:x,onApproverChange:g,onApproverTypeChange:f,onDateRangeChange:y,onCustomStartDateChange:b,onCustomEndDateChange:v,onShowCustomDatePickerChange:A,onApplyCustomDate:w,onClearFilters:T,hasActiveFilters:C,..._}){return e.jsx(J,{className:"border-gray-200 shadow-md","data-testid":"dealer-user-all-requests-filters",children:e.jsx(q,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),C&&e.jsx(ie,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),C&&e.jsxs(I,{variant:"ghost",size:"sm",onClick:T,className:"gap-2",children:[e.jsx(zt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx($t,{}),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(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ie,{placeholder:"Search requests...",value:t,onChange:D=>u(D.target.value),className:"pl-10 h-10","data-testid":"dealer-search-input"})]}),e.jsxs(He,{value:s,onValueChange:h,children:[e.jsx(Ge,{className:"h-10","data-testid":"dealer-status-filter",children:e.jsx(We,{placeholder:"All Status"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Status"}),e.jsx(X,{value:"pending",children:"Pending"}),e.jsx(X,{value:"paused",children:"Paused"}),e.jsx(X,{value:"approved",children:"Approved"}),e.jsx(X,{value:"rejected",children:"Rejected"}),e.jsx(X,{value:"closed",children:"Closed"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:d.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:d.selectedUser.displayName||d.selectedUser.email}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:d.handleClear,children:e.jsx(gt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{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(ne,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r!=="all"&&f&&e.jsxs(He,{value:n,onValueChange:D=>f(D),children:[e.jsx(Ge,{className:"h-7 w-32 text-xs",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"current",children:"Current Only"}),e.jsx(X,{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(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:m.handleClear,children:e.jsx(gt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{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(lt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:i,onValueChange:D=>y(D),children:[e.jsx(Ge,{className:"w-[160px] h-10",children:e.jsx(We,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),i==="custom"&&e.jsxs(Zs,{open:c,onOpenChange:A,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),l&&o?`${Ye(l,"MMM d, yyyy")} - ${Ye(o,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Qs,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Bs,{value:l||null,onChange:D=>{const S=D?new Date(D):void 0;S?(b==null||b(S),o&&S>o&&(v==null||v(S))):b==null||b(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",children:"End Date"}),e.jsx(Bs,{value:o||null,onChange:D=>{const S=D?new Date(D):void 0;S?(v==null||v(S),l&&S<l&&(b==null||b(S))):v==null||v(void 0)},minDate:l||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(I,{size:"sm",onClick:w,disabled:!l||!o,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(I,{size:"sm",variant:"outline",onClick:()=>{A==null||A(!1),b==null||b(void 0),v==null||v(void 0),y("month")},children:"Cancel"})]})]})})]})]})]})})})}function DT(t){switch(t){case"DEALER_CLAIM":return AT;case"CUSTOM":default:return OS}}function PT(t){switch(t){case"DEALER":return TT;case"STANDARD":default:return $S}}function IT(t){switch(t){case"DEALER":return kT;case"STANDARD":default:return US}}function ET(t){switch(t){case"DEALER":return RT;case"STANDARD":default:return BS}}const FT=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ga,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ht,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ht,iconColor:"text-gray-600"}}},MT=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Xe,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ve,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Nt,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ve,iconColor:"text-gray-600",label:t}}};function _T({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),[u]=p.useState(10),h=p.useRef(null),x=tN(),g=p.useMemo(()=>{try{const S=at.getUserData();return Vo(S)}catch(S){return console.error("[OpenRequests] Error getting user filter type:",S),"STANDARD"}},[]),f=p.useMemo(()=>PT(g),[g]),y=g==="DEALER",b=S=>({search:x.searchTerm||void 0,status:S&&!y&&x.statusFilter!=="all"?x.statusFilter:void 0,priority:!y&&x.priorityFilter!=="all"?x.priorityFilter:void 0,templateType:!y&&x.templateTypeFilter!=="all"?x.templateTypeFilter:void 0,sortBy:x.sortBy,sortOrder:x.sortOrder}),v=p.useCallback(async(S=1,j)=>{try{S===1&&(n(!0),a([]));const P=await Ms.listOpenForMe({page:S,limit:u,search:j==null?void 0:j.search,status:j==null?void 0:j.status,priority:j==null?void 0:j.priority,templateType:j==null?void 0:j.templateType,sortBy:j==null?void 0:j.sortBy,sortOrder:j==null?void 0:j.sortOrder}),R=Array.isArray(P==null?void 0:P.data)?P.data:[],O=P==null?void 0:P.pagination;O&&(x.setCurrentPage(O.page||1),c(O.totalPages||1),m(O.total||0));const F=R.map(M=>{var k,N,U,$;const B=M.submittedAt||M.submitted_at||M.createdAt||M.created_at;return{id:M.requestNumber||M.request_number||M.requestId,requestId:M.requestId,displayId:M.requestNumber||M.request_number||M.requestId,title:M.title,description:M.description,status:(M.status||"").toString().toLowerCase().replace("_","-"),priority:(M.priority||"").toString().toLowerCase(),initiator:{name:((k=M.initiator)==null?void 0:k.displayName)||((N=M.initiator)==null?void 0:N.email)||"—",avatar:(((U=M.initiator)==null?void 0:U.displayName)||(($=M.initiator)==null?void 0:$.email)||"NA").split(" ").map(L=>L[0]).join("").slice(0,2).toUpperCase()},currentApprover:M.currentApprover?{name:M.currentApprover.name||M.currentApprover.email||"—",avatar:(M.currentApprover.name||M.currentApprover.email||"CA").split(" ").map(L=>L[0]).join("").slice(0,2).toUpperCase(),sla:M.currentApprover.sla}:void 0,createdAt:B||"—",approvalStep:M.currentLevel?`Step ${M.currentLevel} of ${M.totalLevels||"?"}`:void 0,department:M.department,currentLevelSLA:M.currentLevelSLA,templateType:M.templateType||M.template_type}});a(F)}finally{n(!1),l(!1)}},[u,x]);h.current=v;const A=p.useCallback(()=>{l(!0),v(x.currentPage,b(!0))},[x.currentPage,v]),w=p.useCallback(S=>{S>=1&&S<=o&&(x.setCurrentPage(S),v(S,b(!0)))},[o,x,v]),T=()=>{const S=[];let P=Math.max(1,x.currentPage-Math.floor(2.5)),R=Math.min(o,P+5-1);R-P<4&&(P=Math.max(1,R-5+1));for(let O=P;O<=R;O++)S.push(O);return S},C=p.useRef(!1);p.useEffect(()=>{if(!C.current){C.current=!0;const S=x.currentPage||1;v(S,b(!0))}},[]);const _=p.useRef({searchTerm:x.searchTerm,statusFilter:x.statusFilter,priorityFilter:x.priorityFilter,templateTypeFilter:x.templateTypeFilter,sortBy:x.sortBy,sortOrder:x.sortOrder,isDealer:y});p.useEffect(()=>{if(!C.current)return;const S=_.current;if(!(S.searchTerm!==x.searchTerm||S.statusFilter!==x.statusFilter||S.priorityFilter!==x.priorityFilter||S.templateTypeFilter!==x.templateTypeFilter||S.sortBy!==x.sortBy||S.sortOrder!==x.sortOrder||S.isDealer!==y))return;const P=setTimeout(()=>{x.setCurrentPage(1),v(1,b(!0)),_.current={searchTerm:x.searchTerm,statusFilter:x.statusFilter,priorityFilter:x.priorityFilter,templateTypeFilter:x.templateTypeFilter,sortBy:x.sortBy,sortOrder:x.sortOrder,isDealer:y}},x.searchTerm?500:0);return()=>clearTimeout(P)},[x.searchTerm,x.statusFilter,x.priorityFilter,x.templateTypeFilter,x.sortBy,x.sortOrder,y]);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(De,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900",children:"My Open Requests"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:"Manage and track your active approval requests"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsxs(ie,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold",children:[r?"Loading…":`${d||s.length} open`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:A,disabled:i,children:[e.jsx(zt,{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(f,{searchTerm:x.searchTerm,statusFilter:x.statusFilter,priorityFilter:x.priorityFilter,templateTypeFilter:x.templateTypeFilter,sortBy:x.sortBy,sortOrder:x.sortOrder,onSearchChange:x.setSearchTerm,onStatusFilterChange:x.setStatusFilter,onPriorityFilterChange:x.setPriorityFilter,onTemplateTypeFilterChange:x.setTemplateTypeFilter,onSortByChange:x.setSortBy,onSortOrderChange:x.setSortOrder,onClearFilters:x.clearFilters,activeFiltersCount:x.activeFiltersCount}),e.jsx("div",{className:"space-y-3",children:D.map(S=>{const j=FT(S.priority),P=MT(S.status);return e.jsx(J,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>t==null?void 0:t(S.id,S.title),children:e.jsx(q,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${j.color} border shadow-sm`,children:e.jsx(j.icon,{className:`w-5 h-5 ${j.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:S.displayId||S.id}),e.jsxs(ie,{variant:"outline",className:`${P.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(P.icon,{className:"w-3.5 h-3.5 mr-1"}),P.label||S.status]}),S.department&&e.jsx(ie,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:S.department}),e.jsx(ie,{variant:"outline",className:`${j.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:S.priority}),(()=>{const R=(S==null?void 0:S.templateType)||(S==null?void 0:S.template_type)||"",O=(R==null?void 0:R.toUpperCase())||"";let F="Non-Templatized",M="bg-purple-100 !text-purple-600 border-purple-200";return O==="DEALER CLAIM"?(F="Dealer Claim",M="bg-blue-100 !text-blue-700 border-blue-200"):O==="TEMPLATE"&&(F="Template"),e.jsx(ie,{variant:"outline",className:`${M} 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:S.title}),S.currentLevelSLA&&(()=>{var B;const R=!!(S.isPaused||(B=S.pauseInfo)!=null&&B.isPaused||S.status==="paused"),O=S.currentLevelSLA.percentageUsed||0,M=R?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:O>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:O>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:O>=50?{bg:"bg-amber-50 border border-amber-200",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{bg:"bg-green-50 border border-green-200",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"};return e.jsxs("div",{className:`p-2 rounded-md ${M.bg}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[R?e.jsx(vn,{className:`w-3.5 h-3.5 ${M.icon}`}):e.jsx(Xe,{className:`w-3.5 h-3.5 ${M.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",O,"% ",R&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:S.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${M.text}`,children:[S.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(oa,{value:O,className:"h-1.5",indicatorClassName:M.progress})]})})(),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(es,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ts,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:S.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:S.initiator.name})]}),S.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(es,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(ts,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:S.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:S.currentApprover.name})]}),S.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ve,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:S.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(lt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",S.createdAt!=="—"?pa(S.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(xs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},S.id)})}),D.length===0&&e.jsx(J,{className:"shadow-lg border-0",children:e.jsxs(q,{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(De,{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:x.searchTerm||x.activeFiltersCount>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),x.activeFiltersCount>0&&e.jsx(I,{variant:"outline",className:"mt-4",onClick:x.clearFilters,children:"Clear all filters"})]})}),o>1&&!r&&e.jsx(J,{className:"shadow-md",children:e.jsx(q,{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 ",(x.currentPage-1)*u+1," to ",Math.min(x.currentPage*u,d)," of ",d," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>w(x.currentPage-1),disabled:x.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(xs,{className:"h-4 w-4 rotate-180"})}),x.currentPage>3&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>w(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),T().map(S=>e.jsx(I,{variant:S===x.currentPage?"default":"outline",size:"sm",onClick:()=>w(S),className:`h-8 w-8 p-0 ${S===x.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:S},S)),x.currentPage<o-2&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>w(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>w(x.currentPage+1),disabled:x.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(xs,{className:"h-4 w-4"})})]})]})})})]})}function LT({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(De,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900",children:"My Closed Requests"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:"Review your completed and archived requests"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsxs(ie,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold","data-testid":"closed-requests-count",children:[s?"Loading…":`${t} closed`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:r,disabled:a,"data-testid":"closed-requests-refresh",children:[e.jsx(zt,{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 OT(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ga,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ht,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ht,iconColor:"text-gray-600"}}}function $T(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:Pe,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:Nt,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ve,iconColor:"text-gray-600",label:t,description:""}}}function UT({request:t,onViewRequest:s}){const a=OT(t.priority),r=$T(t.status),n=a.icon,i=r.icon;return e.jsx(J,{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(q,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-5",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${a.color} border shadow-sm`,children:e.jsx(n,{className:`w-5 h-5 ${a.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:t.displayId||t.id}),e.jsxs(ie,{variant:"outline",className:`${r.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(i,{className:"w-3.5 h-3.5 mr-1"}),r.label]}),t.department&&e.jsx(ie,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:t.department}),e.jsx(ie,{variant:"outline",className:`${a.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:t.priority}),(()=>{const l=t.templateType||"",o=(l==null?void 0:l.toUpperCase())||"";let c="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(ie,{variant:"outline",className:`${d} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:c})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(es,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ts,{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(Pe,{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(lt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?pa(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Pe,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",pa(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(xs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function BT({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(UT,{request:r,onViewRequest:a},r.id))})}function VT({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(J,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(q,{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(De,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:t||s>0?"Try adjusting your filters or search terms to see more results.":"No closed requests available at the moment."}),s>0&&e.jsx(I,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function zT(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 HT({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=zT(a,r);return e.jsx(J,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(q,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(a-1)*i+1," to ",Math.min(a*i,n)," of ",n," closed requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>s(a-1),disabled:a===1,className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-prev",children:e.jsx(xs,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>s(1),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-first",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),l.map(o=>e.jsx(I,{variant:o===a?"default":"outline",size:"sm",onClick:()=>s(o),className:`h-8 w-8 p-0 ${o===a?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`closed-requests-pagination-page-${o}`,children:o},o)),a<r-2&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>s(a+1),disabled:a===r,className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-next",children:e.jsx(xs,{className:"h-4 w-4"})})]})]})})})}function WT(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 GT(t){return t.map(WT)}function KT({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(u=1,h)=>{try{u===1&&(n(!0),a([]));const x=await Ms.listClosedByMe({page:u,limit:t,search:h==null?void 0:h.search,status:h!=null&&h.status&&h.status!=="all"?h.status:void 0,priority:h==null?void 0:h.priority,templateType:h==null?void 0:h.templateType,sortBy:h==null?void 0:h.sortBy,sortOrder:h==null?void 0:h.sortOrder}),g=Array.isArray(x==null?void 0:x.data)?x.data:[],f=GT(g);a(f);const y=x==null?void 0:x.pagination;y&&c({currentPage:y.page||1,totalPages:y.totalPages||1,totalRecords:y.total||0,itemsPerPage:t})}catch(x){console.error("[ClosedRequests] Error fetching requests:",x),a([])}finally{n(!1),l(!1)}},[t]),m=p.useCallback(u=>{l(!0),d(o.currentPage,u)},[d,o.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:o,fetchRequests:d,handleRefresh:m}}const YT={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},vg=Gr({name:"closedRequests",initialState:YT,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:ZT,setStatusFilter:XT,setPriorityFilter:QT,setTemplateTypeFilter:JT,setSortBy:qT,setSortOrder:e5,setCurrentPage:t5,clearFilters:s5}=vg.actions;function a5({onFiltersChange:t,debounceMs:s=500}={}){const a=Dn(),r=p.useRef(null),n=p.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,sortBy:d,sortOrder:m,currentPage:u}=Yr(C=>C.closedRequests),h=p.useCallback(C=>a(ZT(C)),[a]),x=p.useCallback(C=>a(XT(C)),[a]),g=p.useCallback(C=>a(QT(C)),[a]),f=p.useCallback(C=>a(JT(C)),[a]),y=p.useCallback(C=>a(qT(C)),[a]),b=p.useCallback(C=>a(e5(C)),[a]),v=p.useCallback(C=>a(t5(C)),[a]),A=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 C=setTimeout(()=>{t&&t(A())},i?s:0);return r.current=C,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,t,A,s]);const w=p.useCallback(()=>{a(s5())},[a]),T=[i,o!=="all"?o:null,l!=="all"?l:null,c!=="all"?c:null].filter(Boolean).length;return{searchTerm:i,priorityFilter:o,statusFilter:l,templateTypeFilter:c,sortBy:d,sortOrder:m,currentPage:u,setSearchTerm:h,setPriorityFilter:g,setStatusFilter:x,setTemplateTypeFilter:f,setSortBy:y,setSortOrder:b,setCurrentPage:v,clearFilters:w,activeFiltersCount:T,getFilters:A}}function r5({onViewRequest:t}){const s=KT({itemsPerPage:10}),a=p.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=a5(),n=p.useMemo(()=>{try{const u=at.getUserData();return Vo(u)}catch(u){return console.error("[ClosedRequests] Error getting user filter type:",u),"STANDARD"}},[]),i=p.useMemo(()=>IT(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 u=r.currentPage||1;a.current(u,{search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:!l&&r.priorityFilter!=="all"?r.priorityFilter:void 0,templateType:!l&&r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}),c.current=!0},[l]),p.useEffect(()=>{if(!c.current)return;const u=o.current;if(!(u.searchTerm!==r.searchTerm||u.statusFilter!==r.statusFilter||u.priorityFilter!==r.priorityFilter||u.templateTypeFilter!==r.templateTypeFilter||u.sortBy!==r.sortBy||u.sortOrder!==r.sortOrder))return;const x=setTimeout(()=>{r.setCurrentPage(1),a.current(1,{search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:r.priorityFilter!=="all"?r.priorityFilter:void 0,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}),o.current={searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}},r.searchTerm!==u.searchTerm?500:0);return()=>clearTimeout(x)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.templateTypeFilter,r.sortBy,r.sortOrder,l]);const d=p.useCallback(u=>{u>=1&&u<=s.pagination.totalPages&&(r.setCurrentPage(u),s.fetchRequests(u,{search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:r.priorityFilter!=="all"?r.priorityFilter:void 0,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}))},[s,r]),m=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(LT,{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(BT,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(VT,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(HT,{pagination:s.pagination,onPageChange:d})]})}function n5(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 i5(t){return n5(t)?"DEALER_CLAIM":"CUSTOM"}function l5(t,s){return`/request/${t}`}class o5 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(ss,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(I,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(I,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function c5({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=La().requestId||t||"",{user:i}=Qt(),{apiRequest:l,loading:o}=wc(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(zt,{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=i5(l),d=DT(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function d5(t){return e.jsx(o5,{children:e.jsx(c5,{...t})})}function m5({onViewSummary:t}){const s=qs(),[a,r]=p.useState([]),[n,i]=p.useState(!0),[l,o]=p.useState(""),[c,d]=p.useState(1),[m,u]=p.useState(1),[h,x]=p.useState(0),g=10,f=p.useCallback(async(A=1)=>{try{i(!0);const w=await fS({page:A,limit:g});r(w.data||[]),u(w.pagination.totalPages||1),x(w.pagination.total||0),d(w.pagination.page||1)}catch(w){console.error("Failed to fetch shared summaries:",w),K.error("Failed to load shared summaries")}finally{i(!1)}},[]);p.useEffect(()=>{f(1)},[f]);const y=async A=>{try{await cg(A),r(w=>w.map(T=>T.sharedSummaryId===A?{...T,isRead:!0,viewedAt:new Date().toISOString()}:T)),t?t(A):s(`/shared-summaries/${A}`)}catch(w){console.error("Failed to mark as viewed:",w),t?t(A):s(`/shared-summaries/${A}`)}},b=A=>{A>=1&&A<=m&&f(A)},v=a.filter(A=>{var T,C,_,D;if(!l)return!0;const w=l.toLowerCase();return((T=A.title)==null?void 0:T.toLowerCase().includes(w))||((C=A.requestNumber)==null?void 0:C.toLowerCase().includes(w))||((_=A.initiatorName)==null?void 0:_.toLowerCase().includes(w))||((D=A.sharedByName)==null?void 0:D.toLowerCase().includes(w))});return e.jsx("div",{className:"min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden",children:e.jsxs("div",{className:"max-w-7xl mx-auto w-full",children:[e.jsxs("div",{className:"mb-4 sm:mb-6",children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900 mb-1 sm:mb-2",children:"Shared Summaries"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600",children:"View summaries of closed requests shared with you"})]}),e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ie,{placeholder:"Search by title, request number, or user...",value:l,onChange:A=>o(A.target.value),className:"pl-10 text-sm sm:text-base"})]})}),n&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ze,{className:"h-8 w-8 animate-spin text-blue-600"})}),!n&&v.length===0&&e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-6 sm:p-12 text-center",children:[e.jsx(De,{className:"h-8 w-8 sm:h-12 sm:w-12 text-gray-400 mx-auto mb-3 sm:mb-4"}),e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-1 sm:mb-2",children:"No shared summaries"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:l?"No summaries match your search.":"You haven't received any shared summaries yet."})]}),!n&&v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-3 sm:gap-4 mb-4 sm:mb-6",children:v.map(A=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${A.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>y(A.sharedSummaryId),children:e.jsx("div",{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[A.isRead?e.jsx(I0,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(xt,{className:"h-4 w-4 text-blue-600 flex-shrink-0"}),e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900 truncate flex-1 min-w-0",children:A.title}),!A.isRead&&e.jsx("span",{className:"px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded-full flex-shrink-0",children:"New"})]}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 break-words",children:["Request: ",e.jsx("span",{className:"font-medium",children:A.requestNumber})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap items-start sm:items-center gap-2 sm:gap-3 md:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Lt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Initiator: ",e.jsx("span",{className:"font-medium",children:A.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Lt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared by: ",e.jsx("span",{className:"font-medium",children:A.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(lt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",Ye(new Date(A.sharedAt),"MMM dd, yyyy HH:mm")]})]}),A.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(xt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",Ye(new Date(A.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(I,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:w=>{w.stopPropagation(),y(A.sharedSummaryId)},children:"View"})]})})},A.sharedSummaryId))}),m>1&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 sm:gap-4 bg-white rounded-lg shadow-sm border border-gray-200 p-3 sm:p-4",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-gray-600 text-center sm:text-left",children:["Showing ",(c-1)*g+1," to ",Math.min(c*g,h)," of ",h," summaries"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>b(c-1),disabled:c===1,className:"text-xs sm:text-sm",children:"Previous"}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 whitespace-nowrap",children:["Page ",c," of ",m]}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>b(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function u5(){const{sharedSummaryId:t}=La(),s=qs(),[a,r]=p.useState(null),[n,i]=p.useState(!0);p.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,u;try{i(!0);try{await cg(t)}catch(x){console.warn("Failed to mark as viewed:",x)}const h=await Cc(t);r(h)}catch(h){console.error("Failed to fetch summary details:",h),K.error(((u=(m=h==null?void 0:h.response)==null?void 0:m.data)==null?void 0:u.message)||"Failed to load summary"),s("/shared-summaries")}finally{i(!1)}})()},[t,s]);const l=d=>{const m=d.toLowerCase();return m==="approved"?e.jsx(Pe,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(Nt,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(Xe,{className:"h-4 w-4 text-orange-600"}):e.jsx(De,{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(Ze,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):a?e.jsx("div",{className:"min-h-screen bg-gray-50 p-4 sm:p-6",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs(I,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(Ss,{className:"h-4 w-4 mr-2"}),"Back to Shared Summaries"]}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-2",children:"Request Summary"})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 mb-6",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:a.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",a.requestNumber]})]}),e.jsxs(ie,{className:o(a.workflow.status),children:[l(a.workflow.status),e.jsx("span",{className:"ml-1 capitalize",children:a.workflow.status})]})]}),a.description&&e.jsx("div",{className:"mb-4",children:e.jsx(na,{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:Ye(new Date(a.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),a.approvers&&a.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),a.approvers.map((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:Ye(new Date(d.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:d.remarks})]})]},m))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),a.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(ie,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),a.closingRemarks?e.jsx(na,{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(De,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Summary Not Found"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"The summary you're looking for doesn't exist."}),e.jsx(I,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function x5(){const{requestId:t}=La(),s=qs(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(cs,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(og,{requestId:t||""})})})}function jg({icon:t,title:s,description:a,badge:r,actions:n,testId:i="page-header"}){return e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-3 sm:gap-4 md:gap-6","data-testid":i,children:[e.jsx("div",{className:"space-y-1 sm:space-y-2",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-slate-800 to-slate-900 rounded-xl flex items-center justify-center shadow-lg","data-testid":`${i}-icon-container`,children:e.jsx(t,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white","data-testid":`${i}-icon`})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900","data-testid":`${i}-title`,children:s}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600","data-testid":`${i}-description`,children:a})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[r&&e.jsxs(ie,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold","data-testid":`${i}-badge`,children:[r.loading?"Loading…":r.value,e.jsx("span",{className:"hidden sm:inline ml-1",children:r.label})]}),n]})]})}function Ws({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:l,testId:o="stats-card",onClick:c}){return e.jsx(J,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":o,onClick:c,children:e.jsx(q,{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 h5({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(Ws,{label:"Total",value:t.total,icon:De,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(Ws,{label:"Pending",value:t.pending,icon:Xe,iconColor:"text-orange-600",gradient:"bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200",textColor:"text-orange-700",valueColor:"text-orange-900",testId:"stat-pending",onClick:s?()=>a("pending"):void 0}),e.jsx(Ws,{label:"Paused",value:t.paused,icon:Ka,iconColor:"text-amber-600",gradient:"bg-gradient-to-br from-amber-50 to-amber-100 border-amber-200",textColor:"text-amber-700",valueColor:"text-amber-900",testId:"stat-paused",onClick:s?()=>a("paused"):void 0}),e.jsx(Ws,{label:"Approved",value:t.approved,icon:Pe,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(Ws,{label:"Rejected",value:t.rejected,icon:Nt,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(Ws,{label:"Draft",value:t.draft,icon:Oi,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(Ws,{label:"Closed",value:t.closed,icon:$i,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 p5({searchTerm:t,statusFilter:s,priorityFilter:a,onSearchChange:r,onStatusChange:n,onPriorityChange:i}){return e.jsx(J,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(q,{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(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(Ie,{placeholder:"Search requests by title, description, or ID...",value:t,onChange:l=>r(l.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(He,{value:s,onValueChange:n,children:[e.jsx(Ge,{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(We,{placeholder:"Status"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Status"}),e.jsx(X,{value:"draft",children:"Draft"}),e.jsx(X,{value:"pending",children:"Pending"}),e.jsx(X,{value:"paused",children:"Paused"}),e.jsx(X,{value:"approved",children:"Approved"}),e.jsx(X,{value:"rejected",children:"Rejected"}),e.jsx(X,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:i,children:[e.jsx(Ge,{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(We,{placeholder:"Priority"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Priority"}),e.jsx(X,{value:"express",children:"Express"}),e.jsx(X,{value:"standard",children:"Standard"})]})]})]})]})})})}function g5(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ga,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ht,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ht,iconColor:"text-gray-600"}}}function f5(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Pe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Nt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Xe,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Oi,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ve,iconColor:"text-gray-600"}}}const y5=t=>{if(!t)return"";if(typeof document>"u")return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();const s=document.createElement("div");s.innerHTML=t;let a=s.textContent||s.innerText||"";return a=a.replace(/\s+/g," ").trim(),a};function b5({request:t,index:s,onViewRequest:a}){var o;const r=f5(t.status),n=g5(t.priority),i=r.icon,l=n.icon;return e.jsx(ms.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(J,{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(q,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(ie,{variant:"outline",className:`${r.color} border font-medium text-xs shrink-0`,"data-testid":"status-badge",children:[e.jsx(i,{className:"w-3 h-3 mr-1"}),e.jsx("span",{className:"capitalize",children:t.status})]}),(((o=t.pauseInfo)==null?void 0:o.isPaused)||t.isPaused)&&e.jsxs(ie,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-300 font-medium text-xs shrink-0","data-testid":"pause-badge",children:[e.jsx(Ka,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ie,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(l,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Non-Templatized",u="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",u="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(ie,{variant:"outline",className:`${u} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})()]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2 leading-relaxed","data-testid":"request-description",children:y5(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:"})," ",pa(t.submittedDate)]})]})]}),e.jsx(xs,{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(Lt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm truncate","data-testid":"current-approver",children:[e.jsx("span",{className:"text-gray-500",children:"Current Approver:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.currentApprover})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm","data-testid":"approval-level",children:[e.jsx("span",{className:"text-gray-500",children:"Approval Level:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.approverLevel})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-500",children:[e.jsx(Xe,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",pa(t.submittedDate)]})]})]})]})})})})}function v5({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(J,{"data-testid":"loading-state",children:e.jsx(q,{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(J,{"data-testid":"empty-state",children:e.jsxs(q,{className:"p-12 text-center",children:[e.jsx(De,{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(b5,{request:l,index:o,onViewRequest:i},l.id))})}function j5(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 Ng(t){return Array.isArray(t)?t.map(j5):[]}function N5({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,u)=>{try{m===1&&(n(!0),a([]));const h=await Ms.listMyInitiatedWorkflows({page:m,limit:t,search:u==null?void 0:u.search,status:u==null?void 0:u.status,priority:u==null?void 0:u.priority,templateType:u==null?void 0:u.templateType}),x=Array.isArray(h==null?void 0:h.data)?h.data:[],g=Ng(x);a(g),l(!0);const f=h==null?void 0:h.pagination;f&&c({currentPage:f.page||1,totalPages:f.totalPages||1,totalRecords:f.total||0,itemsPerPage:t})}catch(h){console.error("[MyRequests] Error fetching requests:",h),a([]),l(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:o,fetchMyRequests:d}}const w5={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},wg=Gr({name:"myRequests",initialState:w5,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:C5,setStatusFilter:A5,setPriorityFilter:S5,setTemplateTypeFilter:T5,setCurrentPage:k5,clearFilters:R5}=wg.actions;function D5({onFiltersChange:t,debounceMs:s=500}={}){const a=Dn(),r=p.useRef(null),n=p.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d}=Yr(b=>b.myRequests),m=p.useCallback(b=>a(C5(b)),[a]),u=p.useCallback(b=>a(A5(b)),[a]),h=p.useCallback(b=>a(S5(b)),[a]),x=p.useCallback(b=>a(T5(b)),[a]),g=p.useCallback(b=>a(k5(b)),[a]),f=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 b=setTimeout(()=>{t&&t(f())},i?s:0);return r.current=b,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,t,f,s]);const y=p.useCallback(()=>{a(R5())},[a]);return{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d,setSearchTerm:m,setStatusFilter:u,setPriorityFilter:h,setTemplateTypeFilter:x,setCurrentPage:g,getFilters:f,resetFilters:y}}function P5({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=Qt(),r=N5({itemsPerPage:10}),n=p.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=D5(),l=p.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}),o=p.useRef(!1);p.useEffect(()=>{const b=i.currentPage||1;n.current(b,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),o.current=!0},[]),p.useEffect(()=>{if(!o.current)return;const b=l.current;if(!(b.searchTerm!==i.searchTerm||b.statusFilter!==i.statusFilter||b.priorityFilter!==i.priorityFilter||b.templateTypeFilter!==i.templateTypeFilter))return;const A=setTimeout(()=>{i.setCurrentPage(1),n.current(1,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),l.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}},i.searchTerm!==b.searchTerm?500:0);return()=>clearTimeout(A)},[i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter]);const[c,d]=p.useState(null),[m,u]=p.useState(!1),h=p.useCallback(async()=>{if(a!=null&&a.userId)try{u(!0);const b=await St.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:b.totalRequests||0,pending:b.openRequests||0,paused:b.pausedRequests||0,approved:b.approvedRequests||0,rejected:b.rejectedRequests||0,draft:b.draftRequests||0,closed:b.closedRequests||0})}catch(b){console.error("Failed to fetch backend stats:",b),d(null)}finally{u(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter,i.templateTypeFilter]);p.useEffect(()=>{const b=setTimeout(()=>{h()},i.searchTerm?500:0);return()=>clearTimeout(b)},[i.searchTerm,i.priorityFilter,i.templateTypeFilter,h]);const x=Ng(s),g=r.hasFetchedFromApi?r.requests:x,f=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]),y=p.useCallback(b=>{b>=1&&b<=r.pagination.totalPages&&(i.setCurrentPage(b),r.fetchMyRequests(b,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}))},[r,i]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"my-requests-page",children:[e.jsx(jg,{icon:De,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${f.total} total`,label:"requests",loading:r.loading||m},testId:"my-requests-header"}),e.jsx(h5,{stats:f,onStatusFilter:b=>{i.setStatusFilter(b)}}),e.jsx(p5,{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(v5,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(wr,{currentPage:i.currentPage||r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:y,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function Cg({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(jg,{icon:De,title:i(),description:l(),testId:"requests-header"}),e.jsx(ie,{variant:"outline",className:t?"bg-blue-50 text-blue-700 border-blue-200":"bg-green-50 text-green-700 border-green-200",children:t?"Organization":"Personal"})]}),e.jsx(I,{onClick:n,disabled:r||a,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-button",children:r?e.jsxs(e.Fragment,{children:[e.jsx(zt,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function Ag({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(Ws,{label:"Total",value:t.total,icon:De,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(Ws,{label:"Pending",value:t.pending,icon:Xe,iconColor:"text-orange-600",gradient:"bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200",textColor:"text-orange-700",valueColor:"text-orange-900",testId:"stat-pending",onClick:s?()=>a("pending"):void 0}),e.jsx(Ws,{label:"Paused",value:t.paused,icon:Ka,iconColor:"text-amber-600",gradient:"bg-gradient-to-br from-amber-50 to-amber-100 border-amber-200",textColor:"text-amber-700",valueColor:"text-amber-900",testId:"stat-paused",onClick:s?()=>a("paused"):void 0}),e.jsx(Ws,{label:"Approved",value:t.approved,icon:Pe,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(Ws,{label:"Rejected",value:t.rejected,icon:Nt,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(Ws,{label:"Closed",value:t.closed,icon:$i,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 I5=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ga,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ht,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ht,iconColor:"text-gray-600"}}},E5=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Pe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Nt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Xe,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Oi,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ve,iconColor:"text-gray-600"}}},F5=t=>{if(!t)return"";if(typeof document>"u")return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();const s=document.createElement("div");s.innerHTML=t;let a=s.textContent||s.innerText||"";return a=a.replace(/\s+/g," ").trim(),a};function M5({request:t,index:s,onViewRequest:a}){var o;const r=E5(t.status),n=I5(t.priority),i=r.icon,l=n.icon;return e.jsx(ms.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(J,{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(q,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(ie,{variant:"outline",className:`${r.color} border font-medium text-xs shrink-0`,"data-testid":"status-badge",children:[e.jsx(i,{className:"w-3 h-3 mr-1"}),e.jsx("span",{className:"capitalize",children:t.status})]}),(((o=t.pauseInfo)==null?void 0:o.isPaused)||t.isPaused)&&e.jsxs(ie,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-300 font-medium text-xs shrink-0","data-testid":"pause-badge",children:[e.jsx(Ka,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ie,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(l,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Non-Templatized",u="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",u="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(ie,{variant:"outline",className:`${u} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})(),t.department&&e.jsx(ie,{variant:"secondary",className:"bg-purple-100 text-purple-700 text-xs shrink-0","data-testid":"department-badge",children:t.department})]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2 leading-relaxed","data-testid":"request-description",children:F5(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:"})," ",pa(t.submittedDate)]})]})]}),e.jsx(xs,{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(Lt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm truncate","data-testid":"current-approver",children:[e.jsx("span",{className:"text-gray-500",children:"Current Approver:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.currentApprover})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm","data-testid":"approval-level",children:[e.jsx("span",{className:"text-gray-500",children:"Approval Level:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.approverLevel})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-500",children:[e.jsx(Xe,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",pa(t.submittedDate)]})]})]})]})})})})}function Sg({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(J,{"data-testid":"loading-state",children:e.jsx(q,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(J,{"data-testid":"empty-state",children:e.jsxs(q,{className:"p-12 text-center",children:[e.jsx(De,{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(M5,{request:n,index:i,onViewRequest:r},n.id))})}const _5={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},Tg=Gr({name:"requests",initialState:_5,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:L5,setStatusFilter:O5,setPriorityFilter:$5,setTemplateTypeFilter:U5,setSlaComplianceFilter:B5,setDepartmentFilter:V5,setInitiatorFilter:z5,setApproverFilter:H5,setApproverFilterType:W5,setDateRange:_u,setCustomStartDate:_l,setCustomEndDate:Ll,setShowCustomDatePicker:Yn,setCurrentPage:G5,clearFilters:K5}=Tg.actions;function kg(){const t=Dn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:c,approverFilterType:d,dateRange:m,customStartDate:u,customEndDate:h,showCustomDatePicker:x,currentPage:g}=Yr(N=>N.requests),f=p.useCallback(N=>t(L5(N)),[t]),y=p.useCallback(N=>t(O5(N)),[t]),b=p.useCallback(N=>t($5(N)),[t]),v=p.useCallback(N=>t(U5(N)),[t]),A=p.useCallback(N=>t(B5(N)),[t]),w=p.useCallback(N=>t(V5(N)),[t]),T=p.useCallback(N=>t(z5(N)),[t]),C=p.useCallback(N=>t(H5(N)),[t]),_=p.useCallback(N=>t(W5(N)),[t]),D=p.useCallback(N=>t(_u(N)),[t]),S=p.useCallback(N=>t(_l(N)),[t]),j=p.useCallback(N=>t(Ll(N)),[t]),P=p.useCallback(N=>t(Yn(N)),[t]),R=p.useCallback(N=>t(G5(N)),[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:u,endDate:h}),[s,a,r,n,i,l,o,c,d,m,u,h]),F=p.useCallback(()=>{t(K5())},[t]),M=p.useCallback(N=>{const U=N;t(_u(U)),U!=="custom"?(t(_l(void 0)),t(Ll(void 0)),t(Yn(!1))):t(Yn(!0))},[t]),B=p.useCallback(()=>{u&&h&&(u>h&&(t(_l(h)),t(Ll(u))),t(Yn(!1)))},[u,h,t]);return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:c,approverFilterType:d,dateRange:m,customStartDate:u,customEndDate:h,showCustomDatePicker:x,currentPage:g,hasActiveFilters:!!(s||a!=="all"||r!=="all"||n!=="all"||i!=="all"||l!=="all"||o!=="all"||c!=="all"||m!=="all"||u||h),setSearchTerm:f,setStatusFilter:y,setPriorityFilter:b,setTemplateTypeFilter:v,setSlaComplianceFilter:A,setDepartmentFilter:w,setInitiatorFilter:T,setApproverFilter:C,setApproverFilterType:_,setDateRange:D,setCustomStartDate:S,setCustomEndDate:j,setShowCustomDatePicker:P,setCurrentPage:R,getFilters:O,clearFilters:F,handleDateRangeChange:M,handleApplyCustomDate:B}}function wi({allUsers:t,filterValue:s,onFilterChange:a}){const[r,n]=p.useState(""),[i,l]=p.useState([]),[o,c]=p.useState(!1),[d,m]=p.useState(null),u=p.useRef(null);p.useEffect(()=>{if(s!=="all"&&t.length>0){const f=t.find(y=>y.userId===s);f&&(m(f),n(f.displayName||f.email))}},[s,t]),p.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const h=p.useCallback(f=>{if(n(f),u.current&&clearTimeout(u.current),!f||f.trim().length<2){l([]),c(!1);return}u.current=setTimeout(()=>{const y=f.toLowerCase().trim(),b=t.filter(v=>{const A=(v.email||"").toLowerCase(),w=(v.displayName||"").toLowerCase();return A.includes(y)||w.includes(y)});l(b.slice(0,10)),c(b.length>0)},300)},[t]),x=p.useCallback(f=>{m(f),a(f.userId),n(f.displayName||f.email),c(!1),l([])},[a]),g=p.useCallback(()=>{m(null),a("all"),n(""),c(!1),l([])},[a]);return{searchQuery:r,searchResults:i,showResults:o,selectedUser:d,handleSearch:h,handleSelect:x,handleClear:g,setShowResults:c}}function Y5(t){var d,m,u,h,x,g,f;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 y=t.approvals.find(b=>{const v=(b.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(y)n=y.approverName||((d=y.approver)==null?void 0:d.name)||((m=y.approver)==null?void 0:m.displayName)||y.approverEmail||((u=y.approver)==null?void 0:u.email)||"—";else{const v=[...t.approvals].sort((A,w)=>{const T=A.levelNumber||A.level_number||0;return(w.levelNumber||w.level_number||0)-T})[0];v&&(n=v.approverName||((h=v.approver)==null?void 0:h.name)||((x=v.approver)==null?void 0:x.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 y=t.approvals.find(b=>{const v=(b.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(y){const b=y.levelNumber||y.level_number||0,v=c||t.approvals.length;i=`${b} 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||((f=t.initiator)==null?void 0:f.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 Rg(t){return Array.isArray(t)?t.map(Y5):[]}function Z5(t,s,a,r,n,i){if(t.length>0){const l=t.length,o=t.filter(x=>{const g=(x.status||"").toString().toUpperCase();return g==="PENDING"||g==="IN_PROGRESS"}).length,c=t.filter(x=>(x.status||"").toString().toUpperCase()==="APPROVED").length,d=t.filter(x=>(x.status||"").toString().toUpperCase()==="REJECTED").length,m=t.filter(x=>(x.status||"").toString().toUpperCase()==="DRAFT").length,u=t.filter(x=>(x.status||"").toString().toUpperCase()==="CLOSED").length,h=t.filter(x=>(x.status||"").toString().toUpperCase()==="PAUSED").length;return{total:l,pending:o,paused:h,approved:c,rejected:d,draft:m,closed:u}}else return s&&a?{total:a.total,pending:a.pending,paused:a.paused||0,approved:a.approved,rejected:a.rejected,draft:a.draft,closed:a.closed}:{total:n||i.length,pending:i.filter(o=>o.status==="pending"||o.status==="in-progress").length,paused:i.filter(o=>o.status==="paused").length,approved:i.filter(o=>o.status==="approved").length,rejected:i.filter(o=>o.status==="rejected").length,draft:i.filter(o=>o.status==="draft").length,closed:i.filter(o=>o.status==="closed").length}}var Dg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Ai,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(Dg);var X5=Dg.exports;const Pg=Si(X5);var Ig={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Ai,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(Ig);var Q5=Ig.exports;const Eg=Si(Q5);Gt.extend(Eg);Gt.extend(Pg);function J5(t,s){let a=[...t];if(s.search){const r=s.search.toLowerCase();a=a.filter(n=>{var i,l,o,c;return((i=n.title)==null?void 0:i.toLowerCase().includes(r))||((l=n.description)==null?void 0:l.toLowerCase().includes(r))||((o=n.requestNumber)==null?void 0:o.toLowerCase().includes(r))||((c=n.request_number)==null?void 0:c.toLowerCase().includes(r))})}if(s.status&&s.status!=="all")if(s.status.toLowerCase()==="pending")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return(n==="PENDING"||n==="IN_PROGRESS")&&!i});else if(s.status.toLowerCase()==="paused")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return n==="PAUSED"||i});else{const r=s.status.toUpperCase().replace("-","_");a=a.filter(n=>{var o;const i=(n.status||"").toString().toUpperCase(),l=((o=n.pauseInfo)==null?void 0:o.isPaused)||n.isPaused||!1;return r==="IN_PROGRESS"||r==="IN-PROGRESS"?i==="IN_PROGRESS"&&!l:i===r&&!l})}if(s.priority&&s.priority!=="all"&&(a=a.filter(r=>{var n;return(r.priority||"").toString().toLowerCase()===((n=s.priority)==null?void 0:n.toLowerCase())})),s.department&&s.department!=="all"&&(a=a.filter(r=>{var i;return(r.department||((i=r.initiator)==null?void 0:i.department)||"")===s.department})),s.initiator&&s.initiator!=="all"&&(a=a.filter(r=>{var i,l;return(r.initiatorId||r.initiator_id||((i=r.initiator)==null?void 0:i.userId)||((l=r.initiator)==null?void 0:l.user_id)||(r.initiator&&typeof r.initiator=="object"&&"userId"in r.initiator?r.initiator.userId:null))===s.initiator})),s.approver&&s.approver!=="all"&&((s.approverType||"current")==="current"?a=a.filter(n=>{var l,o,c,d,m,u;return(((l=n.currentApprover)==null?void 0:l.userId)||((o=n.currentApprover)==null?void 0:o.user_id)||((d=(c=n.approvals)==null?void 0:c.find(h=>{const x=(h.status||"").toString().toUpperCase();return x==="IN_PROGRESS"||x==="PENDING"}))==null?void 0:d.approverId)||((u=(m=n.approvals)==null?void 0:m.find(h=>{const x=(h.status||"").toString().toUpperCase();return x==="IN_PROGRESS"||x==="PENDING"}))==null?void 0:u.approver_id)||n.currentApproverId||n.current_approver_id)===s.approver}):a=a.filter(n=>{var l,o;const i=[];return(l=n.currentApprover)!=null&&l.userId&&i.push(n.currentApprover.userId),(o=n.currentApprover)!=null&&o.user_id&&i.push(n.currentApprover.user_id),Array.isArray(n.approvals)&&n.approvals.forEach(c=>{c.approverId&&i.push(c.approverId),c.approver_id&&i.push(c.approver_id)}),i.includes(s.approver||"")})),s.slaCompliance&&s.slaCompliance!=="all"&&(a=a.filter(r=>{var c,d,m,u,h,x,g,f,y,b,v,A;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const w=(r.status||"").toString().toUpperCase();if(!(w==="APPROVED"||w==="REJECTED"||w==="CLOSED"))return!1;const C=((c=r.currentLevelSLA)==null?void 0:c.status)||((m=(d=r.currentApprover)==null?void 0:d.sla)==null?void 0:m.status)||((u=r.sla)==null?void 0:u.status)||((x=(h=r.summary)==null?void 0:h.sla)==null?void 0:x.status);return C?C!=="breached"&&C.toLowerCase()!=="breached":!0}const i=((g=r.currentLevelSLA)==null?void 0:g.status)||((y=(f=r.currentApprover)==null?void 0:f.sla)==null?void 0:y.status)||((b=r.sla)==null?void 0:b.status)||((A=(v=r.summary)==null?void 0:v.sla)==null?void 0:A.status);if(!i)return n==="on-track"||n==="on_track";const o={"on-track":"on_track",on_track:"on_track",approaching:"approaching",critical:"critical",breached:"breached"}[n.toLowerCase()]||n.toLowerCase();return i===o||i.toLowerCase()===o})),s.dateRange){let r=null,n=null;if(s.dateRange==="custom"&&s.startDate&&s.endDate)r=Gt(s.startDate).startOf("day").toDate(),n=Gt(s.endDate).endOf("day").toDate();else{const i=Gt();switch(s.dateRange){case"today":r=i.startOf("day").toDate(),n=i.endOf("day").toDate();break;case"week":r=i.startOf("week").toDate(),n=i.endOf("week").toDate();break;case"month":r=i.startOf("month").toDate(),n=i.endOf("month").toDate();break}}r&&n&&(a=a.filter(i=>{const l=i.submittedAt||i.submission_date||i.submitted_at;if(!l){const m=i.createdAt||i.created_at||i.created_date;if(!m)return!1;const u=Gt(m).startOf("day").toDate(),h=Gt(r).startOf("day").toDate(),x=Gt(n).endOf("day").toDate();return u>=h&&u<=x}const o=Gt(l).startOf("day").toDate(),c=Gt(r).startOf("day").toDate(),d=Gt(n).endOf("day").toDate();return o>=c&&o<=d}))}return a}Gt.extend(Pg);Gt.extend(Eg);function q5(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return Ye(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function Fg(t,s){const a=J5(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var v,A,w,T,C;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),u=((v=c.initiator)==null?void 0:v.displayName)||((A=c.initiator)==null?void 0:A.email)||c.initiatorName||"N/A",h=c.department||((w=c.initiator)==null?void 0:w.department)||"N/A",x=((T=c.currentApprover)==null?void 0:T.displayName)||((C=c.currentApprover)==null?void 0:C.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",f=q5(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),y=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),b=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${u.replace(/"/g,'""')}"`,`"${h.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,g,f,`"${y}"`];r.push(b.join(","))});const n=r.join(`
`),i=new Blob([n],{type:"text/csv;charset=utf-8;"}),l=document.createElement("a"),o=URL.createObjectURL(i);l.setAttribute("href",o),l.setAttribute("download",`requests-export-${new Date().toISOString().split("T")[0]}.csv`),l.style.visibility="hidden",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o)}async function ek({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 Ms.listWorkflows({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const u=m.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),h=(d==null?void 0:d.pagination)||{page:t,limit:s,total:u.length,totalPages:1};return{data:u,allData:[],filteredData:u,pagination:{page:h.page,limit:h.limit||s,total:h.total||u.length,totalPages:h.totalPages||1}}}else{const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.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 Ms.listParticipantRequests({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const u=m.filter(x=>(x.status||"").toString().toUpperCase()!=="DRAFT"),h=(d==null?void 0:d.pagination)||{page:t,limit:s,total:u.length,totalPages:1};return{data:u,allData:[],filteredData:u,pagination:h}}}async function tk(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const l=t?await Ms.listWorkflows({page:r,limit:100}):await Ms.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 sk({onViewRequest:t}){const{user:s}=Qt(),a=Yr(G=>G.dashboard.viewAsUser),r=p.useMemo(()=>Ui(s),[s]),n=p.useMemo(()=>r&&!a,[r,a]),i=kg(),[l,o]=p.useState([]),[c,d]=p.useState(!1),[m,u]=p.useState(!1),[h,x]=p.useState(null),[g,f]=p.useState([]),[y,b]=p.useState(!1),[v,A]=p.useState([]),[w,T]=p.useState(1),[C,_]=p.useState(0),[D]=p.useState(10),S=wi({allUsers:v,filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter}),j=wi({allUsers:v,filterValue:i.approverFilter,onFilterChange:i.setApproverFilter}),P=p.useCallback(async(G,oe,Z,E)=>{try{const V=E==null?void 0:E.slaCompliance;if(V&&V!=="all"&&V!=="breached"&&V!=="compliant"){const Q={};E!=null&&E.search&&(Q.search=E.search),E!=null&&E.priority&&E.priority!=="all"&&(Q.priority=E.priority),E!=null&&E.department&&E.department!=="all"&&(Q.department=E.department),E!=null&&E.initiator&&E.initiator!=="all"&&(Q.initiator=E.initiator),E!=null&&E.approver&&E.approver!=="all"&&(Q.approver=E.approver,Q.approverType=E.approverType||"current"),Q.slaCompliance=V,G&&(Q.dateRange=G),oe&&(Q.startDate=oe.toISOString()),Z&&(Q.endDate=Z.toISOString());const Y=n?await Ms.listWorkflows({page:1,limit:1e3,...Q}):await Ms.listParticipantRequests({page:1,limit:1e3,...Q}),W=Array.isArray(Y==null?void 0:Y.data)?Y.data:[],ce=W.length,xe=W.filter(ye=>{const Ne=(ye.status||"").toString().toUpperCase();return Ne==="PENDING"||Ne==="IN_PROGRESS"}).length,ke=W.filter(ye=>(ye.status||"").toString().toUpperCase()==="APPROVED").length,Ae=W.filter(ye=>(ye.status||"").toString().toUpperCase()==="REJECTED").length,ae=W.filter(ye=>(ye.status||"").toString().toUpperCase()==="CLOSED").length;x({total:ce,pending:xe,paused:0,approved:ke,rejected:Ae,draft:0,closed:ae})}else{const Q=await St.getRequestStats(G,oe?oe.toISOString():void 0,Z?Z.toISOString():void 0,void 0,E==null?void 0:E.priority,void 0,E==null?void 0:E.department,E==null?void 0:E.initiator,E==null?void 0:E.approver,E==null?void 0:E.approverType,E==null?void 0:E.search,E==null?void 0:E.slaCompliance,!n);x({total:Q.totalRequests||0,pending:Q.openRequests||0,paused:Q.pausedRequests||0,approved:Q.approvedRequests||0,rejected:Q.rejectedRequests||0,draft:Q.draftRequests||0,closed:Q.closedRequests||0})}}catch(V){console.error("Failed to fetch backend stats:",V)}finally{}},[n]),R=p.useCallback(async()=>{try{b(!0);const G=await St.getDepartments();f(G)}catch{}finally{b(!1)}},[]),O=p.useCallback(async()=>{try{const oe=(await Gs.getAllUsers()).map(Z=>({userId:Z.userId,email:Z.email,displayName:Z.displayName||Z.email}));A(oe)}catch(G){console.error("Failed to fetch users:",G)}},[]),F=p.useRef(i),M=p.useRef(P);p.useEffect(()=>{F.current=i,M.current=P},[i,P]),p.useEffect(()=>{const G=new URLSearchParams(window.location.search),oe=G.get("approver"),Z=G.get("approverType"),E=G.get("slaCompliance"),V=G.get("dateRange"),H=G.get("startDate"),Q=G.get("endDate");oe&&i.setApproverFilter(oe),(Z==="current"||Z==="any")&&i.setApproverFilterType(Z),E&&i.setSlaComplianceFilter(E),V&&i.setDateRange(V),H&&i.setCustomStartDate(new Date(H)),Q&&i.setCustomEndDate(new Date(Q))},[]);const B=p.useCallback(async(G=1)=>{try{G===1&&(d(!0),o([]));const oe=F.current.getFilters(),Z=await ek({page:G,itemsPerPage:D,filters:oe,isOrgLevel:n});o(Z.data),i.setCurrentPage(Z.pagination.page),T(Z.pagination.totalPages),_(Z.pagination.total)}catch{o([])}finally{d(!1)}},[D,n]),k=p.useCallback(async()=>{try{u(!0);const G=await tk(n);await Fg(G,i.getFilters())}catch(G){console.error("Failed to export requests:",G),alert("Failed to export requests. Please try again.")}finally{u(!1)}},[n,i]);p.useEffect(()=>{R(),O()},[R,O]),p.useEffect(()=>{const G=setTimeout(()=>{const oe={priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0,department:i.departmentFilter!=="all"?i.departmentFilter:void 0,initiator:i.initiatorFilter!=="all"?i.initiatorFilter:void 0,approver:i.approverFilter!=="all"?i.approverFilter:void 0,approverType:i.approverFilter!=="all"?i.approverFilterType:void 0,search:i.searchTerm||void 0,slaCompliance:i.slaComplianceFilter!=="all"?i.slaComplianceFilter:void 0},Z=i.dateRange||"all";M.current(Z,i.customStartDate,i.customEndDate,oe)},i.searchTerm?500:0);return()=>clearTimeout(G)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.templateTypeFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const N=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}),U=p.useRef(!1);p.useEffect(()=>{const G=i.currentPage||1;B(G),U.current=!0},[]),p.useEffect(()=>{if(!U.current)return;const G=N.current;if(!(G.searchTerm!==i.searchTerm||G.statusFilter!==i.statusFilter||G.priorityFilter!==i.priorityFilter||G.templateTypeFilter!==i.templateTypeFilter||G.slaComplianceFilter!==i.slaComplianceFilter||G.departmentFilter!==i.departmentFilter||G.initiatorFilter!==i.initiatorFilter||G.approverFilter!==i.approverFilter||G.approverFilterType!==i.approverFilterType||G.dateRange!==i.dateRange||G.customStartDate!==i.customStartDate||G.customEndDate!==i.customEndDate||G.isOrgLevel!==n))return;const Z=setTimeout(()=>{i.setCurrentPage(1),B(1),N.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!==G.searchTerm?500:0);return()=>clearTimeout(Z)},[n,i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter,i.slaComplianceFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.dateRange,i.customStartDate,i.customEndDate]);const $=p.useCallback(G=>{G>=1&&G<=w&&(i.setCurrentPage(G),B(G))},[w,B,i]),L=p.useMemo(()=>Rg(l),[l]),se=p.useMemo(()=>h?{total:h.total||0,pending:h.pending||0,paused:h.paused||0,approved:h.approved||0,rejected:h.rejected||0,draft:h.draft||0,closed:h.closed||0}:Z5([],n,h,!1,C,L),[n,h,C,L]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(Cg,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:k}),e.jsx(Ag,{stats:se,onStatusFilter:G=>{i.setStatusFilter(G)}}),e.jsx(J,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(q,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(ie,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(I,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx(zt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx($t,{}),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(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ie,{placeholder:"Search requests...",value:i.searchTerm,onChange:G=>i.setSearchTerm(G.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Ge,{className:"h-10","data-testid":"status-filter",children:e.jsx(We,{placeholder:"All Status"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Status"}),e.jsx(X,{value:"pending",children:"Pending"}),e.jsx(X,{value:"paused",children:"Paused"}),e.jsx(X,{value:"approved",children:"Approved"}),e.jsx(X,{value:"rejected",children:"Rejected"}),e.jsx(X,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(Ge,{className:"h-10","data-testid":"priority-filter",children:e.jsx(We,{placeholder:"All Priority"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Priority"}),e.jsx(X,{value:"express",children:"Express"}),e.jsx(X,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:y||g.length===0,children:[e.jsx(Ge,{className:"h-10","data-testid":"department-filter",children:e.jsx(We,{placeholder:y?"Loading...":"All Departments"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Departments"}),g.map(G=>e.jsx(X,{value:G,children:G},G))]})]}),e.jsxs(He,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Ge,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(We,{placeholder:"All SLA Status"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All SLA Status"}),e.jsx(X,{value:"compliant",children:"Compliant"}),e.jsx(X,{value:"on-track",children:"On Track"}),e.jsx(X,{value:"approaching",children:"Approaching"}),e.jsx(X,{value:"critical",children:"Critical"}),e.jsx(X,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:S.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:S.selectedUser.displayName||S.selectedUser.email}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:S.handleClear,children:e.jsx(gt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{placeholder:"Search initiator...",value:S.searchQuery,onChange:G=>S.handleSearch(G.target.value),onFocus:()=>{S.searchResults.length>0&&S.setShowResults(!0)},onBlur:()=>setTimeout(()=>S.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),S.showResults&&S.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:S.searchResults.map(G=>e.jsx("button",{type:"button",onClick:()=>S.handleSelect(G),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:G.displayName||G.email}),G.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:G.email})]})},G.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(He,{value:i.approverFilterType,onValueChange:G=>i.setApproverFilterType(G),children:[e.jsx(Ge,{className:"h-7 w-32 text-xs",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"current",children:"Current Only"}),e.jsx(X,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:j.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:j.selectedUser.displayName||j.selectedUser.email}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:j.handleClear,children:e.jsx(gt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{placeholder:"Search approver...",value:j.searchQuery,onChange:G=>j.handleSearch(G.target.value),onFocus:()=>{j.searchResults.length>0&&j.setShowResults(!0)},onBlur:()=>setTimeout(()=>j.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),j.showResults&&j.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:j.searchResults.map(G=>e.jsx("button",{type:"button",onClick:()=>j.handleSelect(G),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:G.displayName||G.email}),G.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:G.email})]})},G.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(lt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Ge,{className:"w-[160px] h-10",children:e.jsx(We,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(Zs,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${Ye(i.customStartDate,"MMM d, yyyy")} - ${Ye(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Qs,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Bs,{value:i.customStartDate||null,onChange:G=>{const oe=G?new Date(G):void 0;oe?(i.setCustomStartDate(oe),i.customEndDate&&oe>i.customEndDate&&i.setCustomEndDate(oe)):i.setCustomStartDate(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",children:"End Date"}),e.jsx(Bs,{value:i.customEndDate||null,onChange:G=>{const oe=G?new Date(G):void 0;oe?(i.setCustomEndDate(oe),i.customStartDate&&oe<i.customStartDate&&i.setCustomStartDate(oe)):i.setCustomEndDate(void 0)},minDate:i.customStartDate||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsx(I,{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(I,{size:"sm",variant:"outline",onClick:()=>{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})})]})})]})]})]})})}),e.jsx(Sg,{requests:L,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(wr,{currentPage:i.currentPage||1,totalPages:w,totalRecords:C,itemsPerPage:D,onPageChange:$,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function ak({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 Ms.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 Lu=100;async function rk(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 Ms.listParticipantRequests({page:r,limit:Lu,...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===Lu}}return s}function nk({onViewRequest:t}){const s=kg(),a=p.useMemo(()=>{try{const Z=at.getUserData();return Vo(Z)}catch(Z){return console.error("[UserAllRequests] Error getting user filter type:",Z),"STANDARD"}},[]),r=p.useMemo(()=>ET(a),[a]),n=a==="DEALER",i=p.useCallback(()=>{const Z=s.getFilters();if(n){const{priority:E,templateType:V,department:H,slaCompliance:Q,...Y}=Z;return Y}return Z},[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),[u,h]=p.useState(!1),[x,g]=p.useState(null),[f,y]=p.useState([]),[b,v]=p.useState(!1),[A,w]=p.useState([]),[T,C]=p.useState(1),[_,D]=p.useState(0),[S]=p.useState(10),j=wi({allUsers:A,filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter}),P=wi({allUsers:A,filterValue:s.approverFilter,onFilterChange:s.setApproverFilter}),R=p.useCallback(async(Z,E,V,H)=>{try{const Q=await St.getRequestStats(Z,E?E.toISOString():void 0,V?V.toISOString():void 0,void 0,H==null?void 0:H.priority,H==null?void 0:H.templateType,H==null?void 0:H.department,H==null?void 0:H.initiator,H==null?void 0:H.approver,H==null?void 0:H.approverType,H==null?void 0:H.search,H==null?void 0:H.slaCompliance,!0);g({total:Q.totalRequests||0,pending:Q.openRequests||0,paused:Q.pausedRequests||0,approved:Q.approvedRequests||0,rejected:Q.rejectedRequests||0,draft:Q.draftRequests||0,closed:Q.closedRequests||0})}catch(Q){console.error("Failed to fetch backend stats:",Q)}},[]),O=p.useCallback(async()=>{try{v(!0);const Z=await St.getDepartments();y(Z)}catch{}finally{v(!1)}},[]),F=p.useCallback(async()=>{try{const E=(await Gs.getAllUsers()).map(V=>({userId:V.userId,email:V.email,displayName:V.displayName||V.email}));w(E)}catch(Z){console.error("Failed to fetch users:",Z)}},[]),M=p.useRef(s),B=p.useRef(R),k=p.useRef(i);p.useEffect(()=>{M.current=s,B.current=R,k.current=i},[s,R,i]);const N=p.useCallback(async(Z=1)=>{try{Z===1&&(m(!0),c([]));const E=k.current(),V=await ak({page:Z,itemsPerPage:S,filters:E});c(V.data),s.setCurrentPage(V.pagination.page),C(V.pagination.totalPages),D(V.pagination.total)}catch{c([])}finally{m(!1)}},[S,s]),U=p.useCallback(async()=>{try{h(!0);const Z=i(),E=await rk(Z);await Fg(E,Z)}catch(Z){console.error("Failed to export requests:",Z),alert("Failed to export requests. Please try again.")}finally{h(!1)}},[i]);p.useEffect(()=>{O(),F()},[O,F]),p.useEffect(()=>{const Z=setTimeout(()=>{const E={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"&&(E.priority=s.priorityFilter),s.templateTypeFilter!=="all"&&(E.templateType=s.templateTypeFilter),s.departmentFilter!=="all"&&(E.department=s.departmentFilter),s.slaComplianceFilter!=="all"&&(E.slaCompliance=s.slaComplianceFilter));const V=s.dateRange==="all"?"all":s.dateRange||"month";B.current(V,s.customStartDate,s.customEndDate,E)},s.searchTerm?500:0);return()=>clearTimeout(Z)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter,n]);const $=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}),L=p.useRef(!1);p.useEffect(()=>{const Z=s.currentPage||1;N(Z),L.current=!0},[]),p.useEffect(()=>{if(!L.current)return;const Z=$.current;if(!(Z.searchTerm!==s.searchTerm||Z.statusFilter!==s.statusFilter||Z.priorityFilter!==s.priorityFilter||Z.templateTypeFilter!==s.templateTypeFilter||Z.slaComplianceFilter!==s.slaComplianceFilter||Z.departmentFilter!==s.departmentFilter||Z.initiatorFilter!==s.initiatorFilter||Z.approverFilter!==s.approverFilter||Z.approverFilterType!==s.approverFilterType||Z.dateRange!==s.dateRange||Z.customStartDate!==s.customStartDate||Z.customEndDate!==s.customEndDate))return;const V=setTimeout(()=>{s.setCurrentPage(1),N(1),$.current={searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}},s.searchTerm!==Z.searchTerm?500:0);return()=>clearTimeout(V)},[s.searchTerm,s.statusFilter,s.priorityFilter,s.templateTypeFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const se=p.useCallback(Z=>{Z>=1&&Z<=T&&(s.setCurrentPage(Z),N(Z))},[T,N,s]),G=p.useMemo(()=>Rg(o),[o]),oe=p.useMemo(()=>{if(x)return{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};const Z=G.filter(Y=>{const W=(Y.status||"").toString().toLowerCase();return W==="pending"||W==="in-progress"}).length,E=G.filter(Y=>(Y.status||"").toString().toLowerCase()==="paused").length,V=G.filter(Y=>(Y.status||"").toString().toLowerCase()==="approved").length,H=G.filter(Y=>(Y.status||"").toString().toLowerCase()==="rejected").length,Q=G.filter(Y=>(Y.status||"").toString().toLowerCase()==="closed").length;return{total:_>0?_:G.length,pending:Z,paused:E,approved:V,rejected:H,draft:0,closed:Q}},[x,_,G]);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(Cg,{isOrgLevel:!1,isAdmin:!1,loading:d,exporting:u,onExport:U}),e.jsx(Ag,{stats:oe,onStatusFilter:Z=>{s.setStatusFilter(Z)}}),e.jsx(r,{searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,departmentFilter:s.departmentFilter,slaComplianceFilter:s.slaComplianceFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate,showCustomDatePicker:s.showCustomDatePicker,departments:f,loadingDepartments:b,initiatorSearch:j,approverSearch:P,onSearchChange:s.setSearchTerm,onStatusChange:s.setStatusFilter,onPriorityChange:s.setPriorityFilter,onTemplateTypeChange:s.setTemplateTypeFilter,onDepartmentChange:s.setDepartmentFilter,onSlaComplianceChange:s.setSlaComplianceFilter,onInitiatorChange:s.setInitiatorFilter,onApproverChange:s.setApproverFilter,onApproverTypeChange:s.setApproverFilterType,onDateRangeChange:s.handleDateRangeChange,onCustomStartDateChange:s.setCustomStartDate,onCustomEndDateChange:s.setCustomEndDate,onShowCustomDatePickerChange:s.setShowCustomDatePicker,onApplyCustomDate:s.handleApplyCustomDate,onClearFilters:s.clearFilters,hasActiveFilters:l()}),e.jsx(Sg,{requests:G,loading:d,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(wr,{currentPage:s.currentPage||1,totalPages:T,totalRecords:_,itemsPerPage:S,onPageChange:se,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function ik(){const t=qs();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(J,{children:e.jsxs(q,{className:"p-8 text-center",children:[e.jsx(Ve,{className:"w-12 h-12 text-yellow-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Approver ID Required"}),e.jsx("p",{className:"text-gray-600",children:"Please select an approver to view their performance details."}),e.jsxs(I,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(Ss,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function lk({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(Bt,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Approver Performance Report"}),e.jsx("p",{className:"text-sm text-gray-600",children:t})]})]}),e.jsxs(I,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx(zt,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function ok({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(J,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(q,{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(Ht,{className:`w-5 h-5 ${s>=95?"text-green-600":s>=90?"text-blue-600":s>=85?"text-orange-600":"text-red-600"}`})})]}),e.jsx(oa,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(J,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(q,{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(Pe,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(J,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(q,{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(To,{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(J,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(q,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.pendingCount}),e.jsx("div",{className:"p-2 bg-orange-100 rounded-lg",children:e.jsx(Xe,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function ck({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(J,{"data-testid":"approver-actions-stats",children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Approver's Actions"}),e.jsxs(Te,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?Lj(a,r,n,""):"(all time)"]})]}),e.jsxs(q,{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(Bt,{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(Pe,{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(Nt,{className:"w-5 h-5 text-red-600"}),e.jsx("span",{className:"text-xs text-red-600 font-medium",children:s&&s.approvedCount+s.rejectedCount>0?`${Math.round(s.rejectedCount/(s.approvedCount+s.rejectedCount)*100)}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:(s==null?void 0:s.rejectedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Rejected by Approver"})]}),e.jsxs("div",{className:"p-4 bg-yellow-50 rounded-lg border border-yellow-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Xe,{className:"w-5 h-5 text-yellow-600"})}),e.jsx("div",{className:"text-2xl font-bold text-yellow-700",children:(s==null?void 0:s.pendingCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Pending Actions"})]}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg border border-gray-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx($i,{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(De,{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(Ht,{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(E0,{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(Ve,{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(pi,{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 dk({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:l,showCustomDatePicker:o,tempCustomStartDate:c,tempCustomEndDate:d,onSearchChange:m,onStatusChange:u,onPriorityChange:h,onSlaComplianceChange:x,onDateRangeChange:g,onShowCustomDatePickerChange:f,onTempStartDateChange:y,onTempEndDateChange:b,onApplyCustomDate:v,onClearFilters:A}){return e.jsxs(J,{"data-testid":"approver-performance-filters",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Filters"}),e.jsx(I,{variant:"ghost",size:"sm",onClick:A,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(q,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ie,{placeholder:"Search requests...",value:t,onChange:w=>m(w.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:u,children:[e.jsx(Ge,{"data-testid":"status-filter",children:e.jsx(We,{placeholder:"Status"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Status"}),e.jsx(X,{value:"pending",children:"Pending"}),e.jsx(X,{value:"approved",children:"Approved"}),e.jsx(X,{value:"rejected",children:"Rejected"}),e.jsx(X,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:h,children:[e.jsx(Ge,{"data-testid":"priority-filter",children:e.jsx(We,{placeholder:"Priority"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Priority"}),e.jsx(X,{value:"express",children:"Express"}),e.jsx(X,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:x,children:[e.jsx(Ge,{"data-testid":"sla-compliance-filter",children:e.jsx(We,{placeholder:"SLA Compliance"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All SLA"}),e.jsx(X,{value:"compliant",children:"Compliant"}),e.jsx(X,{value:"on-track",children:"On Track"}),e.jsx(X,{value:"approaching",children:"Approaching"}),e.jsx(X,{value:"critical",children:"Critical"}),e.jsx(X,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:n,onValueChange:g,children:[e.jsx(Ge,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(We,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(Zs,{open:o,onOpenChange:f,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(lt,{className:"w-4 h-4"}),c&&d?`${Ye(c,"MMM d")} - ${Ye(d,"MMM d")}`:"Select dates"]})}),e.jsx(Qs,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Ie,{id:"start-date",type:"date",value:c?Ye(c,"yyyy-MM-dd"):"",onChange:w=>{const T=w.target.value?new Date(w.target.value):void 0;T?(y(T),d&&T>d&&b(T)):y(void 0)},max:Ye(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Ie,{id:"end-date",type:"date",value:d?Ye(d,"yyyy-MM-dd"):"",onChange:w=>{const T=w.target.value?new Date(w.target.value):void 0;T?(b(T),c&&T<c&&y(T)):b(void 0)},min:c?Ye(c,"yyyy-MM-dd"):void 0,max:Ye(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(I,{size:"sm",onClick:v,disabled:!c||!d,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-date-button",children:"Apply"}),e.jsx(I,{size:"sm",variant:"outline",onClick:()=>{f(!1),y(i),b(l),(!i||!l)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const mk=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ys,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ht,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ht,iconColor:"text-gray-600"}}},uk=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Pe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Nt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Xe,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Xe,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:De,iconColor:"text-gray-600"}}},xk=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 hk(t){if(!t)return"N/A";try{return Ye(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function pk(t){if(!t)return"N/A";try{return Ye(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function Ci(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=l5(s);n(l)}function gk({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const c=qs();return e.jsxs(J,{"data-testid":"approver-performance-request-list",children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Request Details"}),e.jsxs(Te,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(q,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(zt,{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(De,{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=mk(d.priority),u=uk(d.status),h=xk(d.slaStatus||""),x=m.icon,g=u.icon;return e.jsx(J,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{Ci({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(q,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm text-blue-600 hover:underline","data-testid":"request-number",children:d.requestNumber}),e.jsxs(ie,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(x,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(ie,{className:u.color,"data-testid":"status-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${u.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(ie,{className:d.approvalStatus==="approved"||d.approvalStatus==="APPROVED"?"bg-green-100 text-green-800 border-green-200":d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?"bg-red-100 text-red-800 border-red-200":"bg-yellow-100 text-yellow-800 border-yellow-200","data-testid":"approval-status-badge",children:d.approvalStatus==="approved"||d.approvalStatus==="APPROVED"?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(Nt,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(ie,{className:h.color,"data-testid":"sla-status-badge",children:h.label})]}),e.jsx("h3",{className:"font-medium text-gray-900 mb-1 truncate","data-testid":"request-title",children:d.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-500 mt-2",children:[e.jsxs("span",{className:"flex items-center gap-1","data-testid":"initiator-info",children:[e.jsx(Lt,{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(Xe,{className:"w-3 h-3"}),"Submitted: ",hk(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(Pe,{className:"w-3 h-3"}),"Action: ",pk(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(Ht,{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(To,{className:"w-3 h-3"}),Ot(d.levelElapsedHours)," / ",Ot(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:f=>{f.stopPropagation(),Ci({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(xs,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(wr,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function fk(){const[t]=wx(),[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"),[u,h]=p.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[x,g]=p.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[f,y]=p.useState(!1),[b,v]=p.useState(void 0),[A,w]=p.useState(void 0),T=p.useCallback(()=>{a(""),n("all"),l("all"),c("all"),m("all"),h(void 0),g(void 0),v(void 0),w(void 0),y(!1)},[]),C=p.useCallback(D=>{const S=D;m(S),S!=="custom"?(h(void 0),g(void 0),v(void 0),w(void 0),y(!1)):(v(u),w(x),y(!0))},[u,x]),_=p.useCallback(()=>{if(b&&A){if(b>A){const D=b;h(A),g(D),v(A),w(D)}else h(b),g(A);y(!1)}},[b,A]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:d,customStartDate:u,customEndDate:x,showCustomDatePicker:f,tempCustomStartDate:b,tempCustomEndDate:A,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:h,setCustomEndDate:g,setShowCustomDatePicker:y,setTempCustomStartDate:v,setTempCustomEndDate:w,clearFilters:T,handleDateRangeChange:C,handleApplyCustomDate:_}}function yk({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:l,searchTerm:o,itemsPerPage:c}){const[d,m]=p.useState([]),[u,h]=p.useState(null),[x,g]=p.useState([]),[f,y]=p.useState(!0),[b,v]=p.useState(!1),[A,w]=p.useState(1),[T,C]=p.useState(1),[_,D]=p.useState(0),S=p.useRef(!0),j=p.useCallback(async()=>{if(t)try{const F=s==="all"?void 0:s,M=await St.getSingleApproverStats(t,F,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);h(M)}catch(F){console.error("[ApproverPerformance] Failed to fetch approver stats:",F),h(null)}},[t,s,a,r,i,l]),P=p.useCallback(async(F=1)=>{if(!t){y(!1);return}try{y(!0);const M=await St.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(M.requests),D(M.pagination.totalRecords),C(M.pagination.totalPages),w(M.pagination.currentPage),g(M.requests)}catch(M){console.error("Failed to fetch requests:",M)}finally{y(!1),v(!1)}},[t,s,a,r,n,i,l,o,c]);p.useEffect(()=>{S.current&&(S.current=!1,j(),P(1))},[]),p.useEffect(()=>{S.current||j()},[s,a,r,i,l]),p.useEffect(()=>{S.current||P(1)},[s,a,r,n,i,l,o]);const R=p.useCallback(()=>{v(!0),j(),P(1)},[j,P]),O=p.useCallback(F=>{P(F)},[P]);return{requests:d,approverStats:u,allFilteredRequests:x,loading:f,refreshing:b,currentPage:A,totalPages:T,totalRecords:_,handleRefresh:R,handlePageChange:O}}const Ou=10;function bk(){const[t]=wx(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=fk(),n=yk({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:Ou});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(lk,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(ok,{approverStats:n.approverStats}),n.approverStats&&e.jsx(ck,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(dk,{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(gk,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:Ou,onPageChange:n.handlePageChange})]}):e.jsx(ik,{})}function vk(){const{user:t}=Qt(),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(J,{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(q,{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(es,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Vi,{src:(t==null?void 0:t.picture)||""}),e.jsx(ts,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),mr(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(ds,{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:[mr(t)&&e.jsxs(ie,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(ds,{className:"w-3 h-3 mr-1"}),"Administrator"]}),an(t)&&e.jsxs(ie,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(Bt,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(ie,{variant:"outline",className:"border-white/30 text-white bg-white/10",children:["ID: ",t.employeeId]})]})]})})})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(J,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Lt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(Te,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(q,{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(Ia,{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(Lt,{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(Lt,{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(Lt,{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(Di,{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(J,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-emerald-100 rounded-lg",children:e.jsx(zd,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(Te,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(q,{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(Lt,{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(No,{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(zd,{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(ds,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Role"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ie,{variant:mr(t)||an(t)?"default":"secondary",className:mr(t)?"bg-yellow-400 text-slate-900":an(t)?"bg-blue-400 text-slate-900":"",children:mr(t)?"Administrator":an(t)?"Management":"User"}),(mr(t)||an(t))&&e.jsx(Pe,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(J,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(lt,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(Te,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(q,{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(Pe,{className:"w-4 h-4 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Account Status"}),e.jsx("p",{className:"text-xs text-gray-600",children:"Active and verified"})]})]}),e.jsx(ie,{className:"bg-green-500 hover:bg-green-600 text-white",children:"Active"})]}),(t==null?void 0:t.userId)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500 mb-1",children:"User ID"}),e.jsx("p",{className:"text-sm text-gray-900 font-mono break-all",children:t.userId})]}),t.employeeId&&e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500 mb-1",children:"Employee ID"}),e.jsx("p",{className:"text-sm text-gray-900 font-mono",children:t.employeeId})]})]})]})})]})]})}const Zn="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",jk="https://re-workflow-nt-dev.siplsolutions.com";function Ol(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 Nk(){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 wk(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:Ol(Zn)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Ol(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:Ol(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(`${jk}/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 Ck(){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 Nk()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await wk(s)}catch(a){throw a}}function go({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(Uf,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:Re("relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",t),...i,children:[e.jsx(Bf,{"data-slot":"slider-track",className:Re("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-4 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"),children:e.jsx(Vf,{"data-slot":"slider-range",className:Re("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,c)=>e.jsx(zf,{"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 Ak({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({}),[u,h]=p.useState(null);p.useEffect(()=>{x()},[]);const x=async()=>{var j,P;try{n(!0),c(null);const R=await Zi();a(R)}catch(R){c(((P=(j=R.response)==null?void 0:j.data)==null?void 0:P.error)||"Failed to load configurations")}finally{n(!1)}},g=async j=>{var P,R;try{l(j.configKey),c(null);const O=d[j.configKey]??j.configValue;if(j.validationRules){const F=parseFloat(O);if(j.valueType==="NUMBER"){if(j.validationRules.min!==void 0&&F<j.validationRules.min)throw new Error(`Value must be at least ${j.validationRules.min}`);if(j.validationRules.max!==void 0&&F>j.validationRules.max)throw new Error(`Value must be at most ${j.validationRules.max}`)}}await ks(j.configKey,O),a(F=>F.map(M=>M.configKey===j.configKey?{...M,configValue:O}:M)),m(F=>{const M={...F};return delete M[j.configKey],M}),h(`${j.displayName} updated successfully`),setTimeout(()=>h(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)}},f=async j=>{var P,R;if(confirm(`Reset "${j.displayName}" to default value?`))try{l(j.configKey),c(null),await oA(j.configKey),a(O=>O.map(F=>F.configKey===j.configKey?{...F,configValue:F.defaultValue||""}:F)),m(O=>{const F={...O};return delete F[j.configKey],F}),h(`${j.displayName} reset to default`),setTimeout(()=>h(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)}},y=(j,P)=>{m(R=>({...R,[j]:P}))},b=j=>d[j.configKey]??j.configValue,v=j=>d[j.configKey]!==void 0&&d[j.configKey]!==j.configValue,A=j=>{var O,F,M,B;const P=b(j),R=i===j.configKey;if(!j.isEditable)return e.jsxs("div",{className:"p-3 bg-slate-100 border border-slate-200 rounded-md",children:[e.jsx("p",{className:"text-sm text-slate-700 font-mono",children:j.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Ve,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(j.uiComponent||j.valueType.toLowerCase()){case"toggle":return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${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(Fs,{checked:P==="true",onCheckedChange:$=>y(j.configKey,$?"true":"false"),disabled:R})]});case"slider":const k=parseInt(P)||0,N=((O=j.validationRules)==null?void 0:O.min)||0,U=((F=j.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:[k,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",N,"-",U]})]}),e.jsx(go,{value:[k],min:N,max:U,step:1,onValueChange:([$])=>{$!==void 0&&y(j.configKey,$.toString())},disabled:R,className:"w-full"})]});case"number":return e.jsx(Ie,{type:"number",value:P,onChange:$=>y(j.configKey,$.target.value),disabled:R,min:(M=j.validationRules)==null?void 0:M.min,max:(B=j.validationRules)==null?void 0:B.max,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"});case"text":case"input":default:return e.jsx(Ie,{type:"text",value:P,onChange:$=>y(j.configKey,$.target.value),disabled:R,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},w=j=>{switch(j){case"TAT_SETTINGS":return e.jsx(Xe,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(De,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(Ds,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Pi,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(Hr,{className:"w-5 h-5"});default:return e.jsx(Ga,{className:"w-5 h-5"})}},T=["DASHBOARD_LAYOUT"],C=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],_=s.filter(j=>!T.includes(j.configCategory)&&!C.includes(j.configKey)),D=_.reduce((j,P)=>(j[P.configCategory]||(j[P.configCategory]=[]),j[P.configCategory].push(P),j),{});if(Object.keys(D).forEach(j=>{const P=D[j];P&&P.sort((R,O)=>R.sortOrder-O.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ze,{className:"w-8 h-8 animate-spin text-gray-400"})});if(_.length===0)return e.jsx(J,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(q,{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(Ga,{className:"w-10 h-10 text-slate-400"})}),e.jsx("p",{className:"text-slate-700 font-medium text-lg",children:"No configurations found"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 max-w-md mx-auto",children:"System configurations will appear here once they are initialized"})]})});const S=Object.keys(D);return e.jsxs("div",{className:"space-y-6",children:[u&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(Pe,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:u})]}),o&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Ve,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:o}),e.jsx(I,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(Un,{defaultValue:S[0],className:"w-full",children:[e.jsx(Bn,{className:"flex flex-wrap w-full bg-slate-100/80 backdrop-blur-sm p-1 gap-1 rounded-md h-auto border border-slate-200 shadow-sm",children:S.map(j=>e.jsx(Dt,{value:j,className:"flex-1 min-w-[120px] text-[10px] xs:text-xs sm:text-sm font-medium py-2 sm:py-2.5 px-2 sm:px-3 rounded-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-slate-900 transition-all",children:e.jsx("span",{className:"truncate block",children:j.replace(/_/g," ")})},j))}),S.map(j=>{var P,R,O;return e.jsx(Tt,{value:j,className:"space-y-4 mt-6",children:e.jsxs(J,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx("div",{className:"text-white",children:w(j)})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-slate-900",children:j.replace(/_/g," ")}),e.jsxs(Te,{className:"text-sm",children:[((P=D[j])==null?void 0:P.length)||0," setting",(((R=D[j])==null?void 0:R.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(q,{className:"space-y-6",children:(O=D[j])==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(ne,{className:"text-sm font-semibold text-slate-900",children:F.displayName}),v(F)&&e.jsx(ie,{variant:"outline",className:"text-xs bg-gradient-to-r from-yellow-50 to-amber-50 text-yellow-800 border-yellow-400 font-medium shadow-sm",children:"Modified"}),F.requiresRestart&&e.jsx(ie,{variant:"outline",className:"text-xs bg-gradient-to-r from-orange-50 to-red-50 text-orange-800 border-orange-400 font-medium shadow-sm",children:"Requires Restart"})]}),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})]})]})}),A(F),F.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(I,{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(Ze,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"w-4 h-4"}),"Save Changes"]})}),F.defaultValue&&e.jsxs(I,{size:"sm",variant:"outline",onClick:()=>f(F),disabled:i===F.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(F0,{className:"w-4 h-4"}),"Reset to Default"]})]})]},F.configKey))})]})},j)})]})]})}function Sk(){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,u]=p.useState(null),[h,x]=p.useState(null),[g,f]=p.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});p.useEffect(()=>{y()},[n]);const y=async()=>{var j,P;try{r(!0),u(null);const R=await cA(n);s(R)}catch(R){u(((P=(j=R.response)==null?void 0:j.data)==null?void 0:P.error)||"Failed to load holidays")}finally{r(!1)}},b=()=>{f({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),o(!0)},v=j=>{f({holidayDate:j.holidayDate,holidayName:j.holidayName,description:j.description||"",holidayType:j.holidayType,isRecurring:j.isRecurring}),d(j),o(!0)},A=()=>{if(c)return;const j=new Date;return j.setDate(j.getDate()+1),j.toISOString().split("T")[0]},w=async()=>{var j,P;try{if(u(null),!g.holidayDate||!g.holidayName){u("Holiday date and name are required");return}c?(await mA(c.holidayId,g),x("Holiday updated successfully")):(await dA(g),x("Holiday created successfully")),await y(),o(!1),setTimeout(()=>x(null),3e3)}catch(R){u(((P=(j=R.response)==null?void 0:j.data)==null?void 0:P.error)||"Failed to save holiday")}},T=async j=>{var P,R;if(confirm(`Delete "${j.holidayName}"?`))try{u(null),await uA(j.holidayId),x("Holiday deleted successfully"),await y(),setTimeout(()=>x(null),3e3)}catch(O){u(((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to delete holiday")}},C=j=>{switch(j){case"NATIONAL":return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300";case"REGIONAL":return"bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-800 border-blue-300";case"ORGANIZATIONAL":return"bg-gradient-to-r from-purple-50 to-violet-50 text-purple-800 border-purple-300";case"OPTIONAL":return"bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-300"}},_=Array.from({length:5},(j,P)=>new Date().getFullYear()-1+P),D=t.reduce((j,P)=>{const R=new Date(P.holidayDate).toLocaleString("default",{month:"long"});return j[R]||(j[R]=[]),j[R].push(P),j},{}),S=Object.keys(D).sort((j,P)=>{const R=new Date(Date.parse(j+" 1, 2000")).getMonth(),O=new Date(Date.parse(P+" 1, 2000")).getMonth();return R-O});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(Pe,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:h})]}),m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Ve,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:m}),e.jsx(I,{size:"sm",variant:"ghost",onClick:()=>u(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(J,{className:"shadow-lg border-0 rounded-md",children:e.jsx(me,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(lt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(Te,{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(He,{value:n.toString(),onValueChange:j=>i(parseInt(j)),children:[e.jsx(Ge,{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(We,{})}),e.jsx(Ke,{className:"rounded-md",children:_.map(j=>e.jsx(X,{value:j.toString(),children:j},j))})]}),e.jsxs(I,{onClick:b,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(us,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Add Holiday"}),e.jsx("span",{className:"xs:hidden",children:"Add"})]})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ze,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(J,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(q,{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(lt,{className:"w-10 h-10 text-slate-400"})}),e.jsxs("p",{className:"text-slate-700 font-medium text-lg",children:["No holidays found for ",n]}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:"Add holidays to exclude them from TAT calculations"}),e.jsxs(I,{onClick:b,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(us,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:S.map(j=>{var P,R,O;return e.jsxs(J,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[j," ",n]}),e.jsxs(Te,{className:"text-xs sm:text-sm",children:[((P=D[j])==null?void 0:P.length)||0," holiday",(((R=D[j])==null?void 0:R.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(lt,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(q,{className:"space-y-3 pt-4",children:(O=D[j])==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(ie,{variant:"outline",className:`${C(F.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:F.holidayType}),F.isRecurring&&e.jsx(ie,{variant:"outline",className:"bg-gradient-to-r from-indigo-50 to-purple-50 text-indigo-700 border-indigo-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Recurring"})]}),e.jsx("p",{className:"text-xs sm:text-sm text-slate-600 font-medium",children:uh(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(I,{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(hi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(I,{size:"sm",variant:"ghost",onClick:()=>T(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(kn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},F.holidayId))})]},j)})}),e.jsx(ht,{open:l,onOpenChange:o,children:e.jsxs(ct,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(pt,{className:"pb-4 border-b border-slate-100 px-6 pt-6 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg shadow-md",children:e.jsx(lt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(dt,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(Et,{className:"text-sm text-slate-600 mt-1",children:c?"Update holiday information":"Add a new holiday to the calendar for TAT calculations"})]})]})}),e.jsxs("div",{className:"space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"date",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ie,{id:"date",type:"date",value:g.holidayDate,onChange:j=>f({...g,holidayDate:j.target.value}),min:A(),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:c?"Select the holiday date":"Select the holiday date (minimum: tomorrow)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"name",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Holiday Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ie,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:j=>f({...g,holidayName:j.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"description",className:"text-sm font-semibold text-slate-900",children:["Description ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Ie,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:j=>f({...g,description:j.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(He,{value:g.holidayType,onValueChange:j=>f({...g,holidayType:j}),children:[e.jsx(Ge,{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(We,{})}),e.jsxs(Ke,{className:"rounded-lg",children:[e.jsx(X,{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(X,{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(X,{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(X,{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:()=>f({...g,isRecurring:!g.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:g.isRecurring,onChange:j=>f({...g,isRecurring:j.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ne,{htmlFor:"recurring",className:"font-semibold cursor-pointer text-sm text-slate-900 block mb-1",children:"Recurring Holiday"}),e.jsx("p",{className:"text-xs text-slate-600",children:"This holiday will automatically repeat every year on the same date"})]})]})]}),e.jsxs(kt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(I,{variant:"outline",onClick:()=>o(!1),className:"h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:"Cancel"}),e.jsxs(I,{onClick:w,disabled:!g.holidayDate||!g.holidayName,className:"h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(lt,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function Tk(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function kk(){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,u]=p.useState(!1),[h,x]=p.useState(null),[g,f]=p.useState([]),[y,b]=p.useState(!1),[v,A]=p.useState({admins:0,management:0,users:0}),[w,T]=p.useState("ELEVATED"),[C,_]=p.useState(1),[D,S]=p.useState(1),[j,P]=p.useState(0),R=10,O=p.useRef(null),F=p.useRef(null),M=p.useCallback(Tk(async E=>{var V,H,Q;if(!E||!E.startsWith("@")||E.length<2){r([]),i(!1);return}i(!0);try{const Y=E.slice(1),ce=((V=(await Gs.searchUsers(Y,20)).data)==null?void 0:V.data)||[];r(ce)}catch(Y){console.error("Search failed:",Y),x({type:"error",text:((Q=(H=Y.response)==null?void 0:H.data)==null?void 0:Q.message)||"Failed to search users"})}finally{i(!1)}},300),[]),B=E=>{const V=E.target.value;s(V),M(V)},k=async E=>{o(E),s(E.email),r([]);const V=g.find(H=>H.email.toLowerCase()===E.email.toLowerCase()||H.userId===E.userId);if(V&&V.role)d(V.role);else try{const Q=(await Gs.getAllUsers()).find(Y=>Y.email&&Y.email.toLowerCase()===E.email.toLowerCase()||Y.userId&&Y.userId===E.userId);Q&&Q.role?d(Q.role):d("USER")}catch(H){console.error("Failed to check user role:",H),d("USER")}},N=async()=>{var E,V;if(!l||!c){x({type:"error",text:"Please select a user and role"});return}u(!0),x(null);try{await Gs.assignRole(l.email,c),x({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await U(),await $()}catch(H){console.error("Role assignment failed:",H),x({type:"error",text:((V=(E=H.response)==null?void 0:E.data)==null?void 0:V.error)||"Failed to assign role"})}finally{u(!1)}},U=async(E=C)=>{var V,H,Q,Y,W,ce;b(!0);try{const xe=await Gs.getUsersByRole(w,E,R),ke=((H=(V=xe.data)==null?void 0:V.data)==null?void 0:H.users)||[],Ae=(Y=(Q=xe.data)==null?void 0:Q.data)==null?void 0:Y.pagination,ae=(ce=(W=xe.data)==null?void 0:W.data)==null?void 0:ce.summary;f(ke),Ae&&(_(Ae.currentPage),S(Ae.totalPages),P(Ae.totalUsers)),ae&&A({admins:ae.ADMIN||0,management:ae.MANAGEMENT||0,users:ae.USER||0})}catch(xe){console.error("Failed to fetch users:",xe)}finally{b(!1)}},$=async()=>{var E,V,H,Q,Y,W;try{const ce=await Gs.getRoleStatistics(),xe=((V=(E=ce.data)==null?void 0:E.data)==null?void 0:V.statistics)||((H=ce.data)==null?void 0:H.statistics)||[];A({admins:parseInt(((Q=xe.find(ke=>ke.role==="ADMIN"))==null?void 0:Q.count)||"0"),management:parseInt(((Y=xe.find(ke=>ke.role==="MANAGEMENT"))==null?void 0:Y.count)||"0"),users:parseInt(((W=xe.find(ke=>ke.role==="USER"))==null?void 0:W.count)||"0")})}catch(ce){console.error("Failed to fetch statistics:",ce)}};p.useEffect(()=>{U(1),$()},[w]);const L=E=>{T(E),_(1)},se=E=>{U(E)},G=E=>{T(E),_(1),requestAnimationFrame(()=>{const V=F.current;V&&V.scrollIntoView({behavior:"smooth",block:"start"})})};p.useEffect(()=>{const E=V=>{O.current&&!O.current.contains(V.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",E),()=>{document.removeEventListener("mousedown",E)}},[a]);const oe=E=>{switch(E){case"ADMIN":return"bg-yellow-400 text-slate-800";case"MANAGEMENT":return"bg-blue-400 text-slate-800";default:return"bg-gray-400 text-slate-800"}},Z=E=>{switch(E){case"ADMIN":return e.jsx(Rr,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(Bt,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(Lt,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(J,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(M0,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(q,{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(J,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${w==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>G("ADMIN"),children:e.jsx(q,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Administrators"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"admin-count",children:v.admins}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1 font-semibold",children:w==="ADMIN"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-xl shadow-md",children:e.jsx(Rr,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(J,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${w==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>G("MANAGEMENT"),children:e.jsx(q,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Management"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"management-count",children:v.management}),e.jsx("p",{className:"text-xs text-blue-700 mt-1 font-semibold",children:w==="MANAGEMENT"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-blue-400 to-blue-500 rounded-xl shadow-md",children:e.jsx(Bt,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(J,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${w==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>G("USER"),children:e.jsx(q,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Regular Users"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"user-count",children:v.users}),e.jsx("p",{className:"text-xs text-gray-700 mt-1 font-semibold",children:w==="USER"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-gray-400 to-gray-500 rounded-xl shadow-md",children:e.jsx(Lt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx($t,{}),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(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(Ie,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:B,className:"pl-10 pr-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"user-search-input"}),n&&e.jsx(Ze,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Start with @ to search users (e.g., @john)"}),a.length>0&&e.jsxs("div",{className:"border border-purple-200 rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-purple-50 px-4 py-2 border-b border-purple-100",children:e.jsxs("p",{className:"text-xs font-semibold text-purple-700",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-2",children:a.map(E=>e.jsxs("button",{onClick:()=>k(E),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${E.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:E.displayName||E.email}),e.jsx("p",{className:"text-xs text-gray-600",children:E.email}),E.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[E.department,E.designation?` • ${E.designation}`:""]})]},E.userId))})]})]}),l&&e.jsx("div",{className:"border-2 border-slate-300 bg-gradient-to-br from-slate-100 to-slate-50 rounded-lg p-4 shadow-sm",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-gradient-to-br from-slate-700 to-slate-500 flex items-center justify-center text-white font-bold shadow-md",children:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-slate-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-slate-600",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[l.department,l.designation?` • ${l.designation}`:""]})]})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{o(null),s("")},className:"hover:bg-slate-200",children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Select Role"}),e.jsxs(He,{value:c,onValueChange:E=>d(E),children:[e.jsx(Ge,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(We,{placeholder:"Select role"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(X,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(X,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(I,{onClick:N,disabled:!l||m,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"assign-role-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ds,{className:"w-4 h-4 mr-2"}),"Assign Role"]})}),h&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${h.type==="success"?"border-green-200 bg-green-50":"border-red-200 bg-red-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[h.type==="success"?e.jsx(Pe,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Ve,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${h.type==="success"?"text-green-800":"text-red-800"}`,children:h.text})]})})]})]}),e.jsx($t,{}),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 (",j," ",w!=="ALL"&&w!=="ELEVATED"?w.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(He,{value:w,onValueChange:L,children:[e.jsx(Ge,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(We,{placeholder:"Filter by role"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ds,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",v.admins+v.management,")"]})]})}),e.jsx(X,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",v.admins,")"]})]})}),e.jsx(X,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",v.management,")"]})]})}),e.jsx(X,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",v.users,")"]})]})}),e.jsx(X,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{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:y?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Ze,{className:"w-6 h-6 animate-spin text-purple-500 mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading users..."})]}):g.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(Bt,{className:"w-6 h-6 text-gray-400"})}),e.jsx("p",{className:"font-medium text-gray-700",children:"No users found"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:w==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2","data-testid":"users-list",children:g.map(E=>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-${E.email}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg ${oe(E.role)} flex items-center justify-center shadow-sm`,children:Z(E.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:E.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:E.email}),E.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[E.department,E.designation?` • ${E.designation}`:""]})]})]}),e.jsx(ie,{className:`${oe(E.role)} shrink-0`,"data-testid":`role-badge-${E.role}`,children:E.role})]})},E.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 ",(C-1)*R+1," to ",Math.min(C*R,j)," of ",j," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>se(C-1),disabled:C===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)},(E,V)=>{let H;return D<=5||C<=3?H=V+1:C>=D-2?H=D-4+V:H=C-2+V,e.jsx(I,{variant:C===H?"default":"outline",size:"sm",onClick:()=>se(H),className:`w-9 h-9 p-0 ${C===H?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${H}-button`,children:H},H)})}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>se(C+1),disabled:C===D,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function Rk(){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,u]=p.useState(null),[h,x]=p.useState({title:"",itemCode:"",taxationType:"",sapRefNo:""});p.useEffect(()=>{g()},[]);const g=async()=>{var T,C;try{r(!0),d(null);const _=await hA(!1);s(_)}catch(_){const D=((C=(T=_.response)==null?void 0:T.data)==null?void 0:C.error)||"Failed to load activity types";d(D),K.error(D)}finally{r(!1)}},f=()=>{x({title:"",itemCode:"",taxationType:"",sapRefNo:""}),o(null),i(!0)},y=T=>{x({title:T.title,itemCode:T.itemCode||"",taxationType:T.taxationType||"",sapRefNo:T.sapRefNo||""}),o(T),i(!0)},b=async()=>{var T,C;try{if(d(null),!h.title.trim()){d("Activity type title is required");return}const _={title:h.title.trim(),itemCode:h.itemCode.trim()||null,taxationType:h.taxationType.trim()||null,sapRefNo:h.sapRefNo.trim()||null};l?(await gA(l.activityTypeId,_),u("Activity type updated successfully"),K.success("Activity type updated successfully")):(await pA(_),u("Activity type created successfully"),K.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>u(null),3e3)}catch(_){const D=((C=(T=_.response)==null?void 0:T.data)==null?void 0:C.error)||"Failed to save activity type";d(D),K.error(D)}},v=async T=>{var C,_;if(confirm(`Delete "${T.title}"? This will deactivate the activity type.`))try{d(null),await fA(T.activityTypeId),u("Activity type deleted successfully"),K.success("Activity type deleted successfully"),await g(),setTimeout(()=>u(null),3e3)}catch(D){const S=((_=(C=D.response)==null?void 0:C.data)==null?void 0:_.error)||"Failed to delete activity type";d(S),K.error(S)}},A=t.filter(T=>T.isActive!==!1&&T.isActive!==void 0),w=t.filter(T=>T.isActive===!1);return e.jsxs("div",{className:"space-y-6",children:[m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(Pe,{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(Ve,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:c}),e.jsx(I,{size:"sm",variant:"ghost",onClick:()=>d(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(J,{className:"shadow-lg border-0 rounded-md",children:e.jsx(me,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(De,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Activity Types"}),e.jsx(Te,{className:"text-sm",children:"Manage dealer claim activity types"})]})]}),e.jsxs(I,{onClick:f,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm",children:[e.jsx(us,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Add Activity Type"}),e.jsx("span",{className:"xs:hidden",children:"Add"})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ze,{className:"w-8 h-8 animate-spin text-gray-400"})}):A.length===0?e.jsx(J,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(q,{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(De,{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(I,{onClick:f,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(us,{className:"w-4 h-4"}),"Add First Activity Type"]})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(J,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Active Activity Types"}),e.jsxs(Te,{className:"text-xs sm:text-sm",children:[A.length," active type",A.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-green-50 rounded-md",children:e.jsx(Pe,{className:"w-4 h-4 text-green-600"})})]})}),e.jsx(q,{className:"space-y-3 pt-4",children:A.map(T=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 hover:border-slate-300 transition-all shadow-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-900 text-sm sm:text-base",children:T.title}),e.jsx(ie,{variant:"outline",className:"bg-gradient-to-r from-green-50 to-emerald-50 text-green-800 border-green-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Active"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs sm:text-sm text-slate-600",children:[T.itemCode&&e.jsxs("span",{className:"font-medium",children:["Item Code: ",e.jsx("span",{className:"text-slate-900",children:T.itemCode})]}),T.taxationType&&e.jsxs("span",{className:"font-medium",children:["Taxation: ",e.jsx("span",{className:"text-slate-900",children:T.taxationType})]}),T.sapRefNo&&e.jsxs("span",{className:"font-medium",children:["SAP Ref: ",e.jsx("span",{className:"text-slate-900",children:T.sapRefNo})]}),!T.itemCode&&!T.taxationType&&!T.sapRefNo&&e.jsx("span",{className:"text-slate-500 italic",children:"No additional details"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(I,{size:"sm",variant:"ghost",onClick:()=>y(T),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(hi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(I,{size:"sm",variant:"ghost",onClick:()=>v(T),className:"gap-1.5 text-red-600 hover:text-red-700 hover:bg-red-50 border border-transparent hover:border-red-200 text-xs sm:text-sm",children:[e.jsx(kn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},T.activityTypeId))})]}),w.length>0&&e.jsxs(J,{className:"shadow-lg border-0 rounded-md border-amber-200",children:[e.jsx(me,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Inactive Activity Types"}),e.jsxs(Te,{className:"text-xs sm:text-sm",children:[w.length," inactive type",w.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-amber-50 rounded-md",children:e.jsx(Ve,{className:"w-4 h-4 text-amber-600"})})]})}),e.jsx(q,{className:"space-y-3 pt-4",children:w.map(T=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-amber-50/50 border border-amber-200 rounded-md hover:bg-amber-50 hover:border-amber-300 transition-all shadow-sm",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-700 text-sm sm:text-base line-through",children:T.title}),e.jsx(ie,{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(I,{size:"sm",variant:"ghost",onClick:()=>y(T),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(hi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]})})]},T.activityTypeId))})]})]}),e.jsx(ht,{open:n,onOpenChange:i,children:e.jsxs(ct,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(pt,{className:"pb-4 border-b border-slate-100 px-6 pt-6 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg shadow-md",children:e.jsx(De,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(dt,{className:"text-xl font-semibold text-slate-900",children:l?"Edit Activity Type":"Add New Activity Type"}),e.jsx(Et,{className:"text-sm text-slate-600 mt-1",children:l?"Update activity type information":"Add a new activity type for dealer claim management"})]})]})}),e.jsxs("div",{className:"space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"title",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Title ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ie,{id:"title",placeholder:"e.g., Riders Mania Claims, Legal Claims Reimbursement",value:h.title,onChange:T=>x({...h,title:T.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the activity type title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"itemCode",className:"text-sm font-semibold text-slate-900",children:["Item Code ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Ie,{id:"itemCode",placeholder:"e.g., 1, 2, 3",value:h.itemCode,onChange:T=>x({...h,itemCode:T.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional item code for the activity type"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{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(Ie,{id:"taxationType",placeholder:"e.g., GST, VAT, Exempt",value:h.taxationType,onChange:T=>x({...h,taxationType:T.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional taxation type for the activity"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{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(Ie,{id:"sapRefNo",placeholder:"e.g., SAP-12345",value:h.sapRefNo,onChange:T=>x({...h,sapRefNo:T.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional SAP reference number"})]})]}),e.jsxs(kt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(I,{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(I,{onClick:b,disabled:!h.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(De,{className:"w-4 h-4 mr-2"}),l?"Update Activity Type":"Add Activity Type"]})]})]})})]})}function Dk({open:t,onClose:s,success:a,message:r}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(dt,{className:"flex items-center gap-2",children:[e.jsx(Ds,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(Et,{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(Pe,{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(Nt,{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(kt,{children:e.jsx(I,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const Pk=async()=>(await je.get("/user/preferences/notifications")).data.data,Ik=async t=>(await je.put("/user/preferences/notifications",t)).data.data;function Ek({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,u]=p.useState(null);p.useEffect(()=>{t&&h()},[t]);const h=async()=>{var g,f;try{i(!0),u(null);const y=await Pk();r(y)}catch(y){console.error("[NotificationPreferences] Failed to load preferences:",y),u(((f=(g=y.response)==null?void 0:g.data)==null?void 0:f.message)||"Failed to load notification preferences")}finally{i(!1)}},x=async(g,f)=>{var y,b;try{o(g),u(null),d(null);const v={[g]:f},A=await Ik(v);r(A),d(`${g==="emailNotificationsEnabled"?"Email":g==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${f?"enabled":"disabled"}`),setTimeout(()=>d(null),3e3)}catch(v){console.error("[NotificationPreferences] Failed to update preference:",v),u(((b=(y=v.response)==null?void 0:y.data)==null?void 0:b.message)||"Failed to update notification preference"),h()}finally{o(null)}};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(pt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg",children:e.jsx(Ga,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(dt,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(Et,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx($t,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(Ze,{className:"w-8 h-8 animate-spin text-gray-400"})}):e.jsxs("div",{className:"space-y-6",children:[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(Pe,{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(Ve,{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(Ia,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"email-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Receive important updates and alerts via email"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="emailNotificationsEnabled"&&e.jsx(Ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Fs,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:g=>x("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(Ds,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"push-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Push Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Get instant browser notifications for real-time updates"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="pushNotificationsEnabled"&&e.jsx(Ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Fs,{id:"push-notifications-modal",checked:a.pushNotificationsEnabled,onCheckedChange:g=>x("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(Is,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"inapp-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"View notifications in the notification center"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="inAppNotificationsEnabled"&&e.jsx(Ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Fs,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>x("inAppNotificationsEnabled",g),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx($t,{}),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 Fk(){const{user:t}=Qt(),s=mr(t),[a,r]=p.useState(!1),[n,i]=p.useState(!1),[l,o]=p.useState(),[c,d]=p.useState(!1),[m,u]=p.useState(!1),[h,x]=p.useState(!1),[g,f]=p.useState(!0),[y,b]=p.useState(!1);p.useEffect(()=>{v()},[]);const v=async()=>{try{f(!0);const w=await fb();x(w.length>0)}catch(w){console.error("Failed to check subscription status:",w),x(!1)}finally{f(!1)}},A=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 w=Notification.permission;if(w==="denied"){i(!1),o(`Notification permission was previously denied. To enable notifications:
1. Click the lock icon (🔒) or info icon () in your browser's address bar
2. Find "Notifications" in the permissions list
3. Change it from "Block" to "Allow"
4. Refresh this page and try again
Alternatively, you can enable notifications in your browser's site settings.`),r(!0),d(!1);return}if(w==="default"&&(w=await Notification.requestPermission(),w==="denied")){i(!1),o(`Notification permission was denied. To enable notifications:
1. Click the lock icon (🔒) or info icon () in your browser's address bar
2. Find "Notifications" in the permissions list
3. Change it from "Block" to "Allow"
4. Refresh this page and try again`),r(!0),d(!1);return}if(w!=="granted"){i(!1),o("Notification permission is required to enable push notifications. Please grant permission and try again."),r(!0),d(!1);return}await Ck(),i(!0),o("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),r(!0),await v()}catch(w){console.error("[Settings] Error enabling notifications:",w),i(!1);const T=(w==null?void 0:w.message)||"Unknown error occurred";o(T.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":T.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":T.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${T}`),r(!0)}finally{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(J,{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(q,{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(Ga,{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(Un,{defaultValue:"user",className:"w-full",children:[e.jsxs(Bn,{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(Dt,{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(Ga,{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(Dt,{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(ds,{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(Dt,{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(jx,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(Dt,{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(lt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Holidays"}),e.jsx("span",{className:"sm:hidden",children:"Holidays"})]})]}),e.jsxs("div",{className:"w-full min-h-[600px]",children:[e.jsx(Tt,{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(J,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Ds,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(q,{children:e.jsxs("div",{className:"space-y-4",children:[g?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):h?e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-md",children:e.jsx("p",{className:"text-xs text-green-800 font-medium",children:"✓ This browser is already registered for push notifications."})}):e.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-md",children:e.jsx("p",{className:"text-xs text-blue-800",children:"Click below to register this browser for receiving push notifications. This needs to be done once per browser/device."})}),e.jsxs(I,{onClick:A,disabled:c||h,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(Ds,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(J,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(vn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(q,{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(J,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Hd,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(q,{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(J,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(ds,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(q,{children:e.jsxs(I,{onClick:()=>u(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(ds,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(Tt,{value:"roles",className:"mt-0",children:e.jsx(kk,{})}),e.jsx(Tt,{value:"system",className:"mt-0",children:e.jsx(Ak,{})}),e.jsx(Tt,{value:"holidays",className:"mt-0",children:e.jsx(Sk,{})}),e.jsx(Tt,{value:"templates",className:"mt-0",children:y?e.jsxs("div",{className:"space-y-4",children:[e.jsx(J,{className:"shadow-lg border-0 rounded-md",children:e.jsx(me,{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(I,{variant:"ghost",size:"sm",onClick:()=>b(!1),className:"gap-2 hover:bg-slate-100",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]}),e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(De,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Dealer Claim Activity Settings"}),e.jsx(Te,{className:"text-sm",children:"Manage activity types for dealer claim workflows"})]})]})})})}),e.jsx(Rk,{})]}):e.jsxs(J,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex 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(De,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Template Settings"}),e.jsx(Te,{className:"text-sm",children:"Manage templates and activity types for workflows"})]})]})}),e.jsx(q,{className:"pt-6",children:e.jsx("div",{className:"space-y-4",children:e.jsx(J,{className:"shadow-md hover:shadow-lg transition-all duration-300 border border-slate-200 rounded-lg cursor-pointer group",onClick:()=>b(!0),children:e.jsx(q,{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(De,{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(J,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Ds,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(q,{children:e.jsxs("div",{className:"space-y-4",children:[g?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):h?e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-md",children:e.jsx("p",{className:"text-xs text-green-800 font-medium",children:"✓ This browser is already registered for push notifications."})}):e.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-md",children:e.jsx("p",{className:"text-xs text-blue-800",children:"Click below to register this browser for receiving push notifications. This needs to be done once per browser/device."})}),e.jsxs(I,{onClick:A,disabled:c||h,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(Ds,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(J,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(vn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(q,{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(J,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Hd,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(q,{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(J,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(ds,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(q,{children:e.jsxs(I,{onClick:()=>u(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(ds,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(Dk,{open:a,onClose:()=>r(!1),success:n,message:l}),e.jsx(Ek,{open:m,onClose:()=>u(!1)})]})}function Mk({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),[u,h]=p.useState("all"),[x,g]=p.useState(!1),f=20,y=async(S=i,j=u==="unread")=>{var P,R;try{n(S===1);const O=await Wa.list({page:S,limit:f,unreadOnly:j}),F=((P=O.data)==null?void 0:P.notifications)||[],M=((R=O.data)==null?void 0:R.pagination)||{},B=M.total||0,k=M.totalPages||1;a(F),m(B),c(k),l(S)}catch(O){console.error("[Notifications] Failed to fetch:",O)}finally{n(!1),g(!1)}};p.useEffect(()=>{l(1),y(1,u==="unread")},[u]);const b=async S=>{var j;try{if(S.isRead||(await Wa.markAsRead(S.notificationId),a(P=>P.map(R=>R.notificationId===S.notificationId?{...R,isRead:!0}:R))),S.actionUrl&&t){const P=(j=S.metadata)==null?void 0:j.requestNumber;if(P){let R=`request/${P}`;(S.notificationType==="mention"||S.notificationType==="comment"||S.notificationType==="worknote")&&(R+="?tab=worknotes"),S.notificationType==="document_added"&&(R+="?tab=documents"),t(R)}}}catch(P){console.error("[Notifications] Error handling notification click:",P)}},v=async()=>{try{g(!0),await Wa.markAllAsRead(),await y(i,u==="unread")}catch(S){console.error("[Notifications] Error marking all as read:",S),g(!1)}},A=async S=>{try{await Wa.delete(S),a(j=>j.filter(P=>P.notificationId!==S)),m(j=>j-1)}catch(j){console.error("[Notifications] Error deleting notification:",j)}},w=()=>{g(!0),y(i,u==="unread")},T=S=>{S<1||S>o||(l(S),y(S,u==="unread"))},C=S=>{const j="w-6 h-6";switch(S){case"mention":case"comment":return e.jsx(Is,{className:`${j} text-blue-600`});case"worknote":return e.jsx(De,{className:`${j} text-purple-600`});case"document_added":return e.jsx(De,{className:`${j} text-teal-600`});case"assignment":return e.jsx(Ei,{className:`${j} text-indigo-600`});case"approval":return e.jsx(Pe,{className:`${j} text-green-600`});case"rejection":return e.jsx(Nt,{className:`${j} text-red-600`});case"tat_alert":return e.jsx(Xe,{className:`${j} text-orange-600`});case"tat_breach":return e.jsx(Ve,{className:`${j} text-red-600`});case"tat_breach_initiator":return e.jsx(ss,{className:`${j} text-amber-600`});default:return e.jsx(Ds,{className:`${j} text-gray-600`})}},_=S=>{switch(S==null?void 0:S.toUpperCase()){case"URGENT":return"bg-red-100 text-red-800 border-red-200";case"HIGH":return"bg-orange-100 text-orange-800 border-orange-200";case"MEDIUM":return"bg-blue-100 text-blue-800 border-blue-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},D=s.filter(S=>!S.isRead).length;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-3xl font-bold text-gray-900 flex items-center gap-3",children:[e.jsx(Ds,{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(I,{variant:"outline",size:"sm",onClick:w,disabled:x,className:"gap-2",children:[e.jsx(zt,{className:`w-4 h-4 ${x?"animate-spin":""}`}),"Refresh"]}),D>0&&e.jsxs(I,{variant:"outline",size:"sm",onClick:v,disabled:x,className:"gap-2",children:[e.jsx(_0,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(I,{variant:u==="all"?"default":"outline",size:"sm",onClick:()=>{h("all"),l(1)},children:"All Notifications"}),e.jsxs(I,{variant:u==="unread"?"default":"outline",size:"sm",onClick:()=>{h("unread"),l(1)},children:["Unread",D>0&&e.jsx(ie,{className:"ml-2 bg-red-500 text-white",children:D})]})]}),e.jsxs(J,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Recent Activity"}),e.jsx(Te,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(q,{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(Ds,{className:"w-16 h-16 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-lg font-medium text-gray-900 mb-2",children:"No notifications"}),e.jsx("p",{className:"text-sm text-gray-500",children:u==="unread"?"You're all caught up! No unread notifications.":"You don't have any notifications yet."})]}):e.jsx("div",{className:"space-y-2",children:s.map(S=>{var j;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${S.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>b(S),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:C(S.notificationType)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("h4",{className:`text-sm ${S.isRead?"font-semibold":"font-bold"} text-gray-900`,children:S.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S.priority&&S.priority!=="LOW"&&e.jsx(ie,{variant:"outline",className:`text-xs ${_(S.priority)}`,children:S.priority}),!S.isRead&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-600"})]})]}),e.jsx("p",{className:"text-sm text-gray-700 mb-2 line-clamp-2",children:S.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[rx(new Date(S.createdAt),{addSuffix:!0}),((j=S.metadata)==null?void 0:j.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",S.metadata.requestNumber]})]}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:P=>{P.stopPropagation(),A(S.notificationId)},children:e.jsx(kn,{className:"w-3.5 h-3.5"})})]})]})]})},S.notificationId)})})})]}),!r&&o>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing ",(i-1)*f+1," to ",Math.min(i*f,d)," of ",d," notifications"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(I,{variant:"outline",size:"sm",onClick:()=>T(i-1),disabled:i===1,children:[e.jsx(mx,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,o)},(S,j)=>{let P;return o<=5||i<=3?P=j+1:i>=o-2?P=o-4+j:P=i-2+j,e.jsx(I,{variant:i===P?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>T(P),children:P},P)})}),e.jsxs(I,{variant:"outline",size:"sm",onClick:()=>T(i+1),disabled:i===o,children:["Next",e.jsx(Ti,{className:"w-4 h-4"})]})]})]})]})}function _k({onBack:t}){return e.jsx("div",{className:"flex items-center justify-between","data-testid":"detailed-reports-header",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(I,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(Ss,{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(De,{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 Sc({dateRange:t,customStartDate:s,customEndDate:a,showCustomDatePicker:r,tempCustomStartDate:n,tempCustomEndDate:i,onDateRangeChange:l,onShowCustomDatePickerChange:o,onStartDateChange:c,onEndDateChange:d,onApply:m,onCancel:u,testIdPrefix:h="date-filter"}){const x=s&&a?`${Ye(s,"d MMM yyyy")} - ${Ye(a,"d MMM yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${h}-container`,children:[e.jsx(lt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:t,onValueChange:l,"data-testid":`${h}-select`,children:[e.jsx(Ge,{className:"w-[160px]",children:e.jsx(We,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(Zs,{open:r,onOpenChange:o,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${h}-custom-trigger`,children:[e.jsx(lt,{className:"w-4 h-4"}),x]})}),e.jsx(Qs,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:`${h}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(Bs,{value:n||null,onChange:g=>{const f=g?new Date(g):void 0;c(f)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full",id:`${h}-start-date`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:`${h}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(Bs,{value:i||null,onChange:g=>{const f=g?new Date(g):void 0;d(f)},minDate:n||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full",id:`${h}-end-date`})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(I,{size:"sm",onClick:m,disabled:!n||!i,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":`${h}-apply-button`,children:"Apply"}),e.jsx(I,{size:"sm",variant:"outline",onClick:u,"data-testid":`${h}-cancel-button`,children:"Cancel"})]})]})})]})]})}function Lk(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 Mg(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 _g(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 Ok(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function $k({lifecycleRequests:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,exporting:u,onDateRangeChange:h,onShowCustomDatePickerChange:x,onStartDateChange:g,onEndDateChange:f,onApplyCustomDate:y,onCancelCustomDate:b,onPageChange:v,onExport:A,onViewRequest:w}){return e.jsxs(J,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(me,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Pt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(Te,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",onClick:A,disabled:u,"data-testid":"export-lifecycle-button",children:[e.jsx(wt,{className:"w-4 h-4"}),u?"Exporting...":"Download CSV"]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(Sc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:h,onShowCustomDatePickerChange:x,onStartDateChange:g,onEndDateChange:f,onApply:y,onCancel:b,testIdPrefix:"lifecycle"})})]}),e.jsxs(q,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(Ze,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading lifecycle data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"lifecycle-error",children:[e.jsx(Ve,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"lifecycle-empty",children:e.jsx("p",{className:"text-sm",children:"No lifecycle data available"})}):e.jsx("div",{className:"space-y-4",children:t.map(T=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${T.id}`,children:e.jsx("div",{className:"p-4 bg-gradient-to-r from-gray-50 to-white hover:bg-gray-100 cursor-pointer transition-all",onClick:()=>w(T.requestId||T.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("button",{onClick:C=>{C.stopPropagation(),w(T.requestId||T.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${T.id}`,children:T.id}),e.jsx(ie,{className:Mg(T.priority),"data-testid":`lifecycle-priority-${T.id}`,children:T.priority}),e.jsx(ie,{className:_g(T.status),"data-testid":`lifecycle-status-${T.id}`,children:T.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:T.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:T.initiator})," on ",T.initDate]}),T.currentStage&&!T.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",T.currentStage]})]})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Current Stage"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:T.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",T.currentLevel,"/",T.totalLevels,")"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Overall TAT"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:T.overallTAT}),T.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[T.breachCount," breach",T.breachCount>1?"es":""]})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>w(T.requestId||T.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${T.id}`,children:e.jsx(Ti,{className:"w-4 h-4"})})]})]})})},T.id))}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"lifecycle-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(Ze,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>v(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>v(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function Tc({className:t,...s}){return e.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:e.jsx("table",{"data-slot":"table",className:Re("w-full caption-bottom text-sm",t),...s})})}function kc({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:Re("[&_tr]:border-b",t),...s})}function Rc({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:Re("[&_tr:last-child]:border-0",t),...s})}function jr({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:Re("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function ns({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:Re("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function qt({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:Re("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function Uk({activityLog:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,filterCategory:u,filterSeverity:h,exporting:x,onDateRangeChange:g,onShowCustomDatePickerChange:f,onStartDateChange:y,onEndDateChange:b,onApplyCustomDate:v,onCancelCustomDate:A,onCategoryChange:w,onSeverityChange:T,onClearFilters:C,onPageChange:_,onExport:D,onViewRequest:S}){const j=u!=="all"||h!=="all"||i!=="month"||l||o;return e.jsxs(J,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(me,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-indigo-100 rounded-lg",children:e.jsx(vx,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(Te,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",onClick:D,disabled:x,"data-testid":"export-activity-button",children:[e.jsx(wt,{className:"w-4 h-4"}),x?"Exporting...":"Download CSV"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(Sc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:g,onShowCustomDatePickerChange:f,onStartDateChange:y,onEndDateChange:b,onApply:v,onCancel:A,testIdPrefix:"activity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Category:"}),e.jsxs(He,{value:u,onValueChange:w,"data-testid":"activity-category-filter",children:[e.jsx(Ge,{className:"w-40",children:e.jsx(We,{placeholder:"All Categories"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Categories"}),e.jsx(X,{value:"WORKFLOW",children:"Workflow"}),e.jsx(X,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(X,{value:"DOCUMENT",children:"Document"}),e.jsx(X,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(X,{value:"SYSTEM",children:"System"}),e.jsx(X,{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(He,{value:h,onValueChange:T,"data-testid":"activity-severity-filter",children:[e.jsx(Ge,{className:"w-40",children:e.jsx(We,{placeholder:"All Severities"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"all",children:"All Severities"}),e.jsx(X,{value:"INFO",children:"Info"}),e.jsx(X,{value:"WARNING",children:"Warning"}),e.jsx(X,{value:"ERROR",children:"Error"}),e.jsx(X,{value:"CRITICAL",children:"Critical"})]})]})]}),j&&e.jsx(I,{variant:"ghost",size:"sm",onClick:C,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(q,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(Ze,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading activity data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"activity-error",children:[e.jsx(Ve,{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(Tc,{children:[e.jsx(kc,{children:e.jsxs(jr,{className:"bg-gray-50",children:[e.jsx(ns,{className:"font-semibold",children:"Timestamp"}),e.jsx(ns,{className:"font-semibold",children:"User"}),e.jsx(ns,{className:"font-semibold",children:"Action"}),e.jsx(ns,{className:"font-semibold",children:"Details"}),e.jsx(ns,{className:"font-semibold",children:"IP Address"}),e.jsx(ns,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(Rc,{children:t.map((P,R)=>e.jsxs(jr,{className:"hover:bg-gray-50","data-testid":`activity-row-${R}`,children:[e.jsx(qt,{className:"text-xs font-medium",children:P.timestamp}),e.jsx(qt,{className:"text-sm",children:P.user}),e.jsx(qt,{children:e.jsx(ie,{className:Lk(P.action),"data-testid":`activity-action-${R}`,children:P.action})}),e.jsx(qt,{className:"text-sm text-gray-600",children:P.details}),e.jsx(qt,{className:"text-xs font-mono text-gray-500",children:P.ip&&P.ip!=="N/A"?e.jsx("span",{title:P.userAgent||"",children:P.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(qt,{children:P.requestId!=="-"&&P.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const O=P.requestId;O&&S(O)},className:"hover:underline","data-testid":`activity-request-link-${R}`,children:e.jsx(ie,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:P.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},R))})]}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"activity-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(Ze,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>_(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>_(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function Bk({agingWorkflows:t,loading:s,loadingPage:a,error:r,pagination:n,threshold:i,thresholdError:l,dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:h,searchQuery:x,exporting:g,onThresholdChange:f,onThresholdBlur:y,onDateRangeChange:b,onShowCustomDatePickerChange:v,onStartDateChange:A,onEndDateChange:w,onApplyCustomDate:T,onCancelCustomDate:C,onSearchChange:_,onPageChange:D,onExport:S,onViewRequest:j}){return e.jsxs(J,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(me,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-amber-100 rounded-lg",children:e.jsx(To,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(Te,{className:"text-gray-600",children:"Workflows exceeding aging threshold"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Threshold:"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{type:"number",min:"1",value:i,onChange:P=>f(P.target.value),onBlur:y,className:`w-24 ${l?"border-red-500 focus:border-red-500 focus:ring-red-500":""}`,placeholder:"Days","data-testid":"aging-threshold-input"}),e.jsx("span",{className:"text-sm text-gray-600 whitespace-nowrap",children:"days"})]}),l&&e.jsx("span",{className:"text-xs text-red-600",children:l})]})]}),e.jsxs(ie,{variant:"outline",className:"font-semibold","data-testid":"aging-total-badge",children:[n.totalRecords," workflows"]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",onClick:S,disabled:g,"data-testid":"export-aging-button",children:[e.jsx(wt,{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(Sc,{dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:h,onDateRangeChange:b,onShowCustomDatePickerChange:v,onStartDateChange:A,onEndDateChange:w,onApply:T,onCancel:C,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ie,{placeholder:"Search by Request ID, Title, or Initiator...",value:x,onChange:P=>_(P.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(q,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(Ze,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading aging data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"aging-error",children:[e.jsx(Ve,{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(Tc,{children:[e.jsx(kc,{children:e.jsxs(jr,{className:"bg-gray-50",children:[e.jsx(ns,{className:"font-semibold",children:"Request ID"}),e.jsx(ns,{className:"font-semibold",children:"Title"}),e.jsx(ns,{className:"font-semibold",children:"Initiator"}),e.jsx(ns,{className:"font-semibold",children:"Start Date"}),e.jsx(ns,{className:"font-semibold",children:"Days Open"}),e.jsx(ns,{className:"font-semibold",children:"Current Stage"}),e.jsx(ns,{className:"font-semibold",children:"Assigned To"}),e.jsx(ns,{className:"font-semibold",children:"Priority"}),e.jsx(ns,{className:"font-semibold",children:"Status"})]})}),e.jsx(Rc,{children:t.map(P=>e.jsxs(jr,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${P.id}`,children:[e.jsx(qt,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>j(P.requestId||P.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${P.id}`,children:P.id})}),e.jsx(qt,{className:"text-sm",children:P.title}),e.jsx(qt,{className:"text-sm",children:P.initiator}),e.jsx(qt,{className:"text-sm text-gray-600",children:P.startDate}),e.jsx(qt,{children:e.jsxs(ie,{className:`${Ok(P.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${P.id}`,children:[P.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(qt,{className:"text-sm",children:P.currentStage}),e.jsx(qt,{className:"text-sm",children:P.assignedTo&&P.assignedTo!=="N/A"?P.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(qt,{children:e.jsx(ie,{className:Mg(P.priority),"data-testid":`aging-priority-${P.id}`,children:P.priority})}),e.jsx(qt,{children:e.jsx(ie,{className:_g(P.status),"data-testid":`aging-status-${P.id}`,children:P.status})})]},P.id))})]}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"aging-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(Ze,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>D(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>D(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function $l(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),[u,h]=p.useState(void 0),x=p.useCallback(w=>{const T=w;a(T),T!=="custom"?(n(void 0),l(void 0),m(void 0),h(void 0),c(!1)):(m(r),h(i),c(!0))},[r,i]),g=p.useCallback(()=>{if(d&&u){if(d>u){const w=d;n(u),l(w),m(u),h(w)}else n(d),l(u);c(!1)}},[d,u]),f=p.useCallback(()=>{c(!1),m(r),h(i),(!r||!i)&&(n(void 0),l(void 0),a("month"))},[r,i]),y=p.useCallback(w=>{w?(m(w),u&&w>u&&h(w)):m(void 0)},[u]),b=p.useCallback(w=>{w?(h(w),d&&w<d&&m(w)):h(void 0)},[d]),v=p.useCallback(()=>r&&i?`${Ye(r,"MMM d, yyyy")} - ${Ye(i,"MMM d, yyyy")}`:"Select dates",[r,i]),A=p.useCallback(()=>{a("month"),n(void 0),l(void 0),c(!1),m(void 0),h(void 0)},[]);return{dateRange:s,customStartDate:r,customEndDate:i,showCustomDatePicker:o,tempCustomStartDate:d,tempCustomEndDate:u,setShowCustomDatePicker:c,handleDateRangeChange:x,handleApplyCustomDate:g,handleCancelCustomDate:f,handleStartDateChange:y,handleEndDateChange:b,getDisplayDateRange:v,reset:A}}function Vk(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return Ot(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${Ot(r)}`:`${a}d`}function Lg(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 hr(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 Og(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 zk=10;function Hk({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),[u,h]=p.useState({page:1,totalPages:1,totalRecords:0}),x=p.useRef(!0),g=p.useCallback(async(f=1)=>{const y=f===1&&x.current;try{y?l(!0):c(!0),m(null);const b=await St.getLifecycleReport(f,zk,t,s,a),v=b.lifecycleData.map(A=>{const w=Vk(A.overallTATHours);return{id:A.requestNumber,requestId:A.requestId,title:A.title,priority:A.priority||"medium",status:A.status,initiator:A.initiatorName||"Unknown",initDate:Lg(A.submissionDate),currentStage:A.currentStageName||`Level ${A.currentLevel}`,overallTAT:w,currentLevel:A.currentLevel,totalLevels:A.totalLevels,breachCount:A.breachCount||0}});n(v),h({page:b.pagination.currentPage,totalPages:b.pagination.totalPages,totalRecords:b.pagination.totalRecords})}catch(b){console.error("Failed to fetch lifecycle data:",b),m((b==null?void 0:b.message)||"Failed to load lifecycle data")}finally{y?l(!1):c(!1)}y&&(x.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:u,fetchData:g}}const Wk=20;function Gk({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),[u,h]=p.useState(null),[x,g]=p.useState({page:1,totalPages:1,totalRecords:0}),f=p.useRef(!0),y=p.useCallback(async(b=1)=>{const v=b===1&&f.current;try{v?c(!0):m(!0),h(null);const A=await St.getActivityLogReport(b,Wk,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),w=A.activities.map(T=>{const C=Og(T.type||"",T.details),_=(T.type||"").toLowerCase()==="login"||T.requestId==="00000000-0000-0000-0000-000000000001"||T.requestId==="SYSTEM_LOGIN",D=_?T.details||"User login":T.requestTitle||T.requestNumber||T.details||"N/A";return{timestamp:T.timestamp?Lg(T.timestamp):"N/A",user:T.userName||"Unknown",action:C,details:D,ip:T.ipAddress||"N/A",userAgent:T.userAgent||null,requestId:_?"System Login":T.requestNumber||T.requestId||"-",userId:T.userId}});l(w),g({page:A.pagination.currentPage,totalPages:A.pagination.totalPages,totalRecords:A.pagination.totalRecords})}catch(A){console.error("Failed to fetch activity data:",A),h((A==null?void 0:A.message)||"Failed to load activity data")}finally{v?c(!1):m(!1)}v&&(f.current=!1)},[r,n,t,s,a]);return p.useEffect(()=>{t==="custom"&&(!s||!a)||y(1)},[r,n,t,s,a]),{activityLog:i,loading:o,loadingPage:d,error:u,pagination:x,fetchData:y}}const Kk=20;function Yk({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),[u,h]=p.useState(null),[x,g]=p.useState({page:1,totalPages:1,totalRecords:0}),f=p.useRef(!0),y=p.useCallback(async(v=1)=>{const A=v===1&&f.current;try{A?c(!0):m(!0),h(null);const w=parseInt(t,10);if(isNaN(w)||w<1){h("Please enter a valid threshold (minimum 1 day)");return}const T=await St.getWorkflowAgingReport(w,v,Kk,s,a,r),C=T.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(C),g({page:T.pagination.currentPage,totalPages:T.pagination.totalPages,totalRecords:T.pagination.totalRecords})}catch(w){console.error("Failed to fetch aging data:",w),h((w==null?void 0:w.message)||"Failed to load aging data")}finally{A?c(!1):m(!1)}A&&(f.current=!1)},[t,s,a,r]),b=p.useMemo(()=>i.filter(v=>{var w,T,C;if(!n)return!0;const A=n.toLowerCase();return((w=v.id)==null?void 0:w.toLowerCase().includes(A))||((T=v.title)==null?void 0:T.toLowerCase().includes(A))||((C=v.initiator)==null?void 0:C.toLowerCase().includes(A))}),[i,n]);return p.useEffect(()=>{s==="custom"&&(!a||!r)||y(1)},[t,s,a,r]),{agingWorkflows:b,loading:o,loadingPage:d,error:u,pagination:x,fetchData:y}}function Zk(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 Xk(t,s,a){const r=await St.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 Cs(i.requestId||i.requestNumber),o=i.submissionDate?hr(i.submissionDate):"N/A",c=i.closureDate?hr(i.closureDate):"N/A",d=i.overallTATHours||0,m=d>0?(d/8).toFixed(2):"0",u=i.totalLevels||1,h=Math.min(Math.max(1,i.currentLevel||1),u),x=(l==null?void 0:l.approvals)||[];if(x.length===0){const g=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,c,u.toString(),h.toString(),d.toString(),m,(i.breachCount||0).toString(),"N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(g.join(","))}else x.forEach(g=>{const f=g.levelStartTime?hr(g.levelStartTime):"N/A",y=g.levelEndTime||g.completedAt?hr(g.levelEndTime||g.completedAt):"N/A",b=g.tatHours||0,v=g.tatDays||(b>0?(b/8).toFixed(2):"0");let A="N/A",w="N/A",T="N/A",C="N/A";if(g.levelStartTime){const D=new Date(g.levelStartTime);if(w=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-D.getTime())/(1e3*60*60)).toFixed(2),b>0){const P=parseFloat(w);T=Math.max(0,b-P).toFixed(2),C=(P/b*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?A=P<=b?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?A=P<=b?"On Track":"At Risk":A="N/A"}}const _=[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",f,y,b.toString(),v.toString(),A,w,T,C];n.push(_.join(","))})}catch(l){console.error(`Failed to fetch details for request ${i.requestNumber}:`,l);const o=i.submissionDate?hr(i.submissionDate):"N/A",c=i.overallTATHours||0,d=c>0?(c/8).toFixed(2):"0",m=i.totalLevels||1,u=Math.min(Math.max(1,i.currentLevel||1),m),h=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,"N/A",m.toString(),u.toString(),c.toString(),d,(i.breachCount||0).toString(),"Error","Error fetching details","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(h.join(","))}Dc(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function Qk(t,s,a,r,n){const i=await St.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=Og(o.type||"",o.details),m=[o.timestamp?hr(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(","))}),Dc(l,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function Jk(t,s,a,r){const n=await St.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?hr(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(","))}),Dc(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function Dc(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 qk(){const[t,s]=p.useState(!1),[a,r]=p.useState(!1),[n,i]=p.useState(!1),l=p.useCallback(async(d,m,u)=>{try{s(!0),await Xk(d,m,u)}catch(h){console.error("Failed to export lifecycle data:",h),alert("Failed to export lifecycle data. Please try again.")}finally{s(!1)}},[]),o=p.useCallback(async(d,m,u,h,x)=>{try{r(!0),await Qk(d,m,u,h,x)}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,u,h)=>{try{i(!0),await Jk(d,m,u,h)}catch(x){console.error("Failed to export aging data:",x),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 e4({onBack:t}){const s=qs(),[a,r]=p.useState(""),[n,i]=p.useState("all"),[l,o]=p.useState("all"),c=$l("month"),d=$l("month"),m=$l("month"),u=Zk("7"),h=Hk({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),x=Gk({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:l}),g=Yk({threshold:u.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),f=qk(),y=p.useCallback(()=>{t?t():s("/dashboard")},[t,s]),b=p.useCallback(C=>{Ci({requestId:C,navigate:s})},[s]),v=p.useCallback(()=>{f.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[f,c]),A=p.useCallback(()=>{f.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,l)},[f,d,n,l]),w=p.useCallback(()=>{const C=parseInt(u.threshold,10);!isNaN(C)&&C>=1&&f.handleExportAging(C,m.dateRange,m.customStartDate,m.customEndDate)},[f,u.threshold,m]),T=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(_k,{onBack:y}),e.jsx($k,{lifecycleRequests:h.lifecycleRequests,loading:h.loading,loadingPage:h.loadingPage,error:h.error,pagination:h.pagination,dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate,showCustomDatePicker:c.showCustomDatePicker,tempCustomStartDate:c.tempCustomStartDate,tempCustomEndDate:c.tempCustomEndDate,exporting:f.exportingLifecycle,onDateRangeChange:c.handleDateRangeChange,onShowCustomDatePickerChange:c.setShowCustomDatePicker,onStartDateChange:c.handleStartDateChange,onEndDateChange:c.handleEndDateChange,onApplyCustomDate:c.handleApplyCustomDate,onCancelCustomDate:c.handleCancelCustomDate,onPageChange:h.fetchData,onExport:v,onViewRequest:b}),e.jsx(Uk,{activityLog:x.activityLog,loading:x.loading,loadingPage:x.loadingPage,error:x.error,pagination:x.pagination,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,showCustomDatePicker:d.showCustomDatePicker,tempCustomStartDate:d.tempCustomStartDate,tempCustomEndDate:d.tempCustomEndDate,filterCategory:n,filterSeverity:l,exporting:f.exportingActivity,onDateRangeChange:d.handleDateRangeChange,onShowCustomDatePickerChange:d.setShowCustomDatePicker,onStartDateChange:d.handleStartDateChange,onEndDateChange:d.handleEndDateChange,onApplyCustomDate:d.handleApplyCustomDate,onCancelCustomDate:d.handleCancelCustomDate,onCategoryChange:i,onSeverityChange:o,onClearFilters:T,onPageChange:x.fetchData,onExport:A,onViewRequest:b}),e.jsx(Bk,{agingWorkflows:g.agingWorkflows,loading:g.loading,loadingPage:g.loadingPage,error:g.error,pagination:g.pagination,threshold:u.threshold,thresholdError:u.thresholdError,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,showCustomDatePicker:m.showCustomDatePicker,tempCustomStartDate:m.tempCustomStartDate,tempCustomEndDate:m.tempCustomEndDate,searchQuery:a,exporting:f.exportingAging,onThresholdChange:u.handleThresholdChange,onThresholdBlur:u.handleThresholdBlur,onDateRangeChange:m.handleDateRangeChange,onShowCustomDatePickerChange:m.setShowCustomDatePicker,onStartDateChange:m.handleStartDateChange,onEndDateChange:m.handleEndDateChange,onApplyCustomDate:m.handleApplyCustomDate,onCancelCustomDate:m.handleCancelCustomDate,onSearchChange:r,onPageChange:g.fetchData,onExport:w,onViewRequest:b})]})})}function t4({defaultPeriod:t,refreshInterval:s,onDefaultPeriodChange:a,onRefreshIntervalChange:r}){const n=["Today","This Week","This Month","Last Month","This Quarter","This Year","Custom Range"];return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(He,{value:t,onValueChange:a,children:[e.jsx(Ge,{id:"default-period",children:e.jsx(We,{})}),e.jsx(Ke,{children:n.map(i=>e.jsx(X,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(Ie,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function s4({autoRefresh:t,realTimeUpdates:s,dataExport:a,onAutoRefreshChange:r,onRealTimeUpdatesChange:n,onDataExportChange:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Data Features"}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Enable Auto-Refresh"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically refresh dashboard data at set intervals"})]}),e.jsx(Fs,{checked:t,onCheckedChange:r})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Enable Real-time Updates"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Show live updates when data changes occur"})]}),e.jsx(Fs,{checked:s,onCheckedChange:n})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Enable Data Export"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Allow users to export analytics data and reports"})]}),e.jsx(Fs,{checked:a,onCheckedChange:i})]})]})}const a4=["CSV","Excel","PDF","JSON"];function r4({exportFormats:t,onExportFormatsChange:s}){const a=(r,n)=>{s(n?[...t,r]:t.filter(i=>i!==r))};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:a4.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Ac,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(ne,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function n4({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(Ie,{id:"data-retention",type:"number",min:"1",max:"120",value:t,onChange:a=>s(parseInt(a.target.value)||24)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Analytics data older than this will be archived or deleted"})]})}function i4(){const[t,s]=p.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{K.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(J,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Analytics & Reporting Configuration"}),e.jsx(Te,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(t4,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx($t,{}),e.jsx(s4,{autoRefresh:t.autoRefresh,realTimeUpdates:t.realTimeUpdates,dataExport:t.dataExport,onAutoRefreshChange:n=>r({autoRefresh:n}),onRealTimeUpdatesChange:n=>r({realTimeUpdates:n}),onDataExportChange:n=>r({dataExport:n})}),e.jsx($t,{}),e.jsx(r4,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(n4,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(_a,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const l4=t=>{switch(t.toUpperCase()){case"ADMIN":return"bg-yellow-100 text-yellow-800 border-yellow-200";case"MANAGEMENT":return"bg-blue-100 text-blue-800 border-blue-200";case"USER":return"bg-gray-100 text-gray-800 border-gray-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},o4=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function c4({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Tc,{children:[e.jsx(kc,{children:e.jsxs(jr,{children:[e.jsx(ns,{children:"User"}),e.jsx(ns,{children:"Role"}),e.jsx(ns,{children:"Department"}),e.jsx(ns,{children:"Status"}),e.jsx(ns,{className:"text-right",children:"Actions"})]})}),e.jsx(Rc,{children:t.length===0?e.jsx(jr,{children:e.jsx(qt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(jr,{className:"hover:bg-muted/50",children:[e.jsx(qt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(es,{className:"size-10",children:e.jsx(ts,{className:"bg-re-green text-white",children:o4(n.name)})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:n.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.email})]})]})}),e.jsx(qt,{children:e.jsx(ie,{className:l4(n.role),children:n.role})}),e.jsx(qt,{children:n.department}),e.jsx(qt,{children:e.jsxs(ie,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Rs,{className:"w-3 h-3 mr-1"}),n.status]})}),e.jsx(qt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx(Oi,{className:"w-4 h-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(L0,{className:"w-4 h-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(kn,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function d4({stats:t}){return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Users"}),e.jsx("p",{className:"text-2xl font-semibold",children:t.total})]}),e.jsxs("div",{className:"p-4 bg-green-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active"}),e.jsx("p",{className:"text-2xl font-semibold text-green-600",children:t.active})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Inactive"}),e.jsx("p",{className:"text-2xl font-semibold text-red-600",children:t.inactive})]}),e.jsxs("div",{className:"p-4 bg-purple-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Admins"}),e.jsx("p",{className:"text-2xl font-semibold text-purple-600",children:t.admins})]})]})}function m4(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function u4(){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,u]=p.useState(!1),[h,x]=p.useState(!1),[g,f]=p.useState(null),[y,b]=p.useState([]),[v,A]=p.useState(!1),[w,T]=p.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[C,_]=p.useState("ELEVATED"),[D,S]=p.useState(1),[j,P]=p.useState(1),[R,O]=p.useState(0),F=10,M=p.useRef(null),B=p.useCallback(m4(async Q=>{var Y,W,ce;if(!Q||!Q.startsWith("@")||Q.length<2){r([]),i(!1);return}i(!0);try{const xe=Q.slice(1),Ae=((Y=(await Gs.searchUsers(xe,20)).data)==null?void 0:Y.data)||[];r(Ae)}catch(xe){console.error("Search failed:",xe),f({type:"error",text:((ce=(W=xe.response)==null?void 0:W.data)==null?void 0:ce.message)||"Failed to search users"})}finally{i(!1)}},300),[]),k=Q=>{const Y=Q.target.value;s(Y),B(Y)},N=async Q=>{var Y,W;try{const ce=y.find(ae=>ae.email.toLowerCase()===Q.toLowerCase());if(ce)return ce.role;const Ae=(((W=(Y=(await Gs.getUsersByRole("ALL",1,1e3)).data)==null?void 0:Y.data)==null?void 0:W.users)||[]).find(ae=>{var ye;return((ye=ae.email)==null?void 0:ye.toLowerCase())===Q.toLowerCase()});return Ae&&Ae.role?Ae.role:null}catch(ce){return console.error("Failed to fetch user role:",ce),null}},U=async Q=>{o(Q),s(Q.email),r([]),x(!0);try{const Y=await N(Q.email);d(Y||"USER")}catch(Y){console.error("Failed to fetch user role:",Y),d("USER")}finally{x(!1)}},$=async()=>{var Q,Y;if(!l||!c){f({type:"error",text:"Please select a user and role"});return}u(!0),f(null);try{await Gs.assignRole(l.email,c),f({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await L(),await se(),K.success("Role assigned successfully")}catch(W){console.error("Role assignment failed:",W);const ce=((Y=(Q=W.response)==null?void 0:Q.data)==null?void 0:Y.error)||"Failed to assign role";f({type:"error",text:ce}),K.error(ce)}finally{u(!1)}},L=async(Q=D)=>{var Y,W,ce,xe,ke,Ae;A(!0);try{const ae=await Gs.getUsersByRole(C,Q,F),ye=((W=(Y=ae.data)==null?void 0:Y.data)==null?void 0:W.users)||[],Ne=(xe=(ce=ae.data)==null?void 0:ce.data)==null?void 0:xe.pagination,ve=(Ae=(ke=ae.data)==null?void 0:ke.data)==null?void 0:Ae.summary;b(ye.map($e=>({userId:$e.userId,email:$e.email,displayName:$e.displayName||$e.email,role:$e.role||"USER",department:$e.department,designation:$e.designation,isActive:$e.isActive!==!1}))),Ne&&(S(Ne.currentPage),P(Ne.totalPages),O(Ne.totalUsers)),ve&&T($e=>({...$e,admins:ve.ADMIN||0,management:ve.MANAGEMENT||0,users:ve.USER||0,total:(ve.ADMIN||0)+(ve.MANAGEMENT||0)+(ve.USER||0)}))}catch(ae){console.error("Failed to fetch users:",ae),K.error("Failed to load users")}finally{A(!1)}},se=async()=>{var Q,Y,W,ce,xe,ke;try{const Ae=await Gs.getRoleStatistics(),ae=((Y=(Q=Ae.data)==null?void 0:Q.data)==null?void 0:Y.statistics)||((W=Ae.data)==null?void 0:W.statistics)||[],ye={admins:parseInt(((ce=ae.find(Ne=>Ne.role==="ADMIN"))==null?void 0:ce.count)||"0"),management:parseInt(((xe=ae.find(Ne=>Ne.role==="MANAGEMENT"))==null?void 0:xe.count)||"0"),users:parseInt(((ke=ae.find(Ne=>Ne.role==="USER"))==null?void 0:ke.count)||"0")};T(Ne=>({...Ne,...ye,total:ye.admins+ye.management+ye.users,active:Ne.active||ye.admins+ye.management+ye.users,inactive:Ne.inactive||0}))}catch(Ae){console.error("Failed to fetch statistics:",Ae)}};p.useEffect(()=>{L(1),se()},[C]);const G=Q=>{_(Q),S(1)},oe=Q=>{L(Q)},Z=async(Q,Y)=>{var W,ce;try{await Gs.updateUserRole(Q,Y),K.success("User role updated successfully"),await L(),await se()}catch(xe){console.error("Failed to update user role:",xe),K.error(((ce=(W=xe.response)==null?void 0:W.data)==null?void 0:ce.error)||"Failed to update user role")}},E=async Q=>{y.find(W=>W.userId===Q)&&K.info("User status toggle functionality coming soon")},V=async Q=>{const Y=y.find(W=>W.userId===Q);if(Y){if(Y.role==="ADMIN"){K.error("Cannot delete admin user");return}K.info("User deletion functionality coming soon")}};p.useEffect(()=>{const Q=Y=>{M.current&&!M.current.contains(Y.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",Q),()=>{document.removeEventListener("mousedown",Q)}},[a]);const H={total:w.total,active:w.active,inactive:w.inactive,admins:w.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(d4,{stats:H}),e.jsxs(J,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Assign User Role"}),e.jsx(Te,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(I,{onClick:$,disabled:!l||m,className:"bg-re-green hover:bg-re-green/90",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(q,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",ref:M,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(Ie,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:k,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx(Ze,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Start with @ to search users (e.g., @john)"}),a.length>0&&e.jsxs("div",{className:"border rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-muted px-4 py-2 border-b",children:e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-3",children:a.map(Q=>e.jsxs("button",{onClick:()=>U(Q),className:"w-full text-left p-3 hover:bg-muted rounded-lg transition-colors mb-1 last:mb-0",children:[e.jsx("p",{className:"font-medium text-gray-900",children:Q.displayName||Q.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Q.email}),Q.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[Q.department,Q.designation?` • ${Q.designation}`:""]})]},Q.userId))})]})]}),l&&e.jsx("div",{className:"border-2 border-re-green/20 bg-re-green/5 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-re-green flex items-center justify-center text-white font-bold shadow-md",children:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-gray-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[l.department,l.designation?` • ${l.designation}`:""]}),h&&e.jsxs("p",{className:"text-xs text-re-green mt-1 flex items-center gap-1",children:[e.jsx(Ze,{className:"w-3 h-3 animate-spin"}),"Checking current role..."]})]})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{o(null),s(""),d("USER"),x(!1)},children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Select Role"}),e.jsxs(He,{value:c,onValueChange:Q=>d(Q),disabled:h,children:[e.jsx(Ge,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(We,{placeholder:h?"Loading current role...":"Select role"})}),e.jsxs(Ke,{className:"rounded-lg",children:[e.jsx(X,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(X,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(X,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),g&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${g.type==="success"?"border-green-200 bg-green-50":"border-red-200 bg-red-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[g.type==="success"?e.jsx(Pe,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Ve,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${g.type==="success"?"text-green-800":"text-red-800"}`,children:g.text})]})})]})]}),e.jsxs(J,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(Te,{children:["View and manage user accounts and roles (",R," ",C!=="ALL"&&C!=="ELEVATED"?C.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(He,{value:C,onValueChange:G,children:[e.jsx(Ge,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(We,{placeholder:"Filter by role"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ds,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",w.admins+w.management,")"]})]})}),e.jsx(X,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",w.admins,")"]})]})}),e.jsx(X,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",w.management,")"]})]})}),e.jsx(X,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",w.users,")"]})]})}),e.jsx(X,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",w.admins+w.management+w.users,")"]})]})})]})]})})]})}),e.jsx(q,{className:"pt-6",children:v?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Ze,{className:"w-6 h-6 animate-spin text-re-green mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading users..."})]}):y.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(Bt,{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(c4,{users:y.map(Q=>({id:Q.userId,name:Q.displayName,email:Q.email,role:Q.role,department:Q.department||"N/A",status:Q.isActive?"active":"inactive"})),onEdit:Q=>{const Y=y.find(W=>W.userId===Q);if(Y){const W=Y.role==="USER"?"MANAGEMENT":Y.role==="MANAGEMENT"?"ADMIN":"USER";Z(Q,W)}},onToggleStatus:E,onDelete:V}),j>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t mt-4",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(D-1)*F+1," to ",Math.min(D*F,R)," of ",R," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>oe(D-1),disabled:D===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,j)},(Q,Y)=>{let W;return j<=5||D<=3?W=Y+1:D>=j-2?W=j-4+Y:W=D-2+Y,e.jsx(I,{variant:D===W?"default":"outline",size:"sm",onClick:()=>oe(W),className:`w-9 h-9 p-0 ${D===W?"bg-re-green hover:bg-re-green/90":""}`,children:W},W)})}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>oe(D+1),disabled:D===j,children:"Next"})]})]})]})})]})]})}function x4({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(J,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ri,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(Te,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(q,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(Ie,{id:"tat-express",type:"number",min:"1",max:"168",value:t,onChange:n=>a(parseInt(n.target.value)||24),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(Ie,{id:"tat-standard",type:"number",min:"1",max:"720",value:s,onChange:n=>r(parseInt(n.target.value)||72),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function h4({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(J,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(Te,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(q,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{htmlFor:"reminder-threshold-1",className:"text-sm font-medium",children:"First Reminder Threshold"}),e.jsxs("span",{className:"text-lg font-semibold text-re-green",children:[t,"%"]})]}),e.jsx(go,{id:"reminder-threshold-1",value:[t],min:1,max:100,step:1,onValueChange:([n])=>{n!==void 0&&a(n)},className:"w-full"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ds,{className:"w-3 h-3"}),"Send first gentle reminder when ",t,"% of TAT elapsed"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{htmlFor:"reminder-threshold-2",className:"text-sm font-medium",children:"Second Reminder Threshold (Escalation)"}),e.jsxs("span",{className:"text-lg font-semibold text-re-green",children:[s,"%"]})]}),e.jsx(go,{id:"reminder-threshold-2",value:[s],min:1,max:100,step:1,onValueChange:([n])=>{n!==void 0&&r(n)},className:"w-full"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ss,{className:"w-3 h-3"}),"Send escalation warning when ",s,"% of TAT elapsed"]})]})]})})]})}const cn=[{value:1,label:"Monday"},{value:2,label:"Tuesday"},{value:3,label:"Wednesday"},{value:4,label:"Thursday"},{value:5,label:"Friday"},{value:6,label:"Saturday"},{value:7,label:"Sunday"}];function p4({workStartHour:t,workEndHour:s,workStartDay:a,workEndDay:r,onWorkStartHourChange:n,onWorkEndHourChange:i,onWorkStartDayChange:l,onWorkEndDayChange:o}){var c,d,m;return e.jsxs(J,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(Te,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(Ie,{id:"work-start-hour",type:"number",min:"0",max:"23",value:t,onChange:u=>n(parseInt(u.target.value)||9),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(Ie,{id:"work-end-hour",type:"number",min:"0",max:"23",value:s,onChange:u=>i(parseInt(u.target.value)||18),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 6 PM"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(He,{value:a.toString(),onValueChange:u=>l(parseInt(u)),children:[e.jsx(Ge,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(We,{placeholder:"Select start day"})}),e.jsx(Ke,{children:cn.map(u=>e.jsx(X,{value:u.value.toString(),children:u.label},u.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Day when the working week starts (1=Monday, 7=Sunday)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(He,{value:r.toString(),onValueChange:u=>o(parseInt(u)),children:[e.jsx(Ge,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(We,{placeholder:"Select end day"})}),e.jsx(Ke,{children:cn.map(u=>e.jsx(X,{value:u.value.toString(),children:u.label},u.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Day when the working week ends (1=Monday, 7=Sunday)"})]})]}),e.jsx("div",{className:"p-4 bg-blue-50 border border-blue-200 rounded-md",children:e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("strong",{children:"Current Configuration:"})," Working hours are from ",t,":00 to ",s,":00,",a===r?` ${(c=cn.find(u=>u.value===a))==null?void 0:c.label} only`:` ${(d=cn.find(u=>u.value===a))==null?void 0:d.label} to ${(m=cn.find(u=>u.value===r))==null?void 0:m.label}`]})})]})]})}function g4(){const[t,s]=p.useState(!0),[a,r]=p.useState(!1),[n,i]=p.useState({expressHours:24,standardHours:72,reminderThreshold1:50,reminderThreshold2:75,workStartHour:9,workEndHour:18,workStartDay:1,workEndDay:5});p.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await Zi("TAT_SETTINGS"),m={};d.forEach(u=>{m[u.configKey]=u.configValue}),i({expressHours:parseInt(m.DEFAULT_TAT_EXPRESS_HOURS||"24"),standardHours:parseInt(m.DEFAULT_TAT_STANDARD_HOURS||"72"),reminderThreshold1:parseInt(m.TAT_REMINDER_THRESHOLD_1||"50"),reminderThreshold2:parseInt(m.TAT_REMINDER_THRESHOLD_2||"75"),workStartHour:parseInt(m.WORK_START_HOUR||"9"),workEndHour:parseInt(m.WORK_END_HOUR||"18"),workStartDay:parseInt(m.WORK_START_DAY||"1"),workEndDay:parseInt(m.WORK_END_DAY||"5")})}catch(d){console.error("Failed to load TAT configurations:",d),K.error("Failed to load TAT configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([ks("DEFAULT_TAT_EXPRESS_HOURS",n.expressHours.toString()),ks("DEFAULT_TAT_STANDARD_HOURS",n.standardHours.toString()),ks("TAT_REMINDER_THRESHOLD_1",n.reminderThreshold1.toString()),ks("TAT_REMINDER_THRESHOLD_2",n.reminderThreshold2.toString()),ks("WORK_START_HOUR",n.workStartHour.toString()),ks("WORK_END_HOUR",n.workEndHour.toString()),ks("WORK_START_DAY",n.workStartDay.toString()),ks("WORK_END_DAY",n.workEndDay.toString())]),K.success("TAT configuration saved successfully"),await l()}catch(u){console.error("Failed to save TAT configuration:",u),K.error(((m=(d=u.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save TAT configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(J,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(q,{className:"p-12 text-center",children:[e.jsx(Ze,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading TAT configuration..."})]})}):e.jsxs(J,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Xe,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(x4,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx($t,{}),e.jsx(p4,{workStartHour:n.workStartHour,workEndHour:n.workEndHour,workStartDay:n.workStartDay,workEndDay:n.workEndDay,onWorkStartHourChange:d=>c({workStartHour:d}),onWorkEndHourChange:d=>c({workEndHour:d}),onWorkStartDayChange:d=>c({workStartDay:d}),onWorkEndDayChange:d=>c({workEndDay:d})}),e.jsx($t,{}),e.jsx(h4,{reminderThreshold1:n.reminderThreshold1,reminderThreshold2:n.reminderThreshold2,onReminderThreshold1Change:d=>c({reminderThreshold1:d}),onReminderThreshold2Change:d=>c({reminderThreshold2:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(I,{onClick:o,disabled:a,className:"bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function f4({emailNotifications:t,inAppNotifications:s,autoReminders:a,onEmailNotificationsChange:r,onInAppNotificationsChange:n,onAutoRemindersChange:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Notification Channels"}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send notifications via email"})]}),e.jsx(Fs,{checked:t,onCheckedChange:r})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Show notifications in the portal"})]}),e.jsx(Fs,{checked:s,onCheckedChange:n})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Auto-Reminders"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically send reminders for pending approvals"})]}),e.jsx(Fs,{checked:a,onCheckedChange:i})]})]})}function y4({notificationFrequency:t,reminderFrequency:s,onNotificationFrequencyChange:a,onReminderFrequencyChange:r}){return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(He,{value:t,onValueChange:a,children:[e.jsx(Ge,{id:"notification-frequency",children:e.jsx(We,{placeholder:"Select frequency"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"Immediate",children:"Immediate"}),e.jsx(X,{value:"Hourly",children:"Hourly"}),e.jsx(X,{value:"Daily",children:"Daily"}),e.jsx(X,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(Ie,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function b4({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(Ts,{id:"email-template",rows:5,value:t,onChange:a=>s(a.target.value),className:"resize-none",placeholder:"Enter email template message..."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use placeholders: [Name], [Request ID], [TAT], [Status]"})]})}function v4(){const[t,s]=p.useState({emailNotifications:!0,inAppNotifications:!0,autoReminders:!0,notificationFrequency:"Immediate",reminderFrequency:12,emailTemplate:"Dear [Name], You have a pending approval request [Request ID] that requires your attention. TAT remaining: [TAT]. Please review at your earliest convenience."}),a=()=>{K.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(J,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Notification Configuration"}),e.jsx(Te,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(f4,{emailNotifications:t.emailNotifications,inAppNotifications:t.inAppNotifications,autoReminders:t.autoReminders,onEmailNotificationsChange:n=>r({emailNotifications:n}),onInAppNotificationsChange:n=>r({inAppNotifications:n}),onAutoRemindersChange:n=>r({autoReminders:n})}),e.jsx($t,{}),e.jsx(y4,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(b4,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(_a,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function j4({maxFileSizeMB:t,retentionDays:s,onMaxFileSizeChange:a,onRetentionDaysChange:r}){const n=Math.round(s/365*10)/10;return e.jsxs(J,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Es,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(Te,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(q,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(Ie,{id:"max-upload",type:"number",min:"1",max:"100",value:t,onChange:i=>a(parseInt(i.target.value)||10),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Es,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(Ie,{id:"retention",type:"number",min:"30",max:"3650",value:s,onChange:i=>r(parseInt(i.target.value)||365),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx($i,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const N4=[{label:"PDF Documents",extensions:["pdf"]},{label:"Microsoft Word",extensions:["doc","docx"]},{label:"Microsoft Excel",extensions:["xls","xlsx"]},{label:"Microsoft PowerPoint",extensions:["ppt","pptx"]},{label:"Images",extensions:["jpg","jpeg","png","gif","bmp","webp"]},{label:"CSV Files",extensions:["csv"]},{label:"Text Files",extensions:["txt","rtf"]}];function w4({allowedFileTypes:t,onAllowedFileTypesChange:s}){const a=t.split(",").map(l=>l.trim().toLowerCase()),r=(l,o)=>{const c=new Set(a);o?l.forEach(d=>c.add(d)):l.forEach(d=>c.delete(d)),s(Array.from(c).join(","))},n=l=>l.some(o=>a.includes(o)),i=l=>{s(l)};return e.jsxs(J,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(So,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(Te,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:N4.map(l=>{const o=n(l.extensions);return e.jsxs("div",{onClick:()=>r(l.extensions,!o),className:`flex items-center justify-between p-3 rounded-md border-2 cursor-pointer transition-all ${o?"bg-re-green/5 border-re-green/30 hover:border-re-green/50":"bg-gray-50 border-gray-200 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-4 h-4 rounded border-2 flex items-center justify-center ${o?"bg-re-green border-re-green":"bg-white border-gray-300"}`,children:o&&e.jsx("svg",{className:"w-3 h-3 text-white",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})}),e.jsx("span",{className:`text-sm font-medium ${o?"text-re-green":"text-gray-600"}`,children:l.label})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:l.extensions.join(", ")})]},l.label)})}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(ne,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(Ie,{id:"file-types-manual",type:"text",value:t,onChange:l=>i(l.target.value),placeholder:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20 font-mono text-sm"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edit directly or use the checkboxes above. Separate extensions with commas."})]})]})]})}function C4(){const[t,s]=p.useState(!0),[a,r]=p.useState(!1),[n,i]=p.useState({maxFileSizeMB:10,retentionDays:365,allowedFileTypes:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"});p.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await Zi("DOCUMENT_POLICY"),m={};d.forEach(u=>{m[u.configKey]=u.configValue}),i({maxFileSizeMB:parseInt(m.MAX_FILE_SIZE_MB||"10"),retentionDays:parseInt(m.DOCUMENT_RETENTION_DAYS||"365"),allowedFileTypes:m.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"})}catch(d){console.error("Failed to load document configurations:",d),K.error("Failed to load document configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([ks("MAX_FILE_SIZE_MB",n.maxFileSizeMB.toString()),ks("DOCUMENT_RETENTION_DAYS",n.retentionDays.toString()),ks("ALLOWED_FILE_TYPES",n.allowedFileTypes)]),K.success("Document policy saved successfully"),await l()}catch(u){console.error("Failed to save document configuration:",u),K.error(((m=(d=u.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save document configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(J,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(q,{className:"p-12 text-center",children:[e.jsx(Ze,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading document policy configuration..."})]})}):e.jsxs(J,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(De,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(j4,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx($t,{}),e.jsx(w4,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:d=>c({allowedFileTypes:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(I,{onClick:o,disabled:a,className:"bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function A4(){return e.jsx("div",{className:"p-4 bg-blue-50 border border-blue-200 rounded-lg",children:e.jsxs("p",{className:"text-sm text-blue-800",children:[e.jsx("strong",{children:"Note:"})," These settings control what information is visible to each role on their dashboard. Admins always have access to all metrics."]})})}const S4=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],T4=t=>{switch(t){case"Initiator":return"bg-blue-100 text-blue-800";case"Approver":return"bg-green-100 text-green-800";case"Spectator":return"bg-gray-100 text-gray-800";default:return"bg-gray-100 text-gray-800"}};function k4({role:t,kpis:s,onKPIToggle:a}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium flex items-center gap-2",children:e.jsxs(ie,{className:T4(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:S4.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Ac,{id:`${t.toLowerCase()}-${r}`,checked:s[r]||!1,onCheckedChange:n=>a(r,n===!0)}),e.jsx("label",{htmlFor:`${t.toLowerCase()}-${r}`,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer",children:r})]},r))})]})}function R4(){const[t,s]=p.useState({Initiator:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0},Approver:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0},Spectator:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0}}),a=()=>{K.success("Dashboard layout saved successfully")},r=(i,l,o)=>{s(c=>({...c,[i]:{...c[i],[l]:o}}))},n=["Initiator","Approver","Spectator"];return e.jsxs(J,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Dashboard Layout Configuration"}),e.jsx(Te,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsx(A4,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(k4,{role:i,kpis:t[i]||{},onKPIToggle:(l,o)=>r(i,l,o)},i))}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(_a,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}function D4({aiEnabled:t,onAiEnabledChange:s}){return e.jsxs(J,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nx,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Vertex AI Gemini Configuration"})]}),e.jsx(Te,{className:"text-sm",children:"Configure AI features. Model and region are configured via environment variables."})]}),e.jsx(q,{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-md",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Enable AI Features"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Master toggle to enable/disable all AI-powered features"})]}),e.jsx(Fs,{checked:t,onCheckedChange:s})]})})]})}function P4({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(J,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pi,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(Te,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(q,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-md hover:bg-gray-100 transition-colors",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"AI Remark Generation"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically generate conclusion remarks for workflow closures"})]}),e.jsx(Fs,{checked:t,onCheckedChange:s})]})})})]})}function I4({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(J,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jx,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(Te,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(q,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Length"}),e.jsx(Ie,{id:"max-remark-chars",type:"number",min:"500",max:"5000",value:t,onChange:a=>s(parseInt(a.target.value)||2e3),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Maximum character length for AI-generated conclusion remarks (500-5000 characters)"})]})})]})}function E4(){const[t,s]=p.useState(!0),[a,r]=p.useState(!1),[n,i]=p.useState({aiEnabled:!0,aiRemarkGeneration:!0,maxRemarkChars:2e3});p.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await Zi("AI_CONFIGURATION"),m={};d.forEach(u=>{m[u.configKey]=u.configValue}),i({aiEnabled:m.AI_ENABLED==="true",aiRemarkGeneration:m.AI_REMARK_GENERATION_ENABLED==="true",maxRemarkChars:parseInt(m.AI_MAX_REMARK_LENGTH||"2000")})}catch(d){console.error("Failed to load AI configurations:",d),K.error("Failed to load AI configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([ks("AI_ENABLED",n.aiEnabled.toString()),ks("AI_REMARK_GENERATION_ENABLED",n.aiRemarkGeneration.toString()),ks("AI_MAX_REMARK_LENGTH",n.maxRemarkChars.toString())]),K.success("AI configuration saved successfully"),await l()}catch(u){console.error("Failed to save AI configuration:",u),K.error(((m=(d=u.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save AI configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(J,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(q,{className:"p-12 text-center",children:[e.jsx(Ze,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading AI configuration..."})]})}):e.jsxs(J,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Pi,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Configure Vertex AI Gemini settings and enable/disable AI-powered features"})]})]})}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(D4,{aiEnabled:n.aiEnabled,onAiEnabledChange:d=>c({aiEnabled:d})}),e.jsx($t,{}),e.jsx(P4,{aiRemarkGeneration:n.aiRemarkGeneration,onRemarkGenerationChange:d=>c({aiRemarkGeneration:d})}),e.jsx($t,{}),e.jsx(I4,{maxRemarkChars:n.maxRemarkChars,onMaxRemarkCharsChange:d=>c({maxRemarkChars:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(I,{onClick:o,disabled:a,className:"bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const $u=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function F4({spectatorPermission:t,linkSharingPermission:s,onSpectatorPermissionChange:a,onLinkSharingPermissionChange:r}){return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(He,{value:t,onValueChange:a,children:[e.jsx(Ge,{id:"spectator-permission",children:e.jsx(We,{placeholder:"Select permission"})}),e.jsx(Ke,{children:$u.map(n=>e.jsx(X,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(He,{value:s,onValueChange:r,children:[e.jsx(Ge,{id:"link-sharing-permission",children:e.jsx(We,{placeholder:"Select permission"})}),e.jsx(Ke,{children:$u.map(n=>e.jsx(X,{value:n,children:n},n))})]})]})]})}function M4({requirePassword:t,allowExternalSharing:s,onRequirePasswordChange:a,onAllowExternalSharingChange:r}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Require Password for Shared Links"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add password protection to workflow sharing links"})]}),e.jsx(Fs,{checked:t,onCheckedChange:a})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Allow External Sharing"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Enable sharing workflows with external users outside the organization"})]}),e.jsx(Fs,{checked:s,onCheckedChange:r})]})]})}function _4(){const[t,s]=p.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{K.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(J,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Workflow Sharing Policy"}),e.jsx(Te,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(F4,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx($t,{}),e.jsx(M4,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(_a,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function Uu(){const{user:t}=Qt(),[s,a]=p.useState(""),[r,n]=p.useState("sharing"),i=[{name:"Request Volume & Status",count:4,kpis:[{id:"total-requests",title:"Total Requests Created",description:"Count of all workflow requests created in a selected period.",value:5,change:12,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"open-requests",title:"Open Requests",description:"Number of workflows currently in progress with age.",value:3,change:-5,changeType:"down",period:"Today",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"approved-requests",title:"Approved Requests",description:"Requests fully approved and closed.",value:1,change:8,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"rejected-requests",title:"Rejected Requests",description:"Requests rejected at any approval stage.",value:1,period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"}]},{name:"TAT Efficiency",count:3,kpis:[{id:"avg-tat-compliance",title:"Average TAT Compliance %",description:"% of workflows completed within defined TAT vs breached ones at every level.",value:100,unit:"%",change:3,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200"},{id:"avg-approval-cycle",title:"Avg Approval Cycle Time (Days)",description:"Average total time from creation to closure.",value:5.2,unit:" days",change:-15,changeType:"down",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200",thresholdBreached:!0},{id:"delayed-workflows",title:"Delayed Workflows",description:"Requests currently breaching their TAT.",value:0,change:-2,changeType:"down",period:"Today",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200"}]},{name:"Approver Load",count:2,kpis:[{id:"pending-actions",title:"Pending Actions (My Queue)",description:"Requests currently awaiting user's approval with age.",value:3,period:"Today",visibleTo:["Management","Admin"],category:"Approver Load",bgColor:"bg-orange-50",borderColor:"border-orange-200"},{id:"approvals-completed",title:"Approvals Completed (Today/Week)",description:"Count of actions taken within a time frame.",value:0,change:22,changeType:"up",period:"Week",visibleTo:["Management","Admin"],category:"Approver Load",bgColor:"bg-orange-50",borderColor:"border-orange-200"}]},{name:"Engagement & Quality",count:2,kpis:[{id:"comments-worknotes",title:"Comments / Work Notes Added",description:"Measures collaboration activity.",value:8,change:18,changeType:"up",period:"Week",visibleTo:["Management","Admin"],category:"Engagement & Quality",bgColor:"bg-purple-50",borderColor:"border-purple-200"},{id:"attachments-uploaded",title:"Attachments Uploaded",description:"Number of documents added to workflows.",value:16,change:10,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Engagement & Quality",bgColor:"bg-purple-50",borderColor:"border-purple-200"}]},{name:"AI & Closure Insights",count:2,kpis:[{id:"avg-conclusion-length",title:"Avg Conclusion Remark Length",description:"Indicates depth of closure remarks (optional).",value:85,unit:" chars",change:5,changeType:"up",period:"Month",visibleTo:["Management","Admin"],category:"AI & Closure Insights",bgColor:"bg-pink-50",borderColor:"border-pink-200"},{id:"ai-summary-adoption",title:"AI Summary Adoption %",description:"How many closures used AI-generated text vs manual edits.",value:0,unit:"%",change:25,changeType:"up",period:"Month",visibleTo:["Management","Admin"],category:"AI & Closure Insights",bgColor:"bg-pink-50",borderColor:"border-pink-200"}]}],l=i.map(d=>({...d,kpis:d.kpis.filter(m=>m.title.toLowerCase().includes(s.toLowerCase())||m.description.toLowerCase().includes(s.toLowerCase())||m.category.toLowerCase().includes(s.toLowerCase()))})).filter(d=>d.kpis.length>0),o=i.reduce((d,m)=>d+m.count,0),c=d=>{switch(d){case"Initiator":return"bg-blue-100 text-blue-800 border-blue-200";case"Management":return"bg-orange-100 text-orange-800 border-orange-200";case"Admin":return"bg-purple-100 text-purple-800 border-purple-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-re-black flex items-center gap-2",children:[e.jsx(ds,{className:"w-8 h-8 text-re-green"}),"Admin Control Panel"]}),e.jsx("p",{className:"text-muted-foreground",children:"Manage users, configure system settings, and control portal behavior"})]}),e.jsxs(ie,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(ds,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]}),e.jsx($t,{}),e.jsxs(Un,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(Bn,{className:"text-muted-foreground items-center justify-center rounded-xl p-[3px] bg-muted grid w-full grid-cols-9 h-auto",children:[e.jsxs(Dt,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(pi,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(Dt,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(Dt,{value:"users",className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Dt,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(Dt,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(Ds,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(Dt,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(Dt,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(O0,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(Dt,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(Nx,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(Dt,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(Hr,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(Tt,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(J,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"KPI Configuration"}),e.jsx(Te,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(ie,{className:"bg-blue-50 text-blue-700",children:[o," / ",o," KPIs Active"]})]})}),e.jsxs(q,{className:"space-y-6",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(Ie,{placeholder:"Search KPIs by name, description, or category...",value:s,onChange:d=>a(d.target.value),className:"pl-10"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:i.map(d=>e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:d.name}),e.jsx("p",{className:"text-2xl font-semibold",children:d.count})]},d.name))}),l.map(d=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:d.name}),e.jsxs(ie,{variant:"outline",className:"ml-auto",children:[d.kpis.length," Active"]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:d.kpis.map(m=>e.jsx("div",{className:`p-4 border rounded-lg ${m.bgColor} ${m.borderColor} transition-all hover:shadow-md ${m.thresholdBreached?"ring-2 ring-orange-500":""}`,children:e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-medium text-sm mb-1",children:m.title}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:m.description})]}),e.jsx(ie,{className:"bg-green-100 text-green-800 text-xs",children:"Active"})]}),e.jsxs("div",{className:"flex items-end gap-3 py-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-4xl font-bold text-re-black",children:m.value}),m.unit&&e.jsx("span",{className:"text-lg text-muted-foreground",children:m.unit})]})}),m.change!==void 0&&e.jsxs("div",{className:`flex items-center gap-1 text-xs px-2 py-1 rounded ${m.changeType==="up"?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:[m.changeType==="up"?e.jsx($0,{className:"w-3 h-3"}):e.jsx(U0,{className:"w-3 h-3"}),e.jsxs("span",{className:"font-semibold",children:[Math.abs(m.change),"%"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Visible:"}),m.visibleTo.map(u=>e.jsx(ie,{className:`${c(u)} text-xs px-1.5 py-0`,children:u},u))]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Period: ",m.period]}),m.thresholdBreached&&e.jsxs("div",{className:"flex items-center gap-1 text-orange-600",children:[e.jsx(Ve,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},m.id))})]},d.name))]})]})}),e.jsx(Tt,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(i4,{})}),e.jsx(Tt,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(u4,{})}),e.jsx(Tt,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(g4,{})}),e.jsx(Tt,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(v4,{})}),e.jsx(Tt,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(C4,{})}),e.jsx(Tt,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(R4,{})}),e.jsx(Tt,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(E4,{})}),e.jsx(Tt,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(_4,{})})]})]})}function Xn({className:t,...s}){return e.jsx("div",{"data-slot":"skeleton",className:Re("bg-accent animate-pulse rounded-md",t),...s})}function Bu(){const t=qs(),[s,a]=p.useState(()=>Du()||[]),[r,n]=p.useState(()=>!Du()),[i,l]=p.useState(""),[o,c]=p.useState(null),[d,m]=p.useState(!1),u=async()=>{try{s.length===0&&n(!0);const f=await Xi();a(f||[])}catch(f){console.error("Failed to fetch templates:",f),K.error("Failed to load templates")}finally{n(!1)}};p.useEffect(()=>{u()},[]);const h=async()=>{if(o)try{m(!0),await OA(o),K.success("Template deleted successfully"),a(f=>f.filter(y=>y.id!==o))}catch(f){console.error("Failed to delete template:",f),K.error("Failed to delete template")}finally{m(!1),c(null)}},x=s.filter(f=>f.name.toLowerCase().includes(i.toLowerCase())||f.category.toLowerCase().includes(i.toLowerCase())),g=f=>{switch(f.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(I,{onClick:()=>t("/admin/create-template"),className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(us,{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(Ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ie,{placeholder:"Search templates...",className:"pl-10 border-gray-200",value:i,onChange:f=>l(f.target.value)})]})}),r?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(f=>e.jsxs(J,{className:"h-48",children:[e.jsxs(me,{children:[e.jsx(Xn,{className:"h-6 w-3/4 mb-2"}),e.jsx(Xn,{className:"h-4 w-1/2"})]}),e.jsxs(q,{children:[e.jsx(Xn,{className:"h-4 w-full mb-2"}),e.jsx(Xn,{className:"h-4 w-2/3"})]})]},f))}):x.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(De,{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(I,{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:x.map(f=>{var y;return e.jsxs(J,{className:"hover:shadow-md transition-shadow duration-200 group",children:[e.jsxs(me,{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(De,{className:"w-5 h-5"})}),e.jsx(ie,{variant:"outline",className:g(f.priority),children:f.priority})]}),e.jsx(ue,{className:"line-clamp-1 text-lg",children:f.name}),e.jsx(Te,{className:"line-clamp-2 h-10",children:f.description})]}),e.jsxs(q,{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:f.category})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"SLA:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[f.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:[((y=f.approvers)==null?void 0:y.length)||0," levels"]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t mt-2",children:[e.jsxs(I,{variant:"outline",className:"flex-1 text-blue-600 hover:text-blue-700 hover:bg-blue-50 border-blue-100",onClick:()=>t(`/admin/edit-template/${f.id}`),children:[e.jsx(B0,{className:"w-4 h-4 mr-2"}),"Edit"]}),e.jsxs(I,{variant:"outline",className:"flex-1 text-red-600 hover:text-red-700 hover:bg-red-50 border-red-100",onClick:()=>c(f.id),children:[e.jsx(kn,{className:"w-4 h-4 mr-2"}),"Delete"]})]})]})]},f.id)})}),e.jsx(Ox,{open:!!o,onOpenChange:f=>!f&&c(null),children:e.jsxs(Io,{children:[e.jsxs(Ux,{children:[e.jsxs(Vx,{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"w-5 h-5 text-red-600"}),"Delete Template"]}),e.jsx(zx,{children:"Are you sure you want to delete this template? This action cannot be undone. Active requests using this template will not be affected."})]}),e.jsxs(Bx,{children:[e.jsx(Wx,{disabled:d,children:"Cancel"}),e.jsx(Hx,{onClick:f=>{f.preventDefault(),h()},className:"bg-red-600 hover:bg-red-700",disabled:d,children:d?"Deleting...":"Delete"})]})]})})]})}function Qn(){const t=qs(),{templateId:s}=La(),a=!!s,[r,n]=p.useState(!1),[i,l]=p.useState(!1),{searchResults:o,searchLoading:c,searchUsersDebounced:d,clearSearch:m}=Jp(),[u,h]=p.useState(""),[x,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 Xi()).find(S=>S.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 f=C=>{const{name:_,value:D}=C.target;g(S=>({...S,[_]:D}))},y=(C,_)=>{g(D=>({...D,[C]:_}))},b=C=>{if(h(C),C.startsWith("@")&&C.slice(1).length>=1){d(C,5);return}m()},v=C=>{if(x.approvers.some(_=>_.userId===C.userId)){K.error("Approver already added");return}g(_=>({..._,approvers:[..._.approvers,{userId:C.userId,name:C.displayName||C.email,email:C.email,level:_.approvers.length+1,tat:24,tatType:"hours"}]})),h(""),m()},A=C=>{const _=[...x.approvers];_.splice(C,1),_.forEach((D,S)=>D.level=S+1),g(D=>({...D,approvers:_}))},w=async C=>{if(C.preventDefault(),!x.name||!x.description){K.error("Please fill in required fields");return}if(x.approvers.length===0){K.error("Please add at least one approver");return}const _={...x,approvers:x.approvers.map(D=>({...D,tat:D.tatType==="days"?parseInt(D.tat)*24:parseInt(D.tat)}))};try{n(!0),a&&s?(await $A(s,_),K.success("Template updated successfully")):(await LA(_),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(Ze,{className:"h-8 w-8 animate-spin text-gray-400"})});const T=x.name&&x.description&&x.approvers.length>0&&x.approvers.every(C=>{const _=parseInt(String(C.tat))||0,D=C.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(I,{variant:"ghost",size:"icon",onClick:()=>t("/admin/templates"),children:e.jsx(Ss,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:a?"Edit Workflow Template":"Create Workflow Template"}),e.jsx("p",{className:"text-gray-500",children:a?"Update existing workflow configuration":"Define a new standardized request workflow"})]})]}),e.jsxs("form",{onSubmit:w,className:"space-y-6",children:[e.jsxs(J,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Basic Information"}),e.jsx(Te,{children:"General details about the template"})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"name",children:"Template Name *"}),e.jsx(Ie,{id:"name",name:"name",placeholder:"e.g., Office Stationery Request",value:x.name,onChange:f,className:"border-gray-200",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"category",children:"Category"}),e.jsx("div",{className:"relative",children:e.jsx(Ie,{id:"category",name:"category",placeholder:"e.g., Admin, HR, Finance",value:x.category,onChange:f,className:"border-gray-200"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"description",children:"Description *"}),e.jsx(Ts,{id:"description",name:"description",placeholder:"Describe what this request is for...",value:x.description,onChange:f,className:"border-gray-200",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"priority",children:"Default Priority"}),e.jsxs(He,{name:"priority",value:x.priority,onValueChange:C=>y("priority",C),children:[e.jsx(Ge,{children:e.jsx(We,{placeholder:"Select priority"})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"low",children:"Low"}),e.jsx(X,{value:"medium",children:"Medium"}),e.jsx(X,{value:"high",children:"High"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"estimatedTime",children:"Estimated Time"}),e.jsx(Ie,{id:"estimatedTime",name:"estimatedTime",placeholder:"e.g., 2 days",value:x.estimatedTime,onChange:f,className:"border-gray-200"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"suggestedSLA",children:"SLA (Hours)"}),e.jsx(Ie,{id:"suggestedSLA",name:"suggestedSLA",type:"number",placeholder:"24",value:x.suggestedSLA,onChange:f,className:"border-gray-200"})]})]})]})]}),e.jsxs(J,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Approver Workflow"}),e.jsx(Te,{children:"Define static approvers for this template"})]}),e.jsxs(q,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[x.approvers.map((C,_)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsxs(ie,{variant:"outline",className:"bg-white",children:["Level ",C.level]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:C.name}),e.jsx("div",{className:"text-sm text-gray-500",children:C.email})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(ne,{htmlFor:`tat-${_}`,className:"text-xs whitespace-nowrap",children:"TAT"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ie,{id:`tat-${_}`,type:"number",className:"h-8 w-16 border-gray-200",value:C.tat||"",min:1,max:C.tatType==="days"?7:24,placeholder:C.tatType==="days"?"1":"24",onChange:D=>{if((parseInt(D.target.value)||0)<0)return;const j=[...x.approvers];j[_].tat=D.target.value,g(P=>({...P,approvers:j}))}}),e.jsxs(He,{value:C.tatType||"hours",onValueChange:D=>{const S=[...x.approvers];S[_].tatType=D,S[_].tat=1,g(j=>({...j,approvers:S}))},children:[e.jsx(Ge,{className:"h-8 w-20 text-xs px-2",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(X,{value:"hours",children:"Hours"}),e.jsx(X,{value:"days",children:"Days"})]})]})]})]})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:()=>A(_),children:e.jsx(gt,{className:"w-4 h-4 text-gray-500 hover:text-red-600"})})]},_)),x.approvers.length===0&&e.jsx("div",{className:"text-center p-8 border-2 border-dashed rounded-lg text-gray-500 text-sm",children:"No approvers defined. Requests will be auto-approved or require manual assignment."})]}),e.jsxs("div",{className:"space-y-2 relative",children:[e.jsx(ne,{children:"Add Approver"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Ie,{placeholder:"Type '@' to search user by name or email...",value:u,onChange:C=>b(C.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(C=>e.jsxs("div",{className:"p-2 hover:bg-gray-50 cursor-pointer flex items-center gap-3",onClick:()=>v(C),children:[e.jsx(es,{className:"h-8 w-8",children:e.jsx(ts,{children:(C.displayName||"U").substring(0,2)})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:C.displayName}),e.jsx("div",{className:"text-xs text-gray-500",children:C.email})]})]},C.userId))]})]}),x.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(Xe,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{const C=x.approvers.reduce((D,S)=>{const j=Number(S.tat||0);return(S.tatType||"hours")==="days"?D+j:D+j/24},0)||0,_=Math.ceil(C);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:x.approvers.map((C,_)=>{const D=Number(C.tat||0),j=(C.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:[j," ",j===1?"hour":"hours"]})]})},_):null})}),(()=>{const C=x.approvers.reduce((D,S)=>{const j=Number(S.tat||0);return(S.tatType||"hours")==="days"?D+j*24:D+j},0)||0,_=Math.ceil(C/8);return C===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:[C,"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(I,{type:"button",variant:"outline",onClick:()=>t("/admin/templates"),children:"Cancel"}),e.jsx(I,{type:"submit",disabled:r||!T,className:"bg-re-green hover:bg-re-green/90",children:r?"Saving...":e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"w-4 h-4 mr-2"}),a?"Update Template":"Create Template"]})})]})]})]})}function L4({template:t,formData:s,setFormData:a,documents:r,setDocuments:n}){const i=p.useRef(null),[l,o]=p.useState(null),c=x=>{x.target.files&&x.target.files.length>0&&n([...r,...Array.from(x.target.files)])},d=x=>{const g=[...r];g.splice(x,1),n(g)},m=x=>{const g=URL.createObjectURL(x);o({file:x,url:g})},u=()=>{l!=null&&l.url&&URL.revokeObjectURL(l.url),o(null)},h=x=>x.type.includes("image")||x.type.includes("pdf");return e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(J,{className:"shadow-sm",children:e.jsxs(q,{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(J,{children:e.jsxs(q,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"requestTitle",children:"Request Title *"}),e.jsx(Ie,{id:"requestTitle",value:s.title,onChange:x=>a({...s,title:x.target.value}),placeholder:`Request for ${t.name}`,className:"border-gray-200"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"justification",className:"text-base font-semibold",children:"Request Detail *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Explain what you need approval for, why it's needed, and any relevant details."}),e.jsx(Fn,{value:s.description||"",onChange:x=>a({...s,description:x}),placeholder:"Provide comprehensive details about your request...",className:"min-h-[120px] text-base border-gray-200 bg-white shadow-sm",minHeight:"120px"})]})]})}),e.jsx(J,{children:e.jsxs(q,{className:"pt-6 space-y-4",children:[e.jsx(ne,{children:"Supporting Documents"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>{var x;return(x=i.current)==null?void 0:x.click()},children:[e.jsx(Es,{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((x,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(De,{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:x.name}),e.jsxs("p",{className:"text-xs text-gray-500",children:[(x.size/1024/1024).toFixed(2)," MB"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[h(x)&&e.jsx(I,{variant:"ghost",size:"icon",onClick:()=>m(x),children:e.jsx(xt,{className:"w-4 h-4 text-gray-500 hover:text-blue-600"})}),e.jsx(I,{variant:"ghost",size:"icon",onClick:()=>d(g),children:e.jsx(gt,{className:"w-4 h-4 text-gray-500 hover:text-red-500"})})]})]},g))})]})}),l&&e.jsx(Cr,{fileName:l.file.name,fileType:l.file.type,fileUrl:l.url,fileSize:l.file.size,open:!!l,onClose:u})]})}function O4({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(Ve,{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(J,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-lg",children:"Request Overview"})}),e.jsx(q,{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: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(ie,{variant:"secondary",className:"pl-1 pr-2 py-1 flex items-center gap-1.5 h-auto",children:[e.jsx(De,{className:"w-3 h-3 text-gray-500"}),e.jsx("span",{className:"truncate max-w-[150px]",children:n.name})]},i))})]})]})})]}),e.jsxs(J,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-lg",children:"Approval Workflow"})}),e.jsx(q,{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(ie,{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(J,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-sm uppercase text-gray-500",children:"Properties"})}),e.jsxs(q,{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($t,{}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Priority"}),e.jsx(ie,{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($t,{}),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 Vu(){const{templateId:t}=La(),s=qs(),{user:a}=Qt(),[r,n]=p.useState(!0),[i,l]=p.useState(!1),[o,c]=p.useState(null),[d,m]=p.useState(1),[u,h]=p.useState([]),[x,g]=p.useState({title:"",description:""}),f=["Request Details","Review & Submit"];p.useEffect(()=>{t&&(async()=>{try{n(!0);const A=(await Xi()).find(w=>w.id===t);if(A){const w={id:A.id,name:A.name,description:A.description,category:A.category,icon:De,estimatedTime:A.estimatedTime,commonApprovers:A.approvers.map(T=>T.name),workflowApprovers:A.approvers,suggestedSLA:A.suggestedSLA,priority:A.priority,fields:A.fields||{}};c(w),g({title:w.name,description:w.description})}else K.error("Template not found")}catch(v){console.error("Error loading template:",v),K.error("Failed to load template details")}finally{n(!1)}})()},[t,s]);const y=async()=>{var b;if(o)try{l(!0);const v={templateId:o.id,templateType:"TEMPLATE",title:x.title,description:x.description,priorityUi:o.priority==="high"?"express":"standard",approverCount:((b=o.workflowApprovers)==null?void 0:b.length)||0,approvers:(o.workflowApprovers||[]).map(w=>({email:w.email,name:w.name,tat:w.tat,tatType:"hours"})),spectators:[],ccList:[]},A=await Uo(v,u);A&&A.id&&await Bo(A.id),K.success("Request Submitted Successfully",{description:`Your request "${x.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(I,{variant:"ghost",size:"icon",onClick:()=>s("/new-request"),children:e.jsx(Ss,{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(I,{variant:"outline",onClick:()=>s("/dashboard"),children:"Cancel Request"})]}),e.jsx(Qp,{currentStep:d,totalSteps:2,stepNames:f})]}),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(L4,{template:o,formData:x,setFormData:g,documents:u,setDocuments:h}):e.jsx(O4,{template:o,formData:x,documents:u})})}),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(I,{variant:"outline",onClick:()=>d===1?s("/new-request"):m(1),disabled:i,children:d===1?"Cancel":"Back to Details"}),e.jsx(I,{onClick:()=>d===1?m(2):y(),disabled:i,className:"bg-re-green hover:bg-re-green/90",children:d===1?e.jsxs(e.Fragment,{children:["Review Request ",e.jsx(Ti,{className:"w-4 h-4 ml-1"})]}):e.jsxs(e.Fragment,{children:[i?"Submitting...":"Submit Request"," ",e.jsx(Nr,{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(De,{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(I,{variant:"outline",onClick:()=>s("/dashboard"),children:"Go to Dashboard"}),e.jsx(I,{onClick:()=>s("/new-request"),children:"Browse Templates"})]})]})})}function $4({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(f){console.error("Error submitting approval action:",f)}finally{d(!1)}}},u=()=>{o(""),s()},x=a==="approve"?{title:"Approve Request",description:"Please provide your approval comments and remarks",icon:Pe,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:Nt,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=x.icon;return e.jsx(ht,{open:t,onOpenChange:u,children:e.jsxs(ct,{className:"max-w-2xl bg-white",children:[e.jsxs(pt,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:`p-2 rounded-lg ${a==="approve"?"bg-green-100":"bg-red-100"}`,children:e.jsx(g,{className:`w-6 h-6 ${x.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(dt,{className:"text-xl",children:x.title}),e.jsx(Et,{className:"mt-1",children:x.description})]})]}),e.jsxs("div",{className:"space-y-3 p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Request ID:"}),e.jsx(ie,{variant:"outline",className:"font-mono",children:r})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Title:"}),e.jsx("p",{className:"text-gray-700 mt-1",children:n})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Action:"}),e.jsxs(ie,{className:x.badgeColor,variant:"outline",children:[e.jsx(g,{className:"w-3 h-3 mr-1"}),a==="approve"?"APPROVE":"REJECT"]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(Ts,{id:"comment",placeholder:x.placeholder,value:l,onChange:f=>o(f.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(ss,{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(ss,{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(Pe,{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(kt,{className:"gap-2",children:[e.jsx(I,{variant:"outline",onClick:u,disabled:c,children:"Cancel"}),e.jsx(I,{onClick:m,disabled:!l.trim()||c||l.length>500,className:x.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 U4=(t,s,a,r,n,i,l,o)=>{let c=document.documentElement,d=["light","dark"];function m(x){(Array.isArray(t)?t:[t]).forEach(g=>{let f=g==="class",y=f&&i?n.map(b=>i[b]||b):n;f?(c.classList.remove(...y),c.classList.add(i&&i[x]?i[x]:x)):c.setAttribute(g,x)}),u(x)}function u(x){o&&d.includes(x)&&(c.style.colorScheme=x)}function h(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let x=localStorage.getItem(s)||a,g=l&&x==="system"?h():x;m(g)}catch{}},B4=p.createContext(void 0),V4={setTheme:t=>{},themes:[]},z4=()=>{var t;return(t=p.useContext(B4))!=null?t:V4};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:`(${U4.toString()})(${m})`}})});const H4=({...t})=>{const{theme:s="system"}=z4();return e.jsx(V0,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function W4({open:t,onClose:s,onSelect:a,managers:r=[],errorType:n,message:i,isLoading:l=!1}){const o=c=>{a(c)};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"sm:max-w-[600px]",children:[e.jsxs(pt,{children:[e.jsx(dt,{className:"flex items-center gap-2",children:n==="NO_MANAGER_FOUND"?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"w-5 h-5 text-amber-500"}),"Manager Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"w-5 h-5 text-blue-500"}),"Select Your Manager"]})}),e.jsx(Et,{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(Ve,{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(Lt,{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(Ia,{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(No,{className:"w-4 h-4"}),e.jsx("span",{children:c.department})]})]})]})]}),e.jsx(I,{onClick:d=>{d.stopPropagation(),o(c.email)},disabled:l,className:"flex-shrink-0",size:"sm",children:"Select"})]})},c.userId))})}),e.jsx("div",{className:"flex justify-end gap-3 mt-6",children:n==="NO_MANAGER_FOUND"?e.jsx(I,{onClick:s,variant:"outline",children:"Close"}):e.jsx(e.Fragment,{children:e.jsx(I,{onClick:s,variant:"outline",disabled:l,children:"Cancel"})})})]})})}function G4({onViewRequest:t}){const{user:s}=Qt();return Ui(s)?e.jsx(sk,{onViewRequest:t}):e.jsx(nk,{onViewRequest:t})}function zu({onNavigate:t,onNewRequest:s}){const[a,r]=p.useState(!1),[n,i]=p.useState(!0);return p.useEffect(()=>{try{const l=at.getUserData();r((l==null?void 0:l.jobTitle)==="Dealer")}catch(l){console.error("[App] Error checking dealer status:",l),r(!1)}finally{i(!1)}},[]),n?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"w-8 h-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})}):a?e.jsx(ST,{onNavigate:t,onNewRequest:s}):e.jsx(Wj,{onNavigate:t,onNewRequest:s})}function K4({onLogout:t}){const s=qs(),[a,r]=p.useState(null),[n,i]=p.useState([]),[l,o]=p.useState(""),[c,d]=p.useState(""),[m,u]=p.useState(!1),[h,x]=p.useState(null);p.useEffect(()=>{const C=localStorage.getItem("dynamicRequests");if(C)try{const _=JSON.parse(C);i(_)}catch(_){console.error("Error parsing dynamic requests:",_)}},[]),p.useEffect(()=>{n.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(n))},[n]);const g=C=>{if(C==="profile"){s("/profile");return}if(C==="settings"){s("/settings");return}C.startsWith("/")?s(C):s(`/${C}`)},f=(C,_,D,S)=>{o(C),d(_||"Unknown Request"),Ci({requestId:C,status:D,request:S,navigate:s})},y=()=>{s(-1)},b=()=>{s("/new-request")},v=C=>{var S,j,P,R,O,F,M,B,k,N,U;if(C.templateType){C.templateType==="claim-management"&&s("/claim-management");return}if(C.backendId){s("/my-requests");return}const D={id:`RE-REQ-2024-${String(Object.keys(eg).length+n.length+1).padStart(3,"0")}`,title:C.title,description:C.description||"",category:C.category||"General",subcategory:C.subcategory||"",status:"pending",priority:C.priority||"standard",amount:C.budget||"N/A",slaProgress:0,slaRemaining:"5 days",slaEndDate:new Date(Date.now()+5*24*60*60*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),currentStep:1,totalSteps:((S=C.approvers)==null?void 0:S.length)||1,currentApprover:((P=(j=C.approvers)==null?void 0:j[0])==null?void 0:P.name)||((F=(O=(R=C.approvers)==null?void 0:R[0])==null?void 0:O.email)==null?void 0:F.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((M=C.approvers)==null?void 0:M.length)||1}`,template:"custom",initiator:{name:"Current User",role:C.initiatorRole||"Employee",department:C.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:C.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:(C.approvers||[]).filter($=>$).map(($,L)=>{var oe;const se=($==null?void 0:$.name)||((oe=$==null?void 0:$.email)==null?void 0:oe.split("@")[0])||`Approver ${L+1}`,G=($==null?void 0:$.email)||"";return{step:L+1,approver:`${se}${G?` (${G})`:""}`,role:($==null?void 0:$.role)||`Level ${($==null?void 0:$.level)||L+1} Approver`,status:L===0?"pending":"waiting",tatHours:$!=null&&$.tat?typeof $.tat=="string"?parseInt($.tat):$.tat:48,elapsedHours:0,assignedAt:L===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(C.spectators||[]).filter($=>$&&($.name||$.email)).map($=>{var se;const L=($==null?void 0:$.name)||((se=$==null?void 0:$.email)==null?void 0:se.split("@")[0])||"Observer";return{name:L,role:($==null?void 0:$.role)||($==null?void 0:$.department)||"Observer",avatar:L.split(" ").map(G=>G[0]).join("").toUpperCase().slice(0,2)||"OB"}}),auditTrail:[{type:"created",action:"Request Created",details:`Custom request "${C.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 ${((k=(B=C.approvers)==null?void 0:B[0])==null?void 0:k.name)||((U=(N=C.approvers)==null?void 0:N[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:C.tags||["custom-request"]};i([...n,D]),s("/my-requests")},A=(C,_)=>new Promise(D=>{setTimeout(()=>{C==="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)}),w=()=>{r(null)},T=async(C,_)=>{var D,S,j,P,R,O,F;try{const M={activityName:C.activityName,activityType:C.activityType,dealerCode:C.dealerCode,dealerName:C.dealerName,dealerEmail:C.dealerEmail||void 0,dealerPhone:C.dealerPhone||void 0,dealerAddress:C.dealerAddress||void 0,activityDate:C.activityDate?new Date(C.activityDate).toISOString():void 0,location:C.location,requestDescription:C.requestDescription,periodStartDate:C.periodStartDate?new Date(C.periodStartDate).toISOString():void 0,periodEndDate:C.periodEndDate?new Date(C.periodEndDate).toISOString():void 0,estimatedBudget:C.estimatedBudget||void 0,approvers:C.approvers||[]},B=await JS(M);if(!B||!B.request)throw new Error("Invalid response from server: Request object not found");const k=B.request;if(!k.requestNumber&&!k.requestId)throw new Error("Invalid response from server: Request identifier not found");u(!1),x(null),K.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),k.requestNumber?s(`/request/${k.requestNumber}`):k.requestId?s(`/request/${k.requestId}`):s("/my-requests")}catch(M){console.error("[App] Error creating claim request:",M);const B=(D=M==null?void 0:M.response)==null?void 0:D.data,k=(B==null?void 0:B.code)||((S=B==null?void 0:B.error)==null?void 0:S.code);if(k==="NO_MANAGER_FOUND"){x({errorType:"NO_MANAGER_FOUND",message:(B==null?void 0:B.message)||((j=B==null?void 0:B.error)==null?void 0:j.message)||"No reporting manager found. Please ensure your manager is correctly configured in the system.",pendingClaimData:C}),u(!0);return}if(k==="MULTIPLE_MANAGERS_FOUND"){const U=(B==null?void 0:B.managers)||((P=B==null?void 0:B.error)==null?void 0:P.managers)||[];x({errorType:"MULTIPLE_MANAGERS_FOUND",managers:U,message:(B==null?void 0:B.message)||((R=B==null?void 0:B.error)==null?void 0:R.message)||"Multiple managers found. Please select one.",pendingClaimData:C}),u(!0);return}const N=((F=(O=M==null?void 0:M.response)==null?void 0:O.data)==null?void 0:F.message)||(M==null?void 0:M.message)||"Failed to create claim request";K.error("Failed to Submit Claim Request",{description:N})}};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(G0,{children:[e.jsx(Ct,{path:"/login/callback",element:e.jsx(Lx,{})}),e.jsx(Ct,{path:"/",element:e.jsx(cs,{currentPage:"dashboard",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(zu,{onNavigate:g,onNewRequest:b})})}),e.jsx(Ct,{path:"/dashboard",element:e.jsx(cs,{currentPage:"dashboard",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(zu,{onNavigate:g,onNewRequest:b})})}),e.jsxs(Ct,{element:e.jsx(cs,{currentPage:"admin-templates",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(Wd,{})}),children:[e.jsx(Ct,{path:"/admin/create-template",element:e.jsx(Qn,{})}),e.jsx(Ct,{path:"/admin/edit-template/:templateId",element:e.jsx(Qn,{})}),e.jsx(Ct,{path:"/admin/templates",element:e.jsx(Bu,{})})]}),e.jsx(Ct,{path:"/create-admin-request/:templateId",element:e.jsx(Vu,{})}),e.jsx(Ct,{path:"/admin",element:e.jsx(cs,{currentPage:"admin",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(Uu,{})})}),e.jsxs(Ct,{element:e.jsx(cs,{currentPage:"admin-templates",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(Wd,{})}),children:[e.jsx(Ct,{path:"/admin/create-template",element:e.jsx(Qn,{})}),e.jsx(Ct,{path:"/admin/edit-template/:templateId",element:e.jsx(Qn,{})}),e.jsx(Ct,{path:"/admin/templates",element:e.jsx(Bu,{})})]}),e.jsx(Ct,{path:"/create-admin-request/:templateId",element:e.jsx(Vu,{})}),e.jsx(Ct,{path:"/admin",element:e.jsx(cs,{currentPage:"admin",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(Uu,{})})}),e.jsx(Ct,{path:"/open-requests",element:e.jsx(cs,{currentPage:"open-requests",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(_T,{onViewRequest:f})})}),e.jsx(Ct,{path:"/closed-requests",element:e.jsx(cs,{currentPage:"closed-requests",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(r5,{onViewRequest:f})})}),e.jsx(Ct,{path:"/shared-summaries",element:e.jsx(cs,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(m5,{})})}),e.jsx(Ct,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(cs,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(u5,{})})}),e.jsx(Ct,{path:"/my-requests",element:e.jsx(cs,{currentPage:"my-requests",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(P5,{onViewRequest:f,dynamicRequests:n})})}),e.jsx(Ct,{path:"/requests",element:e.jsx(cs,{currentPage:"requests",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(G4,{onViewRequest:f})})}),e.jsx(Ct,{path:"/approver-performance",element:e.jsx(cs,{currentPage:"approver-performance",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(bk,{})})}),e.jsx(Ct,{path:"/request/:requestId",element:e.jsx(cs,{currentPage:"request-detail",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(d5,{requestId:"",onBack:y,dynamicRequests:n})})}),e.jsx(Ct,{path:"/work-notes/:requestId",element:e.jsx(x5,{})}),e.jsx(Ct,{path:"/new-request",element:e.jsx(Eu,{onBack:y,onSubmit:v})}),e.jsx(Ct,{path:"/edit-request/:requestId",element:e.jsx(Eu,{onBack:y,onSubmit:v,requestId:void 0,isEditMode:!0})}),e.jsx(Ct,{path:"/claim-management",element:e.jsx(pT,{onBack:y,onSubmit:T})}),e.jsx(Ct,{path:"/profile",element:e.jsx(cs,{currentPage:"profile",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(vk,{})})}),e.jsx(Ct,{path:"/settings",element:e.jsx(cs,{currentPage:"settings",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(Fk,{})})}),e.jsx(Ct,{path:"/notifications",element:e.jsx(cs,{currentPage:"notifications",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(Mk,{onNavigate:g})})}),e.jsx(Ct,{path:"/detailed-reports",element:e.jsx(cs,{currentPage:"detailed-reports",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(e4,{})})})]}),e.jsx(H4,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),e.jsx(W4,{open:m,onClose:()=>{u(!1),x(null)},onSelect:async C=>{h!=null&&h.pendingClaimData&&await T(h.pendingClaimData)},managers:h==null?void 0:h.managers,errorType:(h==null?void 0:h.errorType)||"NO_MANAGER_FOUND",message:h==null?void 0:h.message,isLoading:!1}),a&&e.jsx($4,{isOpen:!!a,onClose:w,action:a,requestId:l,requestTitle:c,onSubmit:A})]})}function Y4(t){const{onLogout:s}=t||{};return e.jsx(W0,{children:e.jsx(K4,{onLogout:s})})}function Z4(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=Qt(),[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"),u=d==null?void 0:d.get("error");if(!m&&!u){console.log("🚪 AuthenticatedApp: Logout redirect detected, redirecting to home");const x=new URLSearchParams;return x.set("tanflow_logged_out","true"),x.set("logout",Date.now().toString()),window.location.replace(`/?${x.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(xb,{}):e.jsx(Lx,{})}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(Y4,{onLogout:c}),i&&e.jsx(pb,{isOpen:i,onClose:()=>l(!1)})]}):e.jsx(ub,{})}const li=()=>{try{return!0}catch{return!1}},X4=()=>{if(li())return null;try{return localStorage.getItem("token")}catch{return null}},Q4={user:null,token:X4(),isAuthenticated:!1,isLoading:!1,error:null},$g=Gr({name:"auth",initialState:Q4,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,!li())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,!li())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!li())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:dR,loginSuccess:mR,loginFailure:uR,logout:xR,clearError:hR,updateUser:pR}=$g.actions,J4=H0({reducer:{auth:$g.reducer,dashboard:Yx.reducer,requests:Tg.reducer,myRequests:wg.reducer,openRequests:ih.reducer,closedRequests:vg.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});Hl.createRoot(document.getElementById("root")).render(e.jsx(Gf.StrictMode,{children:e.jsx(uy,{store:J4,children:e.jsx(Ey,{children:e.jsx(Z4,{})})})}));export{je as a};
//# sourceMappingURL=index-D-8iFw5e.js.map