65 lines
1.5 MiB
65 lines
1.5 MiB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-B_YjyhCb.js","assets/radix-vendor-CYvDqP9X.js","assets/charts-vendor-BVfwAPj-.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-CxsBWvVP.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-BATWUvr6.js"])))=>i.map(i=>d[i]);
|
||
var O0=Object.defineProperty;var $0=(t,s,a)=>s in t?O0(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var hl=(t,s,a)=>$0(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Mx,R as Lx,I as Ox,F as $x,a as U0,T as B0,P as V0,C as z0,b as H0,O as Ux,c as Bx,d as W0,e as G0,f as Y0,D as K0,g as Q0,A as X0,h as J0,i as Z0,k as q0,l as ef,m as tf,n as sf,V as af,o as rf,p as nf,q as lf,r as of,s as cf,t as df,u as mf,v as uf,w as xf,x as hf,y as pf,z as gf,B as ff,E as bf,G as jf,H as yf,J as vf,K as Nf,L as wf,M as Cf,N as Sf,Q as Vx,U as zx,W as Af,X as Hx,Y as Wx,Z as Tf,_ as kf,$ as Rf,a0 as Df,a1 as Ff,a2 as If,a3 as Pf,a4 as Ef,a5 as _f,a6 as Mf,a7 as Lf,a8 as Of,a9 as $f,aa as Uf,ab as Bf}from"./radix-vendor-CYvDqP9X.js";import{a as Vf,r as h,c as Gx,d as Qr,B as so,C as Ai,X as Ti,Y as ki,T as Xr,L as Ri,e as ka,P as Yx,f as Kx,g as Qx,h as zf,i as wm,j as zi,k as Hi,b as Hf}from"./charts-vendor-BVfwAPj-.js";import{a as Eo,f as Xx,s as aa,e as _o,b as Cm,c as Wf,d as Ia,g as Mn,i as Mo,h as Jx,j as Qs,k as ea,l as pl,m as Va,n as Gf,o as ao,p as Yf,q as et,r as ro,t as Kf,u as Qf,v as Xf,w as Jf,x as gl,y as Sm,z as Zf,A as Zx,B as qx,C as Lo,D as Oo,E as qf,F as eb,G as eh,H as Ur,I as fl,J as tb,K as sb,L as ab}from"./utils-vendor-BTBPSQfW.js";import{A as fs,S as ps,C as Ze,a as us,L as Xe,X as bt,H as rb,b as th,U as Vt,F as Ie,c as Le,d as an,R as Pt,e as rn,f as nn,P as bs,g as nb,h as ib,B as _s,i as lr,j as bl,k as $o,l as za,m as Wi,n as Uo,o as dt,p as Pa,q as $t,I as Er,T as es,r as st,s as Sa,t as lb,u as ts,M as zs,v as Gi,w as Ot,x as no,D as kt,Z as Yi,y as Zt,z as ob,E as cb,G as db,J as mb,K as ub,N as xb,O as hb,Q as pb,V as gb,W as sh,Y as fb,_ as bb,$ as ah,a0 as ba,a1 as Wn,a2 as or,a3 as Di,a4 as Am,a5 as ni,a6 as Fi,a7 as rh,a8 as St,a9 as jb,aa as X,ab as Hs,ac as Bo,ad as ws,ae as Ki,af as nh,ag as Ct,ah as yb,ai as vb,aj as ih,ak as Qi,al as lh,am as Nb,an as Vo,ao as js,ap as Ha,aq as oh,ar as Xi,as as Ji,at as Cs,au as wb,av as Cb,aw as ch,ax as dh,ay as pi,az as rr,aA as zo,aB as Zi,aC as Ii,aD as mh,aE as uh,aF as Ho,aG as qi,aH as el,aI as Sb,aJ as ir,aK as xh,aL as Pi,aM as Ab,aN as Tb,aO as kb,aP as tl,aQ as sl,aR as Wo,aS as Rb,aT as Tm,aU as Ea,aV as ln,aW as Db,aX as Vr,aY as Fb,aZ as hh,a_ as km,a$ as ph,b0 as Ib,b1 as Pb,b2 as Eb,b3 as _b,b4 as gh,b5 as Mb,b6 as Lb,b7 as Ob,b8 as $b,b9 as Ub}from"./ui-vendor-CxsBWvVP.js";import{l as Bb}from"./socket-vendor-TjCxX7sJ.js";import{c as on,a as Vb}from"./redux-vendor-tbZCm13o.js";import{u as ys,a as _a,b as fh,c as zb,B as Hb,R as Wb,d as Dt,O as Gb}from"./router-vendor-BATWUvr6.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 io={},Rm=Vf;io.createRoot=Rm.createRoot,io.hydrateRoot=Rm.hydrateRoot;var bh={exports:{}},jh={};var Gn=h;function Yb(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var Kb=typeof Object.is=="function"?Object.is:Yb,Qb=Gn.useSyncExternalStore,Xb=Gn.useRef,Jb=Gn.useEffect,Zb=Gn.useMemo,qb=Gn.useDebugValue;jh.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=Xb(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=Zb(function(){function c(u){if(!d){if(d=!0,m=u,u=r(u),n!==void 0&&l.hasValue){var g=l.value;if(n(g,u))return p=g}return p=u}if(g=p,Kb(m,u))return g;var f=r(u);return n!==void 0&&n(g,f)?(m=u,g):(m=u,p=f)}var d=!1,m,p,x=a===void 0?null:a;return[function(){return c(s())},x===null?void 0:function(){return c(x())}]},[s,a,r,n]);var o=Qb(t,i[0],i[1]);return Jb(function(){l.hasValue=!0,l.value=o},[o]),qb(o),o};bh.exports=jh;var ej=bh.exports;function tj(t){t()}function sj(){let t=null,s=null;return{clear(){t=null,s=null},notify(){tj(()=>{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 Dm={notify(){},get:()=>[]};function aj(t,s){let a,r=Dm,n=0,i=!1;function l(f){m();const b=r.subscribe(f);let j=!1;return()=>{j||(j=!0,b(),p())}}function o(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=sj())}function p(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Dm)}function x(){i||(i=!0,m())}function u(){i&&(i=!1,p())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:x,tryUnsubscribe:u,getListeners:()=>r};return g}var rj=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",nj=rj(),ij=()=>typeof navigator<"u"&&navigator.product==="ReactNative",lj=ij(),oj=()=>nj||lj?h.useLayoutEffect:h.useEffect,cj=oj(),jl=Symbol.for("react-redux-context"),yl=typeof globalThis<"u"?globalThis:{};function dj(){if(!h.createContext)return{};const t=yl[jl]??(yl[jl]=new Map);let s=t.get(h.createContext);return s||(s=h.createContext(null),t.set(h.createContext,s)),s}var cr=dj();function mj(t){const{children:s,context:a,serverState:r,store:n}=t,i=h.useMemo(()=>{const c=aj(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=h.useMemo(()=>n.getState(),[n]);cj(()=>{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||cr;return h.createElement(o.Provider,{value:i},s)}var uj=mj;function Go(t=cr){return function(){return h.useContext(t)}}var yh=Go();function vh(t=cr){const s=t===cr?yh:Go(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var xj=vh();function hj(t=cr){const s=t===cr?xj:vh(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var pj=hj(),gj=(t,s)=>t===s;function fj(t=cr){const s=t===cr?yh:Go(t),a=(r,n={})=>{const{equalityFn:i=gj}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;h.useRef(!0);const m=h.useCallback({[r.name](x){return r(x)}}[r.name],[r]),p=ej.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return h.useDebugValue(p),p};return Object.assign(a,{withTypes:()=>a}),a}var bj=fj(),lo=function(t,s){return lo=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])},lo(t,s)};function jj(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");lo(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var Ei=function(){return Ei=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},Ei.apply(this,arguments)};var Cr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Yo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Ko(t,s){return t(s={exports:{}},s.exports),s.exports}var yr=Ko(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()}});Yo(yr);var yj=Yo(Ko(function(t,s){var a=Cr&&Cr.__awaiter||function(m,p,x,u){return new(x||(x=Promise))(function(g,f){function b(w){try{y(u.next(w))}catch(N){f(N)}}function j(w){try{y(u.throw(w))}catch(N){f(N)}}function y(w){w.done?g(w.value):new x(function(N){N(w.value)}).then(b,j)}y((u=u.apply(m,p||[])).next())})},r=Cr&&Cr.__generator||function(m,p){var x,u,g,f,b={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return f={next:j(0),throw:j(1),return:j(2)},typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function j(y){return function(w){return function(N){if(x)throw new TypeError("Generator is already executing.");for(;b;)try{if(x=1,u&&(g=2&N[0]?u.return:N[0]?u.throw||((g=u.return)&&g.call(u),0):u.next)&&!(g=g.call(u,N[1])).done)return g;switch(u=0,g&&(N=[2&N[0],g.value]),N[0]){case 0:case 1:g=N;break;case 4:return b.label++,{value:N[1],done:!1};case 5:b.label++,u=N[1],N=[0];continue;case 7:N=b.ops.pop(),b.trys.pop();continue;default:if(g=b.trys,!((g=g.length>0&&g[g.length-1])||N[0]!==6&&N[0]!==2)){b=0;continue}if(N[0]===3&&(!g||N[1]>g[0]&&N[1]<g[3])){b.label=N[1];break}if(N[0]===6&&b.label<g[1]){b.label=g[1],g=N;break}if(g&&b.label<g[2]){b.label=g[2],b.ops.push(N);break}g[2]&&b.ops.pop(),b.trys.pop();continue}N=p.call(m,b)}catch(S){N=[6,S],u=0}finally{x=g=0}if(5&N[0])throw N[1];return{value:N[0]?N[1]:void 0,done:!0}}([y,w])}}},n=Cr;Object.defineProperty(s,"__esModule",{value:!0});var i="browser-tabs-lock-key",l={key:function(m){return a(n,void 0,void 0,function(){return r(this,function(p){throw new Error("Unsupported")})})},getItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(p){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(p){throw new Error("Unsupported")})})},setItem:function(m,p){return a(n,void 0,void 0,function(){return r(this,function(x){throw new Error("Unsupported")})})},keySync:function(m){return window.localStorage.key(m)},getItemSync:function(m){return window.localStorage.getItem(m)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(m){return window.localStorage.removeItem(m)},setItemSync:function(m,p){return window.localStorage.setItem(m,p)}};function o(m){return new Promise(function(p){return setTimeout(p,m)})}function c(m){for(var p="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",x="",u=0;u<m;u++)x+=p[Math.floor(Math.random()*p.length)];return x}var d=function(){function m(p){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=p,m.waiters===void 0&&(m.waiters=[])}return m.prototype.acquireLock=function(p,x){return x===void 0&&(x=5e3),a(this,void 0,void 0,function(){var u,g,f,b,j,y,w;return r(this,function(N){switch(N.label){case 0:u=Date.now()+c(4),g=Date.now()+x,f=i+"-"+p,b=this.storageHandler===void 0?l:this.storageHandler,N.label=1;case 1:return Date.now()<g?[4,o(30)]:[3,8];case 2:return N.sent(),b.getItemSync(f)!==null?[3,5]:(j=this.id+"-"+p+"-"+u,[4,o(Math.floor(25*Math.random()))]);case 3:return N.sent(),b.setItemSync(f,JSON.stringify({id:this.id,iat:u,timeoutKey:j,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,o(30)];case 4:return N.sent(),(y=b.getItemSync(f))!==null&&(w=JSON.parse(y)).id===this.id&&w.iat===u?(this.acquiredIatSet.add(u),this.refreshLockWhileAcquired(f,u),[2,!0]):[3,7];case 5:return m.lockCorrector(this.storageHandler===void 0?l:this.storageHandler),[4,this.waitForSomethingToChange(g)];case 6:N.sent(),N.label=7;case 7:return u=Date.now()+c(4),[3,1];case 8:return[2,!1]}})})},m.prototype.refreshLockWhileAcquired=function(p,x){return a(this,void 0,void 0,function(){var u=this;return r(this,function(g){return setTimeout(function(){return a(u,void 0,void 0,function(){var f,b,j;return r(this,function(y){switch(y.label){case 0:return[4,yr.default().lock(x)];case 1:return y.sent(),this.acquiredIatSet.has(x)?(f=this.storageHandler===void 0?l:this.storageHandler,(b=f.getItemSync(p))===null?(yr.default().unlock(x),[2]):((j=JSON.parse(b)).timeRefreshed=Date.now(),f.setItemSync(p,JSON.stringify(j)),yr.default().unlock(x),this.refreshLockWhileAcquired(p,x),[2])):(yr.default().unlock(x),[2])}})})},1e3),[2]})})},m.prototype.waitForSomethingToChange=function(p){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,new Promise(function(u){var g=!1,f=Date.now(),b=!1;function j(){if(b||(window.removeEventListener("storage",j),m.removeFromWaiting(j),clearTimeout(y),b=!0),!g){g=!0;var w=50-(Date.now()-f);w>0?setTimeout(u,w):u(null)}}window.addEventListener("storage",j),m.addToWaiting(j);var y=setTimeout(j,Math.max(0,p-Date.now()))})];case 1:return x.sent(),[2]}})})},m.addToWaiting=function(p){this.removeFromWaiting(p),m.waiters!==void 0&&m.waiters.push(p)},m.removeFromWaiting=function(p){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(x){return x!==p}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(p){return p()})},m.prototype.releaseLock=function(p){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,this.releaseLock__private__(p)];case 1:return[2,x.sent()]}})})},m.prototype.releaseLock__private__=function(p){return a(this,void 0,void 0,function(){var x,u,g,f;return r(this,function(b){switch(b.label){case 0:return x=this.storageHandler===void 0?l:this.storageHandler,u=i+"-"+p,(g=x.getItemSync(u))===null?[2]:(f=JSON.parse(g)).id!==this.id?[3,2]:[4,yr.default().lock(f.iat)];case 1:b.sent(),this.acquiredIatSet.delete(f.iat),x.removeItemSync(u),yr.default().unlock(f.iat),m.notifyWaiters(),b.label=2;case 2:return[2]}})})},m.lockCorrector=function(p){for(var x=Date.now()-5e3,u=p,g=[],f=0;;){var b=u.keySync(f);if(b===null)break;g.push(b),f++}for(var j=!1,y=0;y<g.length;y++){var w=g[y];if(w.includes(i)){var N=u.getItemSync(w);if(N!==null){var S=JSON.parse(N);(S.timeRefreshed===void 0&&S.timeAcquired<x||S.timeRefreshed!==void 0&&S.timeRefreshed<x)&&(u.removeItemSync(w),j=!0)}}}j&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var Ar=Ko(function(t,s){var a=Cr&&Cr.__assign||function(){return a=Object.assign||function(c){for(var d,m=1,p=arguments.length;m<p;m++)for(var x in d=arguments[m])Object.prototype.hasOwnProperty.call(d,x)&&(c[x]=d[x]);return c},a.apply(this,arguments)};function r(c,d){if(!d)return"";var m="; "+c;return d===!0?m:m+"="+d}function n(c,d,m){return encodeURIComponent(c).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(d).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(p){if(typeof p.expires=="number"){var x=new Date;x.setMilliseconds(x.getMilliseconds()+864e5*p.expires),p.expires=x}return r("Expires",p.expires?p.expires.toUTCString():"")+r("Domain",p.domain)+r("Path",p.path)+r("Secure",p.secure)+r("SameSite",p.sameSite)}(m)}function i(c){for(var d={},m=c?c.split("; "):[],p=/(%[\dA-F]{2})+/gi,x=0;x<m.length;x++){var u=m[x].split("="),g=u.slice(1).join("=");g.charAt(0)==='"'&&(g=g.slice(1,-1));try{d[u[0].replace(p,decodeURIComponent)]=g.replace(p,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}))}});Yo(Ar),Ar.encode,Ar.parse,Ar.getAll;Ar.get;Ar.set;Ar.remove;var Fm;(function(t){t.Code="code",t.ConnectCode="connect_code"})(Fm||(Fm={}));var Im;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(Im||(Im={}));new yj;var vj={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Gs=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},Nj=Ei(Ei({},vj),{buildAuthorizeUrl:Gs,buildLogoutUrl:Gs,getAccessTokenSilently:Gs,getAccessTokenWithPopup:Gs,getIdTokenClaims:Gs,loginWithRedirect:Gs,loginWithPopup:Gs,connectAccountWithRedirect:Gs,logout:Gs,handleRedirectCallback:Gs,getDpopNonce:Gs,setDpopNonce:Gs,generateDpopProof:Gs,createFetcher:Gs}),wj=h.createContext(Nj);(function(t){jj(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 Cj=function(t){return t===void 0&&(t=wj),h.useContext(t)};const vl="idToken",Nl="userData",Sj=()=>!0;class at{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(vl,s)}static getIdToken(){return sessionStorage.getItem(vl)}static setUserData(s){localStorage.setItem(Nl,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(Nl);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(Nl),sessionStorage.removeItem(vl)}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 Sj()}}function wl(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 Nh="https://reflow-uat.royalenfield.com/api/v1/",je=Eo.create({baseURL:Nh,headers:{"Content-Type":"application/json"},withCredentials:!0});je.interceptors.request.use(t=>{if(t.data instanceof FormData){const s=t.headers;delete s["Content-Type"],s.common&&typeof s.common=="object"&&delete s.common["Content-Type"],s.post&&typeof s.post=="object"&&delete s.post["Content-Type"]}return 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 Eo.post(`${Nh}/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 Aj(t,s){const r=(await je.post("/auth/login",{username:t,password:s},{withCredentials:!0})).data,n=r.data||r;return n.user&&at.setUserData(n.user),n.accessToken&&n.refreshToken&&(at.setAccessToken(n.accessToken),at.setRefreshToken(n.refreshToken)),n}async function Tj(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 kj(){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 An(){const s=(await je.get("/auth/me")).data;return s.data||s}async function Rj(){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 oo="https://ssodev.rebridge.co.in/realms/RE",wh="REFLOW",Qo=`${window.location.origin}/login/callback`;function Dj(){const t=new URLSearchParams(window.location.search),s=t.has("logout")||t.has("tanflow_logged_out");s&&(sessionStorage.removeItem("tanflow_logged_out"),sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),console.log("🚪 Cleared logout flags before initiating Tanflow login"));const a=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","tanflow"),sessionStorage.setItem("tanflow_auth_state",a);let r=`${oo}/protocol/openid-connect/auth?client_id=${wh}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(Qo)}&state=${a}`;s&&(r+="&prompt=login",console.log("🚪 Adding prompt=login to force re-authentication after logout")),console.log("🚪 Initiating Tanflow login",{isAfterLogout:s,hasPrompt:s}),window.location.href=r}async function Fj(t,s){var r,n,i;const a="https://reflow-uat.royalenfield.com/api/v1/";try{const l=await Eo.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:Qo,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 Ij(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=Qo,a=new URL(`${oo}/protocol/openid-connect/logout`);a.searchParams.set("client_id",wh),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:`${oo}/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 Ch=h.createContext(void 0);function Pj({children:t}){const[s,a]=h.useState(!1),[r,n]=h.useState(!0),[i,l]=h.useState(null),[o,c]=h.useState(null),[d,m]=h.useState(!1);h.useEffect(()=>{const w=sessionStorage.getItem("__logout_in_progress__"),N=sessionStorage.getItem("__force_logout__");if(w==="true"||N==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),at.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(D){console.error("Error clearing storage:",D)}a(!1),l(null),n(!1),c(null);return}const S=new URLSearchParams(window.location.search),A=S.has("code");if((S.has("logout")||S.has("okta_logged_out")||S.has("tanflow_logged_out"))&&!A){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);try{sessionStorage.setItem("__force_reauth_after_logout__","true")}catch(D){console.warn("Could not set force reauth flag:",D)}window.history.replaceState({},document.title,"/");return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(at.getUserData(),d?n(!1):x())},[d]),h.useEffect(()=>{if(!s)return;const w=async()=>{try{await j()}catch(A){console.error("Silent refresh failed:",A)}},N=10*60*1e3,S=setInterval(w,N);return()=>clearInterval(S)},[s]);const p=h.useRef(!1);h.useEffect(()=>{if(p.current||window.location.pathname!=="/login/callback")return;(async()=>{const N=new URLSearchParams(window.location.search);if(sessionStorage.getItem("auth_provider")==="tanflow")return;if((N.has("logout")||N.has("tanflow_logged_out")||N.has("okta_logged_out"))&&!N.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const D=new URLSearchParams;N.has("tanflow_logged_out")&&D.set("tanflow_logged_out","true"),N.has("okta_logged_out")&&D.set("okta_logged_out","true"),N.has("logout")&&D.set("logout",N.get("logout")||Date.now().toString());const R=D.toString()?`/?${D.toString()}`:"/?logout="+Date.now();window.location.replace(R);return}p.current=!0;const A=N.get("code"),_=N.get("error");if(window.history.replaceState({},document.title,"/login/callback"),_){c(new Error(`Authentication error: ${_}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!A){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),c(null);const D=`${window.location.origin}/login/callback`,R=await Tj(A,D);l(R.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(D){console.error("❌ Token exchange error in AuthContext:",D),c(D),a(!1),l(null),sessionStorage.removeItem("auth_provider"),p.current=!1}finally{n(!1)}})()},[]);const x=async()=>{var N;if(d){n(!1);return}const w=!0;try{if(n(!0),w){const _=at.getUserData();try{const D=await An();l(D),at.setUserData(D),a(!0)}catch(D){if(((N=D==null?void 0:D.response)==null?void 0:N.status)===401)try{await j();const R=await An();l(R),at.setUserData(R),a(!0)}catch{at.clearAll(),a(!1),l(null)}else D!=null&&D.isConnectionError?_?(l(_),a(!0)):(a(!1),l(null)):(at.clearAll(),a(!1),l(null))}return}const S=at.getAccessToken(),A=at.getUserData();if(!S){a(!1),l(null),n(!1);return}if(wl(S))try{await j();const _=at.getAccessToken();if(_&&!wl(_)){const D=at.getUserData();if(D)l(D),a(!0);else try{const R=await An();l(R),at.setUserData(R),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(A)l(A),a(!0);else try{const _=await An();l(_),at.setUserData(_),a(!0)}catch{at.clearAll(),a(!1),l(null)}}catch(S){console.error("Error checking auth status:",S),c(S),at.clearAll(),a(!1),l(null)}finally{n(!1)}},u=async()=>{try{c(null);const w="https://dev-830839.oktapreview.com",N="0oa2jgzvrpdwx2iqd0h8",S=`${window.location.origin}/login/callback`,A="code",_="openid profile email",D=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const R=new URLSearchParams(window.location.search),v=R.has("logout")||R.has("okta_logged_out")||R.has("tanflow_logged_out"),P=sessionStorage.getItem("__force_reauth_after_logout__")==="true",C=v||P;let V=`${w}/oauth2/default/v1/authorize?client_id=${N}&redirect_uri=${encodeURIComponent(S)}&response_type=${A}&scope=${encodeURIComponent(_)}&state=${D}`;C&&(V+="&prompt=login",sessionStorage.removeItem("__force_reauth_after_logout__")),window.location.href=V}catch(w){throw c(w),w}},g=async(w,N)=>{c(null),n(!0);try{const S=await Aj(w,N);l(S.user),a(!0),window.history.replaceState({},document.title,"/")}catch(S){throw c(S),a(!1),l(null),S}finally{n(!1)}},f=async()=>{try{const w=at.getIdToken(),N=sessionStorage.getItem("auth_provider")||(w&&w.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 Rj(),console.log("🚪 Backend logout API called successfully")}catch(R){console.error("🚪 Logout API error:",R),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const S=sessionStorage.getItem("__logout_in_progress__"),A=sessionStorage.getItem("__force_logout__"),_=sessionStorage.getItem("auth_provider");if(at.clearAll(),S&&sessionStorage.setItem("__logout_in_progress__",S),A&&sessionStorage.setItem("__force_logout__",A),w&&at.setIdToken(w),_&&sessionStorage.setItem("auth_provider",_),await new Promise(R=>setTimeout(R,100)),N==="tanflow"&&w){console.log("🚪 Initiating Tanflow logout...");try{Ij(w);return}catch(R){console.error("🚪 Tanflow logout error:",R)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),w&&at.clearAll();const D=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(D)}catch(w){console.error("🚪 Logout error:",w);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const N=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(N)}catch{window.location.replace("/?logout="+Date.now())}}},b=async()=>{{if(s)return"cookie-based-auth";try{return await j(),s?"cookie-based-auth":null}catch{return null}}const w=at.getAccessToken();if(w&&!wl(w))return w;try{return await j(),at.getAccessToken()}catch{return null}},j=async()=>{try{const N=await kj();return}catch(N){throw at.clearAll(),a(!1),l(null),N}},y={isAuthenticated:s,isLoading:r,user:i,error:o,login:u,loginWithPassword:g,logout:f,getAccessTokenSilently:b,refreshTokenSilently:j};return e.jsx(Ch.Provider,{value:y,children:t})}function Ej({children:t}){return e.jsx(Pj,{children:t})}function cs(){const t=h.useContext(Ch);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function vr(t){return(t==null?void 0:t.role)==="ADMIN"}function bn(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function al(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Pm=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,Em=Gx,Xo=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return Em(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],p=i==null?void 0:i[d];if(m===null)return null;const x=Pm(m)||Pm(p);return n[d][x]}),o=a&&Object.entries(a).reduce((d,m)=>{let[p,x]=m;return x===void 0||(d[p]=x),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:p,className:x,...u}=m;return Object.entries(u).every(g=>{let[f,b]=g;return Array.isArray(b)?b.includes({...i,...o}[f]):{...i,...o}[f]===b})?[...d,p,x]:d},[]);return Em(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},Jo="-",_j=t=>{const s=Lj(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(Jo);return o[0]===""&&o.length!==1&&o.shift(),Sh(o,s)||Mj(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},Sh=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Sh(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Jo);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},_m=/^\[(.+)\]$/,Mj=t=>{if(_m.test(t)){const s=_m.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Lj=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return $j(Object.entries(t.classGroups),a).forEach(([i,l])=>{co(l,r,i,s)}),r},co=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:Mm(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Oj(n)){co(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{co(l,Mm(s,i),a,r)})})},Mm=(t,s)=>{let a=t;return s.split(Jo).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Oj=t=>t.isThemeGetter,$j=(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,Uj=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)}}},Ah="!",Bj=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,p;for(let b=0;b<o.length;b++){let j=o[b];if(d===0){if(j===n&&(r||o.slice(b,b+i)===s)){c.push(o.slice(m,b)),m=b+i;continue}if(j==="/"){p=b;continue}}j==="["?d++:j==="]"&&d--}const x=c.length===0?o:o.substring(m),u=x.startsWith(Ah),g=u?x.substring(1):x,f=p&&p>m?p-m:void 0;return{modifiers:c,hasImportantModifier:u,baseClassName:g,maybePostfixModifierPosition:f}};return a?o=>a({className:o,parseClassName:l}):l},Vj=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},zj=t=>({cache:Uj(t.cacheSize),parseClassName:Bj(t),..._j(t)}),Hj=/\s+/,Wj=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(Hj);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:p,baseClassName:x,maybePostfixModifierPosition:u}=a(d);let g=!!u,f=r(g?x.substring(0,u):x);if(!f){if(!g){o=d+(o.length>0?" "+o:o);continue}if(f=r(x),!f){o=d+(o.length>0?" "+o:o);continue}g=!1}const b=Vj(m).join(":"),j=p?b+Ah:b,y=j+f;if(i.includes(y))continue;i.push(y);const w=n(f,g);for(let N=0;N<w.length;++N){const S=w[N];i.push(j+S)}o=d+(o.length>0?" "+o:o)}return o};function Gj(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=Th(s))&&(r&&(r+=" "),r+=a);return r}const Th=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=Th(t[r]))&&(a&&(a+=" "),a+=s);return a};function Yj(t,...s){let a,r,n,i=l;function l(c){const d=s.reduce((m,p)=>p(m),t());return a=zj(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=Wj(c,a);return n(c,m),m}return function(){return i(Gj.apply(null,arguments))}}const Yt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},kh=/^\[(?:([a-z-]+):)?(.+)\]$/i,Kj=/^\d+\/\d+$/,Qj=new Set(["px","full","screen"]),Xj=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Jj=/\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$/,Zj=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,qj=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ey=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,$a=t=>Jr(t)||Qj.has(t)||Kj.test(t),tr=t=>cn(t,"length",oy),Jr=t=>!!t&&!Number.isNaN(Number(t)),Cl=t=>cn(t,"number",Jr),jn=t=>!!t&&Number.isInteger(Number(t)),ty=t=>t.endsWith("%")&&Jr(t.slice(0,-1)),ft=t=>kh.test(t),sr=t=>Xj.test(t),sy=new Set(["length","size","percentage"]),ay=t=>cn(t,sy,Rh),ry=t=>cn(t,"position",Rh),ny=new Set(["image","url"]),iy=t=>cn(t,ny,dy),ly=t=>cn(t,"",cy),yn=()=>!0,cn=(t,s,a)=>{const r=kh.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},oy=t=>Jj.test(t)&&!Zj.test(t),Rh=()=>!1,cy=t=>qj.test(t),dy=t=>ey.test(t),my=()=>{const t=Yt("colors"),s=Yt("spacing"),a=Yt("blur"),r=Yt("brightness"),n=Yt("borderColor"),i=Yt("borderRadius"),l=Yt("borderSpacing"),o=Yt("borderWidth"),c=Yt("contrast"),d=Yt("grayscale"),m=Yt("hueRotate"),p=Yt("invert"),x=Yt("gap"),u=Yt("gradientColorStops"),g=Yt("gradientColorStopPositions"),f=Yt("inset"),b=Yt("margin"),j=Yt("opacity"),y=Yt("padding"),w=Yt("saturate"),N=Yt("scale"),S=Yt("sepia"),A=Yt("skew"),_=Yt("space"),D=Yt("translate"),R=()=>["auto","contain","none"],v=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto",ft,s],C=()=>[ft,s],V=()=>["",$a,tr],F=()=>["auto",Jr,ft],$=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],I=()=>["solid","dashed","dotted","double","none"],T=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],k=()=>["start","end","center","between","around","evenly","stretch"],z=()=>["","0",ft],L=()=>["auto","avoid","all","avoid-page","page","left","right","column"],M=()=>[Jr,ft];return{cacheSize:500,separator:":",theme:{colors:[yn],spacing:[$a,tr],blur:["none","",sr,ft],brightness:M(),borderColor:[t],borderRadius:["none","","full",sr,ft],borderSpacing:C(),borderWidth:V(),contrast:M(),grayscale:z(),hueRotate:M(),invert:z(),gap:C(),gradientColorStops:[t],gradientColorStopPositions:[ty,tr],inset:P(),margin:P(),opacity:M(),padding:C(),saturate:M(),scale:M(),sepia:z(),skew:M(),space:C(),translate:C()},classGroups:{aspect:[{aspect:["auto","square","video",ft]}],container:["container"],columns:[{columns:[sr]}],"break-after":[{"break-after":L()}],"break-before":[{"break-before":L()}],"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:[...$(),ft]}],overflow:[{overflow:v()}],"overflow-x":[{"overflow-x":v()}],"overflow-y":[{"overflow-y":v()}],overscroll:[{overscroll:R()}],"overscroll-x":[{"overscroll-x":R()}],"overscroll-y":[{"overscroll-y":R()}],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",jn,ft]}],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",ft]}],grow:[{grow:z()}],shrink:[{shrink:z()}],order:[{order:["first","last","none",jn,ft]}],"grid-cols":[{"grid-cols":[yn]}],"col-start-end":[{col:["auto",{span:["full",jn,ft]},ft]}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":[yn]}],"row-start-end":[{row:["auto",{span:[jn,ft]},ft]}],"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",ft]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",ft]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...k()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...k(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...k(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[b]}],mx:[{mx:[b]}],my:[{my:[b]}],ms:[{ms:[b]}],me:[{me:[b]}],mt:[{mt:[b]}],mr:[{mr:[b]}],mb:[{mb:[b]}],ml:[{ml:[b]}],"space-x":[{"space-x":[_]}],"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",ft,s]}],"min-w":[{"min-w":[ft,s,"min","max","fit"]}],"max-w":[{"max-w":[ft,s,"none","full","min","max","fit","prose",{screen:[sr]},sr]}],h:[{h:[ft,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[ft,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[ft,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[ft,s,"auto","min","max","fit"]}],"font-size":[{text:["base",sr,tr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Cl]}],"font-family":[{font:[yn]}],"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",ft]}],"line-clamp":[{"line-clamp":["none",Jr,Cl]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",$a,ft]}],"list-image":[{"list-image":["none",ft]}],"list-style-type":[{list:["none","disc","decimal",ft]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[j]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...I(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",$a,tr]}],"underline-offset":[{"underline-offset":["auto",$a,ft]}],"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:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",ft]}],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",ft]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[j]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...$(),ry]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",ay]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},iy]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[u]}],"gradient-via":[{via:[u]}],"gradient-to":[{to:[u]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[j]}],"border-style":[{border:[...I(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[j]}],"divide-style":[{divide:I()}],"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:["",...I()]}],"outline-offset":[{"outline-offset":[$a,ft]}],"outline-w":[{outline:[$a,tr]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:V()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[$a,tr]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",sr,ly]}],"shadow-color":[{shadow:[yn]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...T(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":T()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",sr,ft]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[w]}],sepia:[{sepia:[S]}],"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":[p]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[S]}],"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",ft]}],duration:[{duration:M()}],ease:[{ease:["linear","in","out","in-out",ft]}],delay:[{delay:M()}],animate:[{animate:["none","spin","ping","pulse","bounce",ft]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[N]}],"scale-x":[{"scale-x":[N]}],"scale-y":[{"scale-y":[N]}],rotate:[{rotate:[jn,ft]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[A]}],"skew-y":[{"skew-y":[A]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",ft]}],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",ft]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"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",ft]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[$a,tr,Cl]}],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"]}}},uy=Yj(my);function _e(...t){return uy(Gx(t))}const Ln=Xo("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),E=h.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Mx:"button";return e.jsx(l,{"data-slot":"button",className:_e(Ln({variant:s,size:a,className:t})),ref:i,...n})});E.displayName="Button";function Z({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:_e("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function oe({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:_e("@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 me({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:_e("leading-none",t),...s})}function ve({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:_e("text-muted-foreground",t),...s})}function ee({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:_e("px-6 [&:last-child]:pb-6",t),...s})}const rl="/assets/Re_Logo-By51taPS.png",Lm="/assets/landing_page_image-ClTD-4qZ.jpg";function xy(){var p,x;const{login:t,isLoading:s,error:a}=cs(),[r,n]=h.useState(!1),[i,l]=h.useState(null),[o,c]=h.useState(!1);h.useEffect(()=>{const u=new Image;u.src=Lm,u.onload=()=>c(!0),u.complete&&c(!0)},[]);const d=async()=>{const u=sessionStorage.getItem("__force_reauth_after_logout__");localStorage.clear(),sessionStorage.clear(),u&&sessionStorage.setItem("__force_reauth_after_logout__",u);try{sessionStorage.setItem("auth_provider","okta"),await t()}catch(g){console.error("OKTA LOGIN ERROR",g)}},m=()=>{l(null),localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("auth_provider","tanflow"),n(!0);try{Dj()}catch(u){const g=u instanceof Error?u.message:"Dealer login failed. Check console for details.";console.error("TANFLOW LOGIN ERROR",u),l(g),n(!1)}};return a&&console.error("Auth Error:",{message:a.message,error:a}),e.jsxs("div",{className:"min-h-screen flex items-center justify-center p-4 relative overflow-hidden",style:{backgroundImage:o?`url(${Lm})`:"none",backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},children:[!o&&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/50 backdrop-blur-[2px]","aria-hidden":!0}),e.jsx("div",{className:"absolute inset-0 bg-black/30","aria-hidden":!0}),e.jsxs(Z,{className:"w-full max-w-md shadow-2xl relative z-10 bg-gray-900/95 border border-gray-700 text-white",children:[e.jsx(oe,{className:"space-y-1 text-center pb-6 pt-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:rl,alt:"Royal Enfield",className:"h-9 w-auto max-w-[180px] object-contain mb-2"}),e.jsx("p",{className:"text-sm text-gray-400",children:"Approval Portal"})]})}),e.jsxs(ee,{className:"space-y-5 pb-8 px-8",children:[a&&e.jsxs("div",{className:"bg-red-900/40 border border-red-700 text-red-200 px-4 py-3 rounded-lg text-sm",children:[e.jsx("p",{className:"font-medium",children:"Authentication Error"}),e.jsx("p",{children:a.message}),(((p=a.message)==null?void 0:p.includes("401"))||((x=a.message)==null?void 0:x.toLowerCase().includes("unauthorized")))&&e.jsxs("p",{className:"mt-2 text-xs text-red-300",children:["If you see 401 from Okta: your Okta admin must add this site’s URL to ",e.jsx("strong",{children:"Trusted Origins"})," and ensure the RE Employee application is active. Use ",e.jsx("strong",{children:"Dealer Login"})," if you are a dealer."]})]}),i&&e.jsxs("div",{className:"bg-amber-900/40 border border-amber-700 text-amber-200 px-4 py-3 rounded-lg text-sm",children:[e.jsx("p",{className:"font-medium",children:"Dealer Login (Tanflow)"}),e.jsx("p",{children:i})]}),e.jsx(E,{onClick:d,disabled:s||r,className:"w-full h-12 bg-re-red hover:bg-re-red/90 text-white font-semibold text-base border-0",size:"lg",children:s?e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent"}):e.jsxs(e.Fragment,{children:[e.jsx(fs,{className:"mr-2 h-5 w-5"}),"RE Employee Login"]})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex-1 h-px bg-gray-600"}),e.jsx("span",{className:"text-sm text-gray-400 uppercase tracking-wide",children:"Or"}),e.jsx("span",{className:"flex-1 h-px bg-gray-600"})]}),e.jsx(E,{onClick:m,disabled:s||r,className:"w-full h-12 bg-blue-600 hover:bg-blue-700 text-white font-semibold text-base border-0",size:"lg",children:r?e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent"}):e.jsxs(e.Fragment,{children:[e.jsx(ps,{className:"mr-2 h-5 w-5"}),"Dealer Login"]})}),e.jsxs("div",{className:"text-center pt-2",children:[e.jsx("p",{className:"text-sm text-gray-400",children:"Secure Single Sign On"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Choose your authentication provider."})]})]})]})]})}function Dh(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=cs(),[n,i]=h.useState("exchanging");h.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:rl,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:n==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(Ze,{className:"w-16 h-16 text-red-500"})}),e.jsx(Ze,{className:"w-16 h-16 text-red-500 relative"})]}):n==="complete"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(us,{className:"w-16 h-16 text-green-500"})}),e.jsx(us,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Xe,{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 hy(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=cs(),[n,i]=h.useState("exchanging"),[l,o]=h.useState(""),c=h.useRef(!1);h.useEffect(()=>{if(a){i("error");return}if(s){const p=new URLSearchParams(window.location.search).get("code");i(p&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&(i("complete"),setTimeout(()=>{window.location.href="/"},1e3))},[t,s,a,r]),h.useEffect(()=>{if(c.current||window.location.pathname!=="/login/callback")return;const m=new URLSearchParams(window.location.search),p=m.get("code"),x=m.get("error");if(!p&&!x){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 b=`/?${f.toString()}`;console.log("🚪 Redirecting to:",b),window.location.replace(b);return}if(sessionStorage.getItem("auth_provider")!=="tanflow")return;(async()=>{c.current=!0;const f=new URLSearchParams(window.location.search),b=f.get("code"),j=f.get("state"),y=f.get("error");if(window.history.replaceState({},document.title,"/login/callback"),y){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}const w=sessionStorage.getItem("tanflow_auth_state");if(j&&j!==w){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}if(!b){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}try{i("exchanging");const N=await Fj(b,j||"");sessionStorage.removeItem("tanflow_auth_state"),i("fetching");const S=N.user||await An();if(S)at.setUserData(S),i("complete"),setTimeout(()=>{window.history.replaceState({},document.title,"/"),window.location.href="/"},1e3);else throw new Error("User data not received")}catch(N){console.error("Tanflow callback error:",N),i("error"),o(N.message||"Authentication failed"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state")}})()},[]);const d=()=>{switch(n){case"exchanging":return"Exchanging authorization code...";case"fetching":return"Fetching your profile...";case"complete":return"Authentication successful!";case"error":return"Authentication failed";default:return"Completing authentication..."}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"}),e.jsxs("div",{className:"relative z-10 text-center px-4 max-w-md w-full",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:rl,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:n==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(Ze,{className:"w-16 h-16 text-red-500"})}),e.jsx(Ze,{className:"w-16 h-16 text-red-500 relative"})]}):n==="complete"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(us,{className:"w-16 h-16 text-green-500"})}),e.jsx(us,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Xe,{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 py=Xo("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 se({className:t,variant:s,asChild:a=!1,...r}){const n=a?Mx:"span";return e.jsx(n,{"data-slot":"badge",className:_e(py({variant:s}),t),...r})}function gy({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=Cj();return h.useEffect(()=>{},[a,r,n,i]),t?e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4",children:e.jsxs(Z,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{children:"Authentication Debug Information"}),e.jsx(E,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(bt,{className:"h-4 w-4"})})]})}),e.jsxs(ee,{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(se,{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 ls=h.forwardRef(({className:t,...s},a)=>e.jsx(Lx,{ref:a,"data-slot":"avatar",className:_e("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));ls.displayName=Lx.displayName;const nl=h.forwardRef(({className:t,...s},a)=>e.jsx(Ox,{ref:a,"data-slot":"avatar-image",className:_e("aspect-square size-full",t),...s}));nl.displayName=Ox.displayName;const os=h.forwardRef(({className:t,...s},a)=>e.jsx($x,{ref:a,"data-slot":"avatar-fallback",className:_e("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));os.displayName=$x.displayName;function Om({...t}){return e.jsx(U0,{"data-slot":"dropdown-menu",...t})}function $m({...t}){return e.jsx(B0,{"data-slot":"dropdown-menu-trigger",...t})}function Um({className:t,sideOffset:s=4,...a}){return e.jsx(V0,{children:e.jsx(z0,{"data-slot":"dropdown-menu-content",sideOffset:s,className:_e("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 Sl({className:t,inset:s,variant:a="default",...r}){return e.jsx(H0,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:_e("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 Fh({...t}){return e.jsx(G0,{"data-slot":"alert-dialog",...t})}function fy({...t}){return e.jsx(W0,{"data-slot":"alert-dialog-portal",...t})}const Ih=h.forwardRef(({className:t,...s},a)=>e.jsx(Ux,{"data-slot":"alert-dialog-overlay",className:_e("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}));Ih.displayName=Ux.displayName;const Zo=h.forwardRef(({className:t,...s},a)=>e.jsxs(fy,{children:[e.jsx(Ih,{}),e.jsx(Bx,{"data-slot":"alert-dialog-content",ref:a,className:_e("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})]}));Zo.displayName=Bx.displayName;function Ph({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:_e("flex flex-col gap-2 text-center sm:text-left",t),...s})}function Eh({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:_e("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function _h({className:t,...s}){return e.jsx(Y0,{"data-slot":"alert-dialog-title",className:_e("text-lg font-semibold",t),...s})}function Mh({className:t,...s}){return e.jsx(K0,{"data-slot":"alert-dialog-description",className:_e("text-muted-foreground text-sm",t),...s})}function Lh({className:t,...s}){return e.jsx(X0,{className:_e(Ln(),t),...s})}function Oh({className:t,...s}){return e.jsx(Q0,{className:_e(Ln({variant:"outline"}),t),...s})}const nr={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}},by=async()=>(await je.get("/notifications/subscriptions")).data.data.subscriptions,$h="https://reflow-uat.royalenfield.com/api/v1/";async function Uh(t,s={}){const a=at.getAccessToken(),r={...s.headers||{}};s.body instanceof FormData||(r["Content-Type"]="application/json"),a&&(r.Authorization=`Bearer ${a}`);const n=await fetch(`${$h}${t}`,{...s,headers:r,credentials:"include"}),i=n.headers.get("content-type"),o=(i==null?void 0:i.includes("application/json"))?await n.json():{message:await n.text()||"Request failed"};if(!n.ok){const c=new Error(o.message||`Request failed ${n.status}`);throw c.response={status:n.status,data:o},c}return o}async function Bh(){var a;const t=await je.get("/form16/permissions"),s=((a=t.data)==null?void 0:a.data)??t.data;return{canViewForm16Submission:!!(s!=null&&s.canViewForm16Submission),canView26AS:!!(s!=null&&s.canView26AS)}}async function jy(t){const s=new URLSearchParams;t!=null&&t.financialYear&&s.set("financialYear",t.financialYear),t!=null&&t.quarter&&s.set("quarter",t.quarter);const a=s.toString(),r=a?`/form16/credit-notes?${a}`:"/form16/credit-notes",{data:n}=await je.get(r),i=(n==null?void 0:n.data)??n;return{creditNotes:(i==null?void 0:i.creditNotes)??[],total:(i==null?void 0:i.total)??0,summary:i==null?void 0:i.summary}}async function Vh(t){const{data:s}=await je.get(`/form16/requests/${encodeURIComponent(t)}/credit-note`),a=(s==null?void 0:s.data)??s;return(a==null?void 0:a.creditNote)??null}async function yy(t){await je.post(`/form16/requests/${encodeURIComponent(t)}/cancel-submission`)}async function vy(t){await je.post(`/form16/requests/${encodeURIComponent(t)}/resubmission-needed`)}async function Ny(t){const{data:s}=await je.get(`/form16/credit-notes/${t}`),a=s&&typeof s=="object"&&"data"in s?s.data:s;if(!(a!=null&&a.creditNote))throw new Error("Credit note not found");return a}async function wy(t){const s=new FormData;s.append("document",t);const a=await Uh("/form16/extract",{method:"POST",body:s}),r=a,n=(r==null?void 0:r.data)??r,i=n==null?void 0:n.extractedData,l=n==null?void 0:n.ocrProvider;if(!i)throw new Error(a.message||"No extracted data returned");return{extractedData:i,ocrProvider:l}}async function Cy(t){const s=new FormData;s.append("document",t.file),s.append("financialYear",t.financialYear),s.append("quarter",t.quarter),s.append("form16aNumber",t.form16aNumber),s.append("tdsAmount",String(t.tdsAmount)),s.append("totalAmount",String(t.totalAmount)),s.append("tanNumber",t.tanNumber),s.append("deductorName",t.deductorName),t.version!=null&&s.append("version",String(t.version)),t.extractedData!=null&&s.append("ocrExtractedData",JSON.stringify(t.extractedData));const a=await Uh("/form16/submissions",{method:"POST",body:s}),n=a.data??a;if(!(n!=null&&n.requestNumber))throw new Error(a.message||"Invalid response from server");return n}async function Sy(t){const s=new URLSearchParams;t!=null&&t.financialYear&&s.set("financialYear",t.financialYear),t!=null&&t.quarter&&s.set("quarter",t.quarter),t!=null&&t.tanNumber&&s.set("tanNumber",t.tanNumber),t!=null&&t.search&&s.set("search",t.search),t!=null&&t.status&&s.set("status",t.status),t!=null&&t.assessmentYear&&s.set("assessmentYear",t.assessmentYear),t!=null&&t.sectionCode&&s.set("sectionCode",t.sectionCode),s.set("limit",String(t.limit)),(t==null?void 0:t.offset)!=null&&s.set("offset",String(t.offset));const a=s.toString(),r=a?`/form16/26as?${a}`:"/form16/26as",{data:n}=await je.get(r),i=(n==null?void 0:n.data)??n;return{entries:(i==null?void 0:i.entries)??[],total:(i==null?void 0:i.total)??0,summary:(i==null?void 0:i.summary)??{totalRecords:0,booked:0,notBooked:0,pending:0,totalTaxDeducted:0}}}async function Ay(t){const s=new URLSearchParams;s.set("limit",String(t));const a=s.toString(),r=a?`/form16/26as/upload-history?${a}`:"/form16/26as/upload-history",{data:n}=await je.get(r),i=(n==null?void 0:n.data)??n;return(i==null?void 0:i.history)??[]}const Ty=5*60*1e3;function ky(t,s){return new Promise((a,r)=>{const n=new FormData;n.append("file",t);const i=new XMLHttpRequest,l=`${$h}/form16/26as/upload`,o=at.getAccessToken(),c=setTimeout(()=>{i.abort(),r(new Error("Upload timed out. Try a smaller file or try again."))},Ty);i.upload.addEventListener("progress",d=>{if(d.lengthComputable&&d.total>0){const m=Math.min(100,Math.round(d.loaded/d.total*100));s==null||s(m)}else s==null||s(0)}),i.addEventListener("load",()=>{clearTimeout(c),s==null||s(100);const d=i.getResponseHeader("content-type"),m=d==null?void 0:d.includes("application/json"),p=i.responseText;let x;try{x=m?JSON.parse(p):{message:p||"Request failed"}}catch{x={message:p||"Invalid response"}}if(i.status>=200&&i.status<300){const u=x.data??x;a({imported:(u==null?void 0:u.imported)??0,errors:Array.isArray(u==null?void 0:u.errors)?u.errors:[]})}else r(new Error(x.message||`Request failed ${i.status}`))}),i.addEventListener("error",()=>{clearTimeout(c),r(new Error("Network error during upload"))}),i.addEventListener("abort",()=>{clearTimeout(c),r(new Error("Upload was cancelled or timed out"))}),i.open("POST",l),o&&i.setRequestHeader("Authorization",`Bearer ${o}`),i.withCredentials=!0,i.send(n)})}async function Ry(t){const s=new URLSearchParams;t&&s.set("financialYear",t);const a=s.toString(),r=a?`/form16/non-submitted-dealers?${a}`:"/form16/non-submitted-dealers",{data:n}=await je.get(r),i=(n==null?void 0:n.data)??n;return{summary:(i==null?void 0:i.summary)??{totalDealers:0,nonSubmittedCount:0,neverSubmittedCount:0,overdue90Count:0},dealers:(i==null?void 0:i.dealers)??[]}}async function Dy(t,s){var n;const{data:a}=await je.post("/form16/non-submitted-dealers/notify",{dealerCode:t,financialYear:s||void 0}),r=(n=a==null?void 0:a.data)==null?void 0:n.dealer;if(!r)throw new Error("No dealer returned");return r}async function Fy(t){const s=new URLSearchParams;t!=null&&t.status&&s.set("status",t.status),t!=null&&t.financialYear&&s.set("financialYear",t.financialYear),t!=null&&t.quarter&&s.set("quarter",t.quarter);const a=s.toString(),r=a?`/form16/dealer/submissions?${a}`:"/form16/dealer/submissions",{data:n}=await je.get(r),i=(n==null?void 0:n.data)??n;return Array.isArray(i)?i:[]}async function zh(){const{data:t}=await je.get("/form16/dealer/pending-quarters"),s=(t==null?void 0:t.data)??t;return Array.isArray(s)?s:[]}let fr=null;function Iy(){return"https://reflow-uat.royalenfield.com"}function en(t){const s=Iy();return fr||(fr=Bb(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),fr.on("connect",()=>{}),fr.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),fr.on("disconnect",a=>{}),fr)}function mo(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function Hh(t,s){t.emit("leave:request",s)}function Wh(t,s){t.emit("join:user",{userId:s})}function Jt({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,l]=h.useState(!1),[o,c]=h.useState(()=>(s==null?void 0:s.startsWith("form16"))??!1),[d,m]=h.useState(!1),[p,x]=h.useState([]),[u,g]=h.useState(0),[f,b]=h.useState(!1),[j,y]=h.useState(null),{user:w}=cs(),N=h.useMemo(()=>{try{const I=at.getUserData();return(I==null?void 0:I.jobTitle)==="Dealer"}catch(I){return console.error("[PageLayout] Error checking dealer status:",I),!1}},[]),S=(w==null?void 0:w.role)==="ADMIN",A=()=>{var I,T;try{if(w!=null&&w.displayName&&typeof w.displayName=="string"){const k=w.displayName.split(" ").filter(Boolean);return k.length>=2?`${((I=k[0])==null?void 0:I[0])||""}${((T=k[k.length-1])==null?void 0:T[0])||""}`.toUpperCase():w.displayName.substring(0,2).toUpperCase()}return w!=null&&w.email&&typeof w.email=="string"?w.email.substring(0,2).toUpperCase():"U"}catch(k){return console.error("[PageLayout] Error getting user initials:",k),"U"}},_=h.useMemo(()=>{const I=[{id:"dashboard",label:"Dashboard",icon:rb},{id:"requests",label:"All Requests",icon:th,adminOnly:!1}];return N||I.push({id:"my-requests",label:"My Requests",icon:Vt}),I.push({id:"open-requests",label:"Open Requests",icon:Ie},{id:"closed-requests",label:"Closed Requests",icon:Le},{id:"shared-summaries",label:"Shared Summary",icon:an}),I},[N,S]);h.useEffect(()=>{if(!(w!=null&&w.userId)){y(null);return}let I=!0;return Bh().then(T=>{I&&y(T)}).catch(T=>{I&&(y({canViewForm16Submission:!1,canView26AS:!1}),console.warn("[PageLayout] Form 16 permissions could not be loaded – Form 16 menu will be hidden.",T))}),()=>{I=!1}},[w==null?void 0:w.userId]);const D=j&&(j.canViewForm16Submission||j.canView26AS),R=!!(j!=null&&j.canViewForm16Submission),v=!!(j!=null&&j.canView26AS),P=s==="form16-credit-notes"||s==="form16-submit"||s==="form16-pending-submissions"||s==="form16-26as"||s==="form16-non-submitted-dealers",C=o||P,V=()=>{l(!i)},F=async I=>{var T;try{if(I.isRead||(await nr.markAsRead(I.notificationId),x(k=>k.map(z=>z.notificationId===I.notificationId?{...z,isRead:!0}:z)),g(k=>Math.max(0,k-1))),I.actionUrl&&a){const k=(T=I.metadata)==null?void 0:T.requestNumber;if(k){let z=`request/${k}`;(I.notificationType==="mention"||I.notificationType==="comment"||I.notificationType==="worknote")&&(z+="?tab=worknotes"),a(z)}}b(!1)}catch(k){console.error("[PageLayout] Error handling notification click:",k)}},$=async()=>{try{await nr.markAllAsRead(),x(I=>I.map(T=>({...T,isRead:!0}))),g(0)}catch(I){console.error("[PageLayout] Error marking all as read:",I)}};return h.useEffect(()=>{const I=w==null?void 0:w.userId;if(!I)return;let T=!0;(async()=>{var L,M;try{const U=await nr.list({page:1,limit:4,unreadOnly:!1});if(!T)return;const B=((L=U.data)==null?void 0:L.notifications)||[];x(B),g(((M=U.data)==null?void 0:M.unreadCount)||0)}catch(U){console.error("[PageLayout] Failed to fetch notifications:",U)}})();const z=en();if(z){Wh(z,I);const L=M=>{T&&(x(U=>[M.notification,...U].slice(0,4)),g(U=>U+1))};return z.on("notification:new",L),()=>{T=!1,z.off("notification:new",L)}}return()=>{T=!1}},[w]),h.useEffect(()=>{const I=()=>{window.innerWidth>=768?l(!0):l(!1)};return I(),window.addEventListener("resize",I),()=>window.removeEventListener("resize",I)},[]),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:rl,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.jsxs("div",{className:"space-y-2",children:[_.filter(I=>!I.adminOnly||(w==null?void 0:w.role)==="ADMIN").map(I=>e.jsxs("button",{onClick:()=>{a==null||a(I.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===I.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(I.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:I.label})]},I.id)),D&&e.jsxs("div",{className:"pt-2 border-t border-gray-800",children:[e.jsxs("button",{type:"button",onClick:()=>c(!C),className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${P?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(Pt,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate flex-1 text-left",children:"Form 16"}),C?e.jsx(rn,{className:"w-4 h-4 shrink-0"}):e.jsx(nn,{className:"w-4 h-4 shrink-0"})]}),C&&e.jsx("div",{className:"mt-1 ml-4 pl-2 border-l border-gray-700 space-y-0.5",children:N?e.jsx(e.Fragment,{children:R&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>{a==null||a("/form16/submit"),window.innerWidth<768&&l(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm transition-colors ${s==="form16-submit"?"bg-re-green/80 text-white font-medium":"text-gray-400 hover:bg-gray-800 hover:text-white"}`,children:[e.jsx(Ie,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Submit Form 16"})]}),e.jsxs("button",{type:"button",onClick:()=>{a==null||a("/form16/pending-submissions"),window.innerWidth<768&&l(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm transition-colors ${s==="form16-pending-submissions"?"bg-re-green/80 text-white font-medium":"text-gray-400 hover:bg-gray-800 hover:text-white"}`,children:[e.jsx(Ie,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Pending Submissions"})]}),e.jsxs("button",{type:"button",onClick:()=>{a==null||a("/form16/credit-notes"),window.innerWidth<768&&l(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm transition-colors ${s==="form16-credit-notes"?"bg-re-green/80 text-white font-medium":"text-gray-400 hover:bg-gray-800 hover:text-white"}`,children:[e.jsx(Pt,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Credit Notes"})]})]})}):e.jsxs(e.Fragment,{children:[v&&e.jsxs("button",{type:"button",onClick:()=>{a==null||a("/form16/26as"),window.innerWidth<768&&l(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm transition-colors ${s==="form16-26as"?"bg-re-green/80 text-white font-medium":"text-gray-400 hover:bg-gray-800 hover:text-white"}`,children:[e.jsx(Ie,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"26AS Management"})]}),R&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>{a==null||a("/form16/non-submitted-dealers"),window.innerWidth<768&&l(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm transition-colors ${s==="form16-non-submitted-dealers"?"bg-re-green/80 text-white font-medium":"text-gray-400 hover:bg-gray-800 hover:text-white"}`,children:[e.jsx(Pt,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Non-submitted Dealers"})]}),e.jsxs("button",{type:"button",onClick:()=>{a==null||a("/form16/credit-notes"),window.innerWidth<768&&l(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm transition-colors ${s==="form16-credit-notes"?"bg-re-green/80 text-white font-medium":"text-gray-400 hover:bg-gray-800 hover:text-white"}`,children:[e.jsx(Pt,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Credit Notes"})]})]})]})})]})]}),!N&&e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(E,{onClick:r,className:"w-full bg-re-green hover:bg-re-green/90 text-white text-sm font-medium",size:"sm",children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Raise New Request"]})})]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("header",{className:"h-16 border-b border-gray-200 bg-white flex items-center justify-between px-6 shrink-0",children:[e.jsx("div",{className:"flex items-center gap-4 min-w-0 flex-1",children:e.jsx(E,{variant:"ghost",size:"icon",onClick:V,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(nb,{className:"w-5 h-5 text-gray-600"}):e.jsx(ib,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[!N&&e.jsxs(E,{onClick:r,className:"bg-re-green hover:bg-re-green/90 text-white gap-2 hidden md:flex text-sm",size:"sm",children:[e.jsx(bs,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(Om,{open:f,onOpenChange:b,children:[e.jsx($m,{asChild:!0,children:e.jsxs(E,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(_s,{className:"w-5 h-5"}),u>0&&e.jsx(se,{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(Um,{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(E,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:I=>{I.stopPropagation(),$()},children:"Mark all as read"})]}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:p.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(_s,{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:p.map(I=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${I.isRead?"":"bg-blue-50"}`,onClick:()=>F(I),children:e.jsxs("div",{className:"flex gap-2",children:[!I.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 ${I.isRead?"font-medium":"font-semibold"}`,children:I.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:I.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:Xx(new Date(I.createdAt),{addSuffix:!0})})]})]})},I.notificationId))})}),p.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(E,{variant:"ghost",className:"w-full text-sm text-blue-600 hover:text-blue-700",onClick:()=>{b(!1),a==null||a("notifications")},children:"View all notifications"})})]})]}),e.jsxs(Om,{children:[e.jsx($m,{asChild:!0,children:e.jsxs(ls,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(nl,{src:(w==null?void 0:w.picture)||""}),e.jsx(os,{className:"bg-re-green text-white text-sm",children:A()})]})}),e.jsxs(Um,{align:"end",children:[e.jsxs(Sl,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(Vt,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(Sl,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(lr,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(Sl,{onClick:()=>m(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(bl,{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(Fh,{open:d,onOpenChange:m,children:e.jsxs(Zo,{children:[e.jsxs(Ph,{children:[e.jsxs(_h,{className:"flex items-center gap-2",children:[e.jsx(bl,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(Mh,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(Eh,{children:[e.jsx(Oh,{onClick:()=>m(!1),children:"Cancel"}),e.jsxs(Lh,{onClick:async()=>{if(m(!1),n)try{await n()}catch(I){console.error("🔴 Error calling onLogout:",I)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(bl,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const Yn=()=>pj(),dn=bj,Py=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},Ey={viewAsUser:Py()},Gh=on({name:"dashboard",initialState:Ey,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:_y}=Gh.actions;function My(){const[t,s]=h.useState("all"),[a,r]=h.useState(void 0),[n,i]=h.useState(void 0),[l,o]=h.useState(!1),c=h.useCallback(p=>{const x=p;s(x),x!=="custom"?(r(void 0),i(void 0),o(!1)):o(!0)},[]),d=h.useCallback(p=>{if(a&&n){if(a>n){const x=a;r(n),i(x),p(n,x)}else p(a,n);o(!1)}},[a,n]),m=h.useCallback(()=>{r(void 0),i(void 0),o(!1),s("all")},[]);return{dateRange:t,customStartDate:a,customEndDate:n,showCustomDatePicker:l,setDateRange:s,setCustomStartDate:r,setCustomEndDate:i,setShowCustomDatePicker:o,handleDateRangeChange:c,handleApplyCustomDate:d,resetCustomDates:m}}function Ly(){const[t,s]=h.useState({page:1,totalPages:1,totalRecords:0}),[a,r]=h.useState({page:1,totalPages:1,totalRecords:0}),[n,i]=h.useState({page:1,totalPages:1,totalRecords:0}),[l,o]=h.useState({page:1,totalPages:1,totalRecords:0}),c=h.useCallback((b,j,y)=>{s({page:b,totalPages:j,totalRecords:y})},[]),d=h.useCallback((b,j,y)=>{r({page:b,totalPages:j,totalRecords:y})},[]),m=h.useCallback((b,j,y)=>{i({page:b,totalPages:j,totalRecords:y})},[]),p=h.useCallback((b,j,y)=>{o({page:b,totalPages:j,totalRecords:y})},[]),x=h.useCallback((b,j)=>{b>=1&&b<=t.totalPages&&(s(y=>({...y,page:b})),j(b))},[t.totalPages]),u=h.useCallback((b,j)=>{b>=1&&b<=a.totalPages&&(r(y=>({...y,page:b})),j(b))},[a.totalPages]),g=h.useCallback((b,j)=>{b>=1&&b<=n.totalPages&&(i(y=>({...y,page:b})),j(b))},[n.totalPages]),f=h.useCallback((b,j)=>{b>=1&&b<=l.totalPages&&(o(y=>({...y,page:b})),j(b))},[l.totalPages]);return{activity:t,critical:a,deadlines:n,approver:l,updateActivityPagination:c,updateCriticalPagination:d,updateDeadlinesPagination:m,updateApproverPagination:p,handleActivityPageChange:x,handleCriticalPageChange:u,handleDeadlinesPageChange:g,handleApproverPageChange:f}}class Oy{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,p,x,u){try{const g={dateRange:s};return s==="custom"&&a&&r&&(g.startDate=a,g.endDate=r),n&&n!=="all"&&(g.status=n),i&&i!=="all"&&(g.priority=i),l&&l!=="all"&&(g.templateType=l),o&&o!=="all"&&(g.department=o),c&&c!=="all"&&(g.initiator=c),d&&d!=="all"&&(g.approver=d),m&&(g.approverType=m),p&&(g.search=p),x&&x!=="all"&&(g.slaCompliance=x),u&&(g.viewAsUser="true"),(await je.get("/dashboard/stats/requests",{params:g})).data.data}catch(g){throw console.error("Failed to fetch request stats:",g),g}}async getTATEfficiency(s){try{return(await je.get("/dashboard/stats/tat-efficiency",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch TAT efficiency:",a),a}}async getApproverLoad(s){try{return(await je.get("/dashboard/stats/approver-load",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch approver load:",a),a}}async getEngagementStats(s){try{return(await je.get("/dashboard/stats/engagement",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch engagement stats:",a),a}}async getAIInsights(s){try{return(await je.get("/dashboard/stats/ai-insights",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch AI insights:",a),a}}async getRecentActivity(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await je.get("/dashboard/activity/recent",{params:n});return{activities:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch recent activity:",n),n}}async getCriticalRequests(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await je.get("/dashboard/requests/critical",{params:n});return{criticalRequests:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch critical requests:",n),n}}async getUpcomingDeadlines(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await je.get("/dashboard/deadlines/upcoming",{params:n});return{deadlines:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch upcoming deadlines:",n),n}}async getDepartmentStats(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await je.get("/dashboard/stats/by-department",{params:n})).data.data}catch(n){throw console.error("Failed to fetch department stats:",n),n}}async getPriorityDistribution(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await je.get("/dashboard/stats/priority-distribution",{params:n})).data.data}catch(n){throw console.error("Failed to fetch priority distribution:",n),n}}async getAIRemarkUtilization(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await je.get("/dashboard/stats/ai-remark-utilization",{params:n})).data.data}catch(n){throw console.error("Failed to fetch AI remark utilization:",n),n}}async getApproverPerformance(s,a=1,r=10,n,i,l,o){try{const c={dateRange:s,page:a,limit:r||10};s==="custom"&&n&&i&&(c.startDate=n.toISOString(),c.endDate=i.toISOString()),l&&l!=="all"&&(c.priority=l),o&&o!=="all"&&(c.slaCompliance=o),console.log("[Dashboard Service] Fetching approver performance with params:",c);const d=await je.get("/dashboard/stats/approver-performance",{params:c});return{performance:d.data.data,pagination:d.data.pagination}}catch(c){throw console.error("Failed to fetch approver performance:",c),c}}async getLifecycleReport(s=1,a=50,r,n,i){try{const l={page:s,limit:a};r&&(l.dateRange=r),r==="custom"&&n&&i&&(l.startDate=n.toISOString(),l.endDate=i.toISOString());const o=await je.get("/dashboard/reports/lifecycle",{params:l});return{lifecycleData:o.data.data,pagination:o.data.pagination}}catch(l){throw console.error("Failed to fetch lifecycle report:",l),l}}async getActivityLogReport(s=1,a=50,r,n,i,l,o,c,d){try{const m={page:s,limit:a,filterUserId:n,filterType:i,filterCategory:l,filterSeverity:o};r&&(m.dateRange=r),r==="custom"&&c&&d&&(m.startDate=c.toISOString(),m.endDate=d.toISOString());const p=await je.get("/dashboard/reports/activity-log",{params:m});return{activities:p.data.data,pagination:p.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 p={approverId:s,page:a,limit:r};n&&(p.dateRange=n),n==="custom"&&i&&l&&(p.startDate=i.toISOString(),p.endDate=l.toISOString()),o&&(p.status=o),c&&(p.priority=c),d&&(p.slaCompliance=d),m&&(p.search=m);const x=await je.get("/dashboard/requests/by-approver",{params:p});return{requests:x.data.data,pagination:x.data.pagination}}catch(p){throw console.error("Failed to fetch requests by approver:",p),p}}}const _t=new Oy;function $y({isAdmin:t,viewAsUser:s=!1,userId:a,dateRange:r,customStartDate:n,customEndDate:i,onPaginationUpdate:l}){const[o,c]=h.useState(null),[d,m]=h.useState([]),[p,x]=h.useState([]),[u,g]=h.useState([]),[f,b]=h.useState([]),[j,y]=h.useState([]),[w,N]=h.useState(null),[S,A]=h.useState([]),[_,D]=h.useState(!0),[R,v]=h.useState(!1),P=h.useRef(l);P.current=l;const C=h.useCallback(async(T=!1)=>{try{T?v(!0):D(!0);const k=[_t.getKPIs(r,n,i,s),_t.getRecentActivity(1,10,s),_t.getCriticalRequests(1,10,s),_t.getUpcomingDeadlines(1,10,s)],z=!t&&a?_t.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,L=t?[_t.getDepartmentStats(r,n,i),_t.getPriorityDistribution(r,n,i),_t.getAIRemarkUtilization(r,n,i),_t.getApproverPerformance(r,1,10,n,i)]:[],[M,U,B]=await Promise.all([Promise.all(k),z,Promise.all(L)]),W=M[0],J=M[1],O=M[2],H=M[3];if(!t&&U&&(W.requestVolume=U),c(W),m(J.activities),P.current.activity(J.pagination.currentPage,J.pagination.totalPages,J.pagination.totalRecords),x(O.criticalRequests),P.current.critical(O.pagination.currentPage,O.pagination.totalPages,O.pagination.totalRecords),y(H.deadlines),P.current.deadlines(H.pagination.currentPage,H.pagination.totalPages,H.pagination.totalRecords),t&&B.length>=4){const Y=B[0],re=B[1],K=B[2],ae=B[3];g(Y),b(re),N(K),A(ae.performance),P.current.approver(ae.pagination.currentPage,ae.pagination.totalPages,ae.pagination.totalRecords)}else t||(g([]),b([]),N(null),A([]))}catch(k){console.error("Failed to fetch dashboard data:",k)}finally{D(!1),v(!1)}},[t,s,a,r,n,i]),V=h.useCallback(async(T=1)=>{try{const k=await _t.getRecentActivity(T,10,s);m(k.activities),P.current.activity(k.pagination.currentPage,k.pagination.totalPages,k.pagination.totalRecords)}catch(k){console.error("Failed to fetch recent activities:",k)}},[s]),F=h.useCallback(async(T=1)=>{try{const k=await _t.getCriticalRequests(T,10,s);x(k.criticalRequests),P.current.critical(k.pagination.currentPage,k.pagination.totalPages,k.pagination.totalRecords)}catch(k){console.error("Failed to fetch critical requests:",k)}},[s]),$=h.useCallback(async(T=1)=>{try{const k=await _t.getUpcomingDeadlines(T,10,s);y(k.deadlines),P.current.deadlines(k.pagination.currentPage,k.pagination.totalPages,k.pagination.totalRecords)}catch(k){console.error("Failed to fetch upcoming deadlines:",k)}},[s]),I=h.useCallback(async(T=1)=>{try{const k=await _t.getApproverPerformance(r,T,10,n,i);A(k.performance),P.current.approver(k.pagination.currentPage,k.pagination.totalPages,k.pagination.totalRecords)}catch(k){console.error("Failed to fetch approver performance:",k)}},[r,n,i]);return{kpis:o,recentActivity:d,criticalRequests:p,departmentStats:u,priorityDistribution:f,upcomingDeadlines:j,aiRemarkUtilization:w,approverPerformance:S,loading:_,refreshing:R,fetchDashboardData:C,fetchRecentActivities:V,fetchCriticalRequests:F,fetchUpcomingDeadlines:$,fetchApproverPerformance:I}}const Ua={appName:"Royal Enfield Workflow Management",appVersion:"1.2.0",workingHours:{START_HOUR:9,END_HOUR:18,START_DAY:1,END_DAY:5,TIMEZONE:"Asia/Kolkata"},tat:{thresholds:{warning:50,critical:75,breach:100},testMode:!1},upload:{maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"],maxFilesPerRequest:10},workflow:{maxApprovalLevels:10,maxParticipants:50,maxSpectators:20},workNotes:{maxMessageLength:2e3,maxAttachmentsPerNote:5,enableReactions:!0,enableMentions:!0},features:{ENABLE_AI_CONCLUSION:!0,ENABLE_TEMPLATES:!1,ENABLE_ANALYTICS:!0,ENABLE_EXPORT:!0},ui:{DEFAULT_THEME:"light",DEFAULT_LANGUAGE:"en",DATE_FORMAT:"DD/MM/YYYY",TIME_FORMAT:"12h",CURRENCY:"INR",CURRENCY_SYMBOL:"₹"}};class Uy{constructor(){hl(this,"config",null);hl(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{...Ua,...r,workingHours:{...Ua.workingHours,...r.workingHours},tat:{...Ua.tat,...r.tat},upload:{...Ua.upload,...r.upload},workflow:{...Ua.workflow,...r.workflow},workNotes:{...Ua.workNotes,...r.workNotes},features:{...Ua.features,...r.features},ui:{...Ua.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),Ua}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const By=new Uy;let Vy=9,zy=18,Hy=1,Wy=5,Bm=!1;async function Gy(){if(!Bm)try{const t=await By.getConfig();Vy=t.workingHours.START_HOUR,zy=t.workingHours.END_HOUR,Hy=t.workingHours.START_DAY,Wy=t.workingHours.END_DAY,Bm=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}Gy().catch(()=>{});function Kt(t){if(t==null||t<0||t===0)return"0 hours";const s=8;if(t<1){const o=Math.round(t*60);return o>0?`${o}m`:"0 hours"}const a=Math.floor(t/s),r=Math.floor(t%s),n=Math.round(t%1*60);if(a>0){const o=a===1?"day":"days",c=r===1?"hour":"hours",d=n===1?"min":"m";return n>0?`${a} ${o} ${r} ${c} ${n}${d}`:`${a} ${o} ${r} ${c}`}const i=r===1?"hour":"hours",l=n===1?"min":"m";return n>0?`${r} ${i} ${n}${l}`:`${r} ${i}`}async function Yy(t,s,a){const r=[];let n=1,i=!0;const l=100;for(;i&&n<=l;){const x=await _t.getApproverPerformance(t,n,100,s,a);x.performance&&x.performance.length>0?(r.push(...x.performance),n++,i=n<=x.pagination.totalPages):i=!1}const o=[["Approver Name","Total Approved","TAT Compliance (%)","Avg Response Time","Pending Count"].join(",")];r.forEach(x=>{const u=[`"${(x.approverName||"Unknown").replace(/"/g,'""')}"`,x.totalApproved||0,x.tatCompliancePercent||0,Kt(x.avgResponseHours),x.pendingCount||0];o.push(u.join(","))});const c=o.join(`
|
||
`),d=new Blob([c],{type:"text/csv;charset=utf-8;"}),m=document.createElement("a"),p=URL.createObjectURL(d);m.setAttribute("href",p),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(p)}async function Ky(t,s,a){const r=await _t.getDepartmentStats(t,s,a),n=[["Department","Total Requests","Approved","Rejected","In Progress","Approval Rate (%)"].join(",")];r.forEach(d=>{const m=[`"${(d.department||"Unknown").replace(/"/g,'""')}"`,d.totalRequests||0,d.approved||0,d.rejected||0,d.inProgress||0,d.approvalRate||0];n.push(m.join(","))});const i=n.join(`
|
||
`),l=new Blob([i],{type:"text/csv;charset=utf-8;"}),o=document.createElement("a"),c=URL.createObjectURL(l);o.setAttribute("href",c),o.setAttribute("download",`department-workflow-summary-${new Date().toISOString().split("T")[0]}.csv`),o.style.visibility="hidden",document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(c)}function Qy(){const[t,s]=h.useState(!1),[a,r]=h.useState(!1),n=h.useCallback(async(l,o,c)=>{try{s(!0),await Ky(l,o,c)}catch(d){console.error("Failed to export department stats:",d),alert("Failed to export department statistics. Please try again.")}finally{s(!1)}},[]),i=h.useCallback(async(l,o,c)=>{try{r(!0),await Yy(l,o,c)}catch(d){console.error("Failed to export approver performance:",d),alert("Failed to export approver performance data. Please try again.")}finally{r(!1)}},[]);return{exportingDeptStats:t,exportingApproverPerformance:a,handleExportDepartmentStats:n,handleExportApproverPerformance:i}}function ms({className:t,...s}){return e.jsx(J0,{"data-slot":"switch",className:_e("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(Z0,{"data-slot":"switch-thumb",className:_e("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 te({className:t,...s}){return e.jsx(q0,{"data-slot":"label",className:_e("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 Xy({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(Z,{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(ee,{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($o,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(te,{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(ms,{id:"view-toggle-switch",checked:a,onCheckedChange:r,className:"data-[state=checked]:bg-red-600 data-[state=unchecked]:bg-gray-600 shrink-0 scale-90 sm:scale-100","data-testid":"view-toggle-switch"}),e.jsxs("div",{className:`flex items-center gap-1 sm:gap-1.5 px-1.5 sm:px-2 py-0.5 sm:py-1 rounded transition-all cursor-pointer ${a?"bg-red-600/20 border border-red-600/50":"opacity-60 hover:opacity-80"}`,onClick:()=>r(!0),children:[e.jsx(Vt,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(te,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-red-600":"text-gray-300"}`,children:"Personal"})]})]})}),e.jsx("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 sm:gap-6",children:e.jsxs("div",{className:`text-white w-full lg:w-auto ${t?"pt-12 sm:pt-0":""}`,children:[e.jsx("div",{className:"flex items-center gap-3 sm:gap-4 mb-4 sm:mb-6",children:e.jsxs("div",{className:"pr-2 sm:pr-0",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl lg:text-4xl font-bold mb-1 sm:mb-2 text-white","data-testid":"hero-title",children:["Welcome, ",o,"!"]}),e.jsx("p",{className:"text-sm sm:text-lg lg:text-xl text-gray-200","data-testid":"hero-subtitle",children:s?"Organization-wide analytics and insights":"Track your requests and approvals"})]})}),e.jsx("div",{className:"flex flex-wrap gap-2 sm:gap-4 mt-4 sm:mt-8","data-testid":"quick-actions",children:n.map((c,d)=>e.jsxs(E,{onClick:c.action,className:`${c.color} text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200`,size:window.innerWidth<640?"sm":"lg","data-testid":`quick-action-${c.label.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsx(c.icon,{className:"w-4 h-4 sm:w-5 sm:h-5 mr-1 sm:mr-2"}),c.label]},d))})]})})]})]})}function Be({...t}){return e.jsx(ef,{"data-slot":"select",...t})}function Ve({...t}){return e.jsx(af,{"data-slot":"select-value",...t})}function ze({className:t,size:s="default",children:a,...r}){return e.jsxs(tf,{"data-slot":"select-trigger","data-size":s,className:_e("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(sf,{asChild:!0,children:e.jsx(rn,{className:"size-4 opacity-50"})})]})}function He({className:t,children:s,position:a="popper",...r}){return e.jsx(rf,{children:e.jsxs(nf,{"data-slot":"select-content",className:_e("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",a==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:a,...r,children:[e.jsx(Jy,{}),e.jsx(lf,{className:_e("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(Zy,{})]})})}function Q({className:t,children:s,...a}){return e.jsxs(of,{"data-slot":"select-item",className:_e("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(cf,{children:e.jsx(za,{className:"size-4"})})}),e.jsx(df,{children:s})]})}function Jy({className:t,...s}){return e.jsx(mf,{"data-slot":"select-scroll-up-button",className:_e("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Wi,{className:"size-4"})})}function Zy({className:t,...s}){return e.jsx(uf,{"data-slot":"select-scroll-down-button",className:_e("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(rn,{className:"size-4"})})}function Qt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(xf,{"data-slot":"separator-root",decorative:a,orientation:s,className:_e("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",t),...r})}function ra({...t}){return e.jsx(hf,{"data-slot":"popover",...t})}function na({...t}){return e.jsx(pf,{"data-slot":"popover-trigger",...t})}function ia({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(gf,{children:e.jsx(ff,{"data-slot":"popover-content",align:s,sideOffset:a,className:_e("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 lt=function(){return lt=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},lt.apply(this,arguments)};function qy(t,s){var a={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&s.indexOf(r)<0&&(a[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,r=Object.getOwnPropertySymbols(t);n<r.length;n++)s.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(t,r[n])&&(a[r[n]]=t[r[n]]);return a}function Yh(t,s,a){for(var r=0,n=s.length,i;r<n;r++)(i||!(r in s))&&(i||(i=Array.prototype.slice.call(s,0,r)),i[r]=s[r]);return t.concat(i||Array.prototype.slice.call(s))}function Kn(t){return t.mode==="multiple"}function Qn(t){return t.mode==="range"}function il(t){return t.mode==="single"}var ev={root:"rdp",multiple_months:"rdp-multiple_months",with_weeknumber:"rdp-with_weeknumber",vhidden:"rdp-vhidden",button_reset:"rdp-button_reset",button:"rdp-button",caption:"rdp-caption",caption_start:"rdp-caption_start",caption_end:"rdp-caption_end",caption_between:"rdp-caption_between",caption_label:"rdp-caption_label",caption_dropdowns:"rdp-caption_dropdowns",dropdown:"rdp-dropdown",dropdown_month:"rdp-dropdown_month",dropdown_year:"rdp-dropdown_year",dropdown_icon:"rdp-dropdown_icon",months:"rdp-months",month:"rdp-month",table:"rdp-table",tbody:"rdp-tbody",tfoot:"rdp-tfoot",head:"rdp-head",head_row:"rdp-head_row",head_cell:"rdp-head_cell",nav:"rdp-nav",nav_button:"rdp-nav_button",nav_button_previous:"rdp-nav_button_previous",nav_button_next:"rdp-nav_button_next",nav_icon:"rdp-nav_icon",row:"rdp-row",weeknumber:"rdp-weeknumber",cell:"rdp-cell",day:"rdp-day",day_today:"rdp-day_today",day_outside:"rdp-day_outside",day_selected:"rdp-day_selected",day_disabled:"rdp-day_disabled",day_hidden:"rdp-day_hidden",day_range_start:"rdp-day_range_start",day_range_end:"rdp-day_range_end",day_range_middle:"rdp-day_range_middle"};function tv(t,s){return et(t,"LLLL y",s)}function sv(t,s){return et(t,"d",s)}function av(t,s){return et(t,"LLLL",s)}function rv(t){return"".concat(t)}function nv(t,s){return et(t,"cccccc",s)}function iv(t,s){return et(t,"yyyy",s)}var lv=Object.freeze({__proto__:null,formatCaption:tv,formatDay:sv,formatMonthCaption:av,formatWeekNumber:rv,formatWeekdayName:nv,formatYearCaption:iv}),ov=function(t,s,a){return et(t,"do MMMM (EEEE)",a)},cv=function(){return"Month: "},dv=function(){return"Go to next month"},mv=function(){return"Go to previous month"},uv=function(t,s){return et(t,"cccc",s)},xv=function(t){return"Week n. ".concat(t)},hv=function(){return"Year: "},pv=Object.freeze({__proto__:null,labelDay:ov,labelMonthDropdown:cv,labelNext:dv,labelPrevious:mv,labelWeekNumber:xv,labelWeekday:uv,labelYearDropdown:hv});function gv(){var t="buttons",s=ev,a=Wf,r={},n={},i=1,l={},o=new Date;return{captionLayout:t,classNames:s,formatters:lv,labels:pv,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:l,today:o,mode:"default"}}function fv(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,l=t.toDate;return r?i=aa(r):s&&(i=new Date(s,0,1)),n?l=_o(n):a&&(l=new Date(a,11,31)),{fromDate:i?Cm(i):void 0,toDate:l?Cm(l):void 0}}var Kh=h.createContext(void 0);function bv(t){var s,a=t.initialProps,r=gv(),n=fv(a),i=n.fromDate,l=n.toDate,o=(s=a.captionLayout)!==null&&s!==void 0?s:r.captionLayout;o!=="buttons"&&(!i||!l)&&(o="buttons");var c;(il(a)||Kn(a)||Qn(a))&&(c=a.onSelect);var d=lt(lt(lt({},r),a),{captionLayout:o,classNames:lt(lt({},r.classNames),a.classNames),components:lt({},a.components),formatters:lt(lt({},r.formatters),a.formatters),fromDate:i,labels:lt(lt({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:lt(lt({},r.modifiers),a.modifiers),modifiersClassNames:lt(lt({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:lt(lt({},r.styles),a.styles),toDate:l});return e.jsx(Kh.Provider,{value:d,children:t.children})}function Wt(){var t=h.useContext(Kh);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function Qh(t){var s=Wt(),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 jv(t){return e.jsx("svg",lt({width:"8px",height:"8px",viewBox:"0 0 120 120","data-testid":"iconDropdown"},t,{children:e.jsx("path",{d:"M4.22182541,48.2218254 C8.44222828,44.0014225 15.2388494,43.9273804 19.5496459,47.9996989 L19.7781746,48.2218254 L60,88.443 L100.221825,48.2218254 C104.442228,44.0014225 111.238849,43.9273804 115.549646,47.9996989 L115.778175,48.2218254 C119.998577,52.4422283 120.07262,59.2388494 116.000301,63.5496459 L115.778175,63.7781746 L67.7781746,111.778175 C63.5577717,115.998577 56.7611506,116.07262 52.4503541,112.000301 L52.2218254,111.778175 L4.22182541,63.7781746 C-0.0739418023,59.4824074 -0.0739418023,52.5175926 4.22182541,48.2218254 Z",fill:"currentColor",fillRule:"nonzero"})}))}function Xh(t){var s,a,r=t.onChange,n=t.value,i=t.children,l=t.caption,o=t.className,c=t.style,d=Wt(),m=(a=(s=d.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:jv;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 yv(t){var s,a=Wt(),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 p=[];if(Jf(r,n))for(var x=aa(r),u=r.getMonth();u<=n.getMonth();u++)p.push(gl(x,u));else for(var x=aa(new Date),u=0;u<=11;u++)p.push(gl(x,u));var g=function(b){var j=Number(b.target.value),y=gl(aa(t.displayMonth),j);t.onChange(y)},f=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Xh;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:p.map(function(b){return e.jsx("option",{value:b.getMonth(),children:o(b,{locale:l})},b.getMonth())})})}function vv(t){var s,a=t.displayMonth,r=Wt(),n=r.fromDate,i=r.toDate,l=r.locale,o=r.styles,c=r.classNames,d=r.components,m=r.formatters.formatYearCaption,p=r.labels.labelYearDropdown,x=[];if(!n)return e.jsx(e.Fragment,{});if(!i)return e.jsx(e.Fragment,{});for(var u=n.getFullYear(),g=i.getFullYear(),f=u;f<=g;f++)x.push(Sm(Zf(new Date),f));var b=function(y){var w=Sm(aa(a),Number(y.target.value));t.onChange(w)},j=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Xh;return e.jsx(j,{name:"years","aria-label":p(),className:c.dropdown_year,style:o.dropdown_year,onChange:b,value:a.getFullYear(),caption:m(a,{locale:l}),children:x.map(function(y){return e.jsx("option",{value:y.getFullYear(),children:m(y,{locale:l})},y.getFullYear())})})}function Nv(t,s){var a=h.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function wv(t){var s=t.month,a=t.defaultMonth,r=t.today,n=s||a||r||new Date,i=t.toDate,l=t.fromDate,o=t.numberOfMonths,c=o===void 0?1:o;if(i&&Mn(i,n)<0){var d=-1*(c-1);n=Ia(i,d)}return l&&Mn(n,l)<0&&(n=l),aa(n)}function Cv(){var t=Wt(),s=wv(t),a=Nv(s,t.month),r=a[0],n=a[1],i=function(l){var o;if(!t.disableNavigation){var c=aa(l);n(c),(o=t.onMonthChange)===null||o===void 0||o.call(t,c)}};return[r,i]}function Sv(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=aa(t),i=aa(Ia(n,r)),l=Mn(i,n),o=[],c=0;c<l;c++){var d=Ia(n,c);o.push(d)}return a&&(o=o.reverse()),o}function Av(t,s){if(!s.disableNavigation){var a=s.toDate,r=s.pagedNavigation,n=s.numberOfMonths,i=n===void 0?1:n,l=r?i:1,o=aa(t);if(!a)return Ia(o,l);var c=Mn(a,t);if(!(c<i))return Ia(o,l)}}function Tv(t,s){if(!s.disableNavigation){var a=s.fromDate,r=s.pagedNavigation,n=s.numberOfMonths,i=n===void 0?1:n,l=r?i:1,o=aa(t);if(!a)return Ia(o,-l);var c=Mn(o,a);if(!(c<=0))return Ia(o,-l)}}var Jh=h.createContext(void 0);function kv(t){var s=Wt(),a=Cv(),r=a[0],n=a[1],i=Sv(r,s),l=Av(r,s),o=Tv(r,s),c=function(p){return i.some(function(x){return Mo(p,x)})},d=function(p,x){c(p)||(x&&Jx(p,x)?n(Ia(p,1+s.numberOfMonths*-1)):n(p))},m={currentMonth:r,displayMonths:i,goToMonth:n,goToDate:d,previousMonth:o,nextMonth:l,isDateDisplayed:c};return e.jsx(Jh.Provider,{value:m,children:t.children})}function Xn(){var t=h.useContext(Jh);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function Vm(t){var s,a=Wt(),r=a.classNames,n=a.styles,i=a.components,l=Xn().goToMonth,o=function(m){l(Ia(m,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:Qh,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(yv,{onChange:o,displayMonth:t.displayMonth}),e.jsx(vv,{onChange:o,displayMonth:t.displayMonth})]})}function Rv(t){return e.jsx("svg",lt({width:"16px",height:"16px",viewBox:"0 0 120 120"},t,{children:e.jsx("path",{d:"M69.490332,3.34314575 C72.6145263,0.218951416 77.6798462,0.218951416 80.8040405,3.34314575 C83.8617626,6.40086786 83.9268205,11.3179931 80.9992143,14.4548388 L80.8040405,14.6568542 L35.461,60 L80.8040405,105.343146 C83.8617626,108.400868 83.9268205,113.317993 80.9992143,116.454839 L80.8040405,116.656854 C77.7463184,119.714576 72.8291931,119.779634 69.6923475,116.852028 L69.490332,116.656854 L18.490332,65.6568542 C15.4326099,62.5991321 15.367552,57.6820069 18.2951583,54.5451612 L18.490332,54.3431458 L69.490332,3.34314575 Z",fill:"currentColor",fillRule:"nonzero"})}))}function Dv(t){return e.jsx("svg",lt({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 _i=h.forwardRef(function(t,s){var a=Wt(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var l=i.join(" "),o=lt(lt({},n.button_reset),n.button);return t.style&&Object.assign(o,t.style),e.jsx("button",lt({},t,{ref:s,type:"button",className:l,style:o}))});function Fv(t){var s,a,r=Wt(),n=r.dir,i=r.locale,l=r.classNames,o=r.styles,c=r.labels,d=c.labelPrevious,m=c.labelNext,p=r.components;if(!t.nextMonth&&!t.previousMonth)return e.jsx(e.Fragment,{});var x=d(t.previousMonth,{locale:i}),u=[l.nav_button,l.nav_button_previous].join(" "),g=m(t.nextMonth,{locale:i}),f=[l.nav_button,l.nav_button_next].join(" "),b=(s=p==null?void 0:p.IconRight)!==null&&s!==void 0?s:Dv,j=(a=p==null?void 0:p.IconLeft)!==null&&a!==void 0?a:Rv;return e.jsxs("div",{className:l.nav,style:o.nav,children:[!t.hidePrevious&&e.jsx(_i,{name:"previous-month","aria-label":x,className:u,style:o.nav_button_previous,disabled:!t.previousMonth,onClick:t.onPreviousClick,children:n==="rtl"?e.jsx(b,{className:l.nav_icon,style:o.nav_icon}):e.jsx(j,{className:l.nav_icon,style:o.nav_icon})}),!t.hideNext&&e.jsx(_i,{name:"next-month","aria-label":g,className:f,style:o.nav_button_next,disabled:!t.nextMonth,onClick:t.onNextClick,children:n==="rtl"?e.jsx(j,{className:l.nav_icon,style:o.nav_icon}):e.jsx(b,{className:l.nav_icon,style:o.nav_icon})})]})}function zm(t){var s=Wt().numberOfMonths,a=Xn(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,l=a.displayMonths,o=l.findIndex(function(g){return Mo(t.displayMonth,g)}),c=o===0,d=o===l.length-1,m=s>1&&(c||!d),p=s>1&&(d||!c),x=function(){r&&i(r)},u=function(){n&&i(n)};return e.jsx(Fv,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:p,nextMonth:n,previousMonth:r,onPreviousClick:x,onNextClick:u})}function Iv(t){var s,a=Wt(),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:Qh,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):l==="dropdown"?d=e.jsx(Vm,{displayMonth:t.displayMonth,id:t.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Vm,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(zm,{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(zm,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function Pv(t){var s=Wt(),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 Ev(t,s,a){for(var r=a?Lo(new Date):Oo(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var l=ea(r,i);n.push(l)}return n}function _v(){var t=Wt(),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=Ev(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,p){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})},p)})]})}function Mv(){var t,s=Wt(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:_v;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function Lv(t){var s=Wt(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var qo=h.createContext(void 0);function Ov(t){if(!Kn(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(qo.Provider,{value:s,children:t.children})}return e.jsx($v,{initialProps:t.initialProps,children:t.children})}function $v(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,l=function(d,m,p){var x,u;(x=s.onDayClick)===null||x===void 0||x.call(s,d,m,p);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 b=r?Yh([],r):[];if(m.selected){var j=b.findIndex(function(y){return Qs(d,y)});b.splice(j,1)}else b.push(d);(u=s.onSelect)===null||u===void 0||u.call(s,b,d,m,p)}}},o={disabled:[]};r&&o.disabled.push(function(d){var m=i&&r.length>i-1,p=r.some(function(x){return Qs(x,d)});return!!(m&&!p)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(qo.Provider,{value:c,children:a})}function ec(){var t=h.useContext(qo);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function Uv(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?Qs(n,t)&&Qs(r,t)?void 0:Qs(n,t)?{from:n,to:void 0}:Qs(r,t)?void 0:ro(r,t)?{from:t,to:n}:{from:r,to:t}:n?ro(t,n)?{from:n,to:t}:{from:t,to:n}:r?Jx(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var tc=h.createContext(void 0);function Bv(t){if(!Qn(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(tc.Provider,{value:s,children:t.children})}return e.jsx(Vv,{initialProps:t.initialProps,children:t.children})}function Vv(t){var s=t.initialProps,a=t.children,r=s.selected,n=r||{},i=n.from,l=n.to,o=s.min,c=s.max,d=function(u,g,f){var b,j;(b=s.onDayClick)===null||b===void 0||b.call(s,u,g,f);var y=Uv(u,r);(j=s.onSelect)===null||j===void 0||j.call(s,y,u,g,f)},m={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(m.range_start=[i],l?(m.range_end=[l],Qs(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:pl(i,o-1),before:ea(i,o-1)}),i&&l&&m.disabled.push({after:i,before:ea(i,o-1)}),!i&&l&&m.disabled.push({after:pl(l,o-1),before:ea(l,o-1)})),c){if(i&&!l&&(m.disabled.push({before:ea(i,-c+1)}),m.disabled.push({after:ea(i,c-1)})),i&&l){var p=Va(l,i)+1,x=c-p;m.disabled.push({before:pl(i,x)}),m.disabled.push({after:ea(l,x)})}!i&&l&&(m.disabled.push({before:ea(l,-c+1)}),m.disabled.push({after:ea(l,c-1)}))}return e.jsx(tc.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function sc(){var t=h.useContext(tc);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function gi(t){return Array.isArray(t)?Yh([],t):t!==void 0?[t]:[]}function zv(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=gi(n)}),s}var wa;(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"})(wa||(wa={}));var Hv=wa.Selected,Ba=wa.Disabled,Wv=wa.Hidden,Gv=wa.Today,Al=wa.RangeEnd,Tl=wa.RangeMiddle,kl=wa.RangeStart,Yv=wa.Outside;function Kv(t,s,a){var r,n=(r={},r[Hv]=gi(t.selected),r[Ba]=gi(t.disabled),r[Wv]=gi(t.hidden),r[Gv]=[t.today],r[Al]=[],r[Tl]=[],r[kl]=[],r[Yv]=[],r);return t.fromDate&&n[Ba].push({before:t.fromDate}),t.toDate&&n[Ba].push({after:t.toDate}),Kn(t)?n[Ba]=n[Ba].concat(s.modifiers[Ba]):Qn(t)&&(n[Ba]=n[Ba].concat(a.modifiers[Ba]),n[kl]=a.modifiers[kl],n[Tl]=a.modifiers[Tl],n[Al]=a.modifiers[Al]),n}var Zh=h.createContext(void 0);function Qv(t){var s=Wt(),a=ec(),r=sc(),n=Kv(s,a,r),i=zv(s.modifiers),l=lt(lt({},n),i);return e.jsx(Zh.Provider,{value:l,children:t.children})}function qh(){var t=h.useContext(Zh);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function Xv(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function Jv(t){return!!(t&&typeof t=="object"&&"from"in t)}function Zv(t){return!!(t&&typeof t=="object"&&"after"in t)}function qv(t){return!!(t&&typeof t=="object"&&"before"in t)}function eN(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function tN(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=Va(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var l=Va(t,r)>=0&&Va(n,t)>=0;return l}return n?Qs(n,t):r?Qs(r,t):!1}function sN(t){return eh(t)}function aN(t){return Array.isArray(t)&&t.every(eh)}function rN(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(sN(a))return Qs(t,a);if(aN(a))return a.includes(t);if(Jv(a))return tN(t,a);if(eN(a))return a.dayOfWeek.includes(t.getDay());if(Xv(a)){var r=Va(a.before,t),n=Va(a.after,t),i=r>0,l=n<0,o=ro(a.before,a.after);return o?l&&i:i||l}return Zv(a)?Va(t,a.after)>0:qv(a)?Va(a.before,t)>0:typeof a=="function"?a(t):!1})}function ac(t,s,a){var r=Object.keys(s).reduce(function(i,l){var o=s[l];return rN(t,o)&&i.push(l),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!Mo(t,a)&&(n.outside=!0),n}function nN(t,s){for(var a=aa(t[0]),r=_o(t[t.length-1]),n,i,l=a;l<=r;){var o=ac(l,s),c=!o.disabled&&!o.hidden;if(!c){l=ea(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),n||(n=l),l=ea(l,1)}return i||n}var iN=365;function ep(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,p=n.locale,x={day:ea,week:ao,month:Ia,year:Kf,startOfWeek:function(b){return n.ISOWeek?Lo(b):Oo(b,{locale:p,weekStartsOn:c})},endOfWeek:function(b){return n.ISOWeek?Zx(b):qx(b,{locale:p,weekStartsOn:c})}},u=x[a](t,r==="after"?1:-1);r==="before"&&d?u=Qf([d,u]):r==="after"&&m&&(u=Xf([m,u]));var g=!0;if(i){var f=ac(u,i);g=!f.disabled&&!f.hidden}return g?u:o.count>iN?o.lastFocused:ep(u,{moveBy:a,direction:r,context:n,modifiers:i,retry:lt(lt({},o),{count:o.count+1})})}var tp=h.createContext(void 0);function lN(t){var s=Xn(),a=qh(),r=h.useState(),n=r[0],i=r[1],l=h.useState(),o=l[0],c=l[1],d=nN(s.displayMonths,a),m=n??(o&&s.isDateDisplayed(o))?o:d,p=function(){c(n),i(void 0)},x=function(b){i(b)},u=Wt(),g=function(b,j){if(n){var y=ep(n,{moveBy:b,direction:j,context:u,modifiers:a});Qs(n,y)||(s.goToDate(y,n),x(y))}},f={focusedDay:n,focusTarget:m,blur:p,focus:x,focusDayAfter:function(){return g("day","after")},focusDayBefore:function(){return g("day","before")},focusWeekAfter:function(){return g("week","after")},focusWeekBefore:function(){return g("week","before")},focusMonthBefore:function(){return g("month","before")},focusMonthAfter:function(){return g("month","after")},focusYearBefore:function(){return g("year","before")},focusYearAfter:function(){return g("year","after")},focusStartOfWeek:function(){return g("startOfWeek","before")},focusEndOfWeek:function(){return g("endOfWeek","after")}};return e.jsx(tp.Provider,{value:f,children:t.children})}function rc(){var t=h.useContext(tp);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function oN(t,s){var a=qh(),r=ac(t,a,s);return r}var nc=h.createContext(void 0);function cN(t){if(!il(t.initialProps)){var s={selected:void 0};return e.jsx(nc.Provider,{value:s,children:t.children})}return e.jsx(dN,{initialProps:t.initialProps,children:t.children})}function dN(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(nc.Provider,{value:n,children:a})}function sp(){var t=h.useContext(nc);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function mN(t,s){var a=Wt(),r=sp(),n=ec(),i=sc(),l=rc(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,m=l.focusWeekBefore,p=l.blur,x=l.focus,u=l.focusMonthBefore,g=l.focusMonthAfter,f=l.focusYearBefore,b=l.focusYearAfter,j=l.focusStartOfWeek,y=l.focusEndOfWeek,w=function(T){var k,z,L,M;il(a)?(k=r.onDayClick)===null||k===void 0||k.call(r,t,s,T):Kn(a)?(z=n.onDayClick)===null||z===void 0||z.call(n,t,s,T):Qn(a)?(L=i.onDayClick)===null||L===void 0||L.call(i,t,s,T):(M=a.onDayClick)===null||M===void 0||M.call(a,t,s,T)},N=function(T){var k;x(t),(k=a.onDayFocus)===null||k===void 0||k.call(a,t,s,T)},S=function(T){var k;p(),(k=a.onDayBlur)===null||k===void 0||k.call(a,t,s,T)},A=function(T){var k;(k=a.onDayMouseEnter)===null||k===void 0||k.call(a,t,s,T)},_=function(T){var k;(k=a.onDayMouseLeave)===null||k===void 0||k.call(a,t,s,T)},D=function(T){var k;(k=a.onDayPointerEnter)===null||k===void 0||k.call(a,t,s,T)},R=function(T){var k;(k=a.onDayPointerLeave)===null||k===void 0||k.call(a,t,s,T)},v=function(T){var k;(k=a.onDayTouchCancel)===null||k===void 0||k.call(a,t,s,T)},P=function(T){var k;(k=a.onDayTouchEnd)===null||k===void 0||k.call(a,t,s,T)},C=function(T){var k;(k=a.onDayTouchMove)===null||k===void 0||k.call(a,t,s,T)},V=function(T){var k;(k=a.onDayTouchStart)===null||k===void 0||k.call(a,t,s,T)},F=function(T){var k;(k=a.onDayKeyUp)===null||k===void 0||k.call(a,t,s,T)},$=function(T){var k;switch(T.key){case"ArrowLeft":T.preventDefault(),T.stopPropagation(),a.dir==="rtl"?o():c();break;case"ArrowRight":T.preventDefault(),T.stopPropagation(),a.dir==="rtl"?c():o();break;case"ArrowDown":T.preventDefault(),T.stopPropagation(),d();break;case"ArrowUp":T.preventDefault(),T.stopPropagation(),m();break;case"PageUp":T.preventDefault(),T.stopPropagation(),T.shiftKey?f():u();break;case"PageDown":T.preventDefault(),T.stopPropagation(),T.shiftKey?b():g();break;case"Home":T.preventDefault(),T.stopPropagation(),j();break;case"End":T.preventDefault(),T.stopPropagation(),y();break}(k=a.onDayKeyDown)===null||k===void 0||k.call(a,t,s,T)},I={onClick:w,onFocus:N,onBlur:S,onKeyDown:$,onKeyUp:F,onMouseEnter:A,onMouseLeave:_,onPointerEnter:D,onPointerLeave:R,onTouchCancel:v,onTouchEnd:P,onTouchMove:C,onTouchStart:V};return I}function uN(){var t=Wt(),s=sp(),a=ec(),r=sc(),n=il(t)?s.selected:Kn(t)?a.selected:Qn(t)?r.selected:void 0;return n}function xN(t){return Object.values(wa).includes(t)}function hN(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(xN(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function pN(t,s){var a=lt({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=lt(lt({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function gN(t,s,a){var r,n,i,l=Wt(),o=rc(),c=oN(t,s),d=mN(t,c),m=uN(),p=!!(l.onDayClick||l.mode!=="default");h.useEffect(function(){var A;c.outside||o.focusedDay&&p&&Qs(o.focusedDay,t)&&((A=a.current)===null||A===void 0||A.focus())},[o.focusedDay,t,a,p,c.outside]);var x=hN(l,c).join(" "),u=pN(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:Lv,b=e.jsx(f,{date:t,displayMonth:s,activeModifiers:c}),j={style:u,className:x,children:b,role:"gridcell"},y=o.focusTarget&&Qs(o.focusTarget,t)&&!c.outside,w=o.focusedDay&&Qs(o.focusedDay,t),N=lt(lt(lt({},j),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=w||y?0:-1,r)),d),S={isButton:p,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:N,divProps:j};return S}function fN(t){var s=h.useRef(null),a=gN(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(_i,lt({name:"day",ref:s},a.buttonProps)):e.jsx("div",lt({},a.divProps))}function bN(t){var s=t.number,a=t.dates,r=Wt(),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 p=c(Number(s),{locale:o}),x=function(u){n(s,a,u)};return e.jsx(_i,{name:"week-number","aria-label":p,className:l.weeknumber,style:i.weeknumber,onClick:x,children:m})}function jN(t){var s,a,r=Wt(),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:fN,d=(a=o==null?void 0:o.WeekNumber)!==null&&a!==void 0?a:bN,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(p){return e.jsx("td",{className:i.cell,style:n.cell,role:"presentation",children:e.jsx(c,{displayMonth:t.displayMonth,date:p})},Yf(p))})]})}function Hm(t,s,a){for(var r=a!=null&&a.ISOWeek?Zx(s):qx(s,a),n=a!=null&&a.ISOWeek?Lo(t):Oo(t,a),i=Va(r,n),l=[],o=0;o<=i;o++)l.push(ea(n,o));var c=l.reduce(function(d,m){var p=a!=null&&a.ISOWeek?qf(m):eb(m,a),x=d.find(function(u){return u.weekNumber===p});return x?(x.dates.push(m),d):(d.push({weekNumber:p,dates:[m]}),d)},[]);return c}function yN(t,s){var a=Hm(aa(t),_o(t),s);if(s!=null&&s.useFixedWeeks){var r=Gf(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],l=ao(i,6-r),o=Hm(ao(i,1),l,s);a.push.apply(a,o)}}return a}function vN(t){var s,a,r,n=Wt(),i=n.locale,l=n.classNames,o=n.styles,c=n.hideHead,d=n.fixedWeeks,m=n.components,p=n.weekStartsOn,x=n.firstWeekContainsDate,u=n.ISOWeek,g=yN(t.displayMonth,{useFixedWeeks:!!d,ISOWeek:u,locale:i,weekStartsOn:p,firstWeekContainsDate:x}),f=(s=m==null?void 0:m.Head)!==null&&s!==void 0?s:Mv,b=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:jN,j=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:Pv;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(y){return e.jsx(b,{displayMonth:t.displayMonth,dates:y.dates,weekNumber:y.weekNumber},y.weekNumber)})}),e.jsx(j,{displayMonth:t.displayMonth})]})}function NN(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var wN=NN()?h.useLayoutEffect:h.useEffect,Rl=!1,CN=0;function Wm(){return"react-day-picker-".concat(++CN)}function SN(t){var s,a=t??(Rl?Wm():null),r=h.useState(a),n=r[0],i=r[1];return wN(function(){n===null&&i(Wm())},[]),h.useEffect(function(){Rl===!1&&(Rl=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function AN(t){var s,a,r=Wt(),n=r.dir,i=r.classNames,l=r.styles,o=r.components,c=Xn().displayMonths,d=SN(r.id?"".concat(r.id,"-").concat(t.displayIndex):void 0),m=r.id?"".concat(r.id,"-grid-").concat(t.displayIndex):void 0,p=[i.month],x=l.month,u=t.displayIndex===0,g=t.displayIndex===c.length-1,f=!u&&!g;n==="rtl"&&(s=[u,g],g=s[0],u=s[1]),u&&(p.push(i.caption_start),x=lt(lt({},x),l.caption_start)),g&&(p.push(i.caption_end),x=lt(lt({},x),l.caption_end)),f&&(p.push(i.caption_between),x=lt(lt({},x),l.caption_between));var b=(a=o==null?void 0:o.Caption)!==null&&a!==void 0?a:Iv;return e.jsxs("div",{className:p.join(" "),style:x,children:[e.jsx(b,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(vN,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function TN(t){var s=Wt(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function kN(t){var s,a,r=t.initialProps,n=Wt(),i=rc(),l=Xn(),o=h.useState(!1),c=o[0],d=o[1];h.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 p=lt(lt({},n.styles.root),n.style),x=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,f){var b;return lt(lt({},g),(b={},b[f]=r[f],b))},{}),u=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:TN;return e.jsx("div",lt({className:m.join(" "),style:p,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},x,{children:e.jsx(u,{children:l.displayMonths.map(function(g,f){return e.jsx(AN,{displayIndex:f,displayMonth:g},f)})})}))}function RN(t){var s=t.children,a=qy(t,["children"]);return e.jsx(bv,{initialProps:a,children:e.jsx(kv,{children:e.jsx(cN,{initialProps:a,children:e.jsx(Ov,{initialProps:a,children:e.jsx(Bv,{initialProps:a,children:e.jsx(Qv,{children:e.jsx(lN,{children:s})})})})})})})}function DN(t){return e.jsx(RN,lt({},t,{children:e.jsx(kN,{initialProps:t})}))}function fi({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(DN,{showOutsideDays:a,className:_e("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:_e(Ln({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:_e("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:_e(Ln({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(Uo,{className:_e("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(nn,{className:_e("size-4",n),...i})},...r})}function Xs({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[p,x]=h.useState(!1),u=h.useMemo(()=>{if(t){if(t instanceof Date)return Ur(t)?t:void 0;if(typeof t=="string")try{const j=fl(t,"yyyy-MM-dd",new Date);return Ur(j)?j:void 0}catch{return}}},[t]),g=h.useMemo(()=>{if(a){if(a instanceof Date)return Ur(a)?a:void 0;if(typeof a=="string"){const j=fl(a,"yyyy-MM-dd",new Date);return Ur(j)?j:void 0}}},[a]),f=h.useMemo(()=>{if(r){if(r instanceof Date)return Ur(r)?r:void 0;if(typeof r=="string"){const j=fl(r,"yyyy-MM-dd",new Date);return Ur(j)?j:void 0}}},[r]),b=j=>{if(x(!1),!!s){if(!j){s(null);return}s(et(j,"yyyy-MM-dd"))}};return e.jsx("div",{className:_e("relative",o),children:e.jsxs(ra,{open:p,onOpenChange:x,children:[e.jsx(na,{asChild:!0,children:e.jsxs(E,{id:m,disabled:i,variant:"outline",className:_e("w-full justify-start text-left font-normal",!u&&"text-muted-foreground",c&&"border-destructive ring-destructive/20",l),children:[e.jsx(dt,{className:"mr-2 h-4 w-4"}),u?et(u,d):e.jsx("span",{children:n})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(fi,{mode:"single",selected:u,onSelect:b,disabled:j=>!!(g&&j<g||f&&j>f),initialFocus:!0})})]})})}function FN({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,showCustomDatePicker:n,refreshing:i,onDateRangeChange:l,onCustomStartDateChange:o,onCustomEndDateChange:c,onShowCustomDatePickerChange:d,onApplyCustomDate:m,onResetCustomDates:p,onRefresh:x}){return e.jsx(Z,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(ee,{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(Pa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(se,{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(dt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:s,onValueChange:l,"data-testid":"date-range-select",children:[e.jsx(ze,{className:"w-[140px]",children:e.jsx(Ve,{placeholder:"Select period"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Time"}),e.jsx(Q,{value:"today",children:"Today"}),e.jsx(Q,{value:"week",children:"This Week"}),e.jsx(Q,{value:"month",children:"This Month"}),e.jsx(Q,{value:"last7days",children:"Last 7 Days"}),e.jsx(Q,{value:"last30days",children:"Last 30 Days"}),e.jsx(Q,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(ra,{open:n,onOpenChange:d,children:[e.jsx(na,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(dt,{className:"w-4 h-4"}),a&&r?`${et(a,"MMM d, yyyy")} - ${et(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",sideOffset:8,"data-testid":"custom-date-picker",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Xs,{value:a||null,onChange:u=>{const g=u?new Date(u):void 0;g?(o(g),r&&g>r&&c(g)):o(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Xs,{value:r||null,onChange:u=>{const g=u?new Date(u):void 0;g?(c(g),a&&g<a&&o(g)):c(void 0)},minDate:a||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"end-date-input"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{size:"sm",onClick:m,disabled:!a||!r,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-custom-date",children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:p,"data-testid":"cancel-custom-date",children:"Cancel"})]})]})})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:s,onValueChange:u=>l(u),"data-testid":"date-range-select-user",children:[e.jsx(ze,{className:"w-[140px]",children:e.jsx(Ve,{placeholder:"Select period"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Time"}),e.jsx(Q,{value:"today",children:"Today"}),e.jsx(Q,{value:"week",children:"This Week"}),e.jsx(Q,{value:"month",children:"This Month"}),e.jsx(Q,{value:"last7days",children:"Last 7 Days"}),e.jsx(Q,{value:"last30days",children:"Last 30 Days"}),e.jsx(Q,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(ra,{open:n,onOpenChange:d,children:[e.jsx(na,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(dt,{className:"w-4 h-4"}),a&&r?`${et(a,"MMM d, yyyy")} - ${et(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",sideOffset:8,"data-testid":"custom-date-picker",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"start-date-user",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Xs,{value:a||null,onChange:u=>{const g=u?new Date(u):void 0;g?(o(g),r&&g>r&&c(g)):o(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"start-date-input-user"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"end-date-user",className:"text-sm font-medium",children:"End Date"}),e.jsx(Xs,{value:r||null,onChange:u=>{const g=u?new Date(u):void 0;g?(c(g),a&&g<a&&o(g)):c(void 0)},minDate:a||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"end-date-input-user"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{size:"sm",onClick:m,disabled:!a||!r,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-custom-date-user",children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:p,"data-testid":"cancel-custom-date-user",children:"Cancel"})]})]})})]})]}),e.jsx(Qt,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(E,{variant:"outline",size:"sm",onClick:x,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx($t,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function Tr({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 p=x=>{x.stopPropagation(),d==null||d()};return e.jsxs(Z,{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(oe,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(me,{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:p,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(Er,{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(ee,{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 ks({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 Zs({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(bf,{"data-slot":"progress",className:_e("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(jf,{"data-slot":"progress-indicator",className:_e("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function IN({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(Tr,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Ie,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(ks,{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(ks,{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(ks,{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(ks,{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(ks,{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(Tr,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:es,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(Zs,{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(ks,{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(ks,{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(Tr,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?Kt(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:st,iconBgColor:"bg-purple-50",iconColor:"text-purple-600",subtitle:`≈ ${(t==null?void 0:t.tatEfficiency.avgCycleTimeDays.toFixed(1))||0} working days`,testId:"kpi-avg-cycle-time",onClick:()=>i(l()),children:e.jsx("div",{className:"flex flex-col flex-1",children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(ks,{label:"Express",value:(()=>{const o=s.find(d=>d.priority==="express"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Kt(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(ks,{label:"Standard",value:(()=>{const o=s.find(d=>d.priority==="standard"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Kt(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:o=>{o.stopPropagation(),i({...l(),priority:"standard"})}})]})})})]})}function PN({kpis:t,criticalRequests:s,dateRange:a,customStartDate:r,customEndDate:n,onKPIClick:i,onNavigate:l,userId:o,userDisplayName:c}){const d=()=>({dateRange:a,startDate:r,endDate:n}),m=()=>{if(!o)return;const x=new URLSearchParams;x.set("approverId",o),x.set("approverName",c||"My Performance"),x.set("dateRange",a),a==="custom"&&r&&n&&(x.set("startDate",r.toISOString()),x.set("endDate",n.toISOString())),l==null||l(`/approver-performance?${x.toString()}`)},p=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(Tr,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Ie,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(ks,{label:"Approved",value:(t==null?void 0:t.requestVolume.approvedRequests)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-user-approved",onClick:x=>{x.stopPropagation(),i({...d(),status:"approved"})}}),e.jsx(ks,{label:"Pending",value:(t==null?void 0:t.requestVolume.openRequests)||0,bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-user-pending",onClick:x=>{x.stopPropagation(),i({...d(),status:"pending"})}}),e.jsx(ks,{label:"Paused",value:(t==null?void 0:t.requestVolume.pausedRequests)||0,bgColor:"bg-amber-50",textColor:"text-amber-600",testId:"stat-user-paused",onClick:x=>{x.stopPropagation(),i({...d(),status:"paused"})}}),e.jsx(ks,{label:"Rejected",value:(t==null?void 0:t.requestVolume.rejectedRequests)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-user-rejected",onClick:x=>{x.stopPropagation(),i({...d(),status:"rejected"})}}),e.jsx(ks,{label:"Closed",value:(t==null?void 0:t.requestVolume.closedRequests)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-user-closed",onClick:x=>{x.stopPropagation(),i({...d(),status:"closed"})}})]})}),e.jsx(Tr,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:st,iconBgColor:"bg-orange-50",iconColor:"text-orange-600",subtitle:"at current level",testId:"kpi-pending-actions",onClick:()=>i({...d(),targetPage:"open-requests",status:"pending"}),onJustifyClick:m,showJustifyButton:!!o,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(ks,{label:"Approved Today",value:(t==null?void 0:t.approverLoad.completedToday)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-today",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}}),e.jsx(ks,{label:"This Week",value:(t==null?void 0:t.approverLoad.completedThisWeek)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-week",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}})]})}),e.jsx(Tr,{title:"Critical Alerts",value:s.length,icon:Sa,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(ks,{label:"Breached",value:s.filter(x=>x.breachCount>0).length,bgColor:"bg-orange-50",textColor:"text-red-600",testId:"stat-user-breached",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests"})}}),e.jsx(ks,{label:"Warning",value:s.filter(x=>x.breachCount===0).length,bgColor:"bg-yellow-50",textColor:"text-orange-600",testId:"stat-user-warning",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests"})}})]})}),e.jsx(Tr,{title:"Success Rate",value:`${p.toFixed(0)}%`,icon:Le,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(Zs,{value:p,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 EN=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)))},_N=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 MN({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=EN(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(lb,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(se,{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(se,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:_N(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(Zs,{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 LN(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 ON(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function $N(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 UN(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 ap(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 BN({isAdmin:t,breachedRequests:s,pagination:a,onPageChange:r,onNavigate:n}){return e.jsxs(Z,{className:"lg:col-span-2 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden h-full","data-testid":"critical-alerts-section",children:[e.jsx(oe,{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(Sa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(ve,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(se,{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(ee,{className:`overflow-y-auto flex-1 p-4 ${a.totalPages>1?"max-h-[calc(100%-140px)]":"max-h-[calc(100%-80px)]"}`,children:e.jsx("div",{className:"space-y-3 sm:space-y-4",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-critical-alerts",children:[e.jsx(Le,{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(MN,{alert:i,onNavigate:l=>n==null?void 0:n(`request/${l}`),testId:"dashboard-critical-alert"},i.requestId))})}),a.totalPages>1&&s.length>0&&e.jsx("div",{className:"border-t bg-gray-50 px-4 py-2 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Page ",a.page," of ",a.totalPages," (",a.totalRecords," total)"]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>r(a.page-1),disabled:a.page===1,className:"h-7 w-7 p-0","data-testid":"critical-pagination-prev",children:e.jsx(fs,{className:"h-3 w-3 rotate-180"})}),ap(a.page,a.totalPages,3).map(i=>e.jsx(E,{variant:i===a.page?"default":"outline",size:"sm",onClick:()=>r(i),className:`h-7 w-7 p-0 text-xs ${i===a.page?"bg-red-600 text-white hover:bg-red-700":""}`,"data-testid":`critical-pagination-page-${i}`,children:i},i)),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>r(a.page+1),disabled:a.page===a.totalPages,className:"h-7 w-7 p-0","data-testid":"critical-pagination-next",children:e.jsx(fs,{className:"h-3 w-3"})})]})]})})]})}const VN=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"}},zN=t=>{const s=new Date,a=new Date(t),r=tb(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=sb(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=ab(s,a);return`${i} day${i>1?"s":""} ago`},HN=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()},WN=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(Le,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-green-600"}):s.includes("reject")?e.jsx(ts,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-red-600"}):s.includes("comment")?e.jsx(zs,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(Sa,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(Ie,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(Gi,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(Ot,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function GN({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(ls,{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(nl,{src:""}),e.jsx(os,{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:WN(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(se,{variant:"outline",className:`text-xs ${VN(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:HN(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:zN(t.timestamp)})]})]}),e.jsx(fs,{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 YN({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:l,currentUserId:o,currentUserDisplayName:c,currentUserEmail:d}){return e.jsxs(Z,{className:"lg:col-span-1 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden h-full","data-testid":"recent-activity-section",children:[e.jsx(oe,{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(Ot,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(me,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(ve,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(E,{variant:"ghost",size:"sm",className:"text-blue-600 hover:bg-blue-50 font-medium flex-shrink-0 h-8 sm:h-9 px-2 sm:px-3 sm:min-w-[100px]",onClick:i,disabled:r,"data-testid":"activity-refresh-button",children:[e.jsx($t,{className:`w-3 h-3 sm:w-4 sm:h-4 ${r?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline ml-2 sm:w-[60px] sm:text-center",children:r?"Refreshing...":"Refresh"})]})]})}),e.jsx(ee,{className:`overflow-y-auto flex-1 p-4 ${a.totalPages>1?"max-h-[calc(100%-140px)]":"max-h-[calc(100%-80px)]"}`,children:e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-recent-activity",children:[e.jsx(Ot,{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(GN,{activity:m,currentUserId:o,currentUserDisplayName:c,currentUserEmail:d,onNavigate:p=>l==null?void 0:l(`request/${p}`),testId:"dashboard-activity"},m.activityId))})}),a.totalPages>1&&s.length>0&&e.jsx("div",{className:"border-t bg-gray-50 px-4 py-2 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Page ",a.page," of ",a.totalPages," (",a.totalRecords," total)"]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>n(a.page-1),disabled:a.page===1,className:"h-7 w-7 p-0","data-testid":"activity-pagination-prev",children:e.jsx(fs,{className:"h-3 w-3 rotate-180"})}),ap(a.page,a.totalPages,3).map(m=>e.jsx(E,{variant:m===a.page?"default":"outline",size:"sm",onClick:()=>n(m),className:`h-7 w-7 p-0 text-xs ${m===a.page?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`activity-pagination-page-${m}`,children:m},m)),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>n(a.page+1),disabled:a.page===a.totalPages,className:"h-7 w-7 p-0","data-testid":"activity-pagination-next",children:e.jsx(fs,{className:"h-3 w-3"})})]})]})})]})}function KN({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(Z,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(oe,{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(Ot,{className:"h-4 w-4 text-blue-600"})}),e.jsx(me,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(ee,{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(Qt,{}),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(p=>p.breachCount>0).length})]})]})]})})]}),e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(oe,{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(zs,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(me,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(ee,{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(Qt,{}),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(Z,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(oe,{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(no,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(ve,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2 self-start sm:self-auto",onClick:()=>d(n,i,l),disabled:o,"data-testid":"export-dept-stats-button",children:[e.jsx(kt,{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(ee,{children:e.jsx(Qr,{width:"100%",height:400,children:e.jsxs(so,{data:r,children:[e.jsx(Ai,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Ti,{dataKey:"department",stroke:"#999",tick:p=>{const{x,y:u,payload:g}=p;return e.jsx("g",{transform:`translate(${x},${u})`,children:e.jsx("text",{x:0,y:0,dy:16,textAnchor:"middle",fill:"#999",fontSize:11,className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{c({...m(),department:g.value})},children:g.value})})}}),e.jsx(ki,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Xr,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Ri,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(ka,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(ka,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(ka,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function QN({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(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(oe,{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(zs,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(me,{className:"text-sm",children:"My Activity"})]})}),e.jsx(ee,{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(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(oe,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(st,{className:"h-4 w-4 text-purple-600"})}),e.jsx(me,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(ee,{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:Kt(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(Qt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function XN({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(oe,{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(es,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(ve,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(ee,{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: ",Kt(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Qr,{width:"100%",height:300,children:e.jsxs(Yx,{children:[e.jsx(Kx,{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),p=r+d*Math.sin(-n*c);return e.jsx("text",{x:m,y:p,fill:"#1f2937",textAnchor:m>a?"start":"end",dominantBaseline:"central",className:"text-sm font-semibold pointer-events-none",children:`${l}: ${o}%`})},outerRadius:90,fill:"#8884d8",dataKey:"value",onClick:a=>{a&&a.priority&&s&&s(`requests?priority=${a.priority}`)},className:"cursor-pointer",children:t.map((a,r)=>e.jsx(Qx,{fill:a.priority==="express"?"#ef4444":"#3b82f6",className:"cursor-pointer"},`cell-${r}`))}),e.jsx(Xr,{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 _r({currentPage:t,totalPages:s,itemsPerPage:a,totalRecords:r,onPageChange:n,loading:i=!1,itemLabel:l="items",testIdPrefix:o="pagination"}){const c=()=>{const p=[];let u=Math.max(1,t-Math.floor(2.5)),g=Math.min(s,u+5-1);g-u<4&&(u=Math.max(1,g-5+1));for(let f=u;f<=g;f++)p.push(f);return p},d=r>0?(t-1)*a+1:0,m=Math.min(t*a,r);return s<=1?e.jsx(Z,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(ee,{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(Z,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-sm sm:text-base font-medium text-gray-700","data-testid":`${o}-info`,children:["Showing ",d," to ",m," of ",r," ",l]}),e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${o}-controls`,children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>n(t-1),disabled:t===1,className:"h-8 w-8 p-0","data-testid":`${o}-prev-btn`,"aria-label":"Previous page",children:e.jsx(fs,{className:"h-4 w-4 rotate-180"})}),t>3&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>n(1),className:"h-8 w-8 p-0","data-testid":`${o}-page-1`,children:"1"}),e.jsx("span",{className:"text-muted-foreground","data-testid":`${o}-ellipsis-start`,children:"..."})]}),c().map(p=>e.jsx(E,{variant:p===t?"default":"outline",size:"sm",onClick:()=>n(p),className:`h-8 w-8 p-0 ${p===t?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`${o}-page-${p}`,"aria-current":p===t?"page":void 0,children:p},p)),t<s-2&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground","data-testid":`${o}-ellipsis-end`,children:"..."}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${o}-page-${s}`,children:s})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>n(t+1),disabled:t===s,className:"h-8 w-8 p-0","data-testid":`${o}-next-btn`,"aria-label":"Next page",children:e.jsx(fs,{className:"h-4 w-4"})})]})]})})})}function JN(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${et(s,"MMM d, yyyy")} - ${et(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 ZN(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${et(s,"MMM d, yyyy")} to ${et(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 qN({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(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(oe,{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(ts,{className:"h-5 w-5 sm:h-6 sm:w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs(ve,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",ZN(a,r,n)]})]})]}),e.jsxs(se,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[s.totalRecords," ",s.totalRecords===1?"Breach":"Breaches"]})]})}),e.jsxs(ee,{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 p=d.breachTime||0;return e.jsxs("tr",{className:"border-b border-gray-100 hover:bg-gray-50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-blue-600 cursor-pointer hover:underline",onClick:()=>o==null?void 0:o(`request/${d.requestNumber}`),"data-testid":`breach-request-${d.requestNumber}`,children:d.requestNumber}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-900 w-[250px]",children:e.jsx("p",{className:"break-words leading-relaxed",children:d.title})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{d.department&&d.department!=="Unknown"&&l({...c(),department:d.department})},children:d.department||"Unknown"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.approverId?e.jsx("span",{className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{if(o){const x=new URLSearchParams;x.set("approver",d.approverId),x.set("approverType","current"),x.set("slaCompliance","breached"),a&&x.set("dateRange",a),r&&x.set("startDate",r.toISOString()),n&&x.set("endDate",n.toISOString()),o(`requests?${x.toString()}`)}},title:"Click to view all requests for this approver",children:d.approver||"N/A"}):d.approver||"N/A"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.currentLevel&&d.totalLevels?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/",d.totalLevels]}):d.currentLevel?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/—"]}):e.jsx("span",{className:"text-gray-400",children:"—"})}),e.jsx("td",{className:"py-3 px-4 w-[140px]",children:e.jsx("span",{className:"bg-red-500 text-white px-2 py-1 rounded text-xs font-medium whitespace-nowrap",children:$N(p)})}),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(se,{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(_r,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function ew({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(oe,{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(dt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(me,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(ve,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(ee,{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(se,{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(se,{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(Zs,{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:[Kt(c)," elapsed"]}),e.jsxs("span",{children:[Kt(d)," left"]})]})]})]},l)})}),e.jsx("div",{className:"mt-4",children:e.jsx(_r,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function tw({aiRemarkUtilization:t}){return t?e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(oe,{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(Yi,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(ve,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(ee,{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(Qr,{width:"100%",height:250,children:e.jsxs(zf,{data:t.monthlyTrends,children:[e.jsx(Ai,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Ti,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(ki,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Xr,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Ri,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(wm,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(wm,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function sw({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(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(oe,{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(Zt,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(ve,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(E,{onClick:()=>c(a,r,n),disabled:l||i,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-approver-performance-button",children:l?e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"space-y-3",children:t.map((m,p)=>{const x=m.tatCompliancePercent;return e.jsxs("div",{className:"border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{const u=new URLSearchParams;u.set("approverId",m.approverId),u.set("approverName",m.approverName),u.set("dateRange",a),a==="custom"&&r&&n&&(u.set("startDate",r.toISOString()),u.set("endDate",n.toISOString())),d==null||d(`/approver-performance?${u.toString()}`)},"data-testid":`approver-item-${m.approverId}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-orange-500 rounded-full flex items-center justify-center text-white font-semibold text-sm flex-shrink-0",children:p+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 ${UN(x)} flex-shrink-0`,children:[x,"% TAT"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"Avg Response"}),e.jsx("div",{className:"text-sm font-medium text-gray-900",children:Kt(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})})]})]})]},p)})}),e.jsx("div",{className:"mt-4",children:e.jsx(_r,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:o,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function aw(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 rw(t,s,a,r){const n=[];return r||n.push({label:"New Request",icon:Ie,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"}),n.push({label:"View Pending",icon:st,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:lr,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:Ot,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),n}function nw({onNavigate:t,onNewRequest:s}){const{user:a}=cs(),r=Yn(),n=dn(Ue=>Ue.dashboard.viewAsUser),i=h.useMemo(()=>al(a),[a]),l=i&&!n,o=h.useCallback(Ue=>{r(_y(Ue))},[r]),c=My(),{dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:x,handleDateRangeChange:u,handleApplyCustomDate:g,resetCustomDates:f,setCustomStartDate:b,setCustomEndDate:j,setShowCustomDatePicker:y}=c,w=Ly(),{activity:N,critical:S,deadlines:A,approver:_,updateActivityPagination:D,updateCriticalPagination:R,updateDeadlinesPagination:v,updateApproverPagination:P,handleActivityPageChange:C,handleCriticalPageChange:V,handleDeadlinesPageChange:F,handleApproverPageChange:$}=w,I=$y({isAdmin:l,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:p,onPaginationUpdate:{activity:D,critical:R,deadlines:v,approver:P}}),{kpis:T,recentActivity:k,criticalRequests:z,departmentStats:L,priorityDistribution:M,upcomingDeadlines:U,aiRemarkUtilization:B,approverPerformance:W,loading:J,refreshing:O,fetchDashboardData:H,fetchRecentActivities:Y,fetchCriticalRequests:re,fetchUpcomingDeadlines:K,fetchApproverPerformance:ae}=I,Ne=Qy(),{exportingDeptStats:Se,exportingApproverPerformance:Ge,handleExportDepartmentStats:Je,handleExportApproverPerformance:Pe}=Ne,Oe=h.useMemo(()=>LN(z),[z]),ie=h.useMemo(()=>ON(U),[U]),pe=h.useCallback(()=>{H(!0)},[d,m,p,H]),we=h.useCallback(()=>{g(()=>{m&&p&&H(!1)})},[m,p,g,H]),Ae=h.useCallback(Ue=>{C(Ue,Y)},[C,Y]),ne=h.useCallback(Ue=>{V(Ue,re)},[V,re]),q=h.useCallback(Ue=>{F(Ue,K)},[F,K]),de=h.useCallback(Ue=>{$(Ue,()=>ae(Ue))},[$,ae]);h.useEffect(()=>{d==="custom"?m&&p&&H(!1):H(!1)},[d,m,p,n]);const Ye=h.useMemo(()=>{try{const Ue=at.getUserData();return(Ue==null?void 0:Ue.jobTitle)==="Dealer"}catch(Ue){return console.error("[Dashboard] Error checking dealer status:",Ue),!1}},[]),fe=h.useMemo(()=>rw(i,s,t,Ye),[i,s,t,Ye]),ye=h.useCallback(Ue=>{const nt=aw(Ue);t==null||t(nt)},[t]);return J?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx($t,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto p-3 sm:p-4","data-testid":"dashboard",children:[e.jsx(Xy,{isAdmin:i,effectiveIsAdmin:l,viewAsUser:n,onToggleView:o,quickActions:fe,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(FN,{isAdmin:l,dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:x,refreshing:O,onDateRangeChange:u,onCustomStartDateChange:b,onCustomEndDateChange:j,onShowCustomDatePickerChange:y,onApplyCustomDate:we,onResetCustomDates:f,onRefresh:pe}),l?e.jsx(IN,{kpis:T,priorityDistribution:M,dateRange:d,customStartDate:m,customEndDate:p,onKPIClick:ye}):e.jsx(PN,{kpis:T,criticalRequests:z,dateRange:d,customStartDate:m,customEndDate:p,onKPIClick:ye,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(BN,{isAdmin:l,breachedRequests:Oe,pagination:S,onPageChange:ne,onNavigate:t}),e.jsx(YN,{isAdmin:l,recentActivity:k,pagination:N,refreshing:O,onPageChange:Ae,onRefresh:pe,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),l&&T&&e.jsx(KN,{kpis:T,upcomingDeadlines:U,criticalRequests:z,departmentStats:L,dateRange:d,customStartDate:m,customEndDate:p,exportingDeptStats:Se,onKPIClick:ye,onExportDepartmentStats:Je}),!l&&T&&e.jsx(QN,{kpis:T}),l&&M.length>0&&e.jsx(XN,{priorityDistribution:M,onNavigate:t}),l&&Oe.length>0&&e.jsx(qN,{breachedRequests:Oe,pagination:S,dateRange:d,customStartDate:m,customEndDate:p,onPageChange:ne,onKPIClick:ye,onNavigate:t}),ie.length>0&&e.jsx(ew,{isAdmin:l,upcomingDeadlines:ie,pagination:A,onPageChange:q,onNavigate:t}),l&&B&&e.jsx(tw,{aiRemarkUtilization:B}),l&&W.length>0&&e.jsx(sw,{approverPerformance:W,pagination:_,dateRange:d,customStartDate:m,customEndDate:p,loading:J,exportingApproverPerformance:Ge,onPageChange:de,onExport:Pe,onNavigate:t})]})}const iw={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},rp=on({name:"openRequests",initialState:iw,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},setForm16FinancialYear:(t,s)=>{t.form16FinancialYear=s.payload},setForm16Quarter:(t,s)=>{t.form16Quarter=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.form16FinancialYear="",t.form16Quarter="",t.currentPage=1}}}),{setSearchTerm:lw,setStatusFilter:ow,setPriorityFilter:cw,setTemplateTypeFilter:dw,setForm16FinancialYear:mw,setForm16Quarter:uw,setSortBy:xw,setSortOrder:hw,setCurrentPage:pw,clearFilters:gw}=rp.actions;function fw(){const t=Yn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,form16FinancialYear:i,form16Quarter:l,sortBy:o,sortOrder:c,currentPage:d}=dn(S=>S.openRequests),m=h.useCallback(S=>t(lw(S)),[t]),p=h.useCallback(S=>t(ow(S)),[t]),x=h.useCallback(S=>t(cw(S)),[t]),u=h.useCallback(S=>t(dw(S)),[t]),g=h.useCallback(S=>t(mw(S)),[t]),f=h.useCallback(S=>t(uw(S)),[t]),b=h.useCallback(S=>t(xw(S)),[t]),j=h.useCallback(S=>t(hw(S)),[t]),y=h.useCallback(S=>t(pw(S)),[t]),w=h.useCallback(()=>t(gw()),[t]),N=[s,r!=="all"?r:null,a!=="all"?a:null,n!=="all"?n:null,n==="FORM_16"&&i?"fy":null,n==="FORM_16"&&l?"q":null].filter(Boolean).length;return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,form16FinancialYear:i,form16Quarter:l,sortBy:o,sortOrder:c,currentPage:d,setSearchTerm:m,setStatusFilter:p,setPriorityFilter:x,setTemplateTypeFilter:u,setForm16FinancialYear:g,setForm16Quarter:f,setSortBy:b,setSortOrder:j,setCurrentPage:y,clearFilters:w,activeFiltersCount:N}}function Dl(){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 bw(t){var o;const s=t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",a=Array.from({length:t.approverCount||1},(c,d)=>{const m=d,p=t.approvers[m]||{},x=m+1,u=p.tat??"";let g=0;typeof u=="number"&&(g=p.tatType==="days"?u*24:u);const f=p.email||"",b=p.name&&p.name.trim()||f.split("@")[0]||`Approver ${x}`;return{levelNumber:x,levelName:`Level ${x}`,approverId:Dl(),approverEmail:f,approverName:b,tatHours:g>0?g:24,isFinalApprover:x===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:Dl(),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:Dl(),userEmail:c.email,userName:c.name||c.email.split("@")[0]||"CC",participantType:"CONSULTATION",canComment:!1,canViewDocuments:!0,canDownloadDocuments:!1,notificationEnabled:!0}))],n={templateType:t.templateType,title:t.title,description:t.description,priority:s,approvalLevels:a,participants:r.length?r:void 0,isDraft:t.isDraft},i=await je.post("/workflows",n),l=((o=i.data)==null?void 0:o.data)||i.data;return{id:l.id||l.workflowId||""}}async function ic(t,s,a="SUPPORTING"){var o;const r={templateType:t.templateType,title:t.title,description:t.description,priority:t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",isDraft:t.isDraft,approvers:Array.from({length:t.approverCount||1},(c,d)=>{const m=t.approvers[d]||{},p=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:p,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 jw(t={}){var j;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,department:d,initiator:m,approver:p,slaCompliance:x,dateRange:u,startDate:g,endDate:f}=t,b=await je.get("/workflows",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,department:d,initiator:m,approver:p,slaCompliance:x,dateRange:u,startDate:g,endDate:f}});return((j=b.data)==null?void 0:j.data)||b.data}async function yw(t={}){var y,w,N,S,A;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,department:d,initiator:m,approver:p,approverType:x,slaCompliance:u,dateRange:g,startDate:f,endDate:b}=t,j=await je.get("/workflows/participant-requests",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,department:d,initiator:m,approver:p,approverType:x,slaCompliance:u,dateRange:g,startDate:f,endDate:b}});return{data:((w=(y=j.data)==null?void 0:y.data)==null?void 0:w.data)||((N=j.data)==null?void 0:N.data)||[],pagination:((A=(S=j.data)==null?void 0:S.data)==null?void 0:A.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function vw(t={}){var g,f,b,j,y;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:l,initiator:o,approver:c,slaCompliance:d,dateRange:m,startDate:p,endDate:x}=t,u=await je.get("/workflows/my",{params:{page:s,limit:a,search:r,status:n,priority:i,department:l,initiator:o,approver:c,slaCompliance:d,dateRange:m,startDate:p,endDate:x}});return{data:((f=(g=u.data)==null?void 0:g.data)==null?void 0:f.data)||((b=u.data)==null?void 0:b.data)||[],pagination:((y=(j=u.data)==null?void 0:j.data)==null?void 0:y.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Nw(t={}){var u,g,f,b,j;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:c,dateRange:d,startDate:m,endDate:p}=t,x=await je.get("/workflows/my-initiated",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:c,dateRange:d,startDate:m,endDate:p}});return{data:((g=(u=x.data)==null?void 0:u.data)==null?void 0:g.data)||((f=x.data)==null?void 0:f.data)||[],pagination:((j=(b=x.data)==null?void 0:b.data)==null?void 0:j.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function ww(t={}){var x,u,g,f,b;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,sortBy:d,sortOrder:m}=t,p=await je.get("/workflows/open-for-me",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,sortBy:d,sortOrder:m}});return{data:((u=(x=p.data)==null?void 0:x.data)==null?void 0:u.data)||((g=p.data)==null?void 0:g.data)||[],pagination:((b=(f=p.data)==null?void 0:f.data)==null?void 0:b.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Cw(t={}){var x,u,g,f,b;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,sortBy:d,sortOrder:m}=t,p=await je.get("/workflows/closed-by-me",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,sortBy:d,sortOrder:m}});return{data:((u=(x=p.data)==null?void 0:x.data)==null?void 0:u.data)||((g=p.data)==null?void 0:g.data)||[],pagination:((b=(f=p.data)==null?void 0:f.data)==null?void 0:b.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Ps(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 Zr(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 np(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 ip(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 Sw(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 lp(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 Aw(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 Tw(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 kw(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 Gm(t){var a;const s=await je.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function Rw(t){return`https://reflow-uat.royalenfield.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function mn(t){return`https://reflow-uat.royalenfield.com/api/v1/workflows/documents/${t}/preview`}function op(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 Ms(t){const a=`https://reflow-uat.royalenfield.com/api/v1/workflows/documents/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const p=await i.text();throw new Error(`Download failed: ${i.status} - ${p}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=op(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 Ym(t){const a=`https://reflow-uat.royalenfield.com/api/v1/workflows/work-notes/attachments/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const p=await i.text();throw new Error(`Download failed: ${i.status} - ${p}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=op(c),m=document.createElement("a");m.href=o,m.download=d,document.body.appendChild(m),m.click(),document.body.removeChild(m),window.URL.revokeObjectURL(o)}catch(n){throw console.error("[Download] Failed:",n),n}}const Ws={createWorkflowFromForm:bw,createWorkflowMultipart:ic,listWorkflows:jw,listParticipantRequests:yw,listMyWorkflows:vw,listMyInitiatedWorkflows:Nw,listOpenForMe:ww,listClosedByMe:Cw,submitWorkflow:cp,getWorkflowDetails:Ps,getWorkNotes:Zr,createWorkNoteMultipart:np,handleInitiatorAction:dp};async function cp(t){var a;const s=await je.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function Dw(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 Fw(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 Tn(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 Nr(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 Iw(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 dp(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 Pw(t){var a;return((a=(await je.get(`/workflows/${t}/history`)).data)==null?void 0:a.data)||[]}function gs(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 mp(t){return gs(t,{includeTime:!1,format:"short"})}function Ca(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"),p=o>=12?"PM":"AM";return`${r} ${i} ${l}, ${c}:${d}:${m} ${p}`}return`${r} ${i} ${l}`}catch(a){return console.error("Error formatting date:",a),String(t)}}function Ew(t){return t?t.jobTitle==="Dealer"||t.jobTitle==="DEALER":!1}function lc(t){return Ew(t)?"DEALER":"STANDARD"}function Ra(t){if(!t)return"";let s=t.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"");return s=s.replace(/\s+on\w+\s*=\s*(?:'[^']*'|"[^"]*"|[^\s>]+)/gi,""),s=s.replace(/(href|src)\s*=\s*(?:'javascript:[^']*'|"javascript:[^"]*"|javascript:[^\s>]+)/gi,'$1="#"'),s=s.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),s=s.replace(/<(meta|link|iframe|object|embed|applet)[^>]*>/gi,""),s=s.replace(/<a[^>]*>([\s\S]*?)<\/a>/gi,"$1"),s}const ii=[{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 Jn({value:t,onChange:s,placeholder:a="Enter text...",className:r,minHeight:n="120px",...i}){const l=h.useRef(null),[o,c]=h.useState(!1),[d,m]=h.useState(new Set),[p,x]=h.useState(!1),[u,g]=h.useState(null),[f,b]=h.useState("#FFEB3B"),[j,y]=h.useState(!1),[w,N]=h.useState(null),[S,A]=h.useState("#000000");h.useEffect(()=>{l.current&&l.current.innerHTML!==t&&l.current.innerHTML!==t&&(l.current.innerHTML=Ra(t||""))},[t]);const _=h.useCallback(T=>(T=T.replace(/<!--[\s\S]*?-->/g,""),T=T.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),T=T.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),T=T.replace(/<meta[^>]*>/gi,""),T=T.replace(/\s*class="Mso[^"]*"/gi,""),T=T.replace(/\s*class="mso[^"]*"/gi,""),T=T.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),T=T.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),T=T.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),T=T.replace(/<\/?o:p[^>]*>/gi,""),T=T.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),T=T.replace(/<v:[^>]*\/>/gi,""),T=T.replace(/<p[^>]*>\s*<\/p>/gi,""),T=T.replace(/<div[^>]*>\s*<\/div>/gi,""),T=T.replace(/\s+/g," "),T=T.trim(),T),[]),D=h.useCallback(T=>{T.preventDefault();const k=T.clipboardData;let z=k.getData("text/html")||k.getData("text/plain");if((z.includes("<!--")||z.includes("<style")||z.includes("MsoNormal"))&&(z=_(z)),!l.current)return;const L=window.getSelection();if(!L||L.rangeCount===0)return;const M=L.getRangeAt(0);M.deleteContents();const U=document.createElement("div");U.innerHTML=z;const B=document.createDocumentFragment();Array.from(U.childNodes).forEach(W=>{if(W.nodeType===Node.ELEMENT_NODE){const J=W;if(J.tagName==="UL"||J.tagName==="OL"){const O=J.cloneNode(!0);O.removeAttribute("style"),O.removeAttribute("class"),O.querySelectorAll("li").forEach(H=>{H.removeAttribute("style"),H.removeAttribute("class");const Y=H.textContent||"";Y.trim()&&(H.textContent=Y.trim())}),B.appendChild(O)}else if(J.tagName==="TABLE"){const O=J.cloneNode(!0);O.removeAttribute("style"),O.removeAttribute("class"),O.querySelectorAll("td, th").forEach(Y=>{Y.removeAttribute("style"),Y.removeAttribute("class")});const H=document.createElement("div");H.className="table-wrapper",H.appendChild(O),B.appendChild(H)}else if(J.tagName==="P"||J.tagName==="DIV"){const O=document.createElement("p"),Y=J.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");O.innerHTML=Y,O.removeAttribute("style"),O.removeAttribute("class"),B.appendChild(O)}else if(J.tagName==="BR")B.appendChild(J.cloneNode(!0));else{const O=J.textContent||"";if(O.trim()){const H=document.createElement("p");H.textContent=O.trim(),B.appendChild(H)}}}else if(W.nodeType===Node.TEXT_NODE){const J=W.textContent||"";if(J.trim()){const O=document.createElement("p");O.textContent=J.trim(),B.appendChild(O)}}}),B.childNodes.length===0&&k.getData("text/plain").split(`
|
||
`).forEach(O=>{if(O.trim()){const H=document.createElement("p");H.textContent=O.trim(),B.appendChild(H)}else B.appendChild(document.createElement("br"))}),M.insertNode(B),M.collapse(!1),L.removeAllRanges(),L.addRange(M),l.current&&s(Ra(l.current.innerHTML))},[s,_]),R=h.useCallback(()=>{if(!l.current||!o)return;const T=new Set,k=window.getSelection();if(k&&k.rangeCount>0){const L=k.getRangeAt(0).commonAncestorContainer;let M=null;for(L.nodeType===Node.TEXT_NODE?M=L.parentElement:M=L;M&&M!==l.current;){const U=M.tagName.toLowerCase();(U==="strong"||U==="b")&&T.add("bold"),(U==="em"||U==="i")&&T.add("italic"),U==="u"&&T.add("underline"),U==="h1"&&T.add("h1"),U==="h2"&&T.add("h2"),U==="h3"&&T.add("h3"),U==="ul"&&T.add("ul"),U==="ol"&&T.add("ol");const B=window.getComputedStyle(M);B.textAlign==="center"&&T.add("center"),B.textAlign==="right"&&T.add("right"),B.textAlign==="left"&&T.add("left");const W=Y=>{if(Y.startsWith("#"))return Y.toUpperCase();const re=Y.match(/\d+/g);if(!re||re.length<3)return null;const K=re[0],ae=re[1],Ne=re[2];if(!K||!ae||!Ne)return null;const Se=parseInt(K).toString(16).padStart(2,"0"),Ge=parseInt(ae).toString(16).padStart(2,"0"),Je=parseInt(Ne).toString(16).padStart(2,"0");return`#${Se}${Ge}${Je}`.toUpperCase()},J=B.backgroundColor;if(J&&J!=="rgba(0, 0, 0, 0)"&&J!=="transparent"&&J!=="rgb(255, 255, 255)"&&J!=="#ffffff"&&J!=="#FFFFFF"){T.add("highlight");const Y=W(J);if(Y){const re=ii.find(K=>K.value==="transparent"?!1:K.value.toUpperCase()===Y);g(re?re.value:Y)}}else T.has("highlight")||g(null);const O=B.color,H=W(O);if(O&&H&&O!=="rgba(0, 0, 0, 0)"&&H!=="#000000"){T.add("textColor");const Y=ii.find(re=>re.value==="transparent"?!1:re.value.toUpperCase()===H);N(Y?Y.value:H)}else T.has("textColor")||N(H==="#000000"||!H?"#000000":null);M=M.parentElement}}m(T)},[o]),v=h.useCallback((T,k)=>{if(!l.current)return;o||l.current.focus();const z=window.getSelection();if(!z||z.rangeCount===0){l.current.focus();return}document.execCommand(T,!1,k),l.current&&s(Ra(l.current.innerHTML)),setTimeout(R,10)},[o,s,R]),P=h.useCallback(T=>{if(!l.current)return;o||l.current.focus();const k=window.getSelection();if(!k||k.rangeCount===0){l.current.focus();return}let z=!1;if(k.rangeCount>0){const U=k.getRangeAt(0).commonAncestorContainer;let B=null;for(U.nodeType===Node.TEXT_NODE?B=U.parentElement:B=U;B&&B!==l.current;){const J=window.getComputedStyle(B).backgroundColor;if(J&&J!=="rgba(0, 0, 0, 0)"&&J!=="transparent"&&J!=="rgb(255, 255, 255)"&&J!=="#ffffff"&&J!=="#FFFFFF"){const H=(Y=>{if(Y.startsWith("#"))return Y.toUpperCase();const re=Y.match(/\d+/g);if(!re||re.length<3)return null;const K=re[0],ae=re[1],Ne=re[2];if(!K||!ae||!Ne)return null;const Se=parseInt(K).toString(16).padStart(2,"0"),Ge=parseInt(ae).toString(16).padStart(2,"0"),Je=parseInt(Ne).toString(16).padStart(2,"0");return`#${Se}${Ge}${Je}`.toUpperCase()})(J);if(H&&H===T.toUpperCase()){z=!0;break}}B=B.parentElement}}if(T==="transparent"||z){const M=k.getRangeAt(0);if(M.collapsed)document.execCommand("removeFormat",!1);else{const U=M.extractContents(),B=document.createDocumentFragment(),W=J=>{if(J.nodeType===Node.TEXT_NODE)return J.cloneNode(!0);if(J.nodeType===Node.ELEMENT_NODE){const O=J,H=document.createElement(O.tagName.toLowerCase());return Array.from(O.attributes).forEach(Y=>{Y.name!=="style"&&Y.name!=="class"&&H.setAttribute(Y.name,Y.value)}),Array.from(O.childNodes).forEach(Y=>{const re=W(Y);re&&H.appendChild(re)}),O.style.backgroundColor&&(H.style.backgroundColor=""),H}return null};Array.from(U.childNodes).forEach(J=>{const O=W(J);O&&B.appendChild(O)}),M.insertNode(B),document.execCommand("removeFormat",!1)}g(null),b("#FFEB3B")}else if(k.rangeCount>0&&!k.getRangeAt(0).collapsed)document.execCommand("backColor",!1,T),g(T),T!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(T)&&b(T);else return;const L=window.getSelection();L&&L.removeAllRanges(),l.current&&s(Ra(l.current.innerHTML)),x(!1),setTimeout(()=>{l.current&&l.current.focus(),R()},50)},[o,s,R]),C=h.useCallback(T=>{if(!l.current)return;o||l.current.focus();const k=window.getSelection();if(!k||k.rangeCount===0){l.current.focus();return}let z=!1;if(k.rangeCount>0){const M=k.getRangeAt(0).commonAncestorContainer;let U=null;for(M.nodeType===Node.TEXT_NODE?U=M.parentElement:U=M;U&&U!==l.current;){const W=window.getComputedStyle(U).color;if(W){const O=(H=>{if(H.startsWith("#"))return H.toUpperCase();const Y=H.match(/\d+/g);if(!Y||Y.length<3)return null;const re=Y[0],K=Y[1],ae=Y[2];if(!re||!K||!ae)return null;const Ne=parseInt(re).toString(16).padStart(2,"0"),Se=parseInt(K).toString(16).padStart(2,"0"),Ge=parseInt(ae).toString(16).padStart(2,"0");return`#${Ne}${Se}${Ge}`.toUpperCase()})(W);if(T==="#000000"){if(O==="#000000"||!O){z=!0;break}}else if(O&&O===T.toUpperCase()){z=!0;break}}U=U.parentElement}}if(T==="transparent"||T==="default"||z){if(T==="#000000"&&z){y(!1);return}document.execCommand("removeFormat",!1),N(null),A("#000000")}else document.execCommand("foreColor",!1,T),N(T),T!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(T)&&A(T);l.current&&s(Ra(l.current.innerHTML)),y(!1),setTimeout(R,10)},[o,s,R]),V=h.useCallback(()=>{l.current&&s(Ra(l.current.innerHTML)),R()},[s,R]),F=h.useCallback(T=>{if(T.ctrlKey&&T.key==="b"){T.preventDefault(),v("bold");return}if(T.ctrlKey&&T.key==="i"){T.preventDefault(),v("italic");return}if(T.ctrlKey&&T.key==="u"){T.preventDefault(),v("underline");return}},[v]),$=h.useCallback(()=>{c(!0)},[]),I=h.useCallback(()=>{c(!1),l.current&&s(Ra(l.current.innerHTML))},[s]);return h.useEffect(()=>{if(!o)return;const T=()=>{R()};return document.addEventListener("selectionchange",T),()=>{document.removeEventListener("selectionchange",T)}},[o,R]),e.jsxs("div",{className:"relative border border-gray-300 rounded-md bg-white",children:[e.jsxs("div",{className:"flex items-center gap-1 p-2 border-b border-gray-200 bg-gray-50 rounded-t-md flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>v("bold"),title:"Bold (Ctrl+B)",children:e.jsx(ob,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>v("italic"),title:"Italic (Ctrl+I)",children:e.jsx(cb,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>v("underline"),title:"Underline (Ctrl+U)",children:e.jsx(db,{className:"h-4 w-4"})}),e.jsxs(ra,{open:p,onOpenChange:x,children:[e.jsx(na,{asChild:!0,children:e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("highlight")&&"bg-blue-100 text-blue-700"),title:"Text Highlight",children:e.jsx(mb,{className:"h-4 w-4"})})}),e.jsx(ia,{className:"w-auto p-2",align:"start",onPointerDownOutside:T=>{T.target.closest("[data-popover-content]")&&T.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:T=>T.stopPropagation(),children:[e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:T=>{T.stopPropagation(),x(!1)},title:"Close",children:e.jsx(bt,{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:ii.map(T=>{const k=u===T.value,z=T.value==="transparent";return e.jsxs("button",{type:"button",onClick:L=>{L.preventDefault(),L.stopPropagation(),P(k&&!z?"transparent":T.value)},className:_e("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",T.class,k&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",z&&"border-gray-400 bg-white",!z&&!k&&"border-gray-300"),title:k&&!z?`${T.name} (Click to remove)`:T.name,style:z?{}:{backgroundColor:T.value},children:[z&&e.jsx("span",{className:"text-[10px] text-gray-600 font-bold",children:"×"}),k&&!z&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]},T.value)})}),u&&u!=="transparent"&&e.jsx("div",{className:"mb-2",children:e.jsx(E,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:T=>{T.stopPropagation(),P("transparent")},title:"Remove highlight color",children:"Remove Highlight"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u&&u!=="transparent"?u:f,onChange:T=>{const k=T.target.value;b(k);const z=window.getSelection();z&&z.rangeCount>0&&!z.getRangeAt(0).collapsed&&P(k)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom color"}),e.jsx("input",{type:"text",value:u&&u!=="transparent"?u:f,onChange:T=>{T.stopPropagation();const k=T.target.value;b(k)},onKeyDown:T=>{if(T.stopPropagation(),T.key==="Enter"){T.preventDefault();const k=T.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(k)&&P(k)}},onPaste:T=>{T.stopPropagation();const k=T.clipboardData.getData("text").trim();T.preventDefault(),setTimeout(()=>{if(/^#[0-9A-Fa-f]{6}$/i.test(k)){b(k);const z=window.getSelection();z&&z.rangeCount>0&&!z.getRangeAt(0).collapsed&&P(k)}else{const z=k.match(/^([0-9A-Fa-f]{6})$/);if(z){const L=`#${z[1]}`;b(L);const M=window.getSelection();M&&M.rangeCount>0&&!M.getRangeAt(0).collapsed&&P(L)}}},0)},onClick:T=>{T.stopPropagation()},onFocus:T=>{T.stopPropagation(),T.target.select()},onBlur:T=>{const k=T.target.value.trim();if(/^#[0-9A-Fa-f]{6}$/i.test(k)){const z=window.getSelection();z&&z.rangeCount>0&&!z.getRangeAt(0).collapsed&&P(k)}else b(k===""?u||"#FFEB3B":k)},placeholder:"#FFEB3B",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply). Supports copy-paste.",autoComplete:"off",spellCheck:"false"}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{const T=f.trim();/^#[0-9A-Fa-f]{6}$/i.test(T)?P(T):b(u||"#FFEB3B")},title:"Apply custom color",children:"Apply"})]})]})]})})]}),e.jsxs(ra,{open:j,onOpenChange:y,children:[e.jsx(na,{asChild:!0,children:e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("textColor")&&"bg-blue-100 text-blue-700"),title:"Text Color",children:e.jsx(ub,{className:"h-4 w-4"})})}),e.jsx(ia,{className:"w-auto p-2",align:"start",onPointerDownOutside:T=>{T.target.closest("[data-popover-content]")&&T.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:T=>T.stopPropagation(),children:[e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:T=>{T.stopPropagation(),y(!1)},title:"Close",children:e.jsx(bt,{className:"h-4 w-4 text-gray-500"})}),e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-2 pr-6",children:"Text Color"}),e.jsxs("div",{className:"grid grid-cols-6 gap-1.5 pr-1 mb-2",children:[e.jsxs("button",{type:"button",onClick:T=>{T.preventDefault(),T.stopPropagation(),w==="#000000"||!w&&!d.has("textColor")||C("#000000")},className:_e("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center bg-black",(w==="#000000"||!w&&!d.has("textColor"))&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",w!=="#000000"&&(w||d.has("textColor"))&&"border-gray-300"),title:"Default (Black)",children:[e.jsx("span",{className:"text-[10px] text-white font-bold",children:"A"}),(w==="#000000"||!w&&!d.has("textColor"))&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]}),ii.filter(T=>T.value!=="transparent").map(T=>{const k=w===T.value;return e.jsxs("button",{type:"button",onClick:z=>{z.preventDefault(),z.stopPropagation(),C(k?"#000000":T.value)},className:_e("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center relative",k&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",!k&&"border-gray-300"),title:k?`${T.name} (Click to reset to default)`:T.name,style:{color:T.value,borderColor:k?"#2563eb":T.value},children:[e.jsx("span",{className:"text-xs font-bold",children:"A"}),k&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]},`text-${T.value}`)})]}),w&&w!=="#000000"&&e.jsx("div",{className:"mb-2",children:e.jsx(E,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:T=>{T.stopPropagation(),C("#000000")},title:"Reset to default black",children:"Reset to Default"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:w||S,onChange:T=>{const k=T.target.value;A(k),C(k)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom text color"}),e.jsx("input",{type:"text",value:w||S,onChange:T=>{const k=T.target.value;A(k)},onKeyDown:T=>{if(T.key==="Enter"){T.preventDefault();const k=T.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(k)&&C(k)}},onBlur:T=>{const k=T.target.value;/^#[0-9A-Fa-f]{6}$/.test(k)?C(k):k===""&&A(w||"#000000")},placeholder:"#000000",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply)"}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>C(S),title:"Apply custom text color",children:"Apply"})]})]})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>v("formatBlock","<h1>"),title:"Heading 1",children:e.jsx(xb,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>v("formatBlock","<h2>"),title:"Heading 2",children:e.jsx(hb,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>v("formatBlock","<h3>"),title:"Heading 3",children:e.jsx(pb,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>v("insertUnorderedList"),title:"Bullet List",children:e.jsx(th,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>v("insertOrderedList"),title:"Numbered List",children:e.jsx(gb,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>v("justifyLeft"),title:"Align Left",children:e.jsx(sh,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>v("justifyCenter"),title:"Align Center",children:e.jsx(fb,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:_e("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>v("justifyRight"),title:"Align Right",children:e.jsx(bb,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:l,contentEditable:!0,onPaste:D,onInput:V,onFocus:$,onBlur:I,onKeyDown:F,onMouseUp:R,onKeyUp:R,"data-placeholder":a,className:_e("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 Es({content:t,className:s}){const a=h.useMemo(()=>{if(!t)return"";let r=t;const n=/<table[^>]*>[\s\S]*?<\/table>/gi;return r=r.replace(n,i=>i.includes("table-wrapper")?i:`<div class="table-wrapper">${i}</div>`),Ra(r)},[t]);return t?e.jsx("div",{className:_e("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 up={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(zi,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",l="second",o="minute",c="hour",d="day",m="week",p="month",x="quarter",u="year",g="date",f="Invalid Date",b=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,j=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,y={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(F){var $=["th","st","nd","rd"],I=F%100;return"["+F+($[(I-20)%10]||$[I]||$[0])+"]"}},w=function(F,$,I){var T=String(F);return!T||T.length>=$?F:""+Array($+1-T.length).join(I)+F},N={s:w,z:function(F){var $=-F.utcOffset(),I=Math.abs($),T=Math.floor(I/60),k=I%60;return($<=0?"+":"-")+w(T,2,"0")+":"+w(k,2,"0")},m:function F($,I){if($.date()<I.date())return-F(I,$);var T=12*(I.year()-$.year())+(I.month()-$.month()),k=$.clone().add(T,p),z=I-k<0,L=$.clone().add(T+(z?-1:1),p);return+(-(T+(I-k)/(z?k-L:L-k))||0)},a:function(F){return F<0?Math.ceil(F)||0:Math.floor(F)},p:function(F){return{M:p,y:u,w:m,d,D:g,h:c,m:o,s:l,ms:i,Q:x}[F]||String(F||"").toLowerCase().replace(/s$/,"")},u:function(F){return F===void 0}},S="en",A={};A[S]=y;var _="$isDayjsObject",D=function(F){return F instanceof C||!(!F||!F[_])},R=function F($,I,T){var k;if(!$)return S;if(typeof $=="string"){var z=$.toLowerCase();A[z]&&(k=z),I&&(A[z]=I,k=z);var L=$.split("-");if(!k&&L.length>1)return F(L[0])}else{var M=$.name;A[M]=$,k=M}return!T&&k&&(S=k),k||!T&&S},v=function(F,$){if(D(F))return F.clone();var I=typeof $=="object"?$:{};return I.date=F,I.args=arguments,new C(I)},P=N;P.l=R,P.i=D,P.w=function(F,$){return v(F,{locale:$.$L,utc:$.$u,x:$.$x,$offset:$.$offset})};var C=function(){function F(I){this.$L=R(I.locale,null,!0),this.parse(I),this.$x=this.$x||I.x||{},this[_]=!0}var $=F.prototype;return $.parse=function(I){this.$d=function(T){var k=T.date,z=T.utc;if(k===null)return new Date(NaN);if(P.u(k))return new Date;if(k instanceof Date)return new Date(k);if(typeof k=="string"&&!/Z$/i.test(k)){var L=k.match(b);if(L){var M=L[2]-1||0,U=(L[7]||"0").substring(0,3);return z?new Date(Date.UTC(L[1],M,L[3]||1,L[4]||0,L[5]||0,L[6]||0,U)):new Date(L[1],M,L[3]||1,L[4]||0,L[5]||0,L[6]||0,U)}}return new Date(k)}(I),this.init()},$.init=function(){var I=this.$d;this.$y=I.getFullYear(),this.$M=I.getMonth(),this.$D=I.getDate(),this.$W=I.getDay(),this.$H=I.getHours(),this.$m=I.getMinutes(),this.$s=I.getSeconds(),this.$ms=I.getMilliseconds()},$.$utils=function(){return P},$.isValid=function(){return this.$d.toString()!==f},$.isSame=function(I,T){var k=v(I);return this.startOf(T)<=k&&k<=this.endOf(T)},$.isAfter=function(I,T){return v(I)<this.startOf(T)},$.isBefore=function(I,T){return this.endOf(T)<v(I)},$.$g=function(I,T,k){return P.u(I)?this[T]:this.set(k,I)},$.unix=function(){return Math.floor(this.valueOf()/1e3)},$.valueOf=function(){return this.$d.getTime()},$.startOf=function(I,T){var k=this,z=!!P.u(T)||T,L=P.p(I),M=function(re,K){var ae=P.w(k.$u?Date.UTC(k.$y,K,re):new Date(k.$y,K,re),k);return z?ae:ae.endOf(d)},U=function(re,K){return P.w(k.toDate()[re].apply(k.toDate("s"),(z?[0,0,0,0]:[23,59,59,999]).slice(K)),k)},B=this.$W,W=this.$M,J=this.$D,O="set"+(this.$u?"UTC":"");switch(L){case u:return z?M(1,0):M(31,11);case p:return z?M(1,W):M(0,W+1);case m:var H=this.$locale().weekStart||0,Y=(B<H?B+7:B)-H;return M(z?J-Y:J+(6-Y),W);case d:case g:return U(O+"Hours",0);case c:return U(O+"Minutes",1);case o:return U(O+"Seconds",2);case l:return U(O+"Milliseconds",3);default:return this.clone()}},$.endOf=function(I){return this.startOf(I,!1)},$.$set=function(I,T){var k,z=P.p(I),L="set"+(this.$u?"UTC":""),M=(k={},k[d]=L+"Date",k[g]=L+"Date",k[p]=L+"Month",k[u]=L+"FullYear",k[c]=L+"Hours",k[o]=L+"Minutes",k[l]=L+"Seconds",k[i]=L+"Milliseconds",k)[z],U=z===d?this.$D+(T-this.$W):T;if(z===p||z===u){var B=this.clone().set(g,1);B.$d[M](U),B.init(),this.$d=B.set(g,Math.min(this.$D,B.daysInMonth())).$d}else M&&this.$d[M](U);return this.init(),this},$.set=function(I,T){return this.clone().$set(I,T)},$.get=function(I){return this[P.p(I)]()},$.add=function(I,T){var k,z=this;I=Number(I);var L=P.p(T),M=function(W){var J=v(z);return P.w(J.date(J.date()+Math.round(W*I)),z)};if(L===p)return this.set(p,this.$M+I);if(L===u)return this.set(u,this.$y+I);if(L===d)return M(1);if(L===m)return M(7);var U=(k={},k[o]=r,k[c]=n,k[l]=a,k)[L]||1,B=this.$d.getTime()+I*U;return P.w(B,this)},$.subtract=function(I,T){return this.add(-1*I,T)},$.format=function(I){var T=this,k=this.$locale();if(!this.isValid())return k.invalidDate||f;var z=I||"YYYY-MM-DDTHH:mm:ssZ",L=P.z(this),M=this.$H,U=this.$m,B=this.$M,W=k.weekdays,J=k.months,O=k.meridiem,H=function(K,ae,Ne,Se){return K&&(K[ae]||K(T,z))||Ne[ae].slice(0,Se)},Y=function(K){return P.s(M%12||12,K,"0")},re=O||function(K,ae,Ne){var Se=K<12?"AM":"PM";return Ne?Se.toLowerCase():Se};return z.replace(j,function(K,ae){return ae||function(Ne){switch(Ne){case"YY":return String(T.$y).slice(-2);case"YYYY":return P.s(T.$y,4,"0");case"M":return B+1;case"MM":return P.s(B+1,2,"0");case"MMM":return H(k.monthsShort,B,J,3);case"MMMM":return H(J,B);case"D":return T.$D;case"DD":return P.s(T.$D,2,"0");case"d":return String(T.$W);case"dd":return H(k.weekdaysMin,T.$W,W,2);case"ddd":return H(k.weekdaysShort,T.$W,W,3);case"dddd":return W[T.$W];case"H":return String(M);case"HH":return P.s(M,2,"0");case"h":return Y(1);case"hh":return Y(2);case"a":return re(M,U,!0);case"A":return re(M,U,!1);case"m":return String(U);case"mm":return P.s(U,2,"0");case"s":return String(T.$s);case"ss":return P.s(T.$s,2,"0");case"SSS":return P.s(T.$ms,3,"0");case"Z":return L}return null}(K)||L.replace(":","")})},$.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},$.diff=function(I,T,k){var z,L=this,M=P.p(T),U=v(I),B=(U.utcOffset()-this.utcOffset())*r,W=this-U,J=function(){return P.m(L,U)};switch(M){case u:z=J()/12;break;case p:z=J();break;case x:z=J()/3;break;case m:z=(W-B)/6048e5;break;case d:z=(W-B)/864e5;break;case c:z=W/n;break;case o:z=W/r;break;case l:z=W/a;break;default:z=W}return k?z:P.a(z)},$.daysInMonth=function(){return this.endOf(p).$D},$.$locale=function(){return A[this.$L]},$.locale=function(I,T){if(!I)return this.$L;var k=this.clone(),z=R(I,T,!0);return z&&(k.$L=z),k},$.clone=function(){return P.w(this.$d,this)},$.toDate=function(){return new Date(this.valueOf())},$.toJSON=function(){return this.isValid()?this.toISOString():null},$.toISOString=function(){return this.$d.toISOString()},$.toString=function(){return this.$d.toUTCString()},F}(),V=C.prototype;return v.prototype=V,[["$ms",i],["$s",l],["$m",o],["$H",c],["$W",d],["$M",p],["$y",u],["$D",g]].forEach(function(F){V[F[1]]=function($){return this.$g($,F[0],F[1])}}),v.extend=function(F,$){return F.$i||(F($,C,v),F.$i=!0),v},v.locale=R,v.isDayjs=D,v.unix=function(F){return v(1e3*F)},v.en=A[S],v.Ls=A,v.p={},v})})(up);var _w=up.exports;const as=Hi(_w);var xp={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(zi,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,p,x){return i.fromToBase(d,m,p,x)}n.en.relativeTime=l,i.fromToBase=function(d,m,p,x,u){for(var g,f,b,j=p.$locale().relativeTime||l,y=a.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],w=y.length,N=0;N<w;N+=1){var S=y[N];S.d&&(g=x?n(d).diff(p,S.d,!0):p.diff(d,S.d,!0));var A=(a.rounding||Math.round)(Math.abs(g));if(b=g>0,A<=S.r||!S.r){A<=1&&N>0&&(S=y[N-1]);var _=j[S.l];u&&(A=u(""+A)),f=typeof _=="string"?_.replace("%d",A):_(A,m,S.l,b);break}}if(m)return f;var D=b?j.future:j.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)}}})})(xp);var Mw=xp.exports;const Lw=Hi(Mw);as.extend(Lw);function Ow({request:t,isInitiator:s,needsClosure:a,conclusionRemark:r,setConclusionRemark:n,conclusionLoading:i,conclusionSubmitting:l,aiGenerated:o,handleGenerateConclusion:c,handleFinalizeConclusion:d,onPause:m,onResume:p,onRetrigger:x,currentUserIsApprover:u=!1,pausedByUserId:g,currentUserId:f,generationAttempts:b=0,generationFailed:j=!1,maxAttemptsReached:y=!1}){var z,L,M,U,B,W,J,O;const{user:w}=cs(),N=t==null?void 0:t.pauseInfo,S=(N==null?void 0:N.isPaused)||!1,A=(z=N==null?void 0:N.pausedBy)==null?void 0:z.userId,_=(w==null?void 0:w.userId)||"",D=S&&p&&(u||s),R=S&&s&&A&&A!==_&&x,P=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16"||((t==null?void 0:t.title)||"").toLowerCase().includes("form 16")||((t==null?void 0:t.description)||"").toLowerCase().includes("form 16a"),C=t==null?void 0:t.form16Submission,V=P&&(C!=null&&C.ocrExtractedData)&&typeof C.ocrExtractedData=="object"?C.ocrExtractedData:null,F=P&&V&&Object.keys(V).length>0?V:P&&C?{deductorName:C.deductorName,deductor_name:C.deductorName,tanNumber:C.tanNumber,tan_number:C.tanNumber,financialYear:C.financialYear,financial_year:C.financialYear,quarter:C.quarter,form16aNumber:C.form16aNumber,form16a_number:C.form16aNumber,totalAmount:C.totalAmount,total_amount:C.totalAmount,tdsAmount:C.tdsAmount,tds_amount:C.tdsAmount,acknowledgementNumber:C.acknowledgementNumber,acknowledgement_number:C.acknowledgementNumber,dateOfIssue:C.dateOfIssue,date_of_issue:C.dateOfIssue,deduceeName:C.deduceeName,deducee_name:C.deduceeName,deduceePan:C.deduceePan,deducee_pan:C.deduceePan}:null,$=H=>H!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(Number(H)):"–",I=H=>H==null||H===""?"–":String(H),T=H=>{const Y=(H||"").toLowerCase();return Y==="completed"?"bg-emerald-100 text-emerald-800 border-emerald-200":Y==="duplicate"||Y==="duplicate submission"?"bg-amber-100 text-amber-800 border-amber-200":Y==="balance mismatch"||Y==="failed"?"bg-red-100 text-red-800 border-red-200":Y==="resubmission needed"||Y==="partial extracted data"?"bg-amber-50 text-amber-700 border-amber-200":"bg-gray-100 text-gray-700 border-gray-200"},k=H=>{const Y=((H==null?void 0:H.displayStatus)||"").toLowerCase(),re=((H==null?void 0:H.validationNotes)||"").toLowerCase();return Y==="balance mismatch"||Y==="failed"&&(re.includes("mismatch")||re.includes("26as")||re.includes("value"))?"Failed - data mismatch with 26AS, submit the form 16 with correct data":Y==="duplicate"||Y==="duplicate submission"?"Duplicate. A submission for this FY and quarter already exists.":Y==="resubmission needed"?(H==null?void 0:H.validationNotes)||"Resubmission needed. Please submit again with correct data.":Y==="failed"?(H==null?void 0:H.validationNotes)||"Submission failed. Please resubmit.":null};return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[P&&(C==null?void 0:C.displayStatus)!=null&&e.jsxs("div",{className:"flex flex-col gap-2","data-testid":"form16-submission-status",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Submission status:"}),e.jsx(se,{variant:"outline",className:T(C.displayStatus),children:C.displayStatus})]}),k(C)&&e.jsx("p",{className:`text-sm ${(C.displayStatus||"").toLowerCase()==="balance mismatch"||(C.displayStatus||"").toLowerCase()==="failed"?"text-red-700 font-medium":"text-gray-600"}`,children:k(C)})]}),P&&e.jsxs(Z,{"data-testid":"form16-certificate-details",className:"border-emerald-200 bg-emerald-50/30",children:[e.jsxs(oe,{className:"pb-3 sm:pb-4",children:[e.jsxs(me,{className:"flex items-center gap-2 text-sm sm:text-base text-emerald-800",children:[e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-emerald-600"}),"Form 16A Certificate Details"]}),e.jsx(ve,{className:"text-xs text-gray-600",children:"TDS Certificate as per Income Tax Act, 1961"})]}),e.jsx(ee,{className:"space-y-4",children:C?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Certificate Number"}),e.jsx("p",{className:"text-sm font-medium",children:C.form16aNumber||"–"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Financial Year"}),e.jsx("p",{className:"text-sm font-medium",children:C.financialYear||"–"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Acknowledgement Number"}),e.jsx("p",{className:"text-sm font-medium",children:C.acknowledgementNumber||"–"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Date of Issue"}),e.jsx("p",{className:"text-sm font-medium",children:C.dateOfIssue||"–"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Quarter"}),e.jsx("p",{className:"text-sm font-medium",children:C.quarter?`${C.quarter} (${C.financialYear||""})`:"–"})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2",children:"Deductor Details"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Name:"})," ",C.deductorName||"–"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TAN:"})," ",C.tanNumber||"–"]})]})]}),(C.deduceeName||C.deduceePan)&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2",children:"Deductee Details (Dealer)"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm",children:[C.deduceeName&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Name:"})," ",C.deduceeName]}),C.deduceePan&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"PAN:"})," ",C.deduceePan]}),C.deduceeAddress&&e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("span",{className:"text-gray-500",children:"Address:"})," ",C.deduceeAddress]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2",children:"TDS Payment Details"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm",children:[C.section&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Section:"})," ",C.section]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Amount Paid:"})," ",$(C.totalAmount??C.amountPaid)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TDS Deducted:"})," ",$(C.tdsAmount)]}),C.dateOfPayment&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Date of Payment:"})," ",C.dateOfPayment]})]})]}),(C.bsrCode||C.challanSerialNo||C.dateOfDeposit)&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2",children:"Challan Details"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm",children:[C.bsrCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"BSR Code:"})," ",C.bsrCode]}),C.challanSerialNo&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Challan Serial No.:"})," ",C.challanSerialNo]}),C.dateOfDeposit&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Date of Deposit:"})," ",C.dateOfDeposit]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Amount:"})," ",$(C.tdsAmount)]})]})]}),e.jsxs("div",{className:"flex justify-between items-center pt-3 border-t border-emerald-200 bg-emerald-100/50 rounded-lg px-3 py-2",children:[e.jsx("span",{className:"text-sm font-semibold text-emerald-800",children:"Total Tax Deducted (Form 16A)"}),e.jsx("span",{className:"text-sm font-bold text-emerald-800",children:$(C.tdsAmount)})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Submission"}),e.jsx("p",{className:"text-sm font-medium",children:(t==null?void 0:t.title)||"Form 16A"})]})}),e.jsxs("div",{className:"rounded-lg bg-emerald-100/50 border border-emerald-200 p-3 text-sm text-gray-700",children:[e.jsx("p",{className:"font-medium text-emerald-800 mb-1",children:"Request details"}),e.jsx(Es,{content:(t==null?void 0:t.description)||"",className:"text-sm"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Full certificate details (from uploaded PDF) will appear here when available."})]})})]}),P&&F&&Object.keys(F).length>0&&e.jsxs(Z,{"data-testid":"form16-ocr-extracted-data",className:"border-slate-200 bg-slate-50/50",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs(me,{className:"flex items-center gap-2 text-sm sm:text-base text-slate-800",children:[e.jsx(ah,{className:"w-4 h-4 text-slate-600"}),"OCR extracted data"]}),e.jsx(ve,{className:"text-xs text-gray-600",children:"Data extracted from the uploaded Form 16A PDF."})]}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm",children:[(F.deductorName??F.deductor_name??F.nameAndAddressOfDeductor)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Deductor name"}),e.jsx("p",{className:"font-medium",children:I(F.deductorName??F.deductor_name??F.nameAndAddressOfDeductor)})]}),(F.tanNumber??F.tan_number??F.tanOfDeductor)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"TAN"}),e.jsx("p",{className:"font-medium",children:I(F.tanNumber??F.tan_number??F.tanOfDeductor)})]}),(F.financialYear??F.financial_year)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Financial year"}),e.jsx("p",{className:"font-medium",children:I(F.financialYear??F.financial_year)})]}),F.quarter!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Quarter"}),e.jsx("p",{className:"font-medium",children:I(F.quarter)})]}),(F.form16aNumber??F.form16a_number)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Form 16A number"}),e.jsx("p",{className:"font-medium",children:I(F.form16aNumber??F.form16a_number)})]}),(F.totalAmount??F.total_amount??F.totalAmountPaid)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Total amount"}),e.jsx("p",{className:"font-medium",children:$(F.totalAmount??F.total_amount??F.totalAmountPaid)})]}),(F.totalTaxDeducted??F.tdsAmount??F.tds_amount)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"TDS / Tax deducted"}),e.jsx("p",{className:"font-medium",children:$(F.totalTaxDeducted??F.tdsAmount??F.tds_amount)})]}),(F.natureOfPayment??F.nature_of_payment)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Nature of payment"}),e.jsx("p",{className:"font-medium",children:I(F.natureOfPayment??F.nature_of_payment)})]}),(F.transactionDate??F.transaction_date)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Transaction date"}),e.jsx("p",{className:"font-medium",children:I(F.transactionDate??F.transaction_date)})]}),(F.assessmentYear??F.assessment_year)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Assessment year"}),e.jsx("p",{className:"font-medium",children:I(F.assessmentYear??F.assessment_year)})]}),(F.acknowledgementNumber??F.acknowledgement_number)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Acknowledgement number"}),e.jsx("p",{className:"font-medium",children:I(F.acknowledgementNumber??F.acknowledgement_number)})]}),(F.dateOfIssue??F.date_of_issue)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Date of issue"}),e.jsx("p",{className:"font-medium",children:I(F.dateOfIssue??F.date_of_issue)})]}),(F.deduceeName??F.deducee_name)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Deductee name"}),e.jsx("p",{className:"font-medium",children:I(F.deduceeName??F.deducee_name)})]}),(F.deduceePan??F.deducee_pan)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Deductee PAN"}),e.jsx("p",{className:"font-medium",children:I(F.deduceePan??F.deducee_pan)})]})]})})]}),e.jsxs(Z,{"data-testid":"initiator-card",children:[e.jsx(oe,{className:"pb-3 sm:pb-4",children:e.jsxs(me,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Vt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(ee,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(ls,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(os,{className:"bg-gray-700 text-white font-semibold text-sm",children:((L=t.initiator)==null?void 0:L.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:((M=t.initiator)==null?void 0:M.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((U=t.initiator)==null?void 0:U.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((B=t.initiator)==null?void 0:B.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(ba,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((W=t.initiator)==null?void 0:W.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(Wn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((J=t.initiator)==null?void 0:J.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(Z,{"data-testid":"request-details-card",children:[e.jsx(oe,{className:"pb-3 sm:pb-4",children:e.jsxs(me,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(ee,{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(Es,{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:gs(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:gs(t.updatedAt)})]})]})]})]}),S&&N&&e.jsxs(Z,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(oe,{className:"pb-3 sm:pb-4",children:e.jsxs(me,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(or,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(ee,{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:[N.pauseReason&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Reason"}),e.jsx(Es,{content:N.pauseReason,className:"text-sm text-gray-900 mt-1"})]}),N.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:N.pausedBy.name||N.pausedBy.email})]}),N.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:[gs(N.pauseResumeDate),as(N.pauseResumeDate).isAfter(as())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",as(N.pauseResumeDate).fromNow(),")"]})]})]}),N.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:gs(N.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[D&&p&&e.jsxs(E,{onClick:p,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(Di,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),R&&x&&e.jsxs(E,{onClick:x,variant:"outline",className:"border-orange-300 text-orange-700 hover:bg-orange-50 text-xs sm:text-sm h-8 sm:h-9",size:"sm",children:[e.jsx(Ze,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Request Resume"]})]})]})]}),t.claimDetails&&e.jsxs(Z,{children:[e.jsx(oe,{className:"pb-4",children:e.jsxs(me,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ie,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(ee,{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?mp(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(Es,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(Z,{children:[e.jsxs(oe,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(me,{className:"flex items-center gap-2 text-base",children:[e.jsx(Le,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(ve,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(ee,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Es,{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 ",gs(t.closureDate)]}),e.jsxs("span",{children:["By ",((O=t.initiator)==null?void 0:O.name)||"Initiator"]})]})]})]}),a&&e.jsxs(Z,{"data-testid":"conclusion-remark-card",children:[e.jsx(oe,{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(me,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(Le,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(ve,{className:"mt-1 text-xs sm:text-sm",children:t.status==="rejected"?"This request was rejected. Please review the AI-generated closure remark and finalize it to close this request.":"All approvals are complete. Please review and finalize the conclusion to close this request."})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:c,disabled:i||y,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx($t,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),o?"Regenerate":"Generate with AI"]}),o&&!y&&!j&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-b," attempts remaining"]})]})]})}),e.jsx(ee,{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(Xe,{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(Jn,{value:r,onChange:H=>n(H),placeholder:"Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals...",className:"text-sm",minHeight:"160px","data-testid":"conclusion-remark-textarea"}),e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"This will be the final summary for this request"}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":"character-count",children:[r?r.replace(/<[^>]*>/g,"").length:0," / 2000 characters"]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-blue-900 mb-1.5",children:"Finalizing this request will:"}),e.jsxs("ul",{className:"text-xs sm:text-sm text-blue-800 space-y-0.5 pl-4",children:[e.jsx("li",{className:"list-disc",children:'Change request status to "CLOSED"'}),e.jsx("li",{className:"list-disc",children:"Notify all participants of closure"}),e.jsx("li",{className:"list-disc",children:"Move request to Closed Requests"}),e.jsx("li",{className:"list-disc",children:"Save conclusion remark permanently"})]})]}),e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(E,{onClick:d,disabled:l||!r.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:l?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function Dn({delayDuration:t=0,...s}){return e.jsx(yf,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function bi({...t}){return e.jsx(Dn,{children:e.jsx(vf,{"data-slot":"tooltip",...t})})}function ji({...t}){return e.jsx(Nf,{"data-slot":"tooltip-trigger",...t})}function yi({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(wf,{children:e.jsxs(Cf,{"data-slot":"tooltip-content",sideOffset:s,className:_e("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(Sf,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function jt({...t}){return e.jsx(kf,{"data-slot":"dialog",...t})}function $w({...t}){return e.jsx(Tf,{"data-slot":"dialog-portal",...t})}const hp=h.forwardRef(({className:t,...s},a)=>e.jsx(Vx,{ref:a,"data-slot":"dialog-overlay",className:_e("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}));hp.displayName=Vx.displayName;const xt=h.forwardRef(({className:t,children:s,...a},r)=>e.jsxs($w,{"data-slot":"dialog-portal",children:[e.jsx(hp,{}),e.jsxs(zx,{ref:r,"data-slot":"dialog-content",className:_e("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(Af,{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(bt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));xt.displayName=zx.displayName;const yt=h.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:_e("flex flex-col gap-2 text-center sm:text-left",t),...s}));yt.displayName="DialogHeader";const Et=h.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:_e("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));Et.displayName="DialogFooter";const ht=h.forwardRef(({className:t,...s},a)=>e.jsx(Hx,{ref:a,"data-slot":"dialog-title",className:_e("text-lg leading-none font-semibold",t),...s}));ht.displayName=Hx.displayName;const Ut=h.forwardRef(({className:t,...s},a)=>e.jsx(Wx,{ref:a,"data-slot":"dialog-description",className:_e("text-muted-foreground text-sm",t),...s}));Ut.displayName=Wx.displayName;function Os({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:_e("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 Km=t=>{if(t<8)return Kt(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${Kt(r)}`:`${a}d`},Uw=(t,s)=>{if(s)return e.jsx(Ze,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(Le,{className:"w-4 h-4 sm:w-5 sm:w-5 text-green-600"});case"rejected":return e.jsx(St,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"paused":return e.jsx(rh,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(st,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(st,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(st,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function Bw({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}=cs(),[m,p]=h.useState(!1),[x,u]=h.useState(""),[g,f]=h.useState(!1),b=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";h.useEffect(()=>{m||u("")},[m]);const j=t.status==="pending"||t.status==="in-review",y=t.status==="approved",w=t.status==="rejected",N=t.status==="waiting",S=t.status==="paused",A=Number(t.tatHours||0),_=t.actualHours??0,D=y&&_?Math.max(0,A-_):0,R=A>0?_/A*100:0,v=R>=100,P=(d==null?void 0:d.role)==="ADMIN",C=al(d),V=t.approverId===(d==null?void 0:d.userId),F=P||C||V,$=async()=>{var I,T;if(!x.trim()){X.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}f(!0);try{await Iw(t.levelId,x.trim()),p(!1),u(""),X.success("Breach Reason Updated",{description:"The breach reason has been saved and will appear in the TAT Breach Report.",duration:5e3}),o?await o():setTimeout(()=>{window.location.reload()},1e3)}catch(k){console.error("Error updating breach reason:",k);const z=((T=(I=k==null?void 0:k.response)==null?void 0:I.data)==null?void 0:T.error)||(k==null?void 0:k.message)||"Failed to update breach reason. Please try again.";X.error("Failed to Update Breach Reason",{description:z,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":j?"border-blue-500 bg-blue-50 shadow-md":y?"border-green-500 bg-green-50":w?"border-red-500 bg-red-50":N?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${c}-${t.step}`,children:[e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 md:gap-4",children:[e.jsx("div",{className:`p-2 sm:p-2.5 md:p-3 rounded-xl flex-shrink-0 ${t.isSkipped?"bg-orange-100":S?"bg-yellow-100":j?"bg-blue-100":y?"bg-green-100":w?"bg-red-100":N?"bg-gray-200":"bg-gray-100"}`,children:Uw(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(se,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":j?"bg-yellow-100 text-yellow-800 border-yellow-200":y?"bg-green-100 text-green-800 border-green-200":w?"bg-red-100 text-red-800 border-red-200":N?"bg-gray-200 text-gray-600 border-gray-300":"bg-gray-100 text-gray-800 border-gray-200"}`,"data-testid":`${c}-status-badge`,children:t.isSkipped?"skipped":t.status}),t.isSkipped&&t.skipReason&&e.jsx(Dn,{delayDuration:200,children:e.jsxs(bi,{children:[e.jsx(ji,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:I=>I.stopPropagation(),children:e.jsx(Ze,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(yi,{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(Am,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),y&&_&&e.jsx(se,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:Km(_)})]}),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:[A," hours"]})]})]}),y&&_!==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?gs(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:Km(_)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const I=Math.min(100,R),T=()=>v?"bg-red-600":R>=75?"bg-orange-500":R>=50?"bg-amber-500":"bg-green-600",k=()=>v?"text-red-600":R>=75?"text-orange-600":R>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(Zs,{value:I,className:"h-2 bg-gray-200",indicatorClassName:T(),"data-testid":`${c}-progress-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-semibold ${k()}`,children:[Math.round(I),"% of TAT used"]}),v&&F&&e.jsx(Dn,{children:e.jsxs(bi,{children:[e.jsx(ji,{asChild:!0,children:e.jsx(E,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{u(b),p(!0)},children:e.jsx(ni,{className:"w-3 h-3"})})}),e.jsx(yi,{children:e.jsx("p",{children:b?"Edit breach reason":"Add breach reason"})})]})})]}),D>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",Kt(D)]})]})]})})()}),v&&b&&e.jsxs("div",{className:"mt-4 p-3 sm:p-4 bg-red-50 border-l-4 border-red-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 mb-2 flex items-center gap-1.5",children:[e.jsx(ni,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:b})]}),t.comment&&e.jsxs("div",{className:"mt-4 p-3 sm:p-4 bg-blue-50 border-l-4 border-blue-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-700 mb-2 flex items-center gap-1.5",children:[e.jsx(zs,{className:"w-3.5 h-3.5 text-blue-600"}),"Conclusion Remark:"]}),e.jsx("p",{className:"text-sm text-gray-700 italic leading-relaxed",children:t.comment})]})]}),i&&(j||S)&&(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?Ca(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${S?"bg-gray-100 border-gray-300":(a.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(a.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(a.sla.percentageUsed||0)>=50?"bg-amber-50 border-amber-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(st,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",S&&"(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," / ",Kt(A)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const I=a.sla.percentageUsed||0,T=()=>S?"bg-gray-500":I>=100?"bg-red-600":I>=75?"bg-orange-500":I>=50?"bg-amber-500":"bg-green-600",k=()=>S?"text-gray-600":I>=100?"text-red-600":I>=75?"text-orange-600":I>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(Zs,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:T(),"data-testid":`${c}-sla-progress`}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`text-xs font-semibold ${k()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&F&&e.jsx(Dn,{children:e.jsxs(bi,{children:[e.jsx(ji,{asChild:!0,children:e.jsx(E,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{u(b),p(!0)},children:e.jsx(ni,{className:"w-3 h-3"})})}),e.jsx(yi,{children:e.jsx("p",{children:b?"Edit breach reason":"Add breach reason"})})]})})]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[a.sla.remainingText," remaining"]})]})]})})(),a.sla.status==="breached"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs font-semibold text-center text-red-600 flex items-center justify-center gap-1.5",children:[e.jsx(Fi,{className:"w-4 h-4"}),"Deadline Breached"]}),b&&e.jsxs("div",{className:"mt-3 p-3 bg-red-50 border-l-4 border-red-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 mb-2 flex items-center gap-1.5",children:[e.jsx(ni,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:b})]})]}),a.sla.status==="critical"&&e.jsxs("p",{className:"text-xs font-semibold text-center text-orange-600 flex items-center justify-center gap-1.5",children:[e.jsx(ts,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),N&&e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"bg-gray-100 border border-gray-300 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-gray-600 mb-1 flex items-center gap-1.5",children:[e.jsx(rh,{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 ",A," hours for approval"]})]})}),w&&t.comment&&e.jsxs("div",{className:"mt-3 p-3 sm:p-4 bg-red-50 border-l-4 border-red-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 mb-2 flex items-center gap-1.5",children:[e.jsx(St,{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(Am,{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 ",gs(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((I,T)=>{var k,z,L,M,U,B;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${I.isBreached?"bg-red-50 border-red-200":(I.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${T}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(I.thresholdPercentage||0)===50&&e.jsx(jb,{className:"w-5 h-5 text-yellow-600"}),(I.thresholdPercentage||0)===75&&e.jsx(ts,{className:"w-5 h-5 text-orange-600"}),(I.thresholdPercentage||0)===100&&e.jsx(Fi,{className:"w-5 h-5 text-red-600"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-2 mb-1",children:[e.jsxs("p",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:["Reminder ",T+1," - ",I.thresholdPercentage||0,"% TAT"]}),e.jsx(se,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${I.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:I.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[I.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:Kt(Number(I.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:[Kt(Number(I.tatHoursElapsed||0)),((k=I.metadata)==null?void 0:k.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(I.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 ${(I.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[Kt(Number(I.tatHoursRemaining||0)),((z=I.metadata)==null?void 0:z.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(I.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:I.expectedCompletionTime?Ca(I.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"}),(((L=I.metadata)==null?void 0:L.testMode)||((M=I.metadata)==null?void 0:M.tatTestMode))&&e.jsx(se,{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: ",I.alertSentAt?gs(I.alertSentAt):"N/A"]}),(((U=I.metadata)==null?void 0:U.testMode)||((B=I.metadata)==null?void 0:B.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},T)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[y?"Approved":w?"Rejected":"Actioned"," on ",gs(t.timestamp)]}),n&&!S&&(j||t.status==="pending")&&!y&&!w&&t.levelId&&l&&e.jsxs("div",{className:"mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-200",children:[e.jsxs(E,{variant:"outline",size:"sm",className:"w-full border-orange-300 text-orange-700 hover:bg-orange-50 h-9 sm:h-10 text-xs sm:text-sm",onClick:()=>l({levelId:t.levelId,approverName:t.approver,levelNumber:t.step}),"data-testid":`${c}-skip-button`,children:[e.jsx(Ze,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Skip This Approver"]}),e.jsx("p",{className:"text-[10px] sm:text-xs text-gray-500 mt-1 text-center",children:S?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(jt,{open:m,onOpenChange:p,children:e.jsxs(xt,{className:"sm:max-w-[500px]",children:[e.jsxs(yt,{children:[e.jsx(ht,{children:b?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(Ut,{children:b?"Update the reason for the TAT breach. This will be reflected in the TAT Breach Report.":"Please provide a reason for the TAT breach. This will be reflected in the TAT Breach Report."})]}),e.jsxs("div",{className:"py-4",children:[e.jsx(Os,{placeholder:"Enter the reason for the breach...",value:x,onChange:I=>u(I.target.value),className:"min-h-[100px]",maxLength:500}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[x.length,"/500 characters"]})]}),e.jsxs(Et,{children:[e.jsx(E,{variant:"outline",onClick:()=>{p(!1),u("")},disabled:g,children:"Cancel"}),e.jsx(E,{onClick:$,disabled:!x.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function Vw({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(Z,{children:[e.jsx(oe,{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(me,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Hs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(ve,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var u;const i=t.totalSteps||1,l=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,o=((u=t.approvalFlow)==null?void 0:u.filter(g=>{const 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",p=l>i,x=Math.min(Math.max(1,l),i);return p?e.jsxs(se,{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(se,{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(se,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",x," of ",i," - ",o," completed"]})})()]})}),e.jsx(ee,{children:t.approvalFlow&&t.approvalFlow.length>0?e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.approvalFlow.map((i,l)=>{var u,g,f;const o=(u=t.approvals)==null?void 0:u.find(b=>b.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,p=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,x=i.step===p;return e.jsx(Bw,{step:i,index:l,approval:o,isCurrentUser:m,isInitiator:a,isCurrentLevel:x,onSkipApprover:r,onRefresh:n,testId:"workflow-step"},l)})}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-workflow-steps",children:"No workflow steps defined"})})]})}function br(t){return t==null?"–":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(Number(t))}function ua(t){return t==null||t===""?"–":String(t)}function zw(t){const s=(t||"").toLowerCase();return s==="completed"?"bg-emerald-100 text-emerald-800 border-emerald-200":s==="duplicate"||s==="duplicate submission"?"bg-amber-100 text-amber-800 border-amber-200":s==="balance mismatch"||s==="failed"?"bg-red-100 text-red-800 border-red-200":s==="resubmission needed"||s==="partial extracted data"?"bg-amber-50 text-amber-700 border-amber-200":"bg-gray-100 text-gray-700 border-gray-200"}const Qm="Failed - data mismatch with 26AS, submit the Form 16 with correct data.";function Hw(t){const s=(t||"").toLowerCase();return/notnull|violation|sequelize|econnrefused|database|error\./i.test(s)}function Xm(t){const s=((t==null?void 0:t.displayStatus)||"").toLowerCase(),a=String((t==null?void 0:t.validationNotes)||"");return s==="balance mismatch"||s==="failed"?Hw(a)?Qm:a.trim()||Qm:s==="duplicate"||s==="duplicate submission"?"Duplicate. A submission for this FY and quarter already exists.":s==="resubmission needed"?(t==null?void 0:t.validationNotes)||"Resubmission needed. Please submit again with correct data.":null}function Ww({request:t}){var n,i,l,o;const s=t==null?void 0:t.form16Submission,a=s!=null&&s.ocrExtractedData&&typeof s.ocrExtractedData=="object"?s.ocrExtractedData:null,r=a&&Object.keys(a).length>0?a:s?{deductorName:s.deductorName,deductor_name:s.deductorName,tanNumber:s.tanNumber,tan_number:s.tanNumber,financialYear:s.financialYear,financial_year:s.financialYear,quarter:s.quarter,form16aNumber:s.form16aNumber,form16a_number:s.form16aNumber,totalAmount:s.totalAmount,total_amount:s.totalAmount,tdsAmount:s.tdsAmount,tds_amount:s.tdsAmount,acknowledgementNumber:s.acknowledgementNumber,acknowledgement_number:s.acknowledgementNumber,dateOfIssue:s.dateOfIssue,date_of_issue:s.dateOfIssue,deduceeName:s.deduceeName,deducee_name:s.deduceeName,deduceePan:s.deduceePan,deducee_pan:s.deduceePan}:null;return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"form16-overview-tab",children:[s&&e.jsxs("div",{className:"flex flex-col gap-2","data-testid":"form16-submission-status",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.displayStatus!=null&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Submission status:"}),e.jsx(se,{variant:"outline",className:zw(s.displayStatus),"data-testid":"form16-display-status",children:s.displayStatus})]}),s.displayStatus!=="Duplicate"&&s.totalAmount!=null&&e.jsxs("span",{className:"text-sm text-gray-600",children:[e.jsx("span",{className:"font-medium text-gray-700",children:"Total amount:"})," ",br(s.totalAmount)]}),s.displayStatus!=="Duplicate"&&s.creditNoteNumber&&e.jsxs("span",{className:"text-sm text-gray-600",children:[e.jsx("span",{className:"font-medium text-gray-700",children:"Credit note:"})," ",s.creditNoteNumber]})]}),Xm(s)&&e.jsx("p",{className:`text-sm ${(s.displayStatus||"").toLowerCase()==="balance mismatch"||(s.displayStatus||"").toLowerCase()==="failed"?"text-red-700 font-medium":"text-gray-600"}`,"data-testid":"form16-status-message",children:Xm(s)})]}),e.jsxs(Z,{"data-testid":"form16-certificate-details",className:"border-emerald-200 bg-emerald-50/30",children:[e.jsxs(oe,{className:"pb-3 sm:pb-4",children:[e.jsxs(me,{className:"flex items-center gap-2 text-sm sm:text-base text-emerald-800",children:[e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-emerald-600"}),"Form 16A Certificate Details"]}),e.jsx(ve,{className:"text-xs text-gray-600",children:"TDS Certificate as per Income Tax Act, 1961"})]}),e.jsx(ee,{className:"space-y-4",children:s?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Certificate Number"}),e.jsx("p",{className:"text-sm font-medium",children:s.form16aNumber||"–"})]}),s.version!=null&&s.version>=2&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Version"}),e.jsxs("p",{className:"text-sm font-medium",children:["Version ",s.version]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Financial Year"}),e.jsx("p",{className:"text-sm font-medium",children:s.financialYear||"–"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Acknowledgement Number"}),e.jsx("p",{className:"text-sm font-medium",children:s.acknowledgementNumber||"–"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Date of Issue"}),e.jsx("p",{className:"text-sm font-medium",children:s.dateOfIssue||"–"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Quarter"}),e.jsx("p",{className:"text-sm font-medium",children:s.quarter?`${s.quarter} (${s.financialYear||""})`:"–"})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2",children:"Deductor Details"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Name:"})," ",s.deductorName||"–"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TAN:"})," ",s.tanNumber||"–"]})]})]}),(s.deduceeName||s.deduceePan)&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2",children:"Deductee Details (Dealer)"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm",children:[s.deduceeName&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Name:"})," ",s.deduceeName]}),s.deduceePan&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"PAN:"})," ",s.deduceePan]}),s.deduceeAddress&&e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("span",{className:"text-gray-500",children:"Address:"})," ",s.deduceeAddress]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2",children:"TDS Payment Details"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm",children:[s.section&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Section:"})," ",s.section]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Amount Paid:"})," ",br(s.totalAmount??s.amountPaid)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TDS Deducted:"})," ",br(s.tdsAmount)]}),s.dateOfPayment&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Date of Payment:"})," ",s.dateOfPayment]})]})]}),(s.bsrCode||s.challanSerialNo||s.dateOfDeposit)&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2",children:"Challan Details"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm",children:[s.bsrCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"BSR Code:"})," ",s.bsrCode]}),s.challanSerialNo&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Challan Serial No.:"})," ",s.challanSerialNo]}),s.dateOfDeposit&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Date of Deposit:"})," ",s.dateOfDeposit]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Amount:"})," ",br(s.tdsAmount)]})]})]}),e.jsxs("div",{className:"flex justify-between items-center pt-3 border-t border-emerald-200 bg-emerald-100/50 rounded-lg px-3 py-2",children:[e.jsx("span",{className:"text-sm font-semibold text-emerald-800",children:"Total Tax Deducted (Form 16A)"}),e.jsx("span",{className:"text-sm font-bold text-emerald-800",children:br(s.tdsAmount)})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Submission"}),e.jsx("p",{className:"text-sm font-medium",children:(t==null?void 0:t.title)||"Form 16A"})]})}),e.jsxs("div",{className:"rounded-lg bg-emerald-100/50 border border-emerald-200 p-3 text-sm text-gray-700",children:[e.jsx("p",{className:"font-medium text-emerald-800 mb-1",children:"Request details"}),e.jsx(Es,{content:(t==null?void 0:t.description)||"",className:"text-sm"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Full certificate details (from uploaded PDF) will appear here when available."})]})})]}),r&&Object.keys(r).length>0&&e.jsxs(Z,{"data-testid":"form16-ocr-extracted-data",className:"border-slate-200 bg-slate-50/50",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs(me,{className:"flex items-center gap-2 text-sm sm:text-base text-slate-800",children:[e.jsx(ah,{className:"w-4 h-4 text-slate-600"}),"OCR extracted data"]}),e.jsx(ve,{className:"text-xs text-gray-600",children:"Data extracted from the uploaded Form 16A PDF (shown for all submission outcomes)."})]}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm",children:[(r.deductorName??r.deductor_name??r.nameAndAddressOfDeductor??r.name_and_address_of_deductor)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Deductor name"}),e.jsx("p",{className:"font-medium",children:ua(r.deductorName??r.deductor_name??r.nameAndAddressOfDeductor??r.name_and_address_of_deductor)})]}),(r.tanNumber??r.tan_number??r.tanOfDeductor??r.tan_of_deductor)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"TAN"}),e.jsx("p",{className:"font-medium",children:ua(r.tanNumber??r.tan_number??r.tanOfDeductor??r.tan_of_deductor)})]}),(r.financialYear??r.financial_year)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Financial year"}),e.jsx("p",{className:"font-medium",children:ua(r.financialYear??r.financial_year)})]}),r.quarter!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Quarter"}),e.jsx("p",{className:"font-medium",children:ua(r.quarter)})]}),(r.form16aNumber??r.form16a_number)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Form 16A number"}),e.jsx("p",{className:"font-medium",children:ua(r.form16aNumber??r.form16a_number)})]}),(r.totalAmount??r.total_amount??r.totalAmountPaid??r.total_amount_paid)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Total amount"}),e.jsx("p",{className:"font-medium",children:br(r.totalAmount??r.total_amount??r.totalAmountPaid??r.total_amount_paid)})]}),(r.totalTaxDeducted??r.total_tax_deducted??r.tdsAmount??r.tds_amount)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"TDS / Tax deducted"}),e.jsx("p",{className:"font-medium",children:br(r.totalTaxDeducted??r.total_tax_deducted??r.tdsAmount??r.tds_amount)})]}),(r.natureOfPayment??r.nature_of_payment)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Nature of payment"}),e.jsx("p",{className:"font-medium",children:ua(r.natureOfPayment??r.nature_of_payment)})]}),(r.transactionDate??r.transaction_date)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Transaction date"}),e.jsx("p",{className:"font-medium",children:ua(r.transactionDate??r.transaction_date)})]}),(r.assessmentYear??r.assessment_year)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Assessment year"}),e.jsx("p",{className:"font-medium",children:ua(r.assessmentYear??r.assessment_year)})]}),(r.acknowledgementNumber??r.acknowledgement_number)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Acknowledgement number"}),e.jsx("p",{className:"font-medium",children:ua(r.acknowledgementNumber??r.acknowledgement_number)})]}),(r.dateOfIssue??r.date_of_issue)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Date of issue"}),e.jsx("p",{className:"font-medium",children:ua(r.dateOfIssue??r.date_of_issue)})]}),(r.deduceeName??r.deducee_name)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Deductee name"}),e.jsx("p",{className:"font-medium",children:ua(r.deduceeName??r.deducee_name)})]}),(r.deduceePan??r.deducee_pan)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Deductee PAN"}),e.jsx("p",{className:"font-medium",children:ua(r.deduceePan??r.deducee_pan)})]})]})})]}),e.jsxs(Z,{"data-testid":"form16-submission-context",children:[e.jsx(oe,{className:"pb-3",children:e.jsxs(me,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-emerald-600"}),"Submitted by"]})}),e.jsxs(ee,{children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ls,{className:"h-10 w-10 rounded-full flex-shrink-0",children:e.jsx(os,{className:"bg-emerald-100 text-emerald-800 text-sm font-medium",children:((n=t==null?void 0:t.initiator)==null?void 0:n.avatar)||"U"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-gray-900",children:((i=t==null?void 0:t.initiator)==null?void 0:i.name)||"–"}),e.jsx("p",{className:"text-xs text-gray-500",children:((l=t==null?void 0:t.initiator)==null?void 0:l.role)||"–"}),((o=t==null?void 0:t.initiator)==null?void 0:o.email)&&e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-gray-600",children:[e.jsx(ba,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:t.initiator.email})]})]})]}),e.jsxs("div",{className:"mt-3 pt-3 border-t border-gray-100",children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Description"}),e.jsx(Es,{content:(t==null?void 0:t.description)||"",className:"text-sm text-gray-700"})]}),((t==null?void 0:t.createdAt)||(t==null?void 0:t.updatedAt))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-4 text-xs text-gray-500",children:[t.createdAt&&e.jsxs("span",{children:["Created: ",new Date(t.createdAt).toLocaleString("en-IN")]}),t.updatedAt&&e.jsxs("span",{children:["Last updated: ",new Date(t.updatedAt).toLocaleString("en-IN")]})]})]})]})]})}const Gw=[{key:"submit",label:"Dealer submits Form 16",icon:Ie},{key:"ocr",label:"OCR extracts",icon:Ie},{key:"match",label:"Matching with 26AS",icon:$t},{key:"success",label:"Successfully match",icon:Le},{key:"credit",label:"Credit note generated",icon:Pt}];function Yw({request:t,requestId:s}){const[a,r]=h.useState(null),[n,i]=h.useState(!0),l=t==null?void 0:t.form16Submission,o=!!l,c=!!a&&a.status!=="withdrawn",d=!!a&&a.status==="withdrawn",m=(l==null?void 0:l.validationStatus)??null,p=m==="failed"||m==="mismatch"||m==="duplicate",x=c||m==="success"||m==="manually_approved";h.useEffect(()=>{if(!s){i(!1);return}let f=!1;return(async()=>{try{const b=await Vh(s);f||r(b)}catch{f||r(null)}finally{f||i(!1)}})(),()=>{f=!0}},[s]);const u={submit:!0,ocr:o,match:x,success:x,credit:c||d},g={submit:!1,ocr:!1,match:p,success:p,credit:!1};return e.jsxs("div",{className:"space-y-6","data-testid":"form16-workflow-tab",children:[e.jsxs(Z,{className:"border-emerald-200",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs(me,{className:"text-base flex items-center gap-2 text-emerald-800",children:[e.jsx($t,{className:"w-4 h-4"}),"Form 16 process"]})}),e.jsx(ee,{className:"space-y-4",children:Gw.map(f=>{const b=u[f.key],j=g[f.key];return e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center ${j?"bg-red-100 text-red-600":b?"bg-emerald-100 text-emerald-700":"bg-gray-100 text-gray-400"}`,children:j?e.jsx(St,{className:"w-4 h-4"}):b?e.jsx(Le,{className:"w-4 h-4"}):e.jsx(Bo,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${j?"text-red-700":b?"text-gray-900":"text-gray-500"}`,children:f.label}),f.key==="credit"&&c&&a&&e.jsxs("p",{className:"text-xs text-gray-500 mt-0.5",children:["Credit note: ",a.creditNoteNumber,a.amount!=null&&` · ${new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(Number(a.amount))}`,m==="manually_approved"&&e.jsx("span",{className:"ml-1 text-blue-600",children:"(Manually approved Form 16)"})]}),f.key==="credit"&&d&&e.jsx("p",{className:"text-xs text-amber-600 mt-0.5",children:"Withdrawn"})]})]},f.key)})})]}),n&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(Xe,{className:"w-4 h-4 animate-spin"}),"Loading credit note…"]}),!c&&!n&&o&&e.jsx("p",{className:"text-xs text-gray-500",children:"No credit note has been generated for this submission yet. Use Quick Actions (sidebar) for RE actions."})]})}const oc=h.createContext({});function cc(t){const s=h.useRef(null);return s.current===null&&(s.current=t()),s.current}const dc=typeof window<"u",pp=dc?h.useLayoutEffect:h.useEffect,ll=h.createContext(null);function mc(t,s){t.indexOf(s)===-1&&t.push(s)}function uc(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const Wa=(t,s,a)=>a>s?s:a<t?t:a;let xc=()=>{};const Ga={},gp=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function fp(t){return typeof t=="object"&&t!==null}const bp=t=>/^0[^.\s]+$/u.test(t);function hc(t){let s;return()=>(s===void 0&&(s=t()),s)}const ga=t=>t,Kw=(t,s)=>a=>s(t(a)),Zn=(...t)=>t.reduce(Kw),On=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class pc{constructor(){this.subscriptions=[]}add(s){return mc(this.subscriptions,s),()=>uc(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 Da=t=>t*1e3,pa=t=>t/1e3;function jp(t,s){return s?t*(1e3/s):0}const yp=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,Qw=1e-7,Xw=12;function Jw(t,s,a,r,n){let i,l,o=0;do l=s+(a-s)/2,i=yp(l,r,n)-t,i>0?a=l:s=l;while(Math.abs(i)>Qw&&++o<Xw);return l}function qn(t,s,a,r){if(t===s&&a===r)return ga;const n=i=>Jw(i,0,1,t,a);return i=>i===0||i===1?i:yp(n(i),s,r)}const vp=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,Np=t=>s=>1-t(1-s),wp=qn(.33,1.53,.69,.99),gc=Np(wp),Cp=vp(gc),Sp=t=>(t*=2)<1?.5*gc(t):.5*(2-Math.pow(2,-10*(t-1))),fc=t=>1-Math.sin(Math.acos(t)),Ap=Np(fc),Tp=vp(fc),Zw=qn(.42,0,1,1),qw=qn(0,0,.58,1),kp=qn(.42,0,.58,1),e1=t=>Array.isArray(t)&&typeof t[0]!="number",Rp=t=>Array.isArray(t)&&typeof t[0]=="number",t1={linear:ga,easeIn:Zw,easeInOut:kp,easeOut:qw,circIn:fc,circInOut:Tp,circOut:Ap,backIn:gc,backInOut:Cp,backOut:wp,anticipate:Sp},s1=t=>typeof t=="string",Jm=t=>{if(Rp(t)){xc(t.length===4);const[s,a,r,n]=t;return qn(s,a,r,n)}else if(s1(t))return t1[t];return t},li=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function a1(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,p=!1,x=!1)=>{const g=x&&n?a:r;return p&&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 r1=40;function Dp(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,l=li.reduce((w,N)=>(w[N]=a1(i),w),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:m,update:p,preRender:x,render:u,postRender:g}=l,f=()=>{const w=Ga.useManualTiming?n.timestamp:performance.now();a=!1,Ga.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(w-n.timestamp,r1),1)),n.timestamp=w,n.isProcessing=!0,o.process(n),c.process(n),d.process(n),m.process(n),p.process(n),x.process(n),u.process(n),g.process(n),n.isProcessing=!1,a&&s&&(r=!1,t(f))},b=()=>{a=!0,r=!0,n.isProcessing||t(f)};return{schedule:li.reduce((w,N)=>{const S=l[N];return w[N]=(A,_=!1,D=!1)=>(a||b(),S.schedule(A,_,D)),w},{}),cancel:w=>{for(let N=0;N<li.length;N++)l[li[N]].cancel(w)},state:n,steps:l}}const{schedule:qt,cancel:dr,state:Is,steps:Fl}=Dp(typeof requestAnimationFrame<"u"?requestAnimationFrame:ga,!0);let vi;function n1(){vi=void 0}const Js={now:()=>(vi===void 0&&Js.set(Is.isProcessing||Ga.useManualTiming?Is.timestamp:performance.now()),vi),set:t=>{vi=t,queueMicrotask(n1)}},Fp=t=>s=>typeof s=="string"&&s.startsWith(t),bc=Fp("--"),i1=Fp("var(--"),jc=t=>i1(t)?l1.test(t.split("/*")[0].trim()):!1,l1=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,un={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},$n={...un,transform:t=>Wa(0,1,t)},oi={...un,default:1},Fn=t=>Math.round(t*1e5)/1e5,yc=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function o1(t){return t==null}const c1=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,vc=(t,s)=>a=>!!(typeof a=="string"&&c1.test(a)&&a.startsWith(t)||s&&!o1(a)&&Object.prototype.hasOwnProperty.call(a,s)),Ip=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,l,o]=r.match(yc);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},d1=t=>Wa(0,255,t),Il={...un,transform:t=>Math.round(d1(t))},kr={test:vc("rgb","red"),parse:Ip("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+Il.transform(t)+", "+Il.transform(s)+", "+Il.transform(a)+", "+Fn($n.transform(r))+")"};function m1(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 uo={test:vc("#"),parse:m1,transform:kr.transform},ei=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),ar=ei("deg"),Fa=ei("%"),it=ei("px"),u1=ei("vh"),x1=ei("vw"),Zm={...Fa,parse:t=>Fa.parse(t)/100,transform:t=>Fa.transform(t*100)},zr={test:vc("hsl","hue"),parse:Ip("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+Fa.transform(Fn(s))+", "+Fa.transform(Fn(a))+", "+Fn($n.transform(r))+")"},hs={test:t=>kr.test(t)||uo.test(t)||zr.test(t),parse:t=>kr.test(t)?kr.parse(t):zr.test(t)?zr.parse(t):uo.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?kr.transform(t):zr.transform(t),getAnimatableNone:t=>{const s=hs.parse(t);return s.alpha=0,hs.transform(s)}},h1=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function p1(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(yc))==null?void 0:s.length)||0)+(((a=t.match(h1))==null?void 0:a.length)||0)>0}const Pp="number",Ep="color",g1="var",f1="var(",qm="${}",b1=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Un(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const o=s.replace(b1,c=>(hs.test(c)?(r.color.push(i),n.push(Ep),a.push(hs.parse(c))):c.startsWith(f1)?(r.var.push(i),n.push(g1),a.push(c)):(r.number.push(i),n.push(Pp),a.push(parseFloat(c))),++i,qm)).split(qm);return{values:a,split:o,indexes:r,types:n}}function _p(t){return Un(t).values}function Mp(t){const{split:s,types:a}=Un(t),r=s.length;return n=>{let i="";for(let l=0;l<r;l++)if(i+=s[l],n[l]!==void 0){const o=a[l];o===Pp?i+=Fn(n[l]):o===Ep?i+=hs.transform(n[l]):i+=n[l]}return i}}const j1=t=>typeof t=="number"?0:hs.test(t)?hs.getAnimatableNone(t):t;function y1(t){const s=_p(t);return Mp(t)(s.map(j1))}const mr={test:p1,parse:_p,createTransformer:Mp,getAnimatableNone:y1};function Pl(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 v1({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=Pl(c,o,t+1/3),i=Pl(c,o,t),l=Pl(c,o,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function Mi(t,s){return a=>a>0?s:t}const rs=(t,s,a)=>t+(s-t)*a,El=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},N1=[uo,kr,zr],w1=t=>N1.find(s=>s.test(t));function eu(t){const s=w1(t);if(!s)return!1;let a=s.parse(t);return s===zr&&(a=v1(a)),a}const tu=(t,s)=>{const a=eu(t),r=eu(s);if(!a||!r)return Mi(t,s);const n={...a};return i=>(n.red=El(a.red,r.red,i),n.green=El(a.green,r.green,i),n.blue=El(a.blue,r.blue,i),n.alpha=rs(a.alpha,r.alpha,i),kr.transform(n))},xo=new Set(["none","hidden"]);function C1(t,s){return xo.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function S1(t,s){return a=>rs(t,s,a)}function Nc(t){return typeof t=="number"?S1:typeof t=="string"?jc(t)?Mi:hs.test(t)?tu:k1:Array.isArray(t)?Lp:typeof t=="object"?hs.test(t)?tu:A1:Mi}function Lp(t,s){const a=[...t],r=a.length,n=t.map((i,l)=>Nc(i)(i,s[l]));return i=>{for(let l=0;l<r;l++)a[l]=n[l](i);return a}}function A1(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=Nc(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function T1(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 k1=(t,s)=>{const a=mr.createTransformer(s),r=Un(t),n=Un(s);return r.indexes.var.length===n.indexes.var.length&&r.indexes.color.length===n.indexes.color.length&&r.indexes.number.length>=n.indexes.number.length?xo.has(t)&&!n.values.length||xo.has(s)&&!r.values.length?C1(t,s):Zn(Lp(T1(r,n),n.values),a):Mi(t,s)};function Op(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?rs(t,s,a):Nc(t)(t,s)}const R1=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>qt.update(s,a),stop:()=>dr(s),now:()=>Is.isProcessing?Is.timestamp:Js.now()}},$p=(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)})`},Li=2e4;function wc(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<Li;)s+=a,r=t.next(s);return s>=Li?1/0:s}function D1(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(wc(r),Li);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:pa(n)}}const F1=5;function Up(t,s,a){const r=Math.max(s-F1,0);return jp(a-t(r),s-r)}const is={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},_l=.001;function I1({duration:t=is.duration,bounce:s=is.bounce,velocity:a=is.velocity,mass:r=is.mass}){let n,i,l=1-s;l=Wa(is.minDamping,is.maxDamping,l),t=Wa(is.minDuration,is.maxDuration,pa(t)),l<1?(n=d=>{const m=d*l,p=m*t,x=m-a,u=ho(d,l),g=Math.exp(-p);return _l-x/u*g},i=d=>{const p=d*l*t,x=p*a+a,u=Math.pow(l,2)*Math.pow(d,2)*t,g=Math.exp(-p),f=ho(Math.pow(d,2),l);return(-n(d)+_l>0?-1:1)*((x-u)*g)/f}):(n=d=>{const m=Math.exp(-d*t),p=(d-a)*t+1;return-_l+m*p},i=d=>{const m=Math.exp(-d*t),p=(a-d)*(t*t);return m*p});const o=5/t,c=E1(n,i,o);if(t=Da(t),isNaN(c))return{stiffness:is.stiffness,damping:is.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:t}}}const P1=12;function E1(t,s,a){let r=a;for(let n=1;n<P1;n++)r=r-t(r)/s(r);return r}function ho(t,s){return t*Math.sqrt(1-s*s)}const _1=["duration","bounce"],M1=["stiffness","damping","mass"];function su(t,s){return s.some(a=>t[a]!==void 0)}function L1(t){let s={velocity:is.velocity,stiffness:is.stiffness,damping:is.damping,mass:is.mass,isResolvedFromDuration:!1,...t};if(!su(t,M1)&&su(t,_1))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*Wa(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:is.mass,stiffness:n,damping:i}}else{const a=I1(t);s={...s,...a,mass:is.mass},s.isResolvedFromDuration=!0}return s}function Oi(t=is.visualDuration,s=is.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:p,velocity:x,isResolvedFromDuration:u}=L1({...a,velocity:-pa(a.velocity||0)}),g=x||0,f=d/(2*Math.sqrt(c*m)),b=l-i,j=pa(Math.sqrt(c/m)),y=Math.abs(b)<5;r||(r=y?is.restSpeed.granular:is.restSpeed.default),n||(n=y?is.restDelta.granular:is.restDelta.default);let w;if(f<1){const S=ho(j,f);w=A=>{const _=Math.exp(-f*j*A);return l-_*((g+f*j*b)/S*Math.sin(S*A)+b*Math.cos(S*A))}}else if(f===1)w=S=>l-Math.exp(-j*S)*(b+(g+j*b)*S);else{const S=j*Math.sqrt(f*f-1);w=A=>{const _=Math.exp(-f*j*A),D=Math.min(S*A,300);return l-_*((g+f*j*b)*Math.sinh(D)+S*b*Math.cosh(D))/S}}const N={calculatedDuration:u&&p||null,next:S=>{const A=w(S);if(u)o.done=S>=p;else{let _=S===0?g:0;f<1&&(_=S===0?Da(g):Up(w,S,A));const D=Math.abs(_)<=r,R=Math.abs(l-A)<=n;o.done=D&&R}return o.value=o.done?l:A,o},toString:()=>{const S=Math.min(wc(N),Li),A=$p(_=>N.next(S*_).value,S,30);return S+"ms "+A},toTransition:()=>{}};return N}Oi.applyToOptions=t=>{const s=D1(t,100,Oi);return t.ease=s.ease,t.duration=Da(s.duration),t.type="keyframes",t};function po({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 p=t[0],x={done:!1,value:p},u=D=>o!==void 0&&D<o||c!==void 0&&D>c,g=D=>o===void 0?c:c===void 0||Math.abs(o-D)<Math.abs(c-D)?o:c;let f=a*s;const b=p+f,j=l===void 0?b:l(b);j!==b&&(f=j-p);const y=D=>-f*Math.exp(-D/r),w=D=>j+y(D),N=D=>{const R=y(D),v=w(D);x.done=Math.abs(R)<=d,x.value=x.done?j:v};let S,A;const _=D=>{u(x.value)&&(S=D,A=Oi({keyframes:[x.value,g(x.value)],velocity:Up(w,D,x.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return _(0),{calculatedDuration:null,next:D=>{let R=!1;return!A&&S===void 0&&(R=!0,N(D),_(D)),S!==void 0&&D>=S?A.next(D-S):(!R&&N(D),x)}}}function O1(t,s,a){const r=[],n=a||Ga.mix||Op,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]||ga:s;o=Zn(c,o)}r.push(o)}return r}function $1(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(xc(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=O1(s,r,n),c=o.length,d=m=>{if(l&&m<t[0])return s[0];let p=0;if(c>1)for(;p<t.length-2&&!(m<t[p+1]);p++);const x=On(t[p],t[p+1],m);return o[p](x)};return a?m=>d(Wa(t[0],t[i-1],m)):d}function U1(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=On(0,s,r);t.push(rs(a,1,n))}}function B1(t){const s=[0];return U1(s,t.length-1),s}function V1(t,s){return t.map(a=>a*s)}function z1(t,s){return t.map(()=>s||kp).splice(0,t.length-1)}function In({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=e1(r)?r.map(Jm):Jm(r),i={done:!1,value:s[0]},l=V1(a&&a.length===s.length?a:B1(s),t),o=$1(l,s,{ease:Array.isArray(n)?n:z1(s,n)});return{calculatedDuration:t,next:c=>(i.value=o(c),i.done=c>=t,i)}}const H1=t=>t!==null;function Cc(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(H1),o=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const W1={decay:po,inertia:po,tween:In,keyframes:In,spring:Oi};function Bp(t){typeof t.type=="string"&&(t.type=W1[t.type])}class Sc{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 G1=t=>t/100;class Ac extends Sc{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!==Js.now()&&this.tick(Js.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;Bp(s);const{type:a=In,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:l=0}=s;let{keyframes:o}=s;const c=a||In;c!==In&&typeof o[0]!="number"&&(this.mixKeyframes=Zn(G1,Op(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=wc(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:p,repeatType:x,repeatDelay:u,type:g,onUpdate:f,finalKeyframe:b}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,s):this.speed<0&&(this.startTime=Math.min(s-n/this.speed,this.startTime)),a?this.currentTime=s:this.updateTime(s);const j=this.currentTime-d*(this.playbackSpeed>=0?1:-1),y=this.playbackSpeed>=0?j<0:j>n;this.currentTime=Math.max(j,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let w=this.currentTime,N=r;if(p){const D=Math.min(this.currentTime,n)/o;let R=Math.floor(D),v=D%1;!v&&D>=1&&(v=1),v===1&&R--,R=Math.min(R,p+1),!!(R%2)&&(x==="reverse"?(v=1-v,u&&(v-=u/o)):x==="mirror"&&(N=l)),w=Wa(0,1,v)*o}const S=y?{done:!1,value:m[0]}:N.next(w);i&&(S.value=i(S.value));let{done:A}=S;!y&&c!==null&&(A=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const _=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&A);return _&&g!==po&&(S.value=Cc(m,this.options,b,this.speed)),f&&f(S.value),_&&this.finish(),S}then(s,a){return this.finished.then(s,a)}get duration(){return pa(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+pa(s)}get time(){return pa(this.currentTime)}set time(s){var a;s=Da(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(Js.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=pa(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=R1,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(Js.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 Y1(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const Rr=t=>t*180/Math.PI,go=t=>{const s=Rr(Math.atan2(t[1],t[0]));return fo(s)},K1={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:go,rotateZ:go,skewX:t=>Rr(Math.atan(t[1])),skewY:t=>Rr(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},fo=t=>(t=t%360,t<0&&(t+=360),t),au=go,ru=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),nu=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Q1={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ru,scaleY:nu,scale:t=>(ru(t)+nu(t))/2,rotateX:t=>fo(Rr(Math.atan2(t[6],t[5]))),rotateY:t=>fo(Rr(Math.atan2(-t[2],t[0]))),rotateZ:au,rotate:au,skewX:t=>Rr(Math.atan(t[4])),skewY:t=>Rr(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function bo(t){return t.includes("scale")?1:0}function jo(t,s){if(!t||t==="none")return bo(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=Q1,n=a;else{const o=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=K1,n=o}if(!n)return bo(s);const i=r[s],l=n[1].split(",").map(J1);return typeof i=="function"?i(l):l[i]}const X1=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return jo(a,s)};function J1(t){return parseFloat(t.trim())}const xn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],hn=new Set(xn),iu=t=>t===un||t===it,Z1=new Set(["x","y","z"]),q1=xn.filter(t=>!Z1.has(t));function eC(t){const s=[];return q1.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const Dr={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})=>jo(s,"x"),y:(t,{transform:s})=>jo(s,"y")};Dr.translateX=Dr.x;Dr.translateY=Dr.y;const Fr=new Set;let yo=!1,vo=!1,No=!1;function Vp(){if(vo){const t=Array.from(Fr).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=eC(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)})}vo=!1,yo=!1,Fr.forEach(t=>t.complete(No)),Fr.clear()}function zp(){Fr.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(vo=!0)})}function tC(){No=!0,zp(),Vp(),No=!1}class Tc{constructor(s,a,r,n,i,l=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...s],this.onComplete=a,this.name=r,this.motionValue=n,this.element=i,this.isAsync=l}scheduleResolve(){this.state="scheduled",this.isAsync?(Fr.add(this),yo||(yo=!0,qt.read(zp),qt.resolveKeyframes(Vp))):(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])}Y1(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),Fr.delete(this)}cancel(){this.state==="scheduled"&&(Fr.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const sC=t=>t.startsWith("--");function aC(t,s,a){sC(s)?t.style.setProperty(s,a):t.style[s]=a}const rC=hc(()=>window.ScrollTimeline!==void 0),nC={};function iC(t,s){const a=hc(t);return()=>nC[s]??a()}const Hp=iC(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),kn=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,lu={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:kn([0,.65,.55,1]),circOut:kn([.55,0,1,.45]),backIn:kn([.31,.01,.66,-.59]),backOut:kn([.33,1.53,.69,.99])};function Wp(t,s){if(t)return typeof t=="function"?Hp()?$p(t,s):"ease-out":Rp(t)?kn(t):Array.isArray(t)?t.map(a=>Wp(a,s)||lu.easeOut):lu[t]}function lC(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 p=Wp(o,n);Array.isArray(p)&&(m.easing=p);const x={delay:r,duration:n,easing:Array.isArray(p)?"linear":p,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(x.pseudoElement=d),t.animate(m,x)}function Gp(t){return typeof t=="function"&&"applyToOptions"in t}function oC({type:t,...s}){return Gp(t)&&Hp()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class cC extends Sc{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,xc(typeof s.type!="string");const d=oC(s);this.animation=lC(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=Cc(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(m):aC(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 pa(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+pa(s)}get time(){return pa(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=Da(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&&rC()?(this.animation.timeline=s,ga):a(this)}}const Yp={anticipate:Sp,backInOut:Cp,circInOut:Tp};function dC(t){return t in Yp}function mC(t){typeof t.ease=="string"&&dC(t.ease)&&(t.ease=Yp[t.ease])}const ou=10;class uC extends cC{constructor(s){mC(s),Bp(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 Ac({...l,autoplay:!1}),c=Da(this.finishedTime??this.time);a.setWithVelocity(o.sample(c-ou).value,o.sample(c).value,ou),o.stop()}}const cu=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(mr.test(t)||t==="0")&&!t.startsWith("url("));function xC(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 hC(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=cu(n,s),o=cu(i,s);return!l||!o?!1:xC(t)||(a==="spring"||Gp(a))&&r}function wo(t){t.duration=0,t.type="keyframes"}const pC=new Set(["opacity","clipPath","filter","transform"]),gC=hc(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function fC(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 gC()&&a&&pC.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&l!=="inertia"}const bC=40;class jC extends Sc{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,...p}){var g;super(),this.stop=()=>{var f,b;this._animation&&(this._animation.stop(),(f=this.stopTimeline)==null||f.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=Js.now();const x={autoplay:s,delay:a,type:r,repeat:n,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:m,...p},u=(m==null?void 0:m.KeyframeResolver)||Tc;this.keyframeResolver=new u(o,(f,b,j)=>this.onKeyframesResolved(f,b,x,!j),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=Js.now(),hC(s,i,l,o)||((Ga.instantAnimations||!c)&&(m==null||m(Cc(s,r,a))),s[0]=s[s.length-1],wo(r),r.repeat=0);const x={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>bC?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},u=!d&&fC(x)?new uC({...x,element:x.motionValue.owner.current}):new Ac(x);u.finished.then(()=>this.notifyFinished()).catch(ga),this.pendingTimeline&&(this.stopTimeline=u.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=u}get finished(){return this._animation?this.animation.finished:this._finished}then(s,a){return this.finished.finally(s).then(()=>{})}get animation(){var s;return this._animation||((s=this.keyframeResolver)==null||s.resume(),tC()),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 yC=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function vC(t){const s=yC.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Kp(t,s,a=1){const[r,n]=vC(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const l=i.trim();return gp(l)?parseFloat(l):l}return jc(n)?Kp(n,s,a+1):n}function kc(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const Qp=new Set(["width","height","top","left","right","bottom",...xn]),NC={test:t=>t==="auto",parse:t=>t},Xp=t=>s=>s.test(t),Jp=[un,it,Fa,ar,x1,u1,NC],du=t=>Jp.find(Xp(t));function wC(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||bp(t):!0}const CC=new Set(["brightness","contrast","saturate","opacity"]);function SC(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(yc)||[];if(!r)return t;const n=a.replace(r,"");let i=CC.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const AC=/\b([a-z-]*)\(.*?\)/gu,Co={...mr,getAnimatableNone:t=>{const s=t.match(AC);return s?s.map(SC).join(" "):t}},mu={...un,transform:Math.round},TC={rotate:ar,rotateX:ar,rotateY:ar,rotateZ:ar,scale:oi,scaleX:oi,scaleY:oi,scaleZ:oi,skew:ar,skewX:ar,skewY:ar,distance:it,translateX:it,translateY:it,translateZ:it,x:it,y:it,z:it,perspective:it,transformPerspective:it,opacity:$n,originX:Zm,originY:Zm,originZ:it},Rc={borderWidth:it,borderTopWidth:it,borderRightWidth:it,borderBottomWidth:it,borderLeftWidth:it,borderRadius:it,radius:it,borderTopLeftRadius:it,borderTopRightRadius:it,borderBottomRightRadius:it,borderBottomLeftRadius:it,width:it,maxWidth:it,height:it,maxHeight:it,top:it,right:it,bottom:it,left:it,padding:it,paddingTop:it,paddingRight:it,paddingBottom:it,paddingLeft:it,margin:it,marginTop:it,marginRight:it,marginBottom:it,marginLeft:it,backgroundPositionX:it,backgroundPositionY:it,...TC,zIndex:mu,fillOpacity:$n,strokeOpacity:$n,numOctaves:mu},kC={...Rc,color:hs,backgroundColor:hs,outlineColor:hs,fill:hs,stroke:hs,borderColor:hs,borderTopColor:hs,borderRightColor:hs,borderBottomColor:hs,borderLeftColor:hs,filter:Co,WebkitFilter:Co},Zp=t=>kC[t];function qp(t,s){let a=Zp(t);return a!==Co&&(a=mr),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const RC=new Set(["auto","none","0"]);function DC(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!RC.has(i)&&Un(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=qp(a,n)}class FC extends Tc{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(),jc(d))){const m=Kp(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!Qp.has(r)||s.length!==2)return;const[n,i]=s,l=du(n),o=du(i);if(l!==o)if(iu(l)&&iu(o))for(let c=0;c<s.length;c++){const d=s[c];typeof d=="string"&&(s[c]=parseFloat(d))}else Dr[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||wC(s[n]))&&r.push(n);r.length&&DC(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=Dr[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]=Dr[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 IC(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 eg=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function tg(t){return fp(t)&&"offsetHeight"in t}const uu=30,PC=t=>!isNaN(parseFloat(t));class EC{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=Js.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=Js.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=PC(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 pc);const r=this.events[s].add(a);return s==="change"?()=>{r(),qt.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=Js.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>uu)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,uu);return jp(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 tn(t,s){return new EC(t,s)}const{schedule:Dc}=Dp(queueMicrotask,!1),Na={x:!1,y:!1};function sg(){return Na.x||Na.y}function _C(t){return t==="x"||t==="y"?Na[t]?null:(Na[t]=!0,()=>{Na[t]=!1}):Na.x||Na.y?null:(Na.x=Na.y=!0,()=>{Na.x=Na.y=!1})}function ag(t,s){const a=IC(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function xu(t){return!(t.pointerType==="touch"||sg())}function MC(t,s,a={}){const[r,n,i]=ag(t,a),l=o=>{if(!xu(o))return;const{target:c}=o,d=s(c,o);if(typeof d!="function"||!c)return;const m=p=>{xu(p)&&(d(p),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(o=>{o.addEventListener("pointerenter",l,n)}),i}const rg=(t,s)=>s?t===s?!0:rg(t,s.parentElement):!1,Fc=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,LC=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function OC(t){return LC.has(t.tagName)||t.tabIndex!==-1}const Ni=new WeakSet;function hu(t){return s=>{s.key==="Enter"&&t(s)}}function Ml(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const $C=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=hu(()=>{if(Ni.has(a))return;Ml(a,"down");const n=hu(()=>{Ml(a,"up")}),i=()=>Ml(a,"cancel");a.addEventListener("keyup",n,s),a.addEventListener("blur",i,s)});a.addEventListener("keydown",r,s),a.addEventListener("blur",()=>a.removeEventListener("keydown",r),s)};function pu(t){return Fc(t)&&!sg()}function UC(t,s,a={}){const[r,n,i]=ag(t,a),l=o=>{const c=o.currentTarget;if(!pu(o))return;Ni.add(c);const d=s(c,o),m=(u,g)=>{window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",x),Ni.has(c)&&Ni.delete(c),pu(u)&&typeof d=="function"&&d(u,{success:g})},p=u=>{m(u,c===window||c===document||a.useGlobalTarget||rg(c,u.target))},x=u=>{m(u,!1)};window.addEventListener("pointerup",p,n),window.addEventListener("pointercancel",x,n)};return r.forEach(o=>{(a.useGlobalTarget?window:o).addEventListener("pointerdown",l,n),tg(o)&&(o.addEventListener("focus",d=>$C(d,n)),!OC(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function ng(t){return fp(t)&&"ownerSVGElement"in t}function BC(t){return ng(t)&&t.tagName==="svg"}const Ls=t=>!!(t&&t.getVelocity),VC=[...Jp,hs,mr],zC=t=>VC.find(Xp(t)),Ic=h.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function gu(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function HC(...t){return s=>{let a=!1;const r=t.map(n=>{const i=gu(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():gu(t[n],null)}}}}function WC(...t){return h.useCallback(HC(...t),t)}class GC extends h.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=tg(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 YC({children:t,isPresent:s,anchorX:a,root:r}){const n=h.useId(),i=h.useRef(null),l=h.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:o}=h.useContext(Ic),c=WC(i,t==null?void 0:t.ref);return h.useInsertionEffect(()=>{const{width:d,height:m,top:p,left:x,right:u}=l.current;if(s||!i.current||!d||!m)return;const g=a==="left"?`left: ${x}`:`right: ${u}`;i.current.dataset.motionPopId=n;const f=document.createElement("style");o&&(f.nonce=o);const b=r??document.head;return b.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: ${p}px !important;
|
||
}
|
||
`),()=>{b.contains(f)&&b.removeChild(f)}},[s]),e.jsx(GC,{isPresent:s,childRef:i,sizeRef:l,children:h.cloneElement(t,{ref:c})})}const KC=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=cc(QC),m=h.useId();let p=!0,x=h.useMemo(()=>(p=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:u=>{d.set(u,!0);for(const g of d.values())if(!g)return;r&&r()},register:u=>(d.set(u,!1),()=>d.delete(u))}),[a,d,r]);return i&&p&&(x={...x}),h.useMemo(()=>{d.forEach((u,g)=>d.set(g,!1))},[a]),h.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(YC,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(ll.Provider,{value:x,children:t})};function QC(){return new Map}function ig(t=!0){const s=h.useContext(ll);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=h.useId();h.useEffect(()=>{if(t)return n(i)},[t]);const l=h.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const ci=t=>t.key||"";function fu(t){const s=[];return h.Children.forEach(t,a=>{h.isValidElement(a)&&s.push(a)}),s}const ol=({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]=ig(l),p=h.useMemo(()=>fu(t),[t]),x=l&&!d?[]:p.map(ci),u=h.useRef(!0),g=h.useRef(p),f=cc(()=>new Map),[b,j]=h.useState(p),[y,w]=h.useState(p);pp(()=>{u.current=!1,g.current=p;for(let A=0;A<y.length;A++){const _=ci(y[A]);x.includes(_)?f.delete(_):f.get(_)!==!0&&f.set(_,!1)}},[y,x.length,x.join("-")]);const N=[];if(p!==b){let A=[...p];for(let _=0;_<y.length;_++){const D=y[_],R=ci(D);x.includes(R)||(A.splice(_,0,D),N.push(D))}return i==="wait"&&N.length&&(A=N),w(fu(A)),j(p),null}const{forceRender:S}=h.useContext(oc);return e.jsx(e.Fragment,{children:y.map(A=>{const _=ci(A),D=l&&!d?!1:p===y||x.includes(_),R=()=>{if(f.has(_))f.set(_,!0);else return;let v=!0;f.forEach(P=>{P||(v=!1)}),v&&(S==null||S(),w(g.current),l&&(m==null||m()),r&&r())};return e.jsx(KC,{isPresent:D,initial:!u.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:D?void 0:R,anchorX:o,children:A},_)})})},lg=h.createContext({strict:!1}),bu={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"]},sn={};for(const t in bu)sn[t]={isEnabled:s=>bu[t].some(a=>!!s[a])};function XC(t){for(const s in t)sn[s]={...sn[s],...t[s]}}const JC=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 $i(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||JC.has(t)}let og=t=>!$i(t);function ZC(t){typeof t=="function"&&(og=s=>s.startsWith("on")?!$i(s):t(s))}try{ZC(require("@emotion/is-prop-valid").default)}catch{}function qC(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(og(n)||a===!0&&$i(n)||!s&&!$i(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const cl=h.createContext({});function dl(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Bn(t){return typeof t=="string"||Array.isArray(t)}const Pc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Ec=["initial",...Pc];function ml(t){return dl(t.animate)||Ec.some(s=>Bn(t[s]))}function cg(t){return!!(ml(t)||t.variants)}function e2(t,s){if(ml(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Bn(a)?a:void 0,animate:Bn(r)?r:void 0}}return t.inherit!==!1?s:{}}function t2(t){const{initial:s,animate:a}=e2(t,h.useContext(cl));return h.useMemo(()=>({initial:s,animate:a}),[ju(s),ju(a)])}function ju(t){return Array.isArray(t)?t.join(" "):t}const Vn={};function s2(t){for(const s in t)Vn[s]=t[s],bc(s)&&(Vn[s].isCSSVariable=!0)}function dg(t,{layout:s,layoutId:a}){return hn.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!Vn[t]||t==="opacity")}const a2={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},r2=xn.length;function n2(t,s,a){let r="",n=!0;for(let i=0;i<r2;i++){const l=xn[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=eg(o,Rc[l]);if(!c){n=!1;const m=a2[l]||l;r+=`${m}(${d}) `}a&&(s[l]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function _c(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(hn.has(c)){l=!0;continue}else if(bc(c)){n[c]=d;continue}else{const m=eg(d,Rc[c]);c.startsWith("origin")?(o=!0,i[c]=m):r[c]=m}}if(s.transform||(l||a?r.transform=n2(s,t.transform,a):r.transform&&(r.transform="none")),o){const{originX:c="50%",originY:d="50%",originZ:m=0}=i;r.transformOrigin=`${c} ${d} ${m}`}}const Mc=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function mg(t,s,a){for(const r in s)!Ls(s[r])&&!dg(r,a)&&(t[r]=s[r])}function i2({transformTemplate:t},s){return h.useMemo(()=>{const a=Mc();return _c(a,s,t),Object.assign({},a.vars,a.style)},[s])}function l2(t,s){const a=t.style||{},r={};return mg(r,a,t),Object.assign(r,i2(t,s)),r}function o2(t,s){const a={},r=l2(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 c2={offset:"stroke-dashoffset",array:"stroke-dasharray"},d2={offset:"strokeDashoffset",array:"strokeDasharray"};function m2(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?c2:d2;t[i.offset]=it.transform(-r);const l=it.transform(s),o=it.transform(a);t[i.array]=`${l} ${o}`}function ug(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(_c(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:p,style:x}=t;p.transform&&(x.transform=p.transform,delete p.transform),(x.transform||p.transformOrigin)&&(x.transformOrigin=p.transformOrigin??"50% 50%",delete p.transformOrigin),x.transform&&(x.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete p.transformBox),s!==void 0&&(p.x=s),a!==void 0&&(p.y=a),r!==void 0&&(p.scale=r),n!==void 0&&m2(p,n,i,l,!1)}const xg=()=>({...Mc(),attrs:{}}),hg=t=>typeof t=="string"&&t.toLowerCase()==="svg";function u2(t,s,a,r){const n=h.useMemo(()=>{const i=xg();return ug(i,s,hg(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};mg(i,t.style,t),n.style={...i,...n.style}}return n}const x2=["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 Lc(t){return typeof t!="string"||t.includes("-")?!1:!!(x2.indexOf(t)>-1||/[A-Z]/u.test(t))}function h2(t,s,a,{latestValues:r},n,i=!1){const o=(Lc(t)?u2:o2)(s,r,n,t),c=qC(s,typeof t=="string",i),d=t!==h.Fragment?{...c,...o,ref:a}:{},{children:m}=s,p=h.useMemo(()=>Ls(m)?m.get():m,[m]);return h.createElement(t,{...d,children:p})}function yu(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function Oc(t,s,a,r){if(typeof s=="function"){const[n,i]=yu(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]=yu(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function wi(t){return Ls(t)?t.get():t}function p2({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:g2(a,r,n,t),renderState:s()}}function g2(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=wi(i[x]);let{initial:l,animate:o}=t;const c=ml(t),d=cg(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 p=m?o:l;if(p&&typeof p!="boolean"&&!dl(p)){const x=Array.isArray(p)?p:[p];for(let u=0;u<x.length;u++){const g=Oc(t,x[u]);if(g){const{transitionEnd:f,transition:b,...j}=g;for(const y in j){let w=j[y];if(Array.isArray(w)){const N=m?w.length-1:0;w=w[N]}w!==null&&(n[y]=w)}for(const y in f)n[y]=f[y]}}}return n}const pg=t=>(s,a)=>{const r=h.useContext(cl),n=h.useContext(ll),i=()=>p2(t,s,r,n);return a?i():cc(i)};function $c(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(Ls(r[l])||s.style&&Ls(s.style[l])||dg(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const f2=pg({scrapeMotionValuesFromProps:$c,createRenderState:Mc});function gg(t,s,a){const r=$c(t,s,a);for(const n in t)if(Ls(t[n])||Ls(s[n])){const i=xn.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const b2=pg({scrapeMotionValuesFromProps:gg,createRenderState:xg}),j2=Symbol.for("motionComponentSymbol");function Hr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function y2(t,s,a){return h.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):Hr(a)&&(a.current=r))},[s])}const Uc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),v2="framerAppearId",fg="data-"+Uc(v2),bg=h.createContext({});function N2(t,s,a,r,n){var f,b;const{visualElement:i}=h.useContext(cl),l=h.useContext(lg),o=h.useContext(ll),c=h.useContext(Ic).reducedMotion,d=h.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,p=h.useContext(bg);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&w2(d.current,a,n,p);const x=h.useRef(!1);h.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const u=a[fg],g=h.useRef(!!u&&!((f=window.MotionHandoffIsComplete)!=null&&f.call(window,u))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,u)));return pp(()=>{m&&(x.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),h.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var j;(j=window.MotionHandoffMarkAsComplete)==null||j.call(window,u)}),g.current=!1),m.enteringChildren=void 0)}),m}function w2(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:jg(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Hr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function jg(t){if(t)return t.options.allowProjection!==!1?t.projection:jg(t.parent)}function Ll(t,{forwardMotionProps:s=!1}={},a,r){a&&XC(a);const n=Lc(t)?b2:f2;function i(o,c){let d;const m={...h.useContext(Ic),...o,layoutId:C2(o)},{isStatic:p}=m,x=t2(o),u=n(o,p);if(!p&&dc){S2();const g=A2(m);d=g.MeasureLayout,x.visualElement=N2(t,u,m,r,g.ProjectionNode)}return e.jsxs(cl.Provider,{value:x,children:[d&&x.visualElement?e.jsx(d,{visualElement:x.visualElement,...m}):null,h2(t,o,y2(u,x.visualElement,c),u,p,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=h.forwardRef(i);return l[j2]=t,l}function C2({layoutId:t}){const s=h.useContext(oc).id;return s&&t!==void 0?s+"-"+t:t}function S2(t,s){h.useContext(lg).strict}function A2(t){const{drag:s,layout:a}=sn;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 T2(t,s){if(typeof Proxy>"u")return Ll;const a=new Map,r=(i,l)=>Ll(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,Ll(l,void 0,t,s)),a.get(l))})}function yg({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function k2({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function R2(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 Ol(t){return t===void 0||t===1}function So({scale:t,scaleX:s,scaleY:a}){return!Ol(t)||!Ol(s)||!Ol(a)}function wr(t){return So(t)||vg(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function vg(t){return vu(t.x)||vu(t.y)}function vu(t){return t&&t!=="0%"}function Ui(t,s,a){const r=t-a,n=s*r;return a+n}function Nu(t,s,a,r,n){return n!==void 0&&(t=Ui(t,n,r)),Ui(t,a,r)+s}function Ao(t,s=0,a=1,r,n){t.min=Nu(t.min,s,a,r,n),t.max=Nu(t.max,s,a,r,n)}function Ng(t,{x:s,y:a}){Ao(t.x,s.translate,s.scale,s.originPoint),Ao(t.y,a.translate,a.scale,a.originPoint)}const wu=.999999999999,Cu=1.0000000000001;function D2(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&&Gr(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),l&&(s.x*=l.x.scale,s.y*=l.y.scale,Ng(t,l)),r&&wr(i.latestValues)&&Gr(t,i.latestValues))}s.x<Cu&&s.x>wu&&(s.x=1),s.y<Cu&&s.y>wu&&(s.y=1)}function Wr(t,s){t.min=t.min+s,t.max=t.max+s}function Su(t,s,a,r,n=.5){const i=rs(t.min,t.max,n);Ao(t,s,a,i,r)}function Gr(t,s){Su(t.x,s.x,s.scaleX,s.scale,s.originX),Su(t.y,s.y,s.scaleY,s.scale,s.originY)}function wg(t,s){return yg(R2(t.getBoundingClientRect(),s))}function F2(t,s,a){const r=wg(t,a),{scroll:n}=s;return n&&(Wr(r.x,n.offset.x),Wr(r.y,n.offset.y)),r}const Au=()=>({translate:0,scale:1,origin:0,originPoint:0}),Yr=()=>({x:Au(),y:Au()}),Tu=()=>({min:0,max:0}),ds=()=>({x:Tu(),y:Tu()}),To={current:null},Cg={current:!1};function I2(){if(Cg.current=!0,!!dc)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>To.current=t.matches;t.addEventListener("change",s),s()}else To.current=!1}const P2=new WeakMap;function E2(t,s,a){for(const r in s){const n=s[r],i=a[r];if(Ls(n))t.addValue(r,n);else if(Ls(i))t.addValue(r,tn(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,tn(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const ku=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class _2{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=Tc,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const x=Js.now();this.renderScheduledAt<x&&(this.renderScheduledAt=x,qt.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=ml(a),this.isVariantNode=cg(a),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(s&&s.current);const{willChange:m,...p}=this.scrapeMotionValuesFromProps(a,{},this);for(const x in p){const u=p[x];c[x]!==void 0&&Ls(u)&&u.set(c[x])}}mount(s){var a;this.current=s,P2.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)),Cg.current||I2(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:To.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),dr(this.notifyUpdate),dr(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=hn.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&qt.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 sn){const a=sn[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):ds()}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<ku.length;r++){const n=ku[r];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);const i="on"+n,l=s[i];l&&(this.propEventSubscriptions[n]=this.on(n,l))}this.prevMotionValues=E2(this,this.scrapeMotionValuesFromProps(s,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(s){return this.props.variants?this.props.variants[s]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(s){const a=this.getClosestVariantNode();if(a)return a.variantChildren&&a.variantChildren.add(s),()=>a.variantChildren.delete(s)}addValue(s,a){const r=this.values.get(s);a!==r&&(r&&this.removeValue(s),this.bindToMotionValue(s,a),this.values.set(s,a),this.latestValues[s]=a.get())}removeValue(s){this.values.delete(s);const a=this.valueSubscriptions.get(s);a&&(a(),this.valueSubscriptions.delete(s)),delete this.latestValues[s],this.removeValueFromRenderState(s,this.renderState)}hasValue(s){return this.values.has(s)}getValue(s,a){if(this.props.values&&this.props.values[s])return this.props.values[s];let r=this.values.get(s);return r===void 0&&a!==void 0&&(r=tn(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"&&(gp(r)||bp(r))?r=parseFloat(r):!zC(r)&&mr.test(a)&&(r=qp(s,a)),this.setBaseTarget(s,Ls(r)?r.get():r)),Ls(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=Oc(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&&!Ls(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 pc),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){Dc.render(this.render)}}class Sg extends _2{constructor(){super(...arguments),this.KeyframeResolver=FC}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;Ls(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Ag(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 M2(t){return window.getComputedStyle(t)}class L2 extends Sg{constructor(){super(...arguments),this.type="html",this.renderInstance=Ag}readValueFromInstance(s,a){var r;if(hn.has(a))return(r=this.projection)!=null&&r.isProjecting?bo(a):X1(s,a);{const n=M2(s),i=(bc(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return wg(s,a)}build(s,a,r){_c(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return $c(s,a,r)}}const Tg=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 O2(t,s,a,r){Ag(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(Tg.has(n)?n:Uc(n),s.attrs[n])}class $2 extends Sg{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ds}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(hn.has(a)){const r=Zp(a);return r&&r.default||0}return a=Tg.has(a)?a:Uc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return gg(s,a,r)}build(s,a,r){ug(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){O2(s,a,r,n)}mount(s){this.isSVGTag=hg(s.tagName),super.mount(s)}}const U2=(t,s)=>Lc(t)?new $2(s):new L2(s,{allowProjection:t!==h.Fragment});function qr(t,s,a){const r=t.getProps();return Oc(r,s,a!==void 0?a:r.custom,t)}const ko=t=>Array.isArray(t);function B2(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,tn(a))}function V2(t){return ko(t)?t[t.length-1]||0:t}function z2(t,s){const a=qr(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=V2(i[l]);B2(t,l,o)}}function H2(t){return!!(Ls(t)&&t.add)}function Ro(t,s){const a=t.getValue("willChange");if(H2(a))return a.add(s);if(!a&&Ga.WillChange){const r=new Ga.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function kg(t){return t.props[fg]}const W2=t=>t!==null;function G2(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(W2),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const Y2={type:"spring",stiffness:500,damping:25,restSpeed:10},K2=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Q2={type:"keyframes",duration:.8},X2={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},J2=(t,{keyframes:s})=>s.length>2?Q2:hn.has(t)?t.startsWith("scale")?K2(s[1]):Y2:X2;function Z2({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 Bc=(t,s,a,r={},n,i)=>l=>{const o=kc(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Da(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:x=>{s.set(x),o.onUpdate&&o.onUpdate(x)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};Z2(o)||Object.assign(m,J2(t,m)),m.duration&&(m.duration=Da(m.duration)),m.repeatDelay&&(m.repeatDelay=Da(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let p=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(wo(m),m.delay===0&&(p=!0)),(Ga.instantAnimations||Ga.skipAnimations)&&(p=!0,wo(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,p&&!i&&s.get()!==void 0){const x=G2(m.keyframes,o);if(x!==void 0){qt.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Ac(m):new jC(m)};function q2({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Rg(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 p=t.getValue(m,t.latestValues[m]??null),x=o[m];if(x===void 0||d&&q2(d,m))continue;const u={delay:a,...kc(i||{},m)},g=p.get();if(g!==void 0&&!p.isAnimating&&!Array.isArray(x)&&x===g&&!u.velocity)continue;let f=!1;if(window.MotionHandoffAnimation){const j=kg(t);if(j){const y=window.MotionHandoffAnimation(j,m,qt);y!==null&&(u.startTime=y,f=!0)}}Ro(t,m),p.start(Bc(m,p,x,t.shouldReduceMotion&&Qp.has(m)?{type:!1}:u,t,f));const b=p.animation;b&&c.push(b)}return l&&Promise.all(c).then(()=>{qt.update(()=>{l&&z2(t,l)})}),c}function Dg(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 Do(t,s,a={}){var c;const r=qr(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(Rg(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:p,staggerDirection:x}=n;return eS(t,s,d,m,p,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function eS(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(Do(c,s,{...l,delay:a+(typeof r=="function"?0:r)+Dg(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function tS(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>Do(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=Do(t,s,a);else{const n=typeof s=="function"?qr(t,s,a.custom):s;r=Promise.all(Rg(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function Fg(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 sS=Ec.length;function Ig(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?Ig(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<sS;a++){const r=Ec[a],n=t.props[r];(Bn(n)||n===!1)&&(s[r]=n)}return s}const aS=[...Pc].reverse(),rS=Pc.length;function nS(t){return s=>Promise.all(s.map(({animation:a,options:r})=>tS(t,a,r)))}function iS(t){let s=nS(t),a=Ru(),r=!0;const n=c=>(d,m)=>{var x;const p=qr(t,m,c==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(p){const{transition:u,transitionEnd:g,...f}=p;d={...d,...f,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=Ig(t.parent)||{},p=[],x=new Set;let u={},g=1/0;for(let b=0;b<rS;b++){const j=aS[b],y=a[j],w=d[j]!==void 0?d[j]:m[j],N=Bn(w),S=j===c?y.isActive:null;S===!1&&(g=b);let A=w===m[j]&&w!==d[j]&&N;if(A&&r&&t.manuallyAnimateOnMount&&(A=!1),y.protectedKeys={...u},!y.isActive&&S===null||!w&&!y.prevProp||dl(w)||typeof w=="boolean")continue;const _=lS(y.prevProp,w);let D=_||j===c&&y.isActive&&!A&&N||b>g&&N,R=!1;const v=Array.isArray(w)?w:[w];let P=v.reduce(n(j),{});S===!1&&(P={});const{prevResolvedValues:C={}}=y,V={...C,...P},F=T=>{D=!0,x.has(T)&&(R=!0,x.delete(T)),y.needsAnimating[T]=!0;const k=t.getValue(T);k&&(k.liveStyle=!1)};for(const T in V){const k=P[T],z=C[T];if(u.hasOwnProperty(T))continue;let L=!1;ko(k)&&ko(z)?L=!Fg(k,z):L=k!==z,L?k!=null?F(T):x.add(T):k!==void 0&&x.has(T)?F(T):y.protectedKeys[T]=!0}y.prevProp=w,y.prevResolvedValues=P,y.isActive&&(u={...u,...P}),r&&t.blockInitialAnimation&&(D=!1);const $=A&&_;D&&(!$||R)&&p.push(...v.map(T=>{const k={type:j};if(typeof T=="string"&&r&&!$&&t.manuallyAnimateOnMount&&t.parent){const{parent:z}=t,L=qr(z,T);if(z.enteringChildren&&L){const{delayChildren:M}=L.transition||{};k.delay=Dg(z.enteringChildren,t,M)}}return{animation:T,options:k}}))}if(x.size){const b={};if(typeof d.initial!="boolean"){const j=qr(t,Array.isArray(d.initial)?d.initial[0]:d.initial);j&&j.transition&&(b.transition=j.transition)}x.forEach(j=>{const y=t.getBaseTarget(j),w=t.getValue(j);w&&(w.liveStyle=!0),b[j]=y??null}),p.push({animation:b})}let f=!!p.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(f=!1),r=!1,f?s(p):Promise.resolve()}function o(c,d){var p;if(a[c].isActive===d)return Promise.resolve();(p=t.variantChildren)==null||p.forEach(x=>{var u;return(u=x.animationState)==null?void 0:u.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const x in a)a[x].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Ru()}}}function lS(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!Fg(s,t):!1}function jr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Ru(){return{animate:jr(!0),whileInView:jr(),whileHover:jr(),whileTap:jr(),whileDrag:jr(),whileFocus:jr(),exit:jr()}}class ur{constructor(s){this.isMounted=!1,this.node=s}update(){}}class oS extends ur{constructor(s){super(s),s.animationState||(s.animationState=iS(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();dl(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 cS=0;class dS extends ur{constructor(){super(...arguments),this.id=cS++}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 mS={animation:{Feature:oS},exit:{Feature:dS}};function zn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function ti(t){return{point:{x:t.pageX,y:t.pageY}}}const uS=t=>s=>Fc(s)&&t(s,ti(s));function Pn(t,s,a,r){return zn(t,s,uS(a),r)}const Pg=1e-4,xS=1-Pg,hS=1+Pg,Eg=.01,pS=0-Eg,gS=0+Eg;function Vs(t){return t.max-t.min}function fS(t,s,a){return Math.abs(t-s)<=a}function Du(t,s,a,r=.5){t.origin=r,t.originPoint=rs(s.min,s.max,t.origin),t.scale=Vs(a)/Vs(s),t.translate=rs(a.min,a.max,t.origin)-t.originPoint,(t.scale>=xS&&t.scale<=hS||isNaN(t.scale))&&(t.scale=1),(t.translate>=pS&&t.translate<=gS||isNaN(t.translate))&&(t.translate=0)}function En(t,s,a,r){Du(t.x,s.x,a.x,r?r.originX:void 0),Du(t.y,s.y,a.y,r?r.originY:void 0)}function Fu(t,s,a){t.min=a.min+s.min,t.max=t.min+Vs(s)}function bS(t,s,a){Fu(t.x,s.x,a.x),Fu(t.y,s.y,a.y)}function Iu(t,s,a){t.min=s.min-a.min,t.max=t.min+Vs(s)}function _n(t,s,a){Iu(t.x,s.x,a.x),Iu(t.y,s.y,a.y)}function ha(t){return[t("x"),t("y")]}const _g=({current:t})=>t?t.ownerDocument.defaultView:null,Pu=(t,s)=>Math.abs(t-s);function jS(t,s){const a=Pu(t.x,s.x),r=Pu(t.y,s.y);return Math.sqrt(a**2+r**2)}class Mg{constructor(s,a,{transformPagePoint:r,contextWindow:n=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const x=Ul(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,g=jS(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!u&&!g)return;const{point:f}=x,{timestamp:b}=Is;this.history.push({...f,timestamp:b});const{onStart:j,onMove:y}=this.handlers;u||(j&&j(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),y&&y(this.lastMoveEvent,x)},this.handlePointerMove=(x,u)=>{this.lastMoveEvent=x,this.lastMoveEventInfo=$l(u,this.transformPagePoint),qt.update(this.updatePoint,!0)},this.handlePointerUp=(x,u)=>{this.end();const{onEnd:g,onSessionEnd:f,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=Ul(x.type==="pointercancel"?this.lastMoveEventInfo:$l(u,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,j),f&&f(x,j)},!Fc(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=ti(s),c=$l(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=Is;this.history=[{...d,timestamp:m}];const{onSessionStart:p}=a;p&&p(s,Ul(c,this.history)),this.removeListeners=Zn(Pn(this.contextWindow,"pointermove",this.handlePointerMove),Pn(this.contextWindow,"pointerup",this.handlePointerUp),Pn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),dr(this.updatePoint)}}function $l(t,s){return s?{point:s(t.point)}:t}function Eu(t,s){return{x:t.x-s.x,y:t.y-s.y}}function Ul({point:t},s){return{point:t,delta:Eu(t,Lg(s)),offset:Eu(t,yS(s)),velocity:vS(s,.1)}}function yS(t){return t[0]}function Lg(t){return t[t.length-1]}function vS(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Lg(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>Da(s)));)a--;if(!r)return{x:0,y:0};const i=pa(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 NS(t,{min:s,max:a},r){return s!==void 0&&t<s?t=r?rs(s,t,r.min):Math.max(t,s):a!==void 0&&t>a&&(t=r?rs(a,t,r.max):Math.min(t,a)),t}function _u(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 wS(t,{top:s,left:a,bottom:r,right:n}){return{x:_u(t.x,a,n),y:_u(t.y,s,r)}}function Mu(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 CS(t,s){return{x:Mu(t.x,s.x),y:Mu(t.y,s.y)}}function SS(t,s){let a=.5;const r=Vs(t),n=Vs(s);return n>r?a=On(s.min,s.max-r,t.min):r>n&&(a=On(t.min,t.max-n,s.min)),Wa(0,1,a)}function AS(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 Fo=.35;function TS(t=Fo){return t===!1?t=0:t===!0&&(t=Fo),{x:Lu(t,"left","right"),y:Lu(t,"top","bottom")}}function Lu(t,s,a){return{min:Ou(t,s),max:Ou(t,a)}}function Ou(t,s){return typeof t=="number"?t:t[s]||0}const kS=new WeakMap;class RS{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=ds(),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=p=>{const{dragSnapToOrigin:x}=this.getProps();x?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(ti(p).point)},l=(p,x)=>{const{drag:u,dragPropagation:g,onDragStart:f}=this.getProps();if(u&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=_C(u),!this.openDragLock))return;this.latestPointerEvent=p,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ha(j=>{let y=this.getAxisMotionValue(j).get()||0;if(Fa.test(y)){const{projection:w}=this.visualElement;if(w&&w.layout){const N=w.layout.layoutBox[j];N&&(y=Vs(N)*(parseFloat(y)/100))}}this.originPoint[j]=y}),f&&qt.postRender(()=>f(p,x)),Ro(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},o=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x;const{dragPropagation:u,dragDirectionLock:g,onDirectionLock:f,onDrag:b}=this.getProps();if(!u&&!this.openDragLock)return;const{offset:j}=x;if(g&&this.currentDirection===null){this.currentDirection=DS(j),this.currentDirection!==null&&f&&f(this.currentDirection);return}this.updateAxis("x",x.point,j),this.updateAxis("y",x.point,j),this.visualElement.render(),b&&b(p,x)},c=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x,this.stop(p,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>ha(p=>{var x;return this.getAnimationState(p)==="paused"&&((x=this.getAxisMotionValue(p).animation)==null?void 0:x.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new Mg(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:_g(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&&qt.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||!di(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=NS(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&&Hr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=wS(r.layoutBox,s):this.constraints=!1,this.elastic=TS(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&ha(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=AS(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Hr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=F2(r,n.root,this.visualElement.getTransformPagePoint());let l=CS(n.layout.layoutBox,i);if(a){const o=a(k2(l));this.hasMutatedConstraints=!!o,o&&(l=yg(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=ha(m=>{if(!di(m,a,this.currentDirection))return;let p=c&&c[m]||{};l&&(p={min:0,max:0});const x=n?200:1e6,u=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:x,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...p};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return Ro(this.visualElement,s),r.start(Bc(s,r,0,a,this.visualElement,!1))}stopAnimation(){ha(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){ha(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){ha(a=>{const{drag:r}=this.getProps();if(!di(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]-rs(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Hr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};ha(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=SS({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(),ha(l=>{if(!di(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(rs(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;kS.set(this.visualElement,this);const s=this.visualElement.current,a=Pn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();Hr(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()),qt.read(r);const l=zn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(ha(m=>{const p=this.getAxisMotionValue(m);p&&(this.originPoint[m]+=c[m].translate,p.set(p.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=Fo,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function di(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function DS(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class FS extends ur{constructor(s){super(s),this.removeGroupControls=ga,this.removeListeners=ga,this.controls=new RS(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ga}unmount(){this.removeGroupControls(),this.removeListeners()}}const $u=t=>(s,a)=>{t&&qt.postRender(()=>t(s,a))};class IS extends ur{constructor(){super(...arguments),this.removePointerDownListener=ga}onPointerDown(s){this.session=new Mg(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:_g(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:$u(s),onStart:$u(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&qt.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=Pn(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 Ci={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Uu(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const vn={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(it.test(t))t=parseFloat(t);else return t;const a=Uu(t,s.target.x),r=Uu(t,s.target.y);return`${a}% ${r}%`}},PS={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=mr.parse(t);if(n.length>5)return r;const i=mr.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=rs(o,c,.5);return typeof n[2+l]=="number"&&(n[2+l]/=d),typeof n[3+l]=="number"&&(n[3+l]/=d),i(n)}};let Bl=!1;class ES extends h.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;s2(_S),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),Bl&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Ci.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,Bl=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||qt.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Dc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;Bl=!0,n&&(n.scheduleCheckAfterUnmount(),a&&a.group&&a.group.remove(n),r&&r.deregister&&r.deregister(n))}safeToRemove(){const{safeToRemove:s}=this.props;s&&s()}render(){return null}}function Og(t){const[s,a]=ig(),r=h.useContext(oc);return e.jsx(ES,{...t,layoutGroup:r,switchLayoutGroup:h.useContext(bg),isPresent:s,safeToRemove:a})}const _S={borderRadius:{...vn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:vn,borderTopRightRadius:vn,borderBottomLeftRadius:vn,borderBottomRightRadius:vn,boxShadow:PS};function MS(t,s,a){const r=Ls(t)?t:tn(t);return r.start(Bc("",r,s,a)),r.animation}const LS=(t,s)=>t.depth-s.depth;class OS{constructor(){this.children=[],this.isDirty=!1}add(s){mc(this.children,s),this.isDirty=!0}remove(s){uc(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(LS),this.isDirty=!1,this.children.forEach(s)}}function $S(t,s){const a=Js.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(dr(r),t(i-s))};return qt.setup(r,!0),()=>dr(r)}const $g=["TopLeft","TopRight","BottomLeft","BottomRight"],US=$g.length,Bu=t=>typeof t=="string"?parseFloat(t):t,Vu=t=>typeof t=="number"||it.test(t);function BS(t,s,a,r,n,i){n?(t.opacity=rs(0,a.opacity??1,VS(r)),t.opacityExit=rs(s.opacity??1,0,zS(r))):i&&(t.opacity=rs(s.opacity??1,a.opacity??1,r));for(let l=0;l<US;l++){const o=`border${$g[l]}Radius`;let c=zu(s,o),d=zu(a,o);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||Vu(c)===Vu(d)?(t[o]=Math.max(rs(Bu(c),Bu(d),r),0),(Fa.test(d)||Fa.test(c))&&(t[o]+="%")):t[o]=d}(s.rotate||a.rotate)&&(t.rotate=rs(s.rotate||0,a.rotate||0,r))}function zu(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const VS=Ug(0,.5,Ap),zS=Ug(.5,.95,ga);function Ug(t,s,a){return r=>r<t?0:r>s?1:a(On(t,s,r))}function Hu(t,s){t.min=s.min,t.max=s.max}function xa(t,s){Hu(t.x,s.x),Hu(t.y,s.y)}function Wu(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Gu(t,s,a,r,n){return t-=s,t=Ui(t,1/a,r),n!==void 0&&(t=Ui(t,1/n,r)),t}function HS(t,s=0,a=1,r=.5,n,i=t,l=t){if(Fa.test(s)&&(s=parseFloat(s),s=rs(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=rs(i.min,i.max,r);t===i&&(o-=s),t.min=Gu(t.min,s,a,o,n),t.max=Gu(t.max,s,a,o,n)}function Yu(t,s,[a,r,n],i,l){HS(t,s[a],s[r],s[n],s.scale,i,l)}const WS=["x","scaleX","originX"],GS=["y","scaleY","originY"];function Ku(t,s,a,r){Yu(t.x,s,WS,a?a.x:void 0,r?r.x:void 0),Yu(t.y,s,GS,a?a.y:void 0,r?r.y:void 0)}function Qu(t){return t.translate===0&&t.scale===1}function Bg(t){return Qu(t.x)&&Qu(t.y)}function Xu(t,s){return t.min===s.min&&t.max===s.max}function YS(t,s){return Xu(t.x,s.x)&&Xu(t.y,s.y)}function Ju(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Vg(t,s){return Ju(t.x,s.x)&&Ju(t.y,s.y)}function Zu(t){return Vs(t.x)/Vs(t.y)}function qu(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class KS{constructor(){this.members=[]}add(s){mc(this.members,s),s.scheduleRender()}remove(s){if(uc(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 QS(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:p,rotateY:x,skewX:u,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),p&&(r+=`rotateX(${p}deg) `),x&&(r+=`rotateY(${x}deg) `),u&&(r+=`skewX(${u}deg) `),g&&(r+=`skewY(${g}deg) `)}const o=t.x.scale*s.x,c=t.y.scale*s.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const Vl=["","X","Y","Z"],XS=1e3;let JS=0;function zl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function zg(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=kg(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",qt,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&zg(r)}function Hg({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=JS++,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(eA),this.nodes.forEach(rA),this.nodes.forEach(nA),this.nodes.forEach(tA)},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 OS)}addEventListener(l,o){return this.eventHandlers.has(l)||this.eventHandlers.set(l,new pc),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=ng(l)&&!BC(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,p=0;const x=()=>this.root.updateBlockedByResize=!1;qt.read(()=>{p=window.innerWidth}),t(l,()=>{const u=window.innerWidth;u!==p&&(p=u,this.root.updateBlockedByResize=!0,m&&m(),m=$S(x,250),Ci.hasAnimatedSinceResize&&(Ci.hasAnimatedSinceResize=!1,this.nodes.forEach(sx)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:p,hasRelativeLayoutChanged:x,layout:u})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||dA,{onLayoutAnimationStart:f,onLayoutAnimationComplete:b}=d.getProps(),j=!this.targetLayout||!Vg(this.targetLayout,u),y=!p&&x;if(this.options.layoutRoot||this.resumeFrom||y||p&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...kc(g,"layout"),onPlay:f,onComplete:b};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(m,y)}else p||sx(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=u})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),dr(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(iA),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&&zg(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let m=0;m<this.path.length;m++){const p=this.path[m];p.shouldResetTransform=!0,p.updateScroll("snapshot"),p.options.layoutRoot&&p.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(ex);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(tx);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(aA),this.nodes.forEach(ZS),this.nodes.forEach(qS)):this.nodes.forEach(tx),this.clearAllSnapshots();const o=Js.now();Is.delta=Wa(0,1e3/60,o-Is.timestamp),Is.timestamp=o,Is.isProcessing=!0,Fl.update.process(Is),Fl.preRender.process(Is),Fl.render.process(Is),Is.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Dc.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(sA),this.sharedNodes.forEach(lA)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,qt.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){qt.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Vs(this.snapshot.measuredBox.x)&&!Vs(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=ds(),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&&!Bg(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,m=d!==this.prevTransformTemplateValue;l&&this.instance&&(o||wr(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)),mA(c),{animationId:this.root.animationId,measuredBox:o,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var d;const{visualElement:l}=this.options;if(!l)return ds();const o=l.measureViewportBox();if(!(((d=this.scroll)==null?void 0:d.wasRoot)||this.path.some(uA))){const{scroll:m}=this.root;m&&(Wr(o.x,m.offset.x),Wr(o.y,m.offset.y))}return o}removeElementScroll(l){var c;const o=ds();if(xa(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:p,options:x}=m;m!==this.root&&p&&x.layoutScroll&&(p.wasRoot&&xa(o,l),Wr(o.x,p.offset.x),Wr(o.y,p.offset.y))}return o}applyTransform(l,o=!1){const c=ds();xa(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&&Gr(c,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),wr(m.latestValues)&&Gr(c,m.latestValues)}return wr(this.latestValues)&&Gr(c,this.latestValues),c}removeTransform(l){const o=ds();xa(o,l);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!wr(d.latestValues))continue;So(d.latestValues)&&d.updateSnapshot();const m=ds(),p=d.measurePageBox();xa(m,p),Ku(o,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return wr(this.latestValues)&&Ku(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!==Is.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(l=!1){var x;const o=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=o.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=o.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=o.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==o;if(!(l||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(x=this.parent)!=null&&x.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:m,layoutId:p}=this.options;if(!(!this.layout||!(m||p))){if(this.resolvedRelativeTargetAt=Is.timestamp,!this.targetDelta&&!this.relativeTarget){const u=this.getClosestProjectingParent();u&&u.layout&&this.animationProgress!==1?(this.relativeParent=u,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ds(),this.relativeTargetOrigin=ds(),_n(this.relativeTargetOrigin,this.layout.layoutBox,u.layout.layoutBox),xa(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ds(),this.targetWithTransforms=ds()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),bS(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):xa(this.target,this.layout.layoutBox),Ng(this.target,this.targetDelta)):xa(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const u=this.getClosestProjectingParent();u&&!!u.resumingFrom==!!this.resumingFrom&&!u.options.layoutScroll&&u.target&&this.animationProgress!==1?(this.relativeParent=u,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ds(),this.relativeTargetOrigin=ds(),_n(this.relativeTargetOrigin,this.target,u.target),xa(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||So(this.parent.latestValues)||vg(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===Is.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;xa(this.layoutCorrected,this.layout.layoutBox);const p=this.treeScale.x,x=this.treeScale.y;D2(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=ds());const{target:u}=l;if(!u){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Wu(this.prevProjectionDelta.x,this.projectionDelta.x),Wu(this.prevProjectionDelta.y,this.projectionDelta.y)),En(this.projectionDelta,this.layoutCorrected,u,this.latestValues),(this.treeScale.x!==p||this.treeScale.y!==x||!qu(this.projectionDelta.x,this.prevProjectionDelta.x)||!qu(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",u))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(l=!0){var o;if((o=this.options.visualElement)==null||o.scheduleRender(),l){const c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Yr(),this.projectionDelta=Yr(),this.projectionDeltaWithTransform=Yr()}setAnimationOrigin(l,o=!1){const c=this.snapshot,d=c?c.latestValues:{},m={...this.latestValues},p=Yr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!o;const x=ds(),u=c?c.source:void 0,g=this.layout?this.layout.source:void 0,f=u!==g,b=this.getStack(),j=!b||b.members.length<=1,y=!!(f&&!j&&this.options.crossfade===!0&&!this.path.some(cA));this.animationProgress=0;let w;this.mixTargetDelta=N=>{const S=N/1e3;ax(p.x,l.x,S),ax(p.y,l.y,S),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(_n(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),oA(this.relativeTarget,this.relativeTargetOrigin,x,S),w&&YS(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=ds()),xa(w,this.relativeTarget)),f&&(this.animationValues=m,BS(m,d,this.latestValues,S,y,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},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&&(dr(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=qt.update(()=>{Ci.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=tn(0)),this.currentAnimation=MS(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(XS),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&&Wg(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||ds();const p=Vs(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+p;const x=Vs(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}xa(o,c),Gr(o,m),En(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new KS),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&&zl("z",l,d,this.animationValues);for(let m=0;m<Vl.length;m++)zl(`rotate${Vl[m]}`,l,d,this.animationValues),zl(`skew${Vl[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=wi(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=wi(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!wr(this.latestValues)&&(l.transform=c?c({},""):"none",this.hasProjected=!1);return}l.visibility="";const m=d.animationValues||d.latestValues;this.applyTransformsToTarget();let p=QS(this.projectionDeltaWithTransform,this.treeScale,m);c&&(p=c(m,p)),l.transform=p;const{x,y:u}=this.projectionDelta;l.transformOrigin=`${x.origin*100}% ${u.origin*100}% 0`,d.animationValues?l.opacity=d===this?m.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:m.opacityExit:l.opacity=d===this?m.opacity!==void 0?m.opacity:"":m.opacityExit!==void 0?m.opacityExit:0;for(const g in Vn){if(m[g]===void 0)continue;const{correct:f,applyTo:b,isCSSVariable:j}=Vn[g],y=p==="none"?m[g]:f(m[g],d);if(b){const w=b.length;for(let N=0;N<w;N++)l[b[N]]=y}else j?this.options.visualElement.renderState.vars[g]=y:l[g]=y}this.options.layoutId&&(l.pointerEvents=d===this?wi(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(ex),this.root.sharedNodes.clear()}}}function ZS(t){t.updateLayout()}function qS(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"?ha(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],u=Vs(x);x.min=r[p].min,x.max=x.min+u}):Wg(i,s.layoutBox,r)&&ha(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],u=Vs(r[p]);x.max=x.min+u,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[p].max=t.relativeTarget[p].min+u)});const o=Yr();En(o,r,s.layoutBox);const c=Yr();l?En(c,t.applyTransform(n,!0),s.measuredBox):En(c,r,s.layoutBox);const d=!Bg(o);let m=!1;if(!t.resumeFrom){const p=t.getClosestProjectingParent();if(p&&!p.resumeFrom){const{snapshot:x,layout:u}=p;if(x&&u){const g=ds();_n(g,s.layoutBox,x.layoutBox);const f=ds();_n(f,r,u.layoutBox),Vg(g,f)||(m=!0),p.options.layoutRoot&&(t.relativeTarget=f,t.relativeTargetOrigin=g,t.relativeParent=p)}}}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 eA(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 tA(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function sA(t){t.clearSnapshot()}function ex(t){t.clearMeasurements()}function tx(t){t.isLayoutDirty=!1}function aA(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function sx(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function rA(t){t.resolveTargetDelta()}function nA(t){t.calcProjection()}function iA(t){t.resetSkewAndRotation()}function lA(t){t.removeLeadSnapshot()}function ax(t,s,a){t.translate=rs(s.translate,0,a),t.scale=rs(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function rx(t,s,a,r){t.min=rs(s.min,a.min,r),t.max=rs(s.max,a.max,r)}function oA(t,s,a,r){rx(t.x,s.x,a.x,r),rx(t.y,s.y,a.y,r)}function cA(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const dA={duration:.45,ease:[.4,0,.1,1]},nx=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),ix=nx("applewebkit/")&&!nx("chrome/")?Math.round:ga;function lx(t){t.min=ix(t.min),t.max=ix(t.max)}function mA(t){lx(t.x),lx(t.y)}function Wg(t,s,a){return t==="position"||t==="preserve-aspect"&&!fS(Zu(s),Zu(a),.2)}function uA(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const xA=Hg({attachResizeListener:(t,s)=>zn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Hl={current:void 0},Gg=Hg({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Hl.current){const t=new xA({});t.mount(window),t.setOptions({layoutScroll:!0}),Hl.current=t}return Hl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),hA={pan:{Feature:IS},drag:{Feature:FS,ProjectionNode:Gg,MeasureLayout:Og}};function ox(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&&qt.postRender(()=>i(s,ti(s)))}class pA extends ur{mount(){const{current:s}=this.node;s&&(this.unmount=MC(s,(a,r)=>(ox(this.node,r,"Start"),n=>ox(this.node,n,"End"))))}unmount(){}}class gA extends ur{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=Zn(zn(this.node.current,"focus",()=>this.onFocus()),zn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function cx(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&&qt.postRender(()=>i(s,ti(s)))}class fA extends ur{mount(){const{current:s}=this.node;s&&(this.unmount=UC(s,(a,r)=>(cx(this.node,r,"Start"),(n,{success:i})=>cx(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Io=new WeakMap,Wl=new WeakMap,bA=t=>{const s=Io.get(t.target);s&&s(t)},jA=t=>{t.forEach(bA)};function yA({root:t,...s}){const a=t||document;Wl.has(a)||Wl.set(a,{});const r=Wl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(jA,{root:t,...s})),r[n]}function vA(t,s,a){const r=yA(s);return Io.set(t,a),r.observe(t),()=>{Io.delete(t),r.unobserve(t)}}const NA={some:0,all:1};class wA extends ur{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:NA[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:p}=this.node.getProps(),x=d?m:p;x&&x(c)};return vA(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(CA(s,a))&&this.startObserver()}unmount(){}}function CA({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const SA={inView:{Feature:wA},tap:{Feature:fA},focus:{Feature:gA},hover:{Feature:pA}},AA={layout:{ProjectionNode:Gg,MeasureLayout:Og}},TA={...mS,...SA,...hA,...AA},Ht=T2(TA,U2),Nn=[{id:"claim-management",name:"Claim Management",description:"End-to-end dealer claim processing workflow with automatic IO generation and budget blocking",category:"Dealer Operations",icon:Pt,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:nh,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 kA({open:t,onClose:s,onSelectTemplate:a}){var d,m,p;const[r,n]=h.useState(null),[i,l]=h.useState(!1);h.useEffect(()=>{const x=at.getUserData();l((x==null?void 0:x.jobTitle)==="Dealer")},[]);const o=x=>{if(i)return;const u=Nn.find(g=>g.id===x);u!=null&&u.disabled||n(x)},c=()=>{r&&(a(r),s())};return e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(xt,{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(ht,{className:"sr-only",children:"Select a Template"}),e.jsx(Ut,{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(ws,{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(Ht.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(Ki,{className:"w-10 h-10 text-white"})}),e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4",children:"Choose Your Template"}),e.jsx("p",{className:"text-lg text-gray-600",children:"Select from pre-configured templates with predefined workflows and approval chains for faster processing."})]}),e.jsx("div",{className:"w-full max-w-5xl grid grid-cols-1 md:grid-cols-2 gap-6 mb-8",children:Nn.map((x,u)=>{const g=x.icon,f=r===x.id,b=i||x.disabled;return e.jsx(Ht.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:u*.1},whileHover:b?{}:{scale:1.03},whileTap:b?{}:{scale:.98},children:e.jsxs(Z,{className:`h-full transition-all duration-300 border-2 ${b?"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(x.id),children:[e.jsxs(oe,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${x.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),f&&e.jsx(Ht.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(za,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(me,{className:"text-xl mb-2",children:x.name}),e.jsx(ve,{className:"text-sm leading-relaxed",children:x.description}),i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsx(Ze,{className:"w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Not accessible for Dealers"})]}),x.comingSoon&&!i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-blue-50 border border-blue-200 rounded-lg",children:[e.jsx(Ze,{className:"w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-blue-800 font-semibold",children:"Coming Soon"})]})]})]}),e.jsxs(ee,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(se,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Qt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(st,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:x.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(es,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[x.steps," steps"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx("p",{className:"text-xs text-gray-500 font-semibold",children:"Key Features:"}),e.jsxs("div",{className:"space-y-1.5",children:[x.features.slice(0,3).map((j,y)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(Le,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:j})]},y)),x.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",x.features.length-3," more features"]})]})]})]})]})},x.id)})}),e.jsxs(Ht.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"flex flex-col sm:flex-row justify-center gap-4 mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(E,{onClick:c,disabled:!r||i||((d=Nn.find(x=>x.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=Nn.find(x=>x.id===r))!=null&&m.disabled)?"bg-blue-600 hover:bg-blue-700":"bg-gray-400 cursor-not-allowed"}`,children:["Continue with Template",e.jsx(fs,{className:"w-4 h-4"})]})]}),e.jsx(ol,{children:r&&e.jsx(Ht.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:(p=Nn.find(x=>x.id===r))==null?void 0:p.name})]})})})]})})]})})}function Mr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=h.useState(100),[m,p]=h.useState(0),[x,u]=h.useState(null),[g,f]=h.useState(!1),[b,j]=h.useState(null),y=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),w=s.toLowerCase().includes("pdf"),N=y||w;h.useEffect(()=>{if(!l||!N||!a){u(null);return}return(async()=>{f(!0),j(null);try{let C=a;a.startsWith("/")&&!a.startsWith("//")&&(C=`${window.location.origin}${a}`);const F=await fetch(C,{headers:{Accept:w?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!F.ok){const T=await F.text().catch(()=>"");throw new Error(`Failed to load file: ${F.status} ${F.statusText}. ${T}`)}const $=await F.blob();if($.size===0)throw new Error("File is empty or could not be loaded");w&&!$.type.includes("pdf")&&$.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${$.type}`);const I=window.URL.createObjectURL($);u(I)}catch(v){console.error("Failed to load file for preview:",v),j(v instanceof Error?v.message:"Failed to load file for preview")}finally{f(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),u(null))}},[l,a,N,w]);const S=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},A=()=>d(R=>Math.min(R+25,200)),_=()=>d(R=>Math.max(R-25,50)),D=()=>p(R=>(R+90)%360);return e.jsx(jt,{open:l,onOpenChange:o,children:e.jsx(xt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(yt,{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(Ct,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ht,{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:[y&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:_,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(yb,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[c,"%"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:A,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(vb,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(ih,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(E,{variant:"outline",size:"sm",onClick:S,className:"gap-2 h-9",children:[e.jsx(kt,{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(Xe,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):b?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(bt,{className:"w-10 h-10 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Failed"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:b}),i&&n&&e.jsxs(E,{onClick:S,className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",t]})]}):N&&x?e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:x,alt:t,style:{transform:`scale(${c/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),w&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:x,className:"w-full h-full rounded-lg border-0",title:t,style:{minHeight:"70vh",height:"100%"},onError:()=>{j("Failed to load PDF preview")}})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(Ct,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),i&&n&&e.jsxs(E,{onClick:S,className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function si({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(xt,{className:"sm:max-w-lg",children:[e.jsxs(yt,{children:[e.jsxs(ht,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Ut,{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(Et,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const la=async t=>{const s=t?{category:t}:{};return(await je.get("/users/configurations",{params:s})).data.data},ul=async t=>{const s=t?{category:t}:{};return(await je.get("/admin/configurations",{params:s})).data.data},Bs=async(t,s)=>{await je.put(`/admin/configurations/${t}`,{configValue:s})},RA=async t=>{await je.post(`/admin/configurations/${t}/reset`)},DA=async()=>{const t=await je.get("/admin/form16-config");return t.data.data??t.data},FA=async t=>{await je.put("/admin/form16-config",t)},IA=async t=>{const s=t?{year:t}:{};return(await je.get("/admin/holidays",{params:s})).data.data},PA=async t=>(await je.post("/admin/holidays",t)).data.data,EA=async(t,s)=>(await je.put(`/admin/holidays/${t}`,s)).data.data,_A=async t=>{await je.delete(`/admin/holidays/${t}`)},MA=async()=>(await je.get("/config/activity-types")).data.data,LA=async t=>{const s={activeOnly:t.toString()};return(await je.get("/admin/activity-types",{params:s})).data.data},OA=async t=>(await je.post("/admin/activity-types",t)).data.data,$A=async(t,s)=>(await je.put(`/admin/activity-types/${t}`,s)).data.data,UA=async t=>{await je.delete(`/admin/activity-types/${t}`)},BA={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 VA(t,s,a){const[r,n]=h.useState(BA),[i,l]=h.useState(null),[o,c]=h.useState(t),[d,m]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[p,x]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[u,g]=h.useState([]);return h.useEffect(()=>{(async()=>{var j;try{const y=await la("DOCUMENT_POLICY"),w={};y.forEach(P=>{w[P.configKey]=P.configValue});const N=parseInt(w.MAX_FILE_SIZE_MB||"10"),A=(w.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(P=>P.trim().toLowerCase());x({maxFileSizeMB:N,allowedFileTypes:A});const _=await la("SYSTEM_SETTINGS"),D=await la("WORKFLOW_SHARING"),R=[..._,...D],v={};R.forEach(P=>{v[P.configKey]=P.configValue}),m({maxApprovalLevels:parseInt(v.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(v.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((j=v.ALLOW_ADD_SPECTATOR)==null?void 0:j.toLowerCase())==="true",maxSpectators:parseInt(v.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(y){console.error("Failed to load policies:",y)}})()},[]),h.useEffect(()=>{if(!t||!s)return;let b=!0;return(async()=>{try{c(!0);const j=await Ps(s);if(!b||!j)return;const y=j.workflow||{},w=Array.isArray(j.approvals)?j.approvals:[],N=Array.isArray(j.participants)?j.participants:[],S=Array.isArray(j.documents)?j.documents.filter(C=>!C.isDeleted):[];g(S);const A=(y.priority||"").toString().toLowerCase(),_={standard:"standard",express:"express"},D=y.templateType==="TEMPLATE"?"existing-template":"custom",R=a.find(C=>C.id===D)||a[0]||null;l(R);const v=w.sort((C,V)=>(C.levelNumber||0)-(V.levelNumber||0)).map(C=>{const V=Number(C.tatHours||24),F=Math.floor(V/24),$=V%24;return{id:C.approverId||`temp-${C.levelNumber}`,name:C.approverName||C.approverEmail||"",email:C.approverEmail||"",role:C.levelName||`Level ${C.levelNumber}`,department:"",avatar:(C.approverName||C.approverEmail||"XX").substring(0,2).toUpperCase(),level:C.levelNumber||1,canClose:!1,tat:F>0?F:$,tatType:F>0?"days":"hours",userId:C.approverId}}),P=N.filter(C=>(C.participantType||C.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(C.userEmail||C.user_email||C.email):!1).map((C,V)=>{const F=C.userId||C.user_id||C.id,$=C.userName||C.user_name||C.name||"",I=C.userEmail||C.user_email||C.email||"",k=($||I||"XX").split(" ").map(z=>z[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${V}-${Date.now()}`,userId:F,name:$||I||"Spectator",email:I,role:"Spectator",department:C.department||"",avatar:k,level:1,canClose:!1}});n(C=>({...C,template:D,title:y.title||"",description:y.description||"",priority:_[A]||"standard",approvers:v,approverCount:v.length||1,spectators:P,maxLevel:Math.max(...v.map(V=>V.level||1),1)}))}catch(j){console.error("Failed to load draft:",j)}finally{b&&c(!1)}})(),()=>{b=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(b,j)=>{n(y=>({...y,[b]:j}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:p,existingDocuments:u,setExistingDocuments:g}}const dx=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function zA(t,s,a){const[r,n]=h.useState(t?2:1),i=dx.length,l=p=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p),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(p=>{if(!p||!p.email||!l(p.email))return!1;if(!p.userId)return!0;const x=p.tatType||"hours";return x==="hours"?p.tat&&p.tat>0&&p.tat<=720:x==="days"?p.tat&&p.tat>0&&p.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:dx,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:p=>{p>=1&&p<=i&&n(p)},validateEmail:l}}function HA(){const[t,s]=h.useState({open:!1,type:"error",email:"",message:""}),[a,r]=h.useState({open:!1,violations:[]}),[n,i]=h.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(x,u,g="")=>{s({open:!0,type:x,email:u,message:g})},closeValidationModal:()=>{s(x=>({...x,open:!1}))},openPolicyViolationModal:x=>{r({open:!0,violations:x})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:x=>{i({open:!0,errors:x})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function WA(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function GA(t,s,a){var n;const r=WA(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 YA(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return GA(a,n,n===s)})}function mx(t,s,a,r=!1){return{templateId:(s==null?void 0:s.id)||null,templateType:(s==null?void 0:s.id)==="custom"?"CUSTOM":"TEMPLATE",title:t.title,description:t.description,priorityUi:t.priority==="express"?"express":"standard",approverCount:t.approverCount||1,approvers:(t.approvers||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",email:(n==null?void 0:n.email)||"",name:n==null?void 0:n.name,tat:(n==null?void 0:n.tat)||24,tatType:(n==null?void 0:n.tatType)||"hours"})),spectators:(t.spectators||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",name:(n==null?void 0:n.name)||"",email:(n==null?void 0:n.email)||""})),ccList:[],participants:[],isDraft:r}}function ux(t,s,a,r=!1){const n=YA(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:n,participants:[],deleteDocumentIds:a.length>0?a:void 0,isDraft:r}}function KA(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 xx(t,s){return{id:(await ic(t,s||[],"SUPPORTING")).id}}async function hx(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await Fw(t,s,a||[],r):await Dw(t,s)}function QA({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=h.useState(!1),[m,p]=h.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var f,b;if(c||m)return;const g=KA(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const j=ux(t,n,r,!1);await hx(l,j,a,r),X.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 j=mx(t,s,n,!1),y=await xx(j,a);X.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been created and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:y.id,template:s})}}catch(j){console.error("Failed to submit workflow:",j),X.error("Failed to Submit Request",{description:((b=(f=j==null?void 0:j.response)==null?void 0:f.data)==null?void 0:b.message)||(j==null?void 0:j.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)){p(!0);try{if(i&&l){const b=ux(t,n,r,!0);await hx(l,b,a,r),X.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 b=mx(t,s,n,!0),j=await xx(b,a);X.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:j.id,template:s})}}catch(b){console.error("Failed to save draft:",b),X.error("Failed to Save Draft",{description:((f=(g=b==null?void 0:b.response)==null?void 0:g.data)==null?void 0:f.message)||(b==null?void 0:b.message)||"An error occurred while saving the draft.",duration:5e3}),p(!1)}}}}}async function ja(t,s=10,a="default"){return await je.get("/users/search",{params:{q:t,limit:s,source:a}})}async function fa(t){var a;const s=await je.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function XA(t,s){return await je.post("/admin/users/assign-role",{email:t,role:s})}async function JA(t,s){return await je.put(`/admin/users/${t}/role`,{role:s})}async function ZA(t,s=1,a=10){return await je.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function qA(){return await je.get("/admin/users/role-statistics")}async function eT(t){var a;const s=await je.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function tT(){var s,a;return((a=(s=(await je.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const sa={searchUsers:ja,getUserById:eT,ensureUserExists:fa,assignRole:XA,updateUserRole:JA,getUsersByRole:ZA,getRoleStatistics:qA,getAllUsers:tT};async function sT(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 ja(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 fa({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 aT(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 sT(l,s);if(!o.success)return{success:!1,error:o.error};try{const m=(((n=(await ja(l.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const p=await fa({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:p.userId,name:p.displayName||l.name,department:p.department||l.department,avatar:(p.displayName||p.email).substring(0,2).toUpperCase()}}}catch(c){console.error(`Failed to update approver ${l.email}:`,c)}}return{success:!0,validatedApprovers:r}}function rT({selectedTemplate:t,setSelectedTemplate:s,updateFormData:a,formData:r,currentStep:n,isStepValid:i,wizardNextStep:l,wizardPrevStep:o,user:c,openValidationModal:d,systemPolicy:m,onPolicyViolation:p,onSubmit:x}){const u=ys(),[g,f]=h.useState(!1),[b,j]=h.useState(null);return{showTemplateModal:g,setShowTemplateModal:f,previewDocument:b,selectTemplate:D=>{s(D),a("template",D.id),a("category",D.category),a("priority",D.priority);const R=new Date;R.setDate(R.getDate()+D.suggestedSLA),a("slaEndDate",R),D.id!=="custom"&&D.id!=="existing-template"&&u(`/create-admin-request/${D.id}`)},handleTemplateSelection:D=>{D==="claim-management"?u("/claim-management"):D==="vendor-payment"?u("/vendor-payment"):x&&x({templateType:D})},nextStep:async()=>{var D;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){f(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&p){const P=r.approverCount||1;if(P>m.maxApprovalLevels){p([{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 R=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",v=await aT(r.approvers,R);if(!v.success&&v.error){d(v.error.type,v.error.email,v.error.message);return}v.validatedApprovers&&a("approvers",v.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(D,R)=>{if(R){const v=D.documentId||D.document_id||"";j({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:mn(v),fileSize:Number(D.fileSize||D.file_size||0),documentId:v})}else{const v=URL.createObjectURL(D);j({fileName:D.name,fileType:D.type||"application/octet-stream",fileUrl:v,fileSize:D.size,file:D})}},closePreview:()=>{b!=null&&b.fileUrl&&(b!=null&&b.file)&&URL.revokeObjectURL(b.fileUrl),j(null)}}}const px=[{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:Qi,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:Ie,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let Ir=null;const gx=()=>Ir,nT=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 Ir&&Ir.push(r),r},xl=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 Ir=a,a},iT=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 Ir&&(Ir=Ir.map(i=>i.id===t?n:i)),n};function Yg({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(za,{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 lT({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:c,loadingDraft:d,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(E,{variant:"outline",onClick:r,disabled:t===1,size:"sm",className:"sm:size-lg order-2 sm:order-1","data-testid":"wizard-footer-prev-button",children:[e.jsx(ws,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Previous"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 order-1 sm:order-2","data-testid":"wizard-footer-actions",children:[e.jsx(E,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||o||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),e.jsx("span",{children:m?"Updating...":"Saving..."})]}):e.jsx("span",{children:m?"Update Draft":"Save Draft"})}),t===s?e.jsx(E,{onClick:i,disabled:!a||d||o||c,size:"sm",className:"sm:size-lg bg-green-600 hover:bg-green-700 flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-submit-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{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(lh,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(E,{onClick:n,disabled:!a,size:"sm",className:"sm:size-lg flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-next-button",children:[e.jsx("span",{className:"hidden sm:inline",children:"Next Step"}),e.jsx("span",{className:"sm:hidden",children:"Next"}),e.jsx(fs,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const fx=t=>{switch(t){case"high":return e.jsx(Sa,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(es,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Hs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(es,{className:"w-4 h-4 text-gray-600"})}};function oT({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=h.useState("main"),l=ys(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},c=n==="main"?[...t]:r;return e.jsxs(Ht.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"min-h-full flex flex-col items-center justify-center py-8","data-testid":"template-selection-step",children:[e.jsxs("div",{className:"text-center mb-12 max-w-3xl","data-testid":"template-selection-header",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4","data-testid":"template-selection-title",children:n==="main"?"Choose Your Request Type":"Organization Templates"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:n==="main"?"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs.":"Select a pre-configured workflow template defined by your organization."})]}),n==="admin"&&e.jsx("div",{className:"w-full max-w-6xl mb-6 flex justify-start",children:e.jsxs(E,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(ws,{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(Nb,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):c.map(m=>{var g;const x=m.id==="admin-templates-category",u=(s==null?void 0:s.id)===m.id;return e.jsx(Ht.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(Z,{className:`h-full transition-all duration-300 border-2 ${u?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer":x?"border-blue-200 bg-blue-50/30 hover:border-blue-400 hover:shadow-lg cursor-pointer":"border-gray-200 hover:border-blue-300 hover:shadow-lg cursor-pointer"}`,onClick:()=>o(m),"data-testid":`template-card-${m.id}-clickable`,children:[e.jsxs(oe,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl flex items-center justify-center ${u||x?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${u||x?"text-blue-600":"text-gray-600"}`})}),u&&e.jsx(Ht.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(za,{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(me,{className:"text-xl","data-testid":`template-card-${m.id}-name`,children:m.name}),!1]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),fx(m.priority)]})]})]}),e.jsxs(ee,{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(Qt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-estimated-time`,children:[e.jsx(st,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:m.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-approvers-count`,children:[e.jsx(Zt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[((g=m.commonApprovers)==null?void 0:g.length)||0," approvers"]})]})]})]}),x&&e.jsx("div",{className:"pt-2",children:e.jsx("p",{className:"text-xs text-blue-600 font-medium flex items-center gap-1",children:"Click to browse templates →"})})]})]})},m.id)})}),e.jsx(ol,{children:s&&e.jsx(Ht.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(Z,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(oe,{children:e.jsxs(me,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Er,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(ee,{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(te,{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(te,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[fx(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(te,{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(te,{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,p)=>e.jsx(se,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${p}`,children:m},`${s.id}-approver-${p}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function ke({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:_e("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 cT({className:t,...s}){return e.jsx(Rf,{"data-slot":"radio-group",className:_e("grid gap-3",t),...s})}function bx({className:t,...s}){return e.jsx(Df,{"data-slot":"radio-group-item",className:_e("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(Ff,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Bo,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function dT({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(Ht.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(Ie,{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(te,{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(ke,{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(te,{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(Jn,{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(te,{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(cT,{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(bx,{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(Yi,{className:"w-4 h-4 text-red-600"}),e.jsx(te,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(se,{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(bx,{value:"standard",id:"standard"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(st,{className:"w-4 h-4 text-blue-600"}),e.jsx(te,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(se,{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(te,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(ke,{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(te,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(Be,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(ze,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Q,{value:"USD",children:"USD ($)"}),e.jsx(Q,{value:"EUR",children:"EUR (€)"}),e.jsx(Q,{value:"GBP",children:"GBP (£)"}),e.jsx(Q,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(te,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(ke,{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(te,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(ke,{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(te,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(ke,{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 Kg(){const[t,s]=h.useState([]),[a,r]=h.useState(!1),n=h.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 p=c.slice(1),u=((m=(await ja(p,d)).data)==null?void 0:m.data)||[];s(u)}catch(p){console.error("User search failed:",p),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await fa({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 Qg(){const[t,s]=h.useState({}),[a,r]=h.useState({}),n=h.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 p=c.slice(1),u=((m=(await ja(p,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:u}))}catch(p){console.error(`User search failed for index ${o}:`,p),s(x=>({...x,[o]:[]}))}finally{r(p=>({...p,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function mT({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var p;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=Qg();h.useEffect(()=>{const x=t.approverCount||1,u=t.approvers||[];if(u.length<x){const g=[...u];for(let f=u.length;f<x;f++)g[f]||(g[f]={email:"",name:"",level:f+1,tat:""});s("approvers",g)}else u.length>x&&s("approvers",u.slice(0,x))},[t.approverCount,s]);const d=(x,u)=>{var j,y,w,N,S;const g=[...t.approvers],b=((j=g[x])==null?void 0:j.email)!==u;if(g[x]={...g[x],email:u,level:x+1,userId:b||(y=g[x])==null?void 0:y.userId,name:b||(w=g[x])==null?void 0:w.name,department:b||(N=g[x])==null?void 0:N.department,avatar:b||(S=g[x])==null?void 0:S.avatar},s("approvers",g),!u||!u.startsWith("@")||u.length<2){c(x);return}o(x,u,10)},m=async(x,u)=>{var g,f;try{if((g=t.approvers)==null?void 0:g.some((N,S)=>{var A,_;return S!==x&&(N.userId===u.userId||((A=N.email)==null?void 0:A.toLowerCase())===((_=u.email)==null?void 0:_.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((f=t.spectators)==null?void 0:f.some(N=>{var S,A;return N.userId===u.userId||((S=N.email)==null?void 0:S.toLowerCase())===((A=u.email)==null?void 0:A.toLowerCase())})){a({type:"error",email:u.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const y=await fa({userId:u.userId,email:u.email,displayName:u.displayName,firstName:u.firstName,lastName:u.lastName,department:u.department,phone:u.phone,mobilePhone:u.mobilePhone,designation:u.designation,jobTitle:u.jobTitle,manager:u.manager,employeeId:u.employeeId,employeeNumber:u.employeeNumber,secondEmail:u.secondEmail,location:u.location}),w=[...t.approvers];w[x]={...w[x],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:y.userId,level:x+1},s("approvers",w),c(x)}catch(b){console.error("Failed to ensure user exists:",b),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(Ht.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(Zt,{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(Z,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(lr,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(ve,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(ee,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(te,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const x=t.approverCount||1,u=Math.max(1,x-1);s("approverCount",u),t.approvers.length>u&&s("approvers",t.approvers.slice(0,u))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(Vo,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-2xl font-semibold w-12 text-center","data-testid":"approval-workflow-count-display",children:t.approverCount||1}),e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const u=(t.approverCount||1)+1;if(u>r.maxApprovalLevels){n([{type:"Maximum Approval Levels Exceeded",message:`Cannot add more than ${r.maxApprovalLevels} approval levels. Please remove an approver level or contact your administrator.`,currentValue:u,maxValue:r.maxApprovalLevels}]);return}s("approverCount",u)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(bs,{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(Z,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(ps,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(ve,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx("div",{className:"p-4 rounded-lg border-2 border-blue-200 bg-blue-50","data-testid":"approval-workflow-initiator-card",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:e.jsx(Vt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-blue-900",children:"Request Initiator"}),e.jsx(se,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-sm text-blue-700",children:"Creates and submits the request"})]})]})}),Array.from({length:t.approverCount||1},(x,u)=>{var j,y;const g=u+1,f=g===(t.approverCount||1),b=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${g}`,children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-6 bg-gray-300"})}),e.jsx("div",{className:`p-4 rounded-lg border-2 transition-all ${b.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 ${b.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(se,{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(te,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),b.email&&b.userId&&e.jsxs(se,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Le,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:b.email||"",onChange:w=>d(u,w.target.value),className:"h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full","data-testid":`approval-workflow-approver-${g}-email-input`}),(l[u]||(((j=i[u])==null?void 0:j.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:l[u]?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:(y=i[u])==null?void 0:y.map(w=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(u,w),"data-testid":`approval-workflow-approver-${g}-search-result-${w.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:w.displayName||w.email}),e.jsx("div",{className:"text-xs text-gray-600",children:w.email})]},w.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-tat-field`,children:[e.jsx(te,{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(ke,{id:`tat-${g}`,type:"number",placeholder:b.tatType==="days"?"7":"24",min:"1",max:b.tatType==="days"?"30":"720",value:b.tat||"",onChange:w=>{const N=[...t.approvers];N[u]={...N[u],tat:parseInt(w.target.value)||"",level:g,tatType:b.tatType||"hours"},s("approvers",N)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(Be,{value:b.tatType||"hours",onValueChange:w=>{const N=[...t.approvers];N[u]={...N[u],tatType:w,level:g,tat:""},s("approvers",N)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(ze,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Q,{value:"hours",children:"Hours"}),e.jsx(Q,{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(Er,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," → ",Array.from({length:t.approverCount||1},(x,u)=>`Level ${u+1} Approver`).join(" → "),". The final approver can close the request."]})]})]})}),e.jsx("div",{className:"p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(st,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((f,b)=>{const j=Number(b.tat||0);return(b.tatType||"hours")==="days"?f+j:f+j/24},0))||0,u=Math.ceil(x);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[u," ",u===1?"Day":"Days"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Duration"})]})})()})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:(p=t.approvers)==null?void 0:p.map((x,u)=>{const g=Number(x.tat||0),b=(x.tatType||"hours")==="days"?g*24:g;return g?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[b," ",b===1?"hour":"hours"]})]})},u):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((f,b)=>{const j=Number(b.tat||0);return(b.tatType||"hours")==="days"?f+j*24:f+j},0))||0,u=Math.ceil(x/8);return x===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[x,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children:u}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Working Days*"})]})]}),e.jsx("p",{className:"text-xs text-emerald-600 mt-2 text-center",children:"*Based on 8-hour working days"})]})})()]})]})]})})]})]})]})}function uT({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=h.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=Kg(),p=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},x=async g=>{var f,b;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 j=t.spectators.some(w=>{var N,S;return w.userId===g.userId||((N=w.email)==null?void 0:N.toLowerCase())===((S=g.email)==null?void 0:S.toLowerCase())}),y=(f=t.approvers)==null?void 0:f.some(w=>{var N,S;return w.userId===g.userId||((N=w.email)==null?void 0:N.toLowerCase())===((S=g.email)==null?void 0:S.toLowerCase())});if(j){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(y){a({type:"error",email:g.email,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}try{const w=await m(g),N={id:w.userId,userId:w.userId,name:w.displayName||g.email.split("@")[0],email:w.email,avatar:(w.displayName||w.email).substring(0,2).toUpperCase(),role:"Spectator",department:w.department||"",level:1,canClose:!1},S=[...t.spectators,N];s("spectators",S),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 j=t.spectators.some(w=>{var N;return((N=w.email)==null?void 0:N.toLowerCase())===n.toLowerCase()}),y=(b=t.approvers)==null?void 0:b.some(w=>{var N;return((N=w.email)==null?void 0:N.toLowerCase())===n.toLowerCase()});if(j){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(y){a({type:"error",email:n,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}}},u=g=>{const f=t.spectators.filter(b=>b.id!==g);s("spectators",f)};return e.jsxs(Ht.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(Ct,{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(Z,{"data-testid":"participants-spectators-card",children:[e.jsxs(oe,{children:[e.jsxs(me,{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(Ct,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(se,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(ve,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(ee,{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(ke,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>p(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await x())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(o||l.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:o?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:l.map(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>x(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(E,{size:"sm",onClick:()=>x(),disabled:!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"data-testid":"participants-spectators-add-button",children:"Add"})]}),e.jsxs("p",{className:"text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1",children:[e.jsx(Er,{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(ls,{className:"h-6 w-6",children:e.jsx(os,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(bt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function xT({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const p=f=>{const b=Array.from(f.target.files||[]);if(b.length===0)return;const j=t.maxFileSizeMB*1024*1024,y=[],w=[];b.forEach(N=>{if(N.size>j){y.push({fileName:N.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(N.size/1048576).toFixed(2)}MB`});return}const S=N.name.toLowerCase(),A=S.substring(S.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(A)){y.push({fileName:N.name,reason:`File type "${A}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}w.push(N)}),w.length>0&&i([...a,...w]),y.length>0&&d&&d(y),f.target&&(f.target.value="")},x=f=>{const b=a.filter((j,y)=>y!==f);i(b)},u=f=>{o([...n,f])},g=(f,b=!1)=>{if(b){const j=(f.fileType||f.file_type||"").toLowerCase(),y=(f.originalFileName||f.fileName||"").toLowerCase();return j.includes("image")||j.includes("pdf")||y.endsWith(".jpg")||y.endsWith(".jpeg")||y.endsWith(".png")||y.endsWith(".gif")||y.endsWith(".pdf")}else{const j=(f.type||"").toLowerCase(),y=(f.name||"").toLowerCase();return j.includes("image")||j.includes("pdf")||y.endsWith(".jpg")||y.endsWith(".jpeg")||y.endsWith(".png")||y.endsWith(".gif")||y.endsWith(".pdf")}};return e.jsxs(Ht.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(js,{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(Z,{"data-testid":"documents-upload-card",children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Ie,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(ve,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(ee,{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(js,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(f=>`.${f}`).join(","),onChange:p,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(E,{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(bs,{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(Z,{"data-testid":"documents-existing-card",children:[e.jsx(oe,{children:e.jsxs(me,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(se,{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(ee,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(f=>{const b=f.documentId||f.document_id||"";return n.includes(b)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Ie,{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(E,{variant:"ghost",size:"sm",onClick:()=>c(f,!0),"data-testid":`documents-existing-${b}-preview`,children:e.jsx(Ct,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(b),"data-testid":`documents-existing-${b}-delete`,children:e.jsx(bt,{className:"h-4 w-4 text-red-600"})})]})]},b)})})})]}),a.length>0&&e.jsxs(Z,{"data-testid":"documents-new-card",children:[e.jsx(oe,{children:e.jsxs(me,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(se,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((f,b)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Ie,{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(E,{variant:"ghost",size:"sm",onClick:()=>c(f,!1),"data-testid":`documents-new-${b}-preview`,children:e.jsx(Ct,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>x(b),"data-testid":`documents-new-${b}-remove`,children:e.jsx(bt,{className:"h-4 w-4"})})]})]},b))})})]})]})]})}const hT=t=>{switch(t){case"high":return e.jsx(Sa,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(es,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Hs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(es,{className:"w-4 h-4 text-gray-600"})}};function pT({formData:t,selectedTemplate:s}){return e.jsxs(Ht.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(Le,{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(Z,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(oe,{children:e.jsxs(me,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(lh,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(ee,{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(te,{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(se,{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(te,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[hT(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(te,{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(te,{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(Z,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(oe,{children:e.jsxs(me,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Ie,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(te,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(Es,{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(Ha,{className:"w-4 h-4 text-blue-600"}),e.jsx(te,{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(Z,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(Zt,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(ve,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(ee,{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(se,{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(Z,{"data-testid":"review-submit-participants-card",children:[e.jsx(oe,{children:e.jsxs(me,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(Ct,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(ee,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(te,{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(se,{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(Z,{"data-testid":"review-submit-documents-card",children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(js,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(ve,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(ee,{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(Ie,{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(Z,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Le,{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 gT({isEditing:t,currentStep:s,totalSteps:a,stepNames:r,onBack:n}){return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0","data-testid":"create-request-header",children:e.jsxs("div",{className:"flex items-center justify-between max-w-6xl mx-auto gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-1 min-w-0",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"create-request-back-button",children:e.jsx(ws,{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 fT({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(ol,{mode:"wait",children:t})})})}function bT({modal:t,onClose:s}){return e.jsx(jt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(xt,{className:"sm:max-w-md",children:[e.jsxs(yt,{children:[e.jsxs(ht,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Ut,{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(Qi,{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(Et,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function jT({modal:t,documentPolicy:s,onClose:a}){return e.jsx(jt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(xt,{className:"sm:max-w-lg",children:[e.jsxs(yt,{children:[e.jsxs(ht,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Ut,{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(Et,{children:e.jsx(E,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function jx({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=_a(),i=ys(),l=n.requestId||a||"",o=r&&!!l,{user:c}=cs(),[d,m]=h.useState([]);h.useEffect(()=>{(async()=>{try{const fe=(await xl()).map(ye=>({id:ye.id,name:ye.name,description:ye.description,category:ye.category,icon:Ie,estimatedTime:ye.estimatedTime,commonApprovers:ye.approvers.map(Ue=>Ue.name),workflowApprovers:ye.approvers,suggestedSLA:ye.suggestedSLA,priority:ye.priority,fields:ye.fields||{}}));m(fe)}catch(Ye){console.error("Failed to fetch admin templates:",Ye)}})()},[]);const p=h.useMemo(()=>[...px,...d],[d]),{formData:x,updateFormData:u,selectedTemplate:g,setSelectedTemplate:f,loadingDraft:b,systemPolicy:j,documentPolicy:y,existingDocuments:w,setExistingDocuments:N}=VA(o,l,p),{currentStep:S,totalSteps:A,stepNames:_,isStepValid:D,nextStep:R,prevStep:v}=zA(o,g,x),[P,C]=h.useState([]),[V,F]=h.useState([]),$=h.useRef(null),{validationModal:I,policyViolationModal:T,documentErrorModal:k,openValidationModal:z,closeValidationModal:L,openPolicyViolationModal:M,closePolicyViolationModal:U,openDocumentErrorModal:B,closeDocumentErrorModal:W}=HA(),{submitting:J,savingDraft:O,handleSubmit:H,handleSaveDraft:Y}=QA({formData:x,selectedTemplate:g,documents:P,documentsToDelete:V,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:re,setShowTemplateModal:K,previewDocument:ae,selectTemplate:Ne,handleTemplateSelection:Se,nextStep:Ge,prevStep:Je,handlePreviewDocument:Pe,closePreview:Oe}=rT({selectedTemplate:g,setSelectedTemplate:f,updateFormData:u,formData:x,currentStep:S,isStepValid:D,wizardNextStep:R,wizardPrevStep:v,user:c,openValidationModal:z,systemPolicy:j,onPolicyViolation:M,onSubmit:s}),ie=h.useCallback(()=>{if(S===1){i("/dashboard",{replace:!0});return}S===3||S===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Je()},[S,t,i,Je]),pe=h.useRef(!0),we=h.useRef(!1);h.useEffect(()=>{pe.current&&x.documents&&x.documents.length>0&&!we.current&&(C(x.documents),we.current=!0),pe.current=!1},[x.documents]);const Ae=h.useRef(!1),ne=h.useRef(P);h.useEffect(()=>{if(Ae.current){Ae.current=!1,ne.current=P;return}ne.current!==P&&(u("documents",P),ne.current=P)},[P]);const q=()=>{switch(S){case 1:return e.jsx(oT,{templates:px,selectedTemplate:g,onSelectTemplate:Ne,adminTemplates:d});case 2:return e.jsx(dT,{formData:x,selectedTemplate:g,updateFormData:u});case 3:return e.jsx(mT,{formData:x,updateFormData:u,systemPolicy:j,onValidationError:de=>z(de.type,de.email,de.message),onPolicyViolation:M});case 4:return e.jsx(uT,{formData:x,updateFormData:u,onValidationError:de=>z(de.type,de.email,de.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(xT,{documentPolicy:y,isEditing:o,documents:P,existingDocuments:w,documentsToDelete:V,onDocumentsChange:C,onExistingDocumentsChange:N,onDocumentsToDeleteChange:F,onPreviewDocument:Pe,onDocumentErrors:de=>B(de),fileInputRef:$});case 6:return e.jsx(pT,{formData:x,selectedTemplate:g});default:return null}};return b?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(gT,{isEditing:o,currentStep:S,totalSteps:A,stepNames:_,onBack:ie}),e.jsx(Yg,{currentStep:S,totalSteps:A,stepNames:_}),e.jsx(fT,{children:q()}),e.jsx(lT,{currentStep:S,totalSteps:A,isStepValid:D(),onPrev:Je,onNext:Ge,onSubmit:H,onSaveDraft:Y,submitting:J,savingDraft:O,loadingDraft:b,isEditing:o}),e.jsx(kA,{open:re,onClose:()=>K(!1),onSelectTemplate:Se}),ae&&e.jsx(Mr,{fileName:ae.fileName,fileType:ae.fileType,fileUrl:ae.fileUrl,fileSize:ae.fileSize,open:!!ae,onClose:Oe,onDownload:async()=>{if(ae.file){const de=document.createElement("a");de.href=ae.fileUrl,de.download=ae.fileName,document.body.appendChild(de),de.click(),document.body.removeChild(de)}else ae.documentId&&await Ms(ae.documentId)},attachmentId:ae.documentId}),e.jsx(bT,{modal:I,onClose:L}),e.jsx(jT,{modal:k,documentPolicy:y,onClose:W}),e.jsx(si,{open:T.open,onClose:U,violations:T.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}function ai({className:t,...s}){return e.jsx(If,{"data-slot":"tabs",className:_e("flex flex-col gap-2",t),...s})}function ri({className:t,...s}){return e.jsx(Pf,{"data-slot":"tabs-list",className:_e("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function Mt({className:t,...s}){return e.jsx(Ef,{"data-slot":"tabs-trigger",className:_e("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 Lt({className:t,...s}){return e.jsx(_f,{"data-slot":"tabs-content",className:_e("flex-1 outline-none",t),...s})}function Hn(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 Vc(t,s=[],a){const[r,n]=h.useState(null),[i,l]=h.useState(!1),[o,c]=h.useState(!0),[d,m]=h.useState(null),[p,x]=h.useState(null),[u,g]=h.useState(!1),f=(S,A)=>(S||A||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),b=S=>{const A=(S||"").toUpperCase();return A==="IN_PROGRESS"?"in-review":A==="PENDING"?"pending":A==="APPROVED"?"approved":A==="REJECTED"?"rejected":A==="CLOSED"?"closed":A==="SKIPPED"?"skipped":(S||"").toLowerCase()},j=h.useCallback(async()=>{var S,A,_,D,R,v,P,C,V,F,$,I,T;l(!0);try{const k=await Ws.getWorkflowDetails(t);if(!k){console.warn("[useRequestDetails] No details returned from API");return}const z=k.workflow||{},L=Array.isArray(k.approvals)?k.approvals:[],M=Array.isArray(k.participants)?k.participants:[],U=Array.isArray(k.documents)?k.documents:[],B=k.summary||{},W=Array.isArray(k.tatAlerts)?k.tatAlerts:[];W.length>0;const J=(B==null?void 0:B.currentLevel)||z.currentLevel||1,O=L.map(q=>{const de=q.levelNumber||0,Ye=(q.status||"").toString().toUpperCase(),fe=q.levelId||q.level_id;let ye=b(q.status);de>J&&Ye!=="APPROVED"&&Ye!=="REJECTED"?ye="waiting":de===J&&Ye==="PENDING"&&(ye="pending");const Ue=W.filter(nt=>nt.levelId===fe);return{step:de,levelId:fe,role:q.levelName||q.approverName||"Approver",status:ye,approver:q.approverName||q.approverEmail,approverId:q.approverId||q.approver_id,approverEmail:q.approverEmail,tatHours:Number(q.tatHours||0),elapsedHours:Number(q.elapsedHours||0),remainingHours:Number(q.remainingHours||0),tatPercentageUsed:Number(q.tatPercentageUsed||0),actualHours:q.levelEndTime&&q.levelStartTime?Math.max(0,(new Date(q.levelEndTime).getTime()-new Date(q.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:q.comments||void 0,timestamp:q.actionDate||void 0,levelStartTime:q.levelStartTime||q.tatStartTime,tatAlerts:Ue,skipReason:q.skipReason||void 0,isSkipped:Ye==="SKIPPED"||q.isSkipped||!1}}),H=M.filter(q=>(q.participantType||q.participant_type||"").toUpperCase()==="SPECTATOR").map(q=>({name:q.userName||q.user_name||q.userEmail||q.user_email,role:"Spectator",email:q.userEmail||q.user_email,avatar:f(q.userName||q.user_name,q.userEmail||q.user_email)})),Y=q=>{var Ye,fe;if(!q)return;const de=M.find(ye=>ye.userId===q||ye.user_id===q);return de!=null&&de.userName||de!=null&&de.user_name?de.userName||de.user_name:z.initiatorId===q?((Ye=z.initiator)==null?void 0:Ye.displayName)||((fe=z.initiator)==null?void 0:fe.email):q},re=U.map(q=>{const de=Number(q.fileSize||q.file_size||0),Ye=(de/(1024*1024)).toFixed(2)+" MB";return{documentId:q.documentId||q.document_id,name:q.originalFileName||q.fileName||q.file_name,fileType:q.fileType||q.file_type||"",size:Ye,sizeBytes:de,uploadedBy:Y(q.uploadedBy||q.uploaded_by),uploadedAt:q.uploadedAt||q.uploaded_at}}),K=Array.isArray(k.activities)?k.activities.filter(q=>(q.type||"").toLowerCase()!=="sla_warning"):[];let ae=null;if(z.isPaused||!1)try{ae=await Gm(z.requestId)}catch{}let Se=null,Ge=null,Je=null,Pe=null,Oe=[],ie=null;if(Hn(z)){try{const q=await je.get(`/dealer-claims/${z.requestId}/credit-note-wfm`),de=q.data??q;ie=Array.isArray(de==null?void 0:de.data)?de.data:Array.isArray(de)?de:[]}catch(q){console.warn("[useRequestDetails] Error fetching credit note WFM data:",q)}try{const q=await je.get(`/dealer-claims/${z.requestId}`),de=((S=q.data)==null?void 0:S.data)||q.data;if(de){Se=de.claimDetails||de.claim_details,Ge=de.proposalDetails||de.proposal_details,Je=de.completionDetails||de.completion_details,Pe=de.internalOrder||de.internal_order||null,Oe=de.internalOrders||de.internal_orders||[];const Ye=de.budgetTracking||de.budget_tracking||null,fe=de.invoice||null,ye=de.creditNote||de.credit_note||null,Ue=de.completionExpenses||de.completion_expenses||null;Se&&(Se.budgetTracking=Ye,Se.invoice=fe,Se.creditNote=ye,Se.completionExpenses=Ue,Se.creditNoteWfmData=ie)}else console.warn("[useRequestDetails] No claimData found in response")}catch(q){console.error("[useRequestDetails] Error fetching claim details:",{error:(q==null?void 0:q.message)||q,status:(A=q==null?void 0:q.response)==null?void 0:A.status,statusText:(_=q==null?void 0:q.response)==null?void 0:_.statusText,responseData:(D=q==null?void 0:q.response)==null?void 0:D.data,requestId:z.requestId})}}const pe={...z,id:z.requestNumber||z.requestId,requestId:z.requestId,requestNumber:z.requestNumber,title:z.title,description:z.description,status:b(z.status),priority:(z.priority||"").toString().toLowerCase(),workflowType:z.workflowType||(z.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:O,approvals:L,participants:M,documents:re,spectators:H,summary:B,sla:(B==null?void 0:B.sla)||z.sla||null,initiator:{name:((R=z.initiator)==null?void 0:R.displayName)||((v=z.initiator)==null?void 0:v.email),role:((P=z.initiator)==null?void 0:P.designation)||void 0,department:((C=z.initiator)==null?void 0:C.department)||void 0,email:((V=z.initiator)==null?void 0:V.email)||void 0,phone:((F=z.initiator)==null?void 0:F.phone)||void 0,avatar:f(($=z.initiator)==null?void 0:$.displayName,(I=z.initiator)==null?void 0:I.email)},createdAt:z.createdAt,updatedAt:z.updatedAt,totalSteps:z.totalLevels||1,currentStepRaw:(B==null?void 0:B.currentLevel)||z.currentLevel||1,currentStep:Math.min(Math.max(1,(B==null?void 0:B.currentLevel)||z.currentLevel||1),z.totalLevels||1),auditTrail:K,conclusionRemark:z.conclusionRemark||null,closureDate:z.closureDate||null,pauseInfo:ae||null,claimDetails:Se||null,proposalDetails:Ge||null,completionDetails:Je||null,internalOrder:Pe||null,internalOrders:Oe||[],budgetTracking:(Se==null?void 0:Se.budgetTracking)||null,invoice:(Se==null?void 0:Se.invoice)||(Se==null?void 0:Se.invoice)||null,creditNote:(Se==null?void 0:Se.creditNote)||null,creditNoteWfmData:ie||(Se==null?void 0:Se.creditNoteWfmData)||null,completionExpenses:(Se==null?void 0:Se.completionExpenses)||null,templateType:z.templateType||z.template_type,form16Submission:k.form16Submission||null};n(pe);const we=(T=a==null?void 0:a.email)==null?void 0:T.toLowerCase(),Ae=L.find(q=>{const de=(q.status||"").toString().toUpperCase(),Ye=(q.approverEmail||"").toLowerCase(),fe=q.levelNumber||0;return(de==="PENDING"||de==="IN_PROGRESS"||de==="PAUSED")&&Ye===we&&fe===J});x(Ae||null);const ne=a==null?void 0:a.userId;if(ne){const q=M.some(de=>(de.participantType||de.participant_type||"").toUpperCase()==="SPECTATOR"&&(de.userId||de.user_id)===ne);g(q)}else g(!1)}catch(k){console.error("[useRequestDetails] Error refreshing details:",k),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);h.useEffect(()=>{if(!t){c(!1);return}let S=!0;return c(!0),m(null),(async()=>{var A,_,D,R,v,P,C,V,F,$,I,T,k,z;try{const L=await Ws.getWorkflowDetails(t);if(!S||!L){S&&c(!1);return}const M=L.workflow||{},U=Array.isArray(L.approvals)?L.approvals:[],B=Array.isArray(L.participants)?L.participants:[],W=Array.isArray(L.documents)?L.documents:[],J=L.summary||{},O=Array.isArray(L.tatAlerts)?L.tatAlerts:[],H=(M.priority||"").toString().toLowerCase(),Y=(J==null?void 0:J.currentLevel)||M.currentLevel||1,re=U.map(fe=>{const ye=fe.levelNumber||0,Ue=(fe.status||"").toString().toUpperCase(),nt=fe.levelId||fe.level_id;let mt=b(fe.status);Ue==="PAUSED"?mt="paused":ye>Y&&Ue!=="APPROVED"&&Ue!=="REJECTED"?mt="waiting":ye===Y&&(Ue==="PENDING"||Ue==="IN_PROGRESS")&&(mt=Ue==="IN_PROGRESS"?"in-review":"pending");const vt=O.filter(xs=>xs.levelId===nt);return{step:ye,levelId:nt,role:fe.levelName||fe.approverName||"Approver",status:mt,approver:fe.approverName||fe.approverEmail,approverId:fe.approverId||fe.approver_id,approverEmail:fe.approverEmail,tatHours:Number(fe.tatHours||0),elapsedHours:Number(fe.elapsedHours||0),remainingHours:Number(fe.remainingHours||0),tatPercentageUsed:Number(fe.tatPercentageUsed||0),actualHours:fe.elapsedHours!==void 0&&fe.elapsedHours!==null?Number(fe.elapsedHours):void 0,comment:fe.comments||void 0,timestamp:fe.actionDate||void 0,levelStartTime:fe.levelStartTime||fe.tatStartTime,tatAlerts:vt}}),K=B.filter(fe=>(fe.participantType||"").toUpperCase()==="SPECTATOR").map(fe=>({name:fe.userName||fe.userEmail,role:"Spectator",avatar:f(fe.userName,fe.userEmail)})),ae=fe=>{var Ue,nt;if(!fe)return;const ye=B.find(mt=>mt.userId===fe);return ye!=null&&ye.userName?ye.userName:M.initiatorId===fe?((Ue=M.initiator)==null?void 0:Ue.displayName)||((nt=M.initiator)==null?void 0:nt.email):fe},Ne=W.map(fe=>{const ye=Number(fe.fileSize||0),Ue=(ye/(1024*1024)).toFixed(2)+" MB";return{documentId:fe.documentId||fe.document_id,name:fe.originalFileName||fe.fileName,fileType:fe.fileType||fe.file_type||"",size:Ue,sizeBytes:ye,uploadedBy:ae(fe.uploadedBy),uploadedAt:fe.uploadedAt}}),Se=Array.isArray(L.activities)?L.activities.filter(fe=>(fe.type||"").toLowerCase()!=="sla_warning"):[];let Ge=null;if(M.isPaused||!1)try{Ge=await Gm(M.requestId)}catch{}let Pe=null,Oe=null,ie=null,pe=null,we=[],Ae=null;if(Hn(M)){try{const fe=await je.get(`/dealer-claims/${M.requestId}/credit-note-wfm`),ye=fe.data??fe;Ae=Array.isArray(ye==null?void 0:ye.data)?ye.data:Array.isArray(ye)?ye:[]}catch(fe){console.warn("[useRequestDetails] Error fetching credit note WFM data:",fe)}try{const fe=await je.get(`/dealer-claims/${M.requestId}`),ye=((A=fe.data)==null?void 0:A.data)||fe.data;if(ye){Pe=ye.claimDetails||ye.claim_details,Oe=ye.proposalDetails||ye.proposal_details,ie=ye.completionDetails||ye.completion_details,pe=ye.internalOrder||ye.internal_order||null,we=ye.internalOrders||ye.internal_orders||[];const Ue=ye.budgetTracking||ye.budget_tracking||null,nt=ye.invoice||null,mt=ye.creditNote||ye.credit_note||null,vt=ye.completionExpenses||ye.completion_expenses||null;Pe&&(Pe.budgetTracking=Ue,Pe.invoice=nt,Pe.creditNote=mt,Pe.completionExpenses=vt,Pe.creditNoteWfmData=Ae)}}catch(fe){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(fe==null?void 0:fe.message)||fe,status:(_=fe==null?void 0:fe.response)==null?void 0:_.status,requestId:M.requestId})}}const ne={id:M.requestNumber||M.requestId,requestId:M.requestId,title:M.title,description:M.description,priority:H,status:b(M.status),workflowType:M.workflowType||(M.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:J,initiator:{name:((D=M.initiator)==null?void 0:D.displayName)||((R=M.initiator)==null?void 0:R.email),role:((v=M.initiator)==null?void 0:v.designation)||void 0,department:((P=M.initiator)==null?void 0:P.department)||void 0,email:((C=M.initiator)==null?void 0:C.email)||void 0,phone:((V=M.initiator)==null?void 0:V.phone)||void 0,avatar:f((F=M.initiator)==null?void 0:F.displayName,($=M.initiator)==null?void 0:$.email)},createdAt:M.createdAt,updatedAt:M.updatedAt,totalSteps:M.totalLevels||1,currentStepRaw:(J==null?void 0:J.currentLevel)||M.currentLevel||1,currentStep:Math.min(Math.max(1,(J==null?void 0:J.currentLevel)||M.currentLevel||1),M.totalLevels||1),approvalFlow:re,approvals:U,documents:Ne,spectators:K,auditTrail:Se,conclusionRemark:M.conclusionRemark||null,closureDate:M.closureDate||null,pauseInfo:Ge||null,claimDetails:Pe||null,proposalDetails:Oe||null,completionDetails:ie||null,internalOrder:pe||null,internalOrders:we||[],budgetTracking:(Pe==null?void 0:Pe.budgetTracking)||null,invoice:(Pe==null?void 0:Pe.invoice)||null,creditNote:(Pe==null?void 0:Pe.creditNote)||null,creditNoteWfmData:Ae||(Pe==null?void 0:Pe.creditNoteWfmData)||null,completionExpenses:(Pe==null?void 0:Pe.completionExpenses)||null,templateType:M.templateType||M.template_type,form16Submission:L.form16Submission||null};n(ne);const q=(I=a==null?void 0:a.email)==null?void 0:I.toLowerCase(),de=U.find(fe=>{const ye=(fe.status||"").toString().toUpperCase(),Ue=(fe.approverEmail||"").toLowerCase(),nt=fe.levelNumber||0;return(ye==="PENDING"||ye==="IN_PROGRESS"||ye==="PAUSED")&&Ue===q&&nt===Y});x(de||null);const Ye=a==null?void 0:a.userId;if(Ye){const fe=B.some(ye=>(ye.participantType||"").toUpperCase()==="SPECTATOR"&&ye.userId===Ye);g(fe)}else g(!1)}catch(L){if(console.error("[useRequestDetails] Error loading request details:",L),S){if(((T=L==null?void 0:L.response)==null?void 0:T.status)===403){const M=((z=(k=L==null?void 0:L.response)==null?void 0:k.data)==null?void 0:z.message)||"You do not have permission to view this request. Access is restricted to the initiator, approvers, and spectators of this request.";m({denied:!0,message:M})}n(null)}}finally{S&&c(!1)}})(),()=>{S=!1}},[t,a]);const y=h.useMemo(()=>{if(r)return r;const S=s.find(A=>A.id===t||A.requestNumber===t||A.request_number===t);return S||null},[t,s,r]),w=h.useMemo(()=>{var _,D,R;if(!y||!a)return!1;const S=(_=a==null?void 0:a.email)==null?void 0:_.toLowerCase(),A=(R=(D=y.initiator)==null?void 0:D.email)==null?void 0:R.toLowerCase();return S===A},[y,a]),N=h.useMemo(()=>{var A;if(!y)return[];const S=[];return(A=y.initiator)!=null&&A.email&&S.push({email:y.initiator.email.toLowerCase(),participantType:"INITIATOR",name:y.initiator.name}),y.approvalFlow&&Array.isArray(y.approvalFlow)&&y.approvalFlow.forEach(_=>{_.approverEmail&&S.push({email:_.approverEmail.toLowerCase(),participantType:"APPROVER",name:_.approver})}),y.spectators&&Array.isArray(y.spectators)&&y.spectators.forEach(_=>{_.email&&S.push({email:_.email.toLowerCase(),participantType:"SPECTATOR",name:_.name})}),y.participants&&Array.isArray(y.participants)&&y.participants.forEach(_=>{const D=(_.userEmail||_.email||"").toLowerCase(),R=(_.participantType||_.participant_type||"").toUpperCase(),v=_.userName||_.user_name||_.name;D&&R&&!S.find(P=>P.email===D)&&S.push({email:D,participantType:R,name:v})}),S},[y]);return h.useEffect(()=>{if(!t||!r)return;const S=en();if(!S)return;const A=_=>{((_==null?void 0:_.requestId)===r.requestId||(_==null?void 0:_.requestNumber)===t)&&j()};return S.on("request:updated",A),()=>{S.off("request:updated",A)}},[t,r,j]),{request:y,apiRequest:r,loading:o,refreshing:i,refreshDetails:j,currentApprovalLevel:p,isSpectator:u,isInitiator:w,existingParticipants:N,accessDenied:d}}function Xg(t,s,a,r){const[n,i]=h.useState([]),[l,o]=h.useState(0),[c,d]=h.useState([]);return h.useEffect(()=>{if(!t){console.warn("[useRequestSocket] No requestIdentifier, cannot join socket room");return}let m=!0,p=t;return(async()=>{var f;try{const b=await Ws.getWorkflowDetails(t);(f=b==null?void 0:b.workflow)!=null&&f.requestId&&m&&(p=b.workflow.requestId)}catch(b){console.error("[useRequestSocket] Failed to resolve UUID:",b)}if(!m)return;const x=en();if(!x){console.error("[useRequestSocket] Socket not available");return}const u=r==null?void 0:r.userId,g=()=>{mo(x,p,u)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Hh(x,p))}})(),()=>{m=!1}},[t,r]),h.useEffect(()=>{!t||!s||(async()=>{try{const m=await Zr(t),p=s.auditTrail||[],x=[...m,...p];x.sort((u,g)=>{const f=new Date(u.createdAt||u.created_at||u.timestamp||0).getTime(),b=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return f-b}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),h.useEffect(()=>{if(!t)return;const m=en();if(!m)return;const p=u=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await Zr(t),f=(s==null?void 0:s.auditTrail)||[],b=[...g,...f].sort((j,y)=>{const w=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime(),N=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime();return w-N});i(b)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=u=>{const g=u.type==="breach"?"⏰":u.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const f=await Ws.getWorkflowDetails(t);f&&(Array.isArray(f.tatAlerts)&&f.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:u.message,icon:"/favicon.ico",tag:`tat-${u.requestId}-${u.type}`,requireInteraction:!1}))}catch(f){console.error("[useRequestSocket] Failed to refresh after TAT alert:",f)}})()};return m.on("noteHandler",p),m.on("worknote:new",p),m.on("tat:alert",x),()=>{m.off("noteHandler",p),m.off("worknote:new",p),m.off("tat:alert",x)}},[t,a,s]),h.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function Rn(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}}const yT=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],vT={MALWARE_DETECTED:"🛑 Malware Detected",FILE_VALIDATION_FAILED:"⛔ File Rejected",CONTENT_THREAT_DETECTED:"⚠️ Malicious Content Detected",SCAN_UNAVAILABLE:"🔒 Security Scan Unavailable",SCAN_ERROR:"❌ Security Scan Error"};function zc(t){var l,o,c,d;const s=(l=t==null?void 0:t.response)==null?void 0:l.data;if(!(s!=null&&s.error))return!1;const a=s.error;if(!yT.includes(a))return!1;const r=vT[a]||"Security Error",n=s.message||"File was blocked by security scan";let i="";return s.details&&((o=s.details.signatures)!=null&&o.length?i=`Virus: ${s.details.signatures.join(", ")}`:(c=s.details.errors)!=null&&c.length?i=s.details.errors[0]||"":(d=s.details.threats)!=null&&d.length&&(i=s.details.threats.map(m=>m.description).join(", "))),X.error(r,{description:i||n,duration:8e3,style:{background:"#fef2f2",border:"1px solid #fca5a5",color:"#991b1b"}}),!0}function Jg(t,s){const[a,r]=h.useState(!1),[n,i]=h.useState(null),[l,o]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=h.useState({show:!1,errors:[]});h.useEffect(()=>{(async()=>{try{const g=await la("DOCUMENT_POLICY"),f={};g.forEach(w=>{f[w.configKey]=w.configValue});const b=parseInt(f.MAX_FILE_SIZE_MB||"10"),y=(f.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(w=>w.trim().toLowerCase());o({maxFileSizeMB:b,allowedFileTypes:y})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=u=>{const g=l.maxFileSizeMB*1024*1024;if(u.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(u.size/(1024*1024)).toFixed(2)}MB`};const f=u.name.toLowerCase(),b=f.substring(f.lastIndexOf(".")+1);return l.allowedFileTypes.includes(b)?{valid:!0}:{valid:!1,reason:`File type "${b}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},p=async u=>{var y,w;const g=u.target.files;if(!g||g.length===0)return;const f=Array.from(g),b=[],j=[];if(f.forEach(N=>{const S=m(N);S.valid?j.push(N):b.push({fileName:N.name,reason:S.reason||"Unknown validation error"})}),b.length>0&&d({show:!0,errors:b}),j.length===0){u.target&&(u.target.value="");return}r(!0);try{const N=j[0],S=t==null?void 0:t.requestId;if(!S){X.error("Request ID not found");return}N&&await Rn(N,S,"SUPPORTING"),await s(),j.length<f.length?X.warning(`${j.length} of ${f.length} file(s) were uploaded. ${b.length} file(s) were rejected.`):X.success("Document uploaded successfully")}catch(N){console.error("[useDocumentUpload] Upload error:",N),zc(N)||X.error(((w=(y=N==null?void 0:N.response)==null?void 0:y.data)==null?void 0:w.message)||"Failed to upload document")}finally{r(!1),u.target&&(u.target.value="")}};return{uploadingDocument:a,handleDocumentUpload:p,triggerFileInput:()=>{const u=document.createElement("input");u.type="file",u.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),u.onchange=p,u.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const NT="modulepreload",wT=function(t){return"/"+t},yx={},Gl=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=wT(c),c in yx)return;yx[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const p=document.createElement("link");if(p.rel=d?"stylesheet":NT,d||(p.as="script"),p.crossOrigin="",p.href=c,o&&p.setAttribute("nonce",o),document.head.appendChild(p),d)return new Promise((x,u)=>{p.addEventListener("load",x),p.addEventListener("error",()=>u(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return n.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};function Zg(t,s,a,r,n,i,l){const[o,c]=h.useState(""),[d,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[f,b]=h.useState(0),[j,y]=h.useState(!1),[w,N]=h.useState(!1),[S,A]=h.useState(0),_=async()=>{var C;const v=(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(v||P){c(v||P),g(!!P);return}try{const{getConclusion:V}=await Gl(async()=>{const{getConclusion:$}=await import("./conclusionApi-B_YjyhCb.js");return{getConclusion:$}},__vite__mapDeps([0,1,2,3,4,5,6,7])),F=await V(t.requestId||s);F&&(F.aiGeneratedRemark||F.finalRemark)&&(c(F.finalRemark||F.aiGeneratedRemark||""),g(!!F.aiGeneratedRemark))}catch(V){((C=V==null?void 0:V.response)==null?void 0:C.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",V)}},D=async()=>{if(!w)try{m(!0),y(!1);const{generateConclusion:v}=await Gl(async()=>{const{generateConclusion:F}=await import("./conclusionApi-B_YjyhCb.js");return{generateConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7])),P=await v(t.requestId||s),C=f+1;if(b(C),!(P!=null&&P.aiGeneratedRemark)||P.aiGeneratedRemark.toLowerCase().includes("unable to generate")||P.aiGeneratedRemark.toLowerCase().includes("sorry")){const F=S+1;A(F),F>=2?(N(!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),A(0),C>=2&&(N(!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(v){console.error("[useConclusionRemark] AI generation failed:",v);const P=S+1;A(P),g(!1),P>=2?(N(!0),i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. Since the maximum of 2 attempts is reached, please proceed with a manual approach."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0)}finally{m(!1)}},R=async()=>{var P,C;const v=o.replace(/<[^>]*>/g,"").trim();if(!v){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(v.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),l==null||l(!0);return}try{x(!0);const{finalizeConclusion:V}=await Gl(async()=>{const{finalizeConclusion:F}=await import("./conclusionApi-B_YjyhCb.js");return{finalizeConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await V(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(V){i==null||i({success:!1,title:"Error",message:((C=(P=V.response)==null?void 0:P.data)==null?void 0:C.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{x(!1)}};return h.useEffect(()=>{var F;const v=(F=t==null?void 0:t.status)==null?void 0:F.toLowerCase();if(!((v==="approved"||v==="rejected"||v==="closed")&&a&&!o))return;const C=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),V=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);C||V?(c(C||V),g(!!V)):_()},[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:p,aiGenerated:u,handleGenerateConclusion:D,handleFinalizeConclusion:R,generationAttempts:f,generationFailed:j,maxAttemptsReached:w}}function qg(t,s,a){const[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState(!1),[d,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[f,b]=h.useState(null),[j,y]=h.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:p,setShowSkipApproverModal:x,showActionStatusModal:u,setShowActionStatusModal:g,skipApproverData:f,setSkipApproverData:b,actionStatus:j,setActionStatus:y,handleApproveConfirm:async D=>{var v,P;const R=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!R){alert("Approval level not found");return}await Tn(t,R,D||""),await new Promise(C=>setTimeout(C,500)),await a(),(v=window==null?void 0:window.closeModal)==null||v.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var v,P;if(!(D!=null&&D.trim())){alert("Comments & remarks are required");return}const R=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!R){alert("Approval level not found");return}await Nr(t,R,D.trim(),D.trim()),await a(),(v=window==null?void 0:window.closeModal)==null||v.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Rejected successfully")},handleAddApprover:async(D,R,v)=>{var P,C;try{await ip(t,D,R,v),await a(),c(!1),y==null||y({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${v} with ${R}h TAT`}),g==null||g(!0)}catch(V){throw y==null||y({success:!1,title:"Failed to Add Approver",message:((C=(P=V==null?void 0:V.response)==null?void 0:P.data)==null?void 0:C.error)||"Failed to add approver. Please try again."}),g==null||g(!0),V}},handleSkipApprover:async D=>{var R,v;if(f)try{await Sw(t,f.levelId,D),await a(),x(!1),b(null),y==null||y({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),g==null||g(!0)}catch(P){throw y==null||y({success:!1,title:"Failed to Skip Approver",message:((v=(R=P==null?void 0:P.response)==null?void 0:R.data)==null?void 0:v.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),P}},handleAddSpectator:async D=>{var R,v;try{await lp(t,D),await a(),m(!1),y==null||y({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),g==null||g(!0)}catch(P){throw y==null||y({success:!1,title:"Failed to Add Spectator",message:((v=(R=P==null?void 0:P.response)==null?void 0:R.data)==null?void 0:v.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),P}}}}function CT({requestId:t,request:s,onRefresh:a}){const[r,n]=h.useState(null),[i,l]=h.useState(!0),[o,c]=h.useState(null),m=!!(s==null?void 0:s.form16Submission),p=!!r&&r.status!=="withdrawn";h.useEffect(()=>{if(!t){l(!1);return}let g=!1;return(async()=>{try{const f=await Vh(t);g||n(f?{id:typeof f.id=="number"?f.id:Number(f.id),status:f.status||""}:null)}catch{g||n(null)}finally{g||l(!1)}})(),()=>{g=!0}},[t]);const x=async()=>{if(!(!t||!window.confirm("Cancel this Form 16 submission? The request will be marked as rejected."))){c("cancel");try{await yy(t),X.success("Submission cancelled"),a==null||a()}catch(g){X.error(g instanceof Error?g.message:"Failed to cancel submission")}finally{c(null)}}},u=async()=>{if(!(!t||!window.confirm("Mark this submission as resubmission needed? The dealer will need to resubmit Form 16."))){c("resubmit");try{await vy(t),X.success("Marked as resubmission needed"),a==null||a()}catch(g){X.error(g instanceof Error?g.message:"Failed to update")}finally{c(null)}}};return i||!m||p?null:e.jsxs(Z,{className:"border-blue-200 bg-blue-50/30","data-testid":"form16-quick-actions-card",children:[e.jsxs(oe,{className:"pb-2",children:[e.jsxs(me,{className:"text-sm flex items-center gap-2 text-blue-800",children:[e.jsx(Pt,{className:"w-4 h-4"}),"Form 16 actions"]}),e.jsx(ve,{className:"text-xs text-gray-600",children:"View the document in the Documents tab. Cancel submission or mark resubmission needed."})]}),e.jsxs(ee,{className:"space-y-2",children:[e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start border-red-300 text-red-700 hover:bg-red-50",onClick:x,disabled:!!o,children:[o==="cancel"?e.jsx(Xe,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(bt,{className:"w-3 h-3 mr-1"}),"Cancel submission"]}),e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start border-amber-300 text-amber-700 hover:bg-amber-50",onClick:u,disabled:!!o,children:[o==="resubmit"?e.jsx(Xe,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(oh,{className:"w-3 h-3 mr-1"}),"Resubmission needed"]})]})]})}const ST=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 Pr({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(Ie,{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 "]}),gs(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&ST(t.fileType)&&s&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>s({fileName:t.name,fileType:t.fileType,documentId:t.documentId,fileSize:t.sizeBytes}),title:"Preview file","data-testid":`${n}-preview-btn`,children:e.jsx(Ct,{className:"w-4 h-4"})}),a&&e.jsx(E,{variant:"ghost",size:"sm",onClick:async()=>{if(!t.documentId){alert("Document ID not available");return}try{await a(t.documentId)}catch{alert("Failed to download document")}},title:"Download file","data-testid":`${n}-download-btn`,children:e.jsx(kt,{className:"w-4 h-4"})})]})]})}function AT({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l}){var c,d,m,p;const o=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16";return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[o&&((d=(c=t==null?void 0:t.form16Submission)==null?void 0:c.previousDocuments)==null?void 0:d.length)>0&&e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2 text-sm sm:text-base text-amber-800",children:[e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-amber-600"}),"Previous submission(s) – same quarter"]}),e.jsxs(ve,{className:"text-xs sm:text-sm mt-1",children:["Documents from earlier Form 16A submissions for this request's financial year and quarter only (",(m=t==null?void 0:t.form16Submission)==null?void 0:m.financialYear," ",(p=t==null?void 0:t.form16Submission)==null?void 0:p.quarter,")"]})]}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-4",children:(()=>{const x=new Map;for(const u of t.form16Submission.previousDocuments){const g=u.requestId||u.request_id,f=u.requestNumber||g;x.has(f)||x.set(f,[]),x.get(f).push(u)}return Array.from(x.entries()).map(([u,g])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600",children:["Request ",u]}),e.jsx("div",{className:"space-y-2 pl-2 border-l-2 border-amber-200",children:g.map((f,b)=>{const j=f.documentId??f.document_id,y=f.originalFileName??f.original_file_name??f.fileName??f.file_name??"Document",w=Number(f.fileSize??f.file_size??0),N=w>0?(w/(1024*1024)).toFixed(2)+" MB":"—";return e.jsx(Pr,{document:{documentId:j,name:y,fileType:f.fileType??f.file_type??"",size:N,sizeBytes:w,uploadedBy:f.uploadedBy??f.uploaded_by,uploadedAt:f.uploadedAt??f.uploaded_at},onPreview:S=>i(S),onDownload:l,testId:"form16-previous-document"},j||b)})})]},u))})()})})]}),e.jsxs(Z,{children:[e.jsx(oe,{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(me,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),o?"Current submission":"Request Documents"]}),e.jsx(ve,{className:"text-xs sm:text-sm mt-1",children:o?"Documents for this Form 16A submission":"Documents attached while creating the request"})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsxs(E,{size:"sm",onClick:n,disabled:a||t.status==="closed",className:"gap-1 sm:gap-2 h-8 sm:h-9 text-xs sm:text-sm shrink-0","data-testid":"upload-document-btn",children:[e.jsx(js,{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(ee,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((x,u)=>e.jsx(Pr,{document:x,onPreview:g=>i(g),onDownload:l,testId:"request-document"},u))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),!o&&e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(zs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(ve,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(ee,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((x,u)=>e.jsx(Pr,{document:{documentId:x.attachmentId||"",name:x.name,fileType:x.type||"",size:x.size?`${(x.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:x.size,uploadedBy:x.uploadedBy,uploadedAt:x.uploadedAt},onPreview:g=>i(g),onDownload:async g=>{const{downloadWorkNoteAttachment:f}=require("@/services/workflowApi");await f(g)},testId:"worknote-attachment"},x.attachmentId||u))}):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 TT=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"}}},vx=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending",icon:st,iconColor:"text-yellow-600"};case"paused":return{color:"bg-gray-400 text-gray-100 border-gray-500",label:"paused",icon:ts,iconColor:"text-gray-600"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review",icon:$t,iconColor:"text-blue-600"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Le,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected",icon:St,iconColor:"text-red-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-300",label:"closed",icon:Le,iconColor:"text-gray-600"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped",icon:Ot,iconColor:"text-orange-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:ts,iconColor:"text-gray-600"}}},kT=t=>{switch(t){case"approval":case"approved":return e.jsx(Le,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(St,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(zs,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx($t,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(Xi,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Ie,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(st,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(Gi,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(ts,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(Ot,{className:"w-5 h-5 text-gray-600"})}};function RT(t){const s=t==null?void 0:t.form16Submission;if(!s)return[];const a=[],r=Array.isArray(s.previousSubmissions)?s.previousSubmissions:[];for(const u of r){const g=u.requestNumber||u.requestId||"",f=u.submittedDate?new Date(u.submittedDate).toISOString():new Date().toISOString();if(a.push({type:"document_added",action:`Previous submission (${g})`,details:"Form 16A certificate was submitted for this FY and quarter.",timestamp:f}),u.creditNoteNumber){const b=u.creditNoteIssueDate?new Date(u.creditNoteIssueDate).toISOString():f;a.push({type:"status_change",action:"Credit note issued",details:`Credit note ${u.creditNoteNumber} issued for previous submission (${g}).`,timestamp:b})}}const n=s.submittedDate||(t==null?void 0:t.submittedDate)||(t==null?void 0:t.createdAt),i=n?new Date(n).toISOString():new Date().toISOString(),l=(s.validationStatus||"").toLowerCase(),o=s.validationNotes||""||"",c=(s.displayStatus||"").toLowerCase(),d=!!(s.ocrExtractedData&&typeof s.ocrExtractedData=="object"&&Object.keys(s.ocrExtractedData).length>0),m=!!s.creditNoteNumber,p=c==="balance mismatch"||l==="failed"&&!m||l==="failed"&&/mismatch|26as|value/i.test(o),x=c==="duplicate"||l==="duplicate";if(a.push({type:"document_added",action:"Form 16A uploaded",details:"Form 16A certificate was uploaded and received.",timestamp:i}),a.push({type:"created",action:"OCR extraction",details:d?"Certificate data was extracted from the uploaded PDF.":"OCR extraction was performed on the uploaded document.",timestamp:i}),p?a.push({type:"rejection",action:"26AS matching",details:"Values of Form 16 did not match with 26AS. Please submit Form 16 with correct data.",timestamp:i}):x?a.push({type:"rejection",action:"26AS matching",details:"Duplicate. A submission for this FY and quarter already exists; credit note was issued for the earlier submission.",timestamp:i}):a.push({type:"status_change",action:"26AS matching",details:l==="success"||m?"26AS matching completed.":"26AS matching was performed.",timestamp:i}),m){const u=s.creditNoteIssueDate?new Date(s.creditNoteIssueDate).toISOString():i;a.push({type:"status_change",action:"Credit note issued",details:`Credit note ${s.creditNoteNumber} issued for this submission.`,timestamp:u})}return a.sort((u,g)=>new Date(u.timestamp).getTime()-new Date(g.timestamp).getTime())}function DT({request:t}){const s=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",a=s?RT(t):[],r=t.auditTrail&&Array.isArray(t.auditTrail)?t.auditTrail:[],n=a.length>0?[...a,...r].sort((i,l)=>{const o=i.timestamp?new Date(i.timestamp).getTime():0,c=l.timestamp?new Date(l.timestamp).getTime():0;return o-c}):r;return e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ot,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(ve,{className:"text-xs sm:text-sm",children:s?"Form 16 submission steps and audit trail":"Complete audit trail of all request activities"})]}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-4 sm:space-y-6",children:n.length>0?n.map((i,l)=>e.jsxs("div",{className:"flex items-start gap-4","data-testid":`activity-item-${l}`,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${i.type==="rejection"?"bg-red-50":"bg-gray-100"}`,children:kT(i.type)})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:`rounded-lg border p-4 shadow-sm ${i.type==="rejection"?"bg-red-50/50 border-red-200":"bg-white border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:`font-semibold ${i.type==="rejection"?"text-red-900":"text-gray-900"}`,children:i.action}),e.jsx("span",{className:"text-xs text-gray-500 whitespace-nowrap ml-4",children:gs(i.timestamp)})]}),e.jsx("div",{className:`text-sm leading-relaxed ${i.type==="rejection"?"text-red-800":"text-gray-600"}`,children:e.jsx("p",{className:"whitespace-pre-line break-words",children:i.details})})]})})]},l)):e.jsxs("div",{className:"text-center py-12","data-testid":"no-activity",children:[e.jsx(Ot,{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 e0({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(xt,{className:"sm:max-w-md",children:[e.jsx(yt,{children:e.jsxs(ht,{className:"flex items-center gap-2",children:[a?e.jsx(Le,{className:"w-5 h-5 text-green-600"}):e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),r||(a?"Success":"Error")]})}),e.jsx("div",{className:"py-6",children:e.jsx("div",{className:"flex flex-col items-center text-center",children:a?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-4",children:e.jsx(Le,{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(St,{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(Et,{children:e.jsx(E,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function t0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=h.useState(""),[l,o]=h.useState(!1),[c,d]=h.useState([]),[m,p]=h.useState(!1),[x,u]=h.useState(null),g=h.useRef(null),f=h.useRef(null),[b,j]=h.useState({open:!1,type:"error",email:"",message:""}),[y,w]=h.useState({open:!1,violations:[]}),[N,S]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});h.useEffect(()=>{t&&(async()=>{var P;try{const C=await la("WORKFLOW_SHARING"),V=await la("TAT_SETTINGS"),F=[...C,...V],$={};F.forEach(I=>{$[I.configKey]=I.configValue}),S({maxApprovalLevels:parseInt($.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt($.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((P=$.ALLOW_ADD_SPECTATOR)==null?void 0:P.toLowerCase())==="true",maxSpectators:parseInt($.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(C){console.error("Failed to load system policy:",C)}})()},[t]);const A=async()=>{var T,k;const v=n.trim().toLowerCase();if(!v){j({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)){j({open:!0,type:"error",email:v,message:"Please enter a valid email address"});return}const C=r.find(z=>(z.email||"").toLowerCase()===v);if(C){const z=((T=C.participantType)==null?void 0:T.toUpperCase())||"PARTICIPANT",L=C.name||v;if(z==="INITIATOR"){j({open:!0,type:"error",email:v,message:`${L} is the request initiator and cannot be added as a spectator.`});return}else if(z==="APPROVER"){j({open:!0,type:"error",email:v,message:`${L} is already an approver on this request and cannot be added as a spectator.`});return}else if(z==="SPECTATOR"){j({open:!0,type:"error",email:v,message:`${L} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:v,message:`${L} is already a participant on this request.`});return}}const V=[];N.allowSpectators||V.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const $=r.filter(z=>(z.participantType||"").toUpperCase()==="SPECTATOR").length;$>=N.maxSpectators&&V.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:$,maxValue:N.maxSpectators});const I=r.length+1;if(I>N.maxParticipants&&V.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:I,maxValue:N.maxParticipants}),V.length>0){w({open:!0,violations:V});return}if(!x||x.email.toLowerCase()!==v)try{const L=((k=(await ja(v,1)).data)==null?void 0:k.data)||[];if(L.length===0){j({open:!0,type:"not-found",email:v,message:""});return}const M=L[0];await fa({userId:M.userId,email:M.email,displayName:M.displayName,firstName:M.firstName,lastName:M.lastName,department:M.department,phone:M.phone,mobilePhone:M.mobilePhone,designation:M.designation,jobTitle:M.jobTitle,manager:M.manager,employeeId:M.employeeId,employeeNumber:M.employeeNumber,secondEmail:M.secondEmail,location:M.location})}catch(z){console.error("Failed to validate spectator:",z),j({open:!0,type:"error",email:v,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(v),i(""),u(null),s()}catch(z){console.error("Failed to add spectator:",z)}finally{o(!1)}},_=()=>{l||(i(""),u(null),d([]),p(!1),s())};h.useEffect(()=>{c.length>0&&f.current&&f.current.scrollTo({top:f.current.scrollHeight,behavior:"smooth"})},[c.length]),h.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const D=v=>{if(i(v),x&&x.email.toLowerCase()!==v.toLowerCase()&&u(null),g.current&&clearTimeout(g.current),!v||!v.startsWith("@")||v.length<2){d([]),p(!1);return}p(!0),g.current=setTimeout(async()=>{var P;try{const C=v.slice(1),F=((P=(await ja(C,10)).data)==null?void 0:P.data)||[];d(F)}catch(C){console.error("Search failed:",C),d([])}finally{p(!1)}},300)},R=async v=>{try{await fa({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}),i(v.email),u(v),d([]),p(!1)}catch(P){console.error("Failed to ensure user exists:",P),j({open:!0,type:"error",email:v.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(jt,{open:t,onOpenChange:_,children:[e.jsxs(xt,{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(bt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(yt,{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(Ct,{className:"w-5 h-5 text-purple-600"})}),e.jsx(ht,{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(Ji,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(ke,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:v=>D(v.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(v=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>R(v),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ls,{className:"h-8 w-8",children:e.jsx(os,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(v.displayName||v.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:v.displayName||[v.firstName,v.lastName].filter(Boolean).join(" ")||v.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:v.email}),v.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:v.designation})]})]})},v.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:_,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:A,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(jt,{open:b.open,onOpenChange:v=>j(P=>({...P,open:v})),children:e.jsxs(xt,{className:"sm:max-w-md",children:[e.jsxs(yt,{children:[e.jsx(ht,{className:"flex items-center gap-2",children:b.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Ut,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[b.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:b.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Qi,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),b.type==="error"&&e.jsxs(e.Fragment,{children:[b.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:b.email}),"."]}),b.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:b.message})})]})]})})]}),e.jsx(Et,{children:e.jsx(E,{onClick:()=>j(v=>({...v,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(si,{open:y.open,onClose:()=>w({open:!1,violations:[]}),violations:y.violations,policyDetails:{maxApprovalLevels:N.maxApprovalLevels,maxParticipants:N.maxParticipants,allowSpectators:N.allowSpectators,maxSpectators:N.maxSpectators}})]})}function s0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=h.useState(""),[d,m]=h.useState(24),[p,x]=h.useState(null),[u,g]=h.useState(!1),[f,b]=h.useState([]),[j,y]=h.useState(!1),[w,N]=h.useState(null),S=h.useRef(null),A=h.useRef(null),[_,D]=h.useState({open:!1,type:"error",email:"",message:""}),R=n.filter(k=>k&&(k.status==="approved"||k.status==="rejected"||k.status==="skipped")),v=Math.max(1,R.length+1),P=Math.max(1,n.length+1),C=P>=v?Array.from({length:P-v+1},(k,z)=>v+z):[v];h.useEffect(()=>{C.length>0&&p===null&&x(C[0]||null)},[C.length,p]);const V=async()=>{var B,W;const k=o.trim().toLowerCase();if(!k){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(k)){D({open:!0,type:"error",email:k,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(!p){D({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(p<v){D({open:!0,type:"error",email:"",message:`Cannot add approver at level ${p}. Minimum allowed level is ${v} (after completed levels)`});return}const L=n.length>0?Math.max(...n.map(J=>J.levelNumber),0):0,M=p>L?p:L+1;if(i&&M>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${p} would result in ${M} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:M,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${L} level(s).`});return}const U=r.find(J=>(J.email||"").toLowerCase()===k);if(U){const J=((B=U.participantType)==null?void 0:B.toUpperCase())||"PARTICIPANT",O=U.name||k;if(J==="INITIATOR"){D({open:!0,type:"error",email:k,message:`${O} is the request initiator and cannot be added as an approver.`});return}else if(J==="APPROVER"){D({open:!0,type:"error",email:k,message:`${O} is already an approver on this request.`});return}else if(J==="SPECTATOR"){D({open:!0,type:"error",email:k,message:`${O} 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:k,message:`${O} is already a participant on this request.`});return}}if(!w||w.email.toLowerCase()!==k)try{const O=((W=(await ja(k,1)).data)==null?void 0:W.data)||[];if(O.length===0){D({open:!0,type:"not-found",email:k,message:""});return}const H=O[0];await fa({userId:H.userId,email:H.email,displayName:H.displayName,firstName:H.firstName,lastName:H.lastName,department:H.department,phone:H.phone,mobilePhone:H.mobilePhone,designation:H.designation,jobTitle:H.jobTitle,manager:H.manager,employeeId:H.employeeId,employeeNumber:H.employeeNumber,secondEmail:H.secondEmail,location:H.location})}catch(J){console.error("Failed to validate approver:",J),D({open:!0,type:"error",email:k,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(k,d,p),c(""),m(24),x(null),N(null),s()}catch(J){console.error("Failed to add approver:",J)}finally{g(!1)}},F=()=>{u||(c(""),m(24),x(null),N(null),b([]),y(!1),s())},$=k=>{const z=k.toLowerCase();return z==="approved"?e.jsx(Le,{className:"w-4 h-4 text-green-600"}):z==="rejected"?e.jsx(St,{className:"w-4 h-4 text-red-600"}):z==="skipped"?e.jsx(Ze,{className:"w-4 h-4 text-orange-600"}):z==="in-review"||z==="pending"?e.jsx(st,{className:"w-4 h-4 text-blue-600"}):e.jsx(st,{className:"w-4 h-4 text-gray-400"})};h.useEffect(()=>{f.length>0&&A.current&&A.current.scrollTo({top:A.current.scrollHeight,behavior:"smooth"})},[f.length]),h.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const I=k=>{if(c(k),w&&w.email.toLowerCase()!==k.toLowerCase()&&N(null),S.current&&clearTimeout(S.current),!k||!k.startsWith("@")||k.length<2){b([]),y(!1);return}y(!0),S.current=setTimeout(async()=>{var z;try{const L=k.slice(1),U=((z=(await ja(L,10)).data)==null?void 0:z.data)||[];b(U)}catch(L){console.error("Search failed:",L),b([])}finally{y(!1)}},300)},T=async k=>{try{await fa({userId:k.userId,email:k.email,displayName:k.displayName,firstName:k.firstName,lastName:k.lastName,department:k.department,phone:k.phone,mobilePhone:k.mobilePhone,designation:k.designation,jobTitle:k.jobTitle,manager:k.manager,employeeId:k.employeeId,employeeNumber:k.employeeNumber,secondEmail:k.secondEmail,location:k.location}),c(k.email),N(k),b([]),y(!1)}catch(z){console.error("Failed to ensure user exists:",z),D({open:!0,type:"error",email:k.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(jt,{open:t,onOpenChange:F,children:[e.jsxs(xt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:F,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:u,children:[e.jsx(bt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(yt,{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(Zt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(ht,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:A,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(k=>k.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(k=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${k.status==="approved"?"bg-green-100 border border-green-200":k.status==="rejected"?"bg-red-100 border border-red-200":k.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:k.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:k.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[k.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$(k.status),e.jsx(se,{variant:"outline",className:`text-xs ${k.status==="approved"?"bg-green-50 text-green-700 border-green-300":k.status==="rejected"?"bg-red-50 text-red-700 border-red-300":k.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:k.status})]})]},k.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:["ℹ️ New approver can only be added at level ",v," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(Be,{value:(p==null?void 0:p.toString())||"",onValueChange:k=>x(Number(k)),disabled:u,children:[e.jsx(ze,{className:"h-11 border-gray-300",children:e.jsx(Ve,{placeholder:"Select level"})}),e.jsx(He,{children:C.map(k=>e.jsx(Q,{value:k.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",k]}),k<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",k,")"]})]})},k))})]}),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(te,{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(ke,{type:"number",min:"1",max:"720",value:d,onChange:k=>m(Number(k.target.value)),className:"h-11 border-gray-300 flex-1",disabled:u,placeholder:"24"}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-600 bg-gray-100 px-3 h-11 rounded-md border border-gray-300",children:[e.jsx(st,{className:"w-4 h-4"}),"hours"]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum time for this approver to respond (1-720 hours)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ji,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(ke,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:k=>I(k.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(j||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:j?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(k=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>T(k),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ls,{className:"h-8 w-8",children:e.jsx(os,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(k.displayName||k.email).split(" ").map(z=>z[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:k.displayName||[k.firstName,k.lastName].filter(Boolean).join(" ")||k.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:k.email}),k.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:k.designation})]})]})},k.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:V,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!o.trim()||!p||!d,children:[e.jsx(Zt,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${p||"?"}`]})]})]}),e.jsx(jt,{open:_.open,onOpenChange:k=>D(z=>({...z,open:k})),children:e.jsxs(xt,{className:"sm:max-w-md",children:[e.jsxs(yt,{children:[e.jsx(ht,{className:"flex items-center gap-2",children:_.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Ut,{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(Qi,{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(Et,{children:e.jsx(E,{onClick:()=>D(k=>({...k,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const FT=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"}},IT=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},PT=t=>{const s=t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(a,r,n,i)=>{const l=n+a.length,o=i[l];return!o||/\s|[.,!?;:]|@/.test(o)?'<span class="inline-flex items-center px-2.5 py-0.5 rounded-md bg-blue-50 text-blue-800 font-black text-base border-2 border-blue-400 shadow-sm">@'+r+"</span>":a}).replace(/\n/g,"<br />");return Ra(s)},ET=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Nx=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Ie,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(dh,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Ie,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Ie,{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(pi,{className:`${s} text-purple-600`}):e.jsx(Gi,{className:`${s} text-gray-600`})};function a0({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:p}){const x=_a(),u=t||x.requestId||"",[g,f]=h.useState(""),[b,j]=h.useState(""),[y,w]=h.useState(!1),[N,S]=h.useState([]),[A,_]=h.useState(!1),[D,R]=h.useState([]),[v,P]=h.useState(null),[C,V]=h.useState(null),[F,$]=h.useState(!1),[I,T]=h.useState(!1),[k,z]=h.useState(!1),[L,M]=h.useState({success:!0,title:"",message:""}),U=h.useRef(null),B=h.useRef(null),W=h.useRef(null),J=h.useRef(!1),[O,H]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[Y,re]=h.useState({open:!1,errors:[]}),K=h.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[ae,Ne]=h.useState([]),Se=ae.filter(le=>le.status==="online"),Ge=N.filter(le=>le.content.toLowerCase().includes(b.toLowerCase())||le.user.name.toLowerCase().includes(b.toLowerCase())),Je=h.useMemo(()=>o!==void 0?o:!v||ae.length===0?!1:ae.some(le=>{const De=le.userId||le.user_id,ce=(le.role||"").toString().toUpperCase(),Ke=(le.participantType||le.participant_type||"").toString().toUpperCase();return De===v&&(ce==="SPECTATOR"||Ke==="SPECTATOR")}),[o,v,ae]);h.useEffect(()=>{},[ae]),h.useEffect(()=>{!u||!v||s||(async()=>{try{const le=await Zr(u),De=Array.isArray(le)?le.map(ce=>{const Ke=ce.userId||ce.user_id;return{id:ce.noteId||ce.id||String(Math.random()),user:{name:ce.userName||"User",avatar:(ce.userName||"U").slice(0,2).toUpperCase(),role:ce.userRole||"Participant"},content:ce.message||"",timestamp:ce.createdAt||new Date().toISOString(),isCurrentUser:Ke===v,attachments:Array.isArray(ce.attachments)?ce.attachments.map(We=>({attachmentId:We.attachmentId||We.attachment_id,name:We.fileName||We.file_name||We.name,fileName:We.fileName||We.file_name||We.name,url:We.storageUrl||We.storage_url||We.url||"#",type:We.fileType||We.file_type||We.type||"file",fileType:We.fileType||We.file_type||We.type||"file",fileSize:We.fileSize||We.file_size})):void 0}}):[];S(De)}catch(le){console.error("[WorkNoteChat] Failed to load messages:",le)}})()},[u,v,s]);const Pe=h.useMemo(()=>{const le=[];return N.forEach(De=>{De.attachments&&De.attachments.length>0&&De.attachments.forEach(ce=>{le.push({attachmentId:ce.attachmentId||ce.attachment_id,name:ce.fileName||ce.file_name||ce.name||"Untitled",fileName:ce.fileName||ce.file_name||ce.name||"Untitled",size:ce.fileSize||ce.file_size,type:ce.fileType||ce.file_type||ce.type||"file",uploadedBy:De.user.name,uploadedAt:De.timestamp,url:ce.storageUrl||ce.storage_url||ce.url||"#"})})}),le},[N]);h.useEffect(()=>{i&&Pe.length>=0&&i(Pe)},[Pe,i]);const Oe=h.useMemo(()=>ae.map(le=>({email:(le.email||"").toLowerCase(),participantType:le.role==="Initiator"?"INITIATOR":le.role==="Approver"?"APPROVER":le.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:le.name})),[ae]),ie=le=>{if(!le)return"Participant";switch(le.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return le.charAt(0).toUpperCase()+le.slice(1).toLowerCase()}},pe=()=>{var le;(le=U.current)==null||le.scrollIntoView({behavior:"smooth"})};h.useEffect(()=>{pe()},[N]);const we=le=>{switch(le.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return le.charAt(0).toUpperCase()+le.slice(1).toLowerCase()}};h.useEffect(()=>{J.current||u&&(async()=>{try{const le=await Ps(u),De=Array.isArray(le==null?void 0:le.participants)?le.participants:[];if(De.length===0)return;const ce=De.map(Qe=>{const rt=Qe.participantType||Qe.participant_type||"participant",qe=Qe.userId||Qe.user_id||"";return{name:Qe.userName||Qe.user_name||Qe.user_email||Qe.userEmail||"User",avatar:(Qe.userName||Qe.user_name||Qe.user_email||"U").toString().split(" ").map(ot=>ot[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:we(rt.toString()),status:"offline",email:Qe.userEmail||Qe.user_email||"",permissions:["read","write","mention"],userId:qe}});J.current=!0,Ne(ce);let Ke=0;const We=3,tt=()=>{W.current&&W.current.connected?(W.current.emit("request:online-users",{requestId:u}),Ke++,Ke<We&&setTimeout(tt,500)):(Ke++,Ke<We&&setTimeout(tt,200))};setTimeout(tt,100)}catch(le){console.error("[WorkNoteChat] ❌ Failed to load participants:",le)}})()},[u]),h.useEffect(()=>()=>{u&&(J.current=!1)},[u]),h.useEffect(()=>{const le=localStorage.getItem("userData");if(le)try{const De=JSON.parse(le),ce=(De==null?void 0:De.id)||(De==null?void 0:De.userId)||(De==null?void 0:De.user_id)||null;P(ce)}catch(De){console.error("[WorkNoteChat] Failed to parse userData:",De)}},[]),h.useEffect(()=>{(async()=>{try{const De=await la("DOCUMENT_POLICY"),ce={};De.forEach(Qe=>{ce[Qe.configKey]=Qe.configValue});const Ke=parseInt(ce.MAX_FILE_SIZE_MB||"10"),tt=(ce.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Qe=>Qe.trim().toLowerCase());H({maxFileSizeMB:Ke,allowedFileTypes:tt})}catch(De){console.error("Failed to load document policy:",De)}})()},[]),h.useEffect(()=>{if(!v)return;let le=u;return(async()=>{var De;try{const ce=await Ps(u);(De=ce==null?void 0:ce.workflow)!=null&&De.requestId&&(le=ce.workflow.requestId)}catch{}try{const ce=en();r?Ne(pt=>pt.map(Ft=>Ft.userId===v?{...Ft,status:"online"}:Ft)):(mo(ce,le,v),Ne(pt=>pt.map(Ft=>Ft.userId===v?{...Ft,status:"online"}:Ft)));const Ke=pt=>{const ct=(pt==null?void 0:pt.note)||pt;if(!ct)return;const Ft=ct.noteId||ct.id;S(Ss=>{if(Ss.some(It=>It.id===Ft))return Ss;const ss=ct.userName||ct.user_name||"User",Ma=ct.userRole||ct.user_role,La=ie(Ma),Aa=ct.userId||ct.user_id,Ya={id:Ft||String(Date.now()),user:{name:ss,avatar:ss.split(" ").map(It=>It[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:La},content:ct.message||"",timestamp:ct.createdAt||new Date().toISOString(),isCurrentUser:Aa===v,attachments:Array.isArray(ct.attachments)?ct.attachments.map(It=>({attachmentId:It.attachmentId||It.attachment_id,name:It.fileName||It.file_name||It.name,fileName:It.fileName||It.file_name||It.name,url:It.storageUrl||It.storage_url||It.url||"#",type:It.fileType||It.file_type||It.type||"file",fileType:It.fileType||It.file_type||It.type||"file",fileSize:It.fileSize||It.file_size})):void 0};return[...Ss,Ya]})},We=pt=>{Ne(ct=>ct.length===0||!ct.find(ss=>ss.userId===pt.userId)?ct:ct.map(ss=>ss.userId===pt.userId?{...ss,status:"online"}:ss))},tt=pt=>{pt.userId!==v&&Ne(ct=>ct.length===0||!ct.find(ss=>ss.userId===pt.userId)?ct:ct.map(ss=>ss.userId===pt.userId?{...ss,status:"offline"}:ss))},Qe=pt=>{Ne(ct=>ct.length===0?ct:ct.map(Ss=>{const ss=Ss.userId||"";if(ss===v)return{...Ss,status:"online"};const La=pt.userIds.includes(ss);return{...Ss,status:La?"online":"offline"}}))},rt=()=>{Ne(pt=>pt.map(Ft=>Ft.userId===v?{...Ft,status:"online"}:Ft)),r||mo(ce,le,v),J.current&&(ce.emit("request:online-users",{requestId:le}),setTimeout(()=>ce.emit("request:online-users",{requestId:le}),300),setTimeout(()=>ce.emit("request:online-users",{requestId:le}),800))},qe=pt=>{console.error("[WorkNoteChat] ❌ Socket error:",pt)},ot=pt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",pt),Ne(ct=>ct.map(Ft=>Ft.userId===v?Ft:{...Ft,status:"offline"}))},$s=pt=>{pt.includes("presence")||pt.includes("worknote")||pt.includes("request")};ce.on("connect",rt),ce.on("disconnect",ot),ce.on("error",qe),ce.on("worknote:new",Ke),ce.on("presence:join",We),ce.on("presence:leave",tt),ce.on("presence:online",Qe),ce.onAny($s),W.current=ce,ce.connected&&J.current&&(ce.emit("request:online-users",{requestId:le}),setTimeout(()=>{ce.emit("request:online-users",{requestId:le})},300),setTimeout(()=>{ce.emit("request:online-users",{requestId:le})},800),setTimeout(()=>{ce.emit("request:online-users",{requestId:le})},1500));const ns=()=>{ce.off("connect",rt),ce.off("disconnect",ot),ce.off("error",qe),ce.off("worknote:new",Ke),ce.off("presence:join",We),ce.off("presence:leave",tt),ce.off("presence:online",Qe),ce.offAny($s),r||Hh(ce,le),W.current=null};window.__wn_cleanup=ns}catch{}})(),()=>{var De;try{(De=window.__wn_cleanup)==null||De.call(window)}catch{}}},[u,v,r]);const Ae=async()=>{if(g.trim()||D.length>0){const le=mt(g),De=le.map(We=>{const tt=ae.find(Qe=>Qe.name.toLowerCase().includes(We.toLowerCase()));return tt==null?void 0:tt.userId}).filter(Boolean),ce=D.map(We=>({name:We.name,url:URL.createObjectURL(We),type:We.type.split("/")[1]||"file"})),Ke={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:le,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:ce.length>0?ce:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await np(u,{message:g,mentions:De},D);const We=await Zr(u),tt=Array.isArray(We)?We.map(Qe=>{const rt=Qe.userId||Qe.user_id;return{id:Qe.noteId||Qe.id||String(Math.random()),user:{name:Qe.userName||"User",avatar:(Qe.userName||"U").slice(0,2).toUpperCase(),role:Qe.userRole||"Participant"},content:Qe.message||"",timestamp:Qe.createdAt||new Date().toISOString(),isCurrentUser:rt===v,attachments:Array.isArray(Qe.attachments)?Qe.attachments.map(qe=>({attachmentId:qe.attachmentId||qe.attachment_id,name:qe.fileName||qe.file_name||qe.name,fileName:qe.fileName||qe.file_name||qe.name,url:qe.storageUrl||qe.storage_url||qe.url||"#",type:qe.fileType||qe.file_type||qe.type||"file",fileType:qe.fileType||qe.file_type||qe.type||"file",fileSize:qe.fileSize||qe.file_size})):void 0}}):[];S(tt)}catch{S(We=>[...We,Ke])}f(""),R([])}};h.useEffect(()=>{if(s&&Array.isArray(s))try{const De=s.filter(ce=>(ce.type||"").toLowerCase()!=="sla_warning").map(ce=>{var We;if(ce.type||ce.activityType||ce.isSystem)return{id:ce.id||`activity-${ce.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:ce.details||ce.action||ce.content||"",timestamp:ce.timestamp||ce.createdAt||ce.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const tt=ce.userName||ce.user_name||((We=ce.user)==null?void 0:We.name)||"User",Qe=ce.userRole||ce.user_role,rt=ie(Qe),qe=ce.userId||ce.user_id;return{id:ce.noteId||ce.note_id||ce.id||String(Math.random()),user:{name:tt,avatar:tt.split(" ").map(ot=>ot[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:rt},content:ce.message||ce.content||"",timestamp:ce.createdAt||ce.created_at||ce.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(ce.attachments)?ce.attachments.map(ot=>({attachmentId:ot.attachmentId||ot.attachment_id,name:ot.fileName||ot.file_name||ot.name,fileName:ot.fileName||ot.file_name||ot.name,url:ot.storageUrl||ot.storage_url||ot.url||"#",type:ot.fileType||ot.file_type||ot.type||"file",fileType:ot.fileType||ot.file_type||ot.type||"file",fileSize:ot.fileSize||ot.file_size})):void 0,isCurrentUser:qe===v}}}).sort((ce,Ke)=>new Date(ce.timestamp).getTime()-new Date(Ke.timestamp).getTime());S(De)}catch(le){console.error("[WorkNoteChat] Error mapping messages:",le)}else(async()=>{try{const le=await Zr(u),De=Array.isArray(le)?le.map(ce=>{const Ke=ce.userName||ce.user_name||"User",We=ce.userRole||ce.user_role,tt=ie(We),Qe=ce.userId||ce.user_id;return{id:ce.noteId||ce.note_id||ce.id||String(Math.random()),user:{name:Ke,avatar:Ke.split(" ").map(rt=>rt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:tt},content:ce.message||"",timestamp:ce.createdAt||ce.created_at||new Date().toISOString(),attachments:Array.isArray(ce.attachments)?ce.attachments.map(rt=>({attachmentId:rt.attachmentId||rt.attachment_id,name:rt.fileName||rt.file_name||rt.name,fileName:rt.fileName||rt.file_name||rt.name,url:rt.storageUrl||rt.storage_url||rt.url||"#",type:rt.fileType||rt.file_type||rt.type||"file",fileType:rt.fileType||rt.file_type||rt.type||"file",fileSize:rt.fileSize||rt.file_size})):void 0,isCurrentUser:Qe===v}}):[];S(De)}catch(le){console.error("[WorkNoteChat] Error loading work notes:",le)}})()},[s,u,ae]);const ne=le=>{const De=O.maxFileSizeMB*1024*1024;if(le.size>De)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${O.maxFileSizeMB}MB. Current size: ${(le.size/(1024*1024)).toFixed(2)}MB`};const ce=le.name.toLowerCase(),Ke=ce.substring(ce.lastIndexOf(".")+1);return O.allowedFileTypes.includes(Ke)?{valid:!0}:{valid:!1,reason:`File type "${Ke}" is not allowed. Allowed types: ${O.allowedFileTypes.join(", ")}`}},q=le=>{if(!le.target.files||le.target.files.length===0)return;const De=Array.from(le.target.files),ce=[],Ke=[];De.forEach(We=>{const tt=ne(We);tt.valid?Ke.push(We):ce.push({fileName:We.name,reason:tt.reason||"Unknown validation error"})}),ce.length>0&&re({open:!0,errors:ce}),Ke.length>0&&(R(We=>[...We,...Ke]),Ke.length<De.length?X.warning(`${Ke.length} of ${De.length} file(s) were added. ${ce.length} file(s) were rejected.`):X.success(`${Ke.length} file(s) added successfully`)),le.target&&(le.target.value="")},de=le=>{R(De=>De.filter((ce,Ke)=>Ke!==le)),B.current&&(B.current.value="")},Ye=le=>{f(De=>De+le),w(!1)},fe=()=>{var le;(le=B.current)==null||le.click()},ye=async le=>{var De,ce;try{await lp(u,le);const Ke=await Ps(u),We=Array.isArray(Ke==null?void 0:Ke.participants)?Ke.participants:[];if(We.length){const tt=We.map(Qe=>{const rt=Qe.participantType||Qe.participant_type||"participant",qe=Qe.userId||Qe.user_id||"",ot=Qe.userName||Qe.user_name||Qe.userEmail||Qe.user_email||"User",$s=Qe.userEmail||Qe.user_email||"",ns=ot.split(" ").map(pt=>pt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ot,avatar:ns,role:we(rt),status:"offline",email:$s,lastSeen:void 0,permissions:["read"],userId:qe}});Ne(tt),W.current&&W.current.connected&&W.current.emit("request:online-users",{requestId:u})}$(!1),M({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),z(!0)}catch(Ke){throw console.error("Failed to add spectator:",Ke),M({success:!1,title:"Failed to Add Spectator",message:((ce=(De=Ke==null?void 0:Ke.response)==null?void 0:De.data)==null?void 0:ce.error)||"Failed to add spectator. Please try again."}),z(!0),Ke}},Ue=async(le,De,ce)=>{var Ke,We;if(d)await d(le,De,ce),T(!1);else try{await ip(u,le,De,ce);const tt=await Ps(u),Qe=Array.isArray(tt==null?void 0:tt.participants)?tt.participants:[];if(Qe.length){const rt=Qe.map(qe=>{const ot=qe.participantType||qe.participant_type||"participant",$s=qe.userId||qe.user_id||"",ns=qe.userName||qe.user_name||qe.userEmail||qe.user_email||"User",pt=qe.userEmail||qe.user_email||"",ct=ns.split(" ").map(Ft=>Ft[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ns,avatar:ct,role:we(ot),status:"offline",email:pt,lastSeen:void 0,permissions:["read"],userId:$s}});Ne(rt),W.current&&W.current.connected&&W.current.emit("request:online-users",{requestId:u})}T(!1),M({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${ce} with ${De}h TAT`}),z(!0)}catch(tt){throw console.error("Failed to add approver:",tt),M({success:!1,title:"Failed to Add Approver",message:((We=(Ke=tt==null?void 0:tt.response)==null?void 0:Ke.data)==null?void 0:We.error)||"Failed to add approver. Please try again."}),z(!0),tt}},nt=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],mt=le=>{const De=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,ce=[];let Ke;for(;(Ke=De.exec(le))!==null;)if(Ke[1]){const We=Ke.index+Ke[0].length,tt=le.slice(We),Qe=le[We];(tt.startsWith("@")||!Qe||/\s|[.,!?;:]|@/.test(Qe))&&ce.push(Ke[1].trim())}return ce},vt=le=>{le.key==="Enter"&&!le.shiftKey&&(le.preventDefault(),Ae())},xs=(le,De)=>{S(ce=>ce.map(Ke=>{if(Ke.id===le){const We=Ke.reactions||[],tt=We.find(Qe=>Qe.emoji===De);if(tt)if(tt.users.includes("You")){if(tt.users=tt.users.filter(Qe=>Qe!=="You"),tt.users.length===0)return{...Ke,reactions:We.filter(Qe=>Qe.emoji!==De)}}else tt.users.push("You");else We.push({emoji:De,users:["You"]});return{...Ke,reactions:We}}return Ke}))};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(zs,{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:K.title}),e.jsx(se,{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:[Se.slice(0,3).map((le,De)=>e.jsx(ls,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(os,{className:"bg-blue-500 text-white text-xs font-semibold",children:le.avatar})},De)),Se.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:["+",Se.length-3]})]})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>_(!A),className:"lg:hidden",children:e.jsx(Zt,{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(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(ke,{placeholder:"Search messages...",value:b,onChange:le=>j(le.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:[Ge.map(le=>{const De=le.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${le.isSystem?"justify-center":De?"justify-end":""}`,children:[!le.isSystem&&!De&&e.jsx(ls,{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(os,{className:`text-white font-semibold text-xs sm:text-sm ${le.user.role==="Initiator"?"bg-green-600":le.user.role==="Current User"?"bg-blue-500":le.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:le.user.avatar})}),e.jsx("div",{className:`${De?"max-w-[70%]":"flex-1"} min-w-0 ${le.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:le.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(Ot,{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:le.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:gs(le.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${De?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[le.user.name," ",De&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(se,{variant:"outline",className:"text-xs flex-shrink-0",children:le.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(st,{className:"w-3 h-3"}),gs(le.timestamp)]}),le.isHighPriority&&e.jsxs(se,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(wb,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${De?"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:PT(le.content)}}),le.attachments&&le.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:le.attachments.map((ce,Ke)=>{const We=ce.fileSize||ce.file_size,tt=ce.fileName||ce.file_name||ce.name,Qe=ce.fileType||ce.file_type||ce.type||"",rt=ce.attachmentId||ce.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(Nx,{type:Qe})}),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:tt}),We&&e.jsx("p",{className:"text-xs text-gray-500",children:ET(We)})]}),rt&&(()=>{const qe=(Qe||"").toLowerCase();return qe.includes("image")||qe.includes("pdf")||qe.includes("jpg")||qe.includes("jpeg")||qe.includes("png")||qe.includes("gif")})()&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-purple-100 hover:text-purple-600",onClick:qe=>{qe.preventDefault(),qe.stopPropagation();const ot=Rw(rt);V({fileName:tt,fileType:Qe,fileUrl:ot,fileSize:We,attachmentId:rt})},title:"Preview file",children:e.jsx(Ct,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-blue-100 hover:text-blue-600",onClick:async qe=>{if(qe.preventDefault(),qe.stopPropagation(),!rt){X.error("Cannot download: Attachment ID missing");return}try{await Ym(rt)}catch{X.error("Failed to download file")}},title:"Download file",children:e.jsx(kt,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Ke)})})}),le.reactions&&le.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:[le.reactions.map((ce,Ke)=>e.jsxs("button",{onClick:()=>xs(le.id,ce.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${ce.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:ce.emoji}),e.jsx("span",{className:"text-xs font-medium",children:ce.users.length})]},Ke)),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>w(!y),children:e.jsx(bs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!le.isSystem&&De&&e.jsx(ls,{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(os,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:le.user.avatar})})]},le.id)}),e.jsx("div",{ref:U})]})}),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:B,onChange:q,className:"hidden",multiple:!0,accept:O.allowedFileTypes.map(le=>`.${le}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((le,De)=>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(Nx,{type:le.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:le.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(le.size/1024).toFixed(1)," KB"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>de(De),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(bt,{className:"h-3 w-3 text-red-600"})})]},De))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const le=g.lastIndexOf("@"),De=le>=0;if(!De)return null;const ce=g.slice(le+1),Ke=ce.trim(),We=ce.endsWith(" "),tt=Ke.length>0,Qe=Ke.includes(" ")&&!We,rt=We&&tt;if(!(De&&ce.length<=20&&!Qe&&!rt))return null;const ot=Ke.toLowerCase(),$s=ae.filter(ns=>ns.userId===v?!1:ot?ns.name.toLowerCase().includes(ot):!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:$s.length>0?$s.map((ns,pt)=>e.jsxs("button",{type:"button",onClick:ct=>{ct.preventDefault(),ct.stopPropagation();const Ft=g.lastIndexOf("@"),Ss=g.slice(0,Ft);f(Ss+"@"+ns.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(ls,{className:"h-10 w-10",children:e.jsx(os,{className:`text-white text-sm font-semibold ${ns.role==="Initiator"?"bg-green-600":ns.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:ns.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:ns.name}),e.jsx("p",{className:"text-xs text-gray-600",children:ns.role})]})]},pt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:ot?`No participants found matching "${ot}"`:"No other participants available"})})]})})(),e.jsx(Os,{placeholder:"Type your message... Use @username to mention someone",value:g,onChange:le=>f(le.target.value),onKeyPress:vt,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}),y&&e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border border-gray-200 rounded-lg shadow-xl p-3 z-50 w-full sm:w-96 max-h-80 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 sticky top-0 bg-white pb-2 border-b",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-700",children:"Pick an emoji"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>w(!1),className:"h-6 w-6 p-0",children:e.jsx(bt,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:nt.map((le,De)=>e.jsx("button",{onClick:()=>Ye(le),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:le,children:le},De))})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-shrink-0",children:[e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:fe,title:"Attach file",children:e.jsx(Gi,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>w(!y),title:"Add emoji",children:e.jsx(Cb,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>f(le=>le+"@"),title:"Mention someone",children:e.jsx(Ji,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-gray-500 hidden md:inline whitespace-nowrap",children:[g.length,"/2000"]}),e.jsxs(E,{onClick:Ae,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(ch,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),A&&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
|
||
${A?"fixed right-0 top-0 bottom-0 z-50 shadow-xl":"hidden lg:flex"}
|
||
`,children:[e.jsxs("div",{className:"p-4 sm:p-6 border-b border-gray-200 flex-1 flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900",children:"Participants"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>_(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(bt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:ae.map((le,De)=>{const ce=le.userId===v;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ls,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(os,{className:`text-white font-semibold text-sm ${le.role==="Initiator"?"bg-green-600":ce?"bg-blue-500":"bg-slate-600"}`,children:le.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${FT(le.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:[le.name," ",ce&&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:le.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:IT(le.status)})]}),le.lastSeen&&le.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:le.lastSeen})]})]},De)})})]}),!Je&&e.jsxs("div",{className:"p-4 sm:p-6 flex-shrink-0",children:[e.jsx("h4",{className:"font-semibold text-gray-900 mb-3 text-sm sm:text-base",children:"Quick Actions"}),e.jsxs("div",{className:"space-y-2",children:[l&&e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>T(!0),children:[e.jsx(Xi,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>$(!0),children:[e.jsx(Ct,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),C&&e.jsx(Mr,{fileName:C.fileName,fileType:C.fileType,fileUrl:C.fileUrl,fileSize:C.fileSize,attachmentId:C.attachmentId,onDownload:Ym,open:!!C,onClose:()=>V(null)}),!Je&&e.jsx(t0,{open:F,onClose:()=>$(!1),onConfirm:ye,requestIdDisplay:u,requestTitle:K.title,existingParticipants:Oe}),!Je&&l&&e.jsx(s0,{open:I,onClose:()=>T(!1),onConfirm:Ue,requestIdDisplay:u,requestTitle:K.title,existingParticipants:Oe,currentLevels:c,maxApprovalLevels:m,onPolicyViolation:p}),e.jsx(jt,{open:Y.open,onOpenChange:le=>re(De=>({...De,open:le})),children:e.jsxs(xt,{className:"sm:max-w-lg",children:[e.jsxs(yt,{children:[e.jsxs(ht,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Ut,{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:Y.errors.map((le,De)=>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:le.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:le.reason})]},De))}),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: ",O.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",O.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Et,{children:e.jsx(E,{onClick:()=>re({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(e0,{open:k,onClose:()=>z(!1),success:L.success,title:L.title,message:L.message})]})}function _T({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(a0,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d})})}function MT({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const c=o.toLowerCase();return c==="approved"?e.jsx(Le,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(St,{className:"h-4 w-4 text-red-600"}):c==="pending"||c==="in progress"?e.jsx(st,{className:"h-4 w-4 text-orange-600"}):e.jsx(Ie,{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(Xe,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):t?e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:t.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",t.requestNumber]})]}),r&&a?e.jsxs(E,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(an,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(se,{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(Es,{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:et(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:et(new Date(o.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),o.remarks?e.jsx(Es,{content:o.remarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]},c))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),t.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(se,{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(Es,{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(Ie,{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 LT({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(rr,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(Le,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(St,{className:"h-4 w-4 text-red-600"}):e.jsx(st,{className:"h-4 w-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-medium text-gray-700",children:s==="closed"?"Request Closed":s==="approved"?"Request Approved":s==="rejected"?"Request Rejected":"SLA Not Available"})]});const i=t.percentageUsed!==void 0?t.percentageUsed:0,l=t.status||"on_track",c=a?{badge:"bg-gray-500 text-white",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-500"}:i>=100?{badge:"bg-red-600 text-white animate-pulse",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:i>=75?{badge:"bg-orange-500 text-white",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:i>=50?{badge:"bg-amber-500 text-white",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{badge:"bg-green-600 text-white",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"},d=l==="on_track"||l==="normal"?"normal":l;return e.jsxs("div",{"data-testid":r,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[a?e.jsx(rr,{className:`h-4 w-4 ${c.icon}`}):e.jsx(st,{className:`h-4 w-4 ${c.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(se,{className:`text-xs ${c.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(Zs,{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:[Kt(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${d==="breached"||d==="critical"?c.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[Kt(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",Ca(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(ts,{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(Fi,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function OT({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var g,f;const c=TT((t==null?void 0:t.priority)||"standard"),d=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",m=(g=t==null?void 0:t.form16Submission)==null?void 0:g.displayStatus,p=m&&/balance mismatch|failed/i.test(String(m)),x=m&&String(m).toLowerCase()==="duplicate",u=d&&m?{color:p?"bg-red-100 !text-red-800 border-red-200":m==="Completed"?"bg-green-100 !text-green-800 border-green-200":x?"bg-amber-100 !text-amber-800 border-amber-200":"bg-gray-100 !text-gray-700 border-gray-200",icon:vx((t==null?void 0:t.status)||"pending").icon,label:m}:vx((t==null?void 0:t.status)||"pending");return e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-300 mb-4 sm:mb-6","data-testid":"request-detail-header",children:[e.jsxs("div",{className:"p-3 sm:p-4 md:p-6 border-b border-gray-300",children:[e.jsxs("div",{className:"flex items-start sm:items-center justify-between gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:a,className:"rounded-lg flex-shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"back-button",children:e.jsx(ws,{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(Ie,{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(se,{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(se,{className:`${u.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:u.label}),(()=>{const b=(t==null?void 0:t.workflowType)||(t==null?void 0:t.workflow_type),j=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",y=(j==null?void 0:j.toString().toUpperCase())||"",w=y==="FORM_16",N=b==="CLAIM_MANAGEMENT"||j==="claim-management",S=b==="DEALER_CLAIM"||y==="DEALER CLAIM"||y==="DEALER_CLAIM";let A="Non-Templatized",_="bg-purple-100 !text-purple-600 border-purple-200";return w?(A="Form 16",_="bg-emerald-100 !text-emerald-700 border-emerald-200"):S?(A="Dealer Claim",_="bg-blue-100 !text-blue-700 border-blue-200"):N?(A="Claim Management",_="bg-blue-100 !text-blue-700 border-blue-200"):y==="TEMPLATE"&&(A="Template"),e.jsx(se,{className:`${_} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:A})})()]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&i&&((f=t==null?void 0:t.status)==null?void 0:f.toLowerCase())==="closed"&&e.jsxs(E,{variant:"default",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:n,"data-testid":"share-summary-button",children:[e.jsx(an,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Share Summary"})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:r,disabled:s,"data-testid":"refresh-button",children:[e.jsx($t,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:s?"Refreshing...":"Refresh"})]})]})]}),e.jsx("div",{className:"mt-3 ml-0 sm:ml-14",children:e.jsx("h2",{className:"text-base sm:text-lg md:text-xl font-semibold text-gray-900 line-clamp-2","data-testid":"request-title",children:t.title})})]}),l!==void 0&&e.jsx("div",{className:`px-3 sm:px-4 md:px-6 py-3 sm:py-4 border-b border-gray-200 ${o?"bg-gradient-to-r from-gray-100 to-gray-200":"bg-gradient-to-r from-blue-50 to-indigo-50"}`,"data-testid":"sla-section",children:e.jsx(LT,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function Hc(t){return(await je.get(`/summaries/${t}`)).data.data}async function $T(t,s){return(await je.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function UT(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 r0(t){await je.patch(`/summaries/shared/${t}/view`)}async function n0(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 BT(t){return(await je.get(`/summaries/${t}/recipients`)).data.data||[]}function VT({activityInfo:t,className:s,createdAt:a,updatedAt:r}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(Z,{className:s,children:e.jsx(ee,{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 et(new Date(l),"MMM d, yyyy")}catch{return l}};return e.jsxs(Z,{className:s,children:[e.jsx(oe,{children:e.jsxs(me,{className:"flex items-center gap-2 text-base",children:[e.jsx(dt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(ee,{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(zo,{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(Ha,{className:"w-4 h-4 text-green-600"}),t.estimatedBudget!==void 0&&t.estimatedBudget!==null?n(t.estimatedBudget):"TBD"]})]}),t.closedExpenses!==void 0&&t.closedExpenses!==null&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Closed Expenses"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-blue-600"}),n(t.closedExpensesBreakdown&&t.closedExpensesBreakdown.length>0?t.closedExpensesBreakdown.reduce((l,o)=>l+(o.totalAmt||Number(o.amount)+Number(o.gstAmt||0)),0):t.closedExpenses)]})]}),t.period&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Period"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1",children:[i(t.period.startDate)," - ",i(t.period.endDate)]})]})]}),t.closedExpensesBreakdown&&t.closedExpensesBreakdown.length>0&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Closed Expenses Breakdown"}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-xs sm:text-sm",children:[e.jsx("thead",{className:"bg-blue-100/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left font-semibold text-blue-900",children:"Description"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-24",children:"Base"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-24",children:"GST"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-28",children:"Total"})]})}),e.jsxs("tbody",{className:"divide-y divide-blue-200/50",children:[t.closedExpensesBreakdown.map((l,o)=>e.jsxs("tr",{className:"hover:bg-blue-100/30",children:[e.jsxs("td",{className:"px-3 py-2 text-gray-700",children:[l.description,l.gstRate?e.jsxs("span",{className:"text-[10px] text-gray-400 block",children:[l.gstRate,"% GST"]}):null]}),e.jsx("td",{className:"px-3 py-2 text-right text-gray-900",children:n(l.amount)}),e.jsx("td",{className:"px-3 py-2 text-right text-gray-900",children:n(l.gstAmt||0)}),e.jsx("td",{className:"px-3 py-2 text-right font-medium text-gray-900",children:n(l.totalAmt||Number(l.amount)+Number(l.gstAmt||0))})]},o)),e.jsxs("tr",{className:"bg-blue-100/50 font-bold",children:[e.jsx("td",{colSpan:3,className:"px-3 py-2 text-blue-900",children:"Final Claim Amount"}),e.jsx("td",{className:"px-3 py-2 text-right text-blue-700",children:n(t.closedExpensesBreakdown.reduce((l,o)=>l+(o.totalAmt||Number(o.amount)+Number(o.gstAmt||0)),0))})]})]})]})})]}),t.description&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Description"}),e.jsx("div",{className:"mt-2 bg-gray-50 p-3 rounded-lg border border-gray-200",children:e.jsx(Es,{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:gs(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:gs(r)})]})]})]})]})}function zT({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(Z,{className:s,children:e.jsx(ee,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(Z,{className:s,children:[e.jsx(oe,{children:e.jsxs(me,{className:"flex items-center gap-2 text-base",children:[e.jsx(Zi,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(ee,{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(ba,{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(Wn,{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(zo,{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(Z,{className:s,children:e.jsx(ee,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function HT({ioDetails:t,dmsDetails:s,claimAmount:a,estimatedBudgetBreakdown:r,closedExpensesBreakdown:n,visibility:i,onEditClaimAmount:l,className:o}){const c=x=>x==null||Number.isNaN(x)?"₹0.00":`₹${x.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,d=x=>{if(!x)return"";try{return et(new Date(x),"MMM d, yyyy, h:mm a")}catch{return x||""}},m=x=>!x||x.length===0?0:x.reduce((u,g)=>u+(g.totalAmt??g.amount+(g.gstAmt??0)),0);return i.showIODetails&&t||i.showDMSDetails&&s||(s==null?void 0:s.creditNoteWfmData)&&s.creditNoteWfmData.length>0||i.showClaimAmount&&a&&a.amount!==void 0&&a.amount!==null||r&&r.length>0||n&&n.length>0?e.jsxs(Z,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${o}`,children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"text-base flex items-center gap-2",children:[e.jsx(Ot,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(ve,{children:"Workflow reference numbers"})]}),e.jsxs(ee,{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(Pt,{className:"w-4 h-4 text-blue-600"}),e.jsx(te,{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(Ot,{className:"w-4 h-4 text-purple-600"}),e.jsx(te,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice Details"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-2",children:s.ackNo&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Ack No"}),e.jsx("p",{className:"font-bold text-sm text-purple-700",children:s.ackNo})]})}),s.irn&&e.jsxs("div",{className:"mb-2 p-2 bg-purple-50 rounded border border-purple-100",children:[e.jsx("p",{className:"text-[10px] text-purple-600 uppercase font-semibold",children:"IRN"}),e.jsx("p",{className:"text-[10px] font-mono break-all text-gray-700 leading-tight",children:s.irn})]}),s.signedInvoiceUrl&&e.jsxs(E,{variant:"outline",size:"sm",className:"w-full h-8 text-xs gap-2 mb-2 border-purple-200 text-purple-700 hover:bg-purple-50",onClick:()=>window.open(s.signedInvoiceUrl,"_blank"),children:[e.jsx(Pt,{className:"w-3.5 h-3.5"}),"View E-Invoice"]}),s.remarks&&e.jsxs("div",{className:"pt-2 border-t border-purple-100",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase mb-1",children:"Remarks"}),e.jsx("p",{className:"text-xs text-gray-900",children:s.remarks})]}),e.jsxs("div",{className:"pt-2 border-t border-purple-100 mt-2",children:[e.jsxs("p",{className:"text-[10px] text-gray-500",children:["By ",s.createdByName]}),e.jsx("p",{className:"text-[10px] text-gray-500",children:d(s.createdAt)})]})]}),(s==null?void 0:s.creditNoteWfmData)&&s.creditNoteWfmData.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-pink-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-pink-600"}),e.jsx(te,{className:"text-xs font-semibold text-pink-900 uppercase tracking-wide",children:"Credit Note Validation"})]}),e.jsx("div",{className:"space-y-2",children:s.creditNoteWfmData.map((x,u)=>e.jsxs("div",{className:"bg-pink-50 p-2 rounded border border-pink-100 text-[10px]",children:[e.jsxs("div",{className:"flex justify-between mb-1 text-pink-900",children:[e.jsxs("span",{className:"font-semibold break-words flex-1 pr-2",children:["Credit Note No: ",x.DOC_NO||"N/A"]}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-sm text-white font-medium self-start whitespace-nowrap ${x.MSG_TYP==="E"?"bg-red-500":"bg-green-500"}`,children:x.MSG_TYP==="E"?"Error":x.MSG_TYP==="S"?"Success":x.MSG_TYP||"Unknown"})]}),e.jsxs("div",{className:"text-gray-500 mb-0.5",children:["Txn: ",x.TRNS_UNIQ_NO||"N/A"]}),e.jsx("div",{className:"text-gray-700 break-words font-medium",children:x.MESSAGE||"No Message"})]},u))})]}),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(Ha,{className:"w-4 h-4 text-green-600"}),e.jsx(te,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),i.canEditClaimAmount&&l&&e.jsxs(E,{variant:"outline",size:"sm",onClick:l,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(Ii,{className:"w-3 h-3 mr-1 text-green-700"}),"Edit"]})]}),e.jsx("p",{className:"text-2xl font-bold text-green-700",children:c(a.amount)}),a.lastUpdatedBy&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-green-100",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["Last updated by ",a.lastUpdatedBy]}),a.lastUpdatedAt&&e.jsx("p",{className:"text-xs text-gray-500",children:d(a.lastUpdatedAt)})]})]}),r&&r.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-amber-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-amber-600"}),e.jsx(te,{className:"text-xs font-semibold text-amber-900 uppercase tracking-wide",children:"Estimated Budget Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[r.map((x,u)=>e.jsxs("div",{className:"flex justify-between items-center text-[10px] sm:text-xs",children:[e.jsx("div",{className:"text-gray-700 truncate mr-2",title:x.description,children:x.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:c(x.totalAmt??x.amount+(x.gstAmt??0))})]},u)),e.jsxs("div",{className:"pt-2 border-t border-amber-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-amber-700",children:c(m(r))})]})]})]}),n&&n.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-indigo-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-indigo-600"}),e.jsx(te,{className:"text-xs font-semibold text-indigo-900 uppercase tracking-wide",children:"Closed Expenses Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[n.map((x,u)=>e.jsxs("div",{className:"flex justify-between items-center text-[10px] sm:text-xs",children:[e.jsx("div",{className:"text-gray-700 truncate mr-2",title:x.description,children:x.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:c(x.totalAmt??x.amount+(x.gstAmt??0))})]},u)),e.jsxs("div",{className:"pt-2 border-t border-indigo-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-indigo-700",children:c(m(n))})]})]})]})]})]}):null}function WT({proposalDetails:t,className:s}){const r=(()=>{const o=t.totalEstimatedBudget??t.estimatedBudgetTotal;return o??(t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((d,m)=>{const p=m.amount||0,x=m.gstAmt||0,u=m.totalAmt||Number(p)+Number(x);return d+(Number.isNaN(u)?0:u)},0):0)})(),n=o=>o==null||Number.isNaN(o)?"₹0.00":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,i=o=>{if(!o)return"";try{return et(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return et(new Date(o),"MMM d, yyyy")}catch{return o||"-"}};return e.jsxs(Z,{className:s,children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2 text-base",children:[e.jsx(Pt,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs(ve,{children:["Submitted on ",i(t.submittedOn)]})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Cost Breakup"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Item Description"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Base Amount"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"GST"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Total"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-200",children:[(t.costBreakup||[]).map((o,c)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsxs("td",{className:"px-4 py-3 text-sm text-gray-900",children:[e.jsx("div",{children:o.description}),o.gstRate?e.jsx("div",{className:"text-[10px] text-gray-400",children:o.cgstAmt?`CGST: ${o.gstRate/2}%, SGST: ${o.gstRate/2}%`:`IGST: ${o.gstRate}%`}):null]}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.amount)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.gstAmt)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right font-medium",children:n(o.totalAmt||Number(o.amount||0)+Number(o.gstAmt||0))})]},c)),e.jsxs("tr",{className:"bg-green-50 font-semibold",children:[e.jsx("td",{colSpan:3,className:"px-4 py-3 text-sm text-gray-900",children:"Estimated Budget (Total Inclusive of GST)"}),e.jsx("td",{className:"px-4 py-3 text-sm text-green-700 text-right",children:n(r)})]})]})]})})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Timeline for Closure"}),e.jsx("div",{className:"mt-2 bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{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 GT({initiatorInfo:t,className:s}){const a=r=>r.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2);return e.jsxs(Z,{className:s,children:[e.jsx(oe,{children:e.jsx(me,{className:"text-base",children:"Request Initiator"})}),e.jsx(ee,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(ls,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(os,{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(ba,{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(Wn,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function i0(t,s){var a,r;try{if(!Hn(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||{},p=t.completionExpenses||t.completion_expenses||[],x=n.periodStartDate||n.period_start_date,u=n.periodEndDate||n.period_end_date,g=n.activityName||n.activity_name||"",f=n.activityType||n.activity_type||"",b=n.location||"",j=c.proposalEstimatedBudget??c.proposal_estimated_budget??c.initialEstimatedBudget??c.initial_estimated_budget??n.estimatedBudget??n.estimated_budget,y=(c==null?void 0:c.closedExpenses)??(c==null?void 0:c.closed_expenses)??(l==null?void 0:l.totalClosedExpenses)??(l==null?void 0:l.total_closed_expenses)??(n==null?void 0:n.closedExpenses)??(n==null?void 0:n.closed_expenses),w=y!=null?Number(y):void 0,N=Array.isArray(p)&&p.length>0?p.map(C=>({description:C.description||C.itemDescription||C.item_description||"",amount:Number(C.amount)||0,gstRate:C.gstRate??C.gst_rate,gstAmt:C.gstAmt??C.gst_amt,cgstAmt:C.cgstAmt??C.cgst_amt,sgstAmt:C.sgstAmt??C.sgst_amt,igstAmt:C.igstAmt??C.igst_amt,totalAmt:C.totalAmt??C.total_amt})):(l==null?void 0:l.closedExpenses)||(l==null?void 0:l.closed_expenses)||(l==null?void 0:l.closedExpensesBreakdown)||[],S={activityName:g,activityType:f,defaultGstRate:n.defaultGstRate||18,requestedDate:n.activityDate||n.activity_date||t.createdAt,location:b,period:x&&u?{startDate:x,endDate:u}:void 0,estimatedBudget:j,closedExpenses:w,closedExpensesBreakdown:N,description:t.description||""},A={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)||""};(!A.dealerCode||!A.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!n,dealerCode:A.dealerCode,dealerName:A.dealerName,rawClaimDetails:n,availableKeys:n?Object.keys(n):[]});const _=(i==null?void 0:i.expectedCompletionDate)||(i==null?void 0:i.expected_completion_date),D=i?{proposalDocumentUrl:i.proposalDocumentUrl||i.proposal_document_url,costBreakup:Array.isArray(i.costItems||i.cost_items)?(i.costItems||i.cost_items).map(C=>({description:C.description||C.itemDescription||C.item_description||"",amount:Number(C.amount)||0,gstRate:Number(C.gstRate??C.gst_rate??0),gstAmt:Number(C.gstAmt??C.gst_amt??0),cgstAmt:Number(C.cgstAmt??C.cgst_amt??0),sgstAmt:Number(C.sgstAmt??C.sgst_amt??0),igstAmt:Number(C.igstAmt??C.igst_amt??0),totalAmt:Number(C.totalAmt??C.total_amt??0)})):Array.isArray(i.costBreakup||i.cost_breakup)?(i.costBreakup||i.cost_breakup).map(C=>({description:C.description||C.itemDescription||C.item_description||"",amount:Number(C.amount)||0,gstRate:C.gstRate??C.gst_rate,gstAmt:C.gstAmt??C.gst_amt,cgstAmt:C.cgstAmt??C.cgst_amt,sgstAmt:C.sgstAmt??C.sgst_amt,igstAmt:C.igstAmt??C.igst_amt,totalAmt:C.totalAmt??C.total_amt})):[],totalEstimatedBudget:i.totalEstimatedBudget||i.total_estimated_budget||0,timelineMode:i.timelineMode||i.timeline_mode,expectedCompletionDate:_,expectedCompletionDays:i.expectedCompletionDays||i.expected_completion_days,timelineForClosure:_,dealerComments:i.dealerComments||i.dealer_comments,submittedOn:i.submittedAt||i.submitted_at||i.submittedOn}:void 0,R={ioNumber:o.ioNumber||o.io_number||n.ioNumber||n.io_number,ioRemark:o.ioRemark||o.io_remark||"",availableBalance:o.ioAvailableBalance||o.io_available_balance||n.ioAvailableBalance||n.io_available_balance,blockedAmount:o.ioBlockedAmount||o.io_blocked_amount||n.ioBlockedAmount||n.io_blocked_amount,remainingBalance:o.ioRemainingBalance||o.io_remaining_balance||n.ioRemainingBalance||n.io_remaining_balance,organizedBy:((a=o.organizer)==null?void 0:a.displayName)||((r=o.organizer)==null?void 0:r.name)||o.organizedBy||"",organizedAt:o.organizedAt||o.organized_at||""},v={eInvoiceNumber:d.invoiceNumber||d.invoice_number||n.eInvoiceNumber||n.e_invoice_number,eInvoiceDate:d.invoiceDate||d.invoice_date||n.eInvoiceDate||n.e_invoice_date,dmsNumber:d.dmsNumber||d.dms_number||n.dmsNumber||n.dms_number,creditNoteNumber:m.creditNoteNumber||m.credit_note_number||n.creditNoteNumber||n.credit_note_number,creditNoteDate:m.creditNoteDate||m.credit_note_date||n.creditNoteDate||n.credit_note_date,creditNoteAmount:m.creditNoteAmount?Number(m.creditNoteAmount):m.credit_note_amount?Number(m.credit_note_amount):m.creditNoteAmount?Number(m.creditNoteAmount):n.creditNoteAmount?Number(n.creditNoteAmount):n.credit_note_amount?Number(n.credit_note_amount):void 0,irn:d.irn||n.irn,ackNo:d.ackNo||n.ackNo,ackDate:d.ackDate||n.ackDate,signedInvoiceUrl:d.signedInvoiceUrl||n.signedInvoiceUrl,taxBreakdown:d.taxBreakdown||n.taxBreakdown,creditNoteWfmData:t.creditNoteWfmData||n.creditNoteWfmData||[]},P={estimated:S.estimatedBudget||0,closed:S.closedExpenses||0};return{activityInfo:S,dealerInfo:A,proposalDetails:D,ioDetails:Object.keys(R).some(C=>R[C])?R:void 0,dmsDetails:Object.keys(v).some(C=>v[C])?v:void 0,claimAmount:P}}catch(n){return console.error("[claimDataMapper] Error mapping claim data:",n),null}}function l0(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 o0(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 YT({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:l,onReject:o,onPause:c,onResume:d,onRetrigger:m,summaryId:p,refreshTrigger:x,pausedByUserId:u,currentUserId:g,apiRequest:f,onEditClaimAmount:b,hideApproveReject:j=!1}){var T,k,z,L,M;const{user:y}=cs(),[w,N]=h.useState([]),[S,A]=h.useState(!1),[_,D]=h.useState(!1),R=(t==null?void 0:t.status)==="closed",v=((T=t==null?void 0:t.pauseInfo)==null?void 0:T.isPaused)||!1,P=u||((z=(k=t==null?void 0:t.pauseInfo)==null?void 0:k.pausedBy)==null?void 0:z.userId),C=g||(y==null?void 0:y.userId)||"",V=!v&&!R&&(r||s),F=v&&d&&(r||s),$=v&&s&&P&&P!==C&&m;h.useEffect(()=>{if(!v||!r||!(t!=null&&t.requestId)){D(!1);return}(async()=>{var B;try{const O=(((B=(await nr.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:B.notifications)||[]).some(H=>H.requestId===t.requestId&&H.notificationType==="pause_retrigger_request");D(O)}catch(W){console.error("Failed to check retrigger notifications:",W),D(!1)}})()},[v,r,t==null?void 0:t.requestId,x]),h.useEffect(()=>{(async()=>{if(!R||!p||!s){N([]);return}try{A(!0);const B=await BT(p);N(B)}catch(B){console.error("Failed to fetch shared recipients:",B),N([])}finally{A(!1)}})()},[R,p,s,x]);const I=h.useMemo(()=>{if(!f||!Hn(f))return null;const U=i0(f);if(!U)return null;const B=l0(f,C),W=o0(B);return{claimRequest:U,visibility:W}},[f,C]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(Z,{"data-testid":"quick-actions-card",children:[e.jsx(oe,{className:"pb-2",children:e.jsx(me,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(ee,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:n,"data-testid":"add-approver-button",children:[e.jsx(Xi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:i,"data-testid":"add-spectator-button",children:[e.jsx(Ct,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),V&&c&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:c,"data-testid":"pause-workflow-button",children:[e.jsx(or,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),F&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-green-700 border-green-300 hover:bg-green-50 hover:text-green-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:d,"data-testid":"resume-workflow-button",children:[e.jsx(Di,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),$&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:m,"data-testid":"request-resume-button",children:[e.jsx(Ze,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Request Resume"]}),e.jsxs("div",{className:"pt-3 sm:pt-4 space-y-2",children:[r&&!v&&!j&&e.jsxs(e.Fragment,{children:[e.jsxs(E,{className:"w-full bg-green-600 hover:bg-green-700 text-white h-9 sm:h-10 text-xs sm:text-sm",onClick:l,"data-testid":"approve-request-button",children:[e.jsx(Le,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(E,{variant:"destructive",className:"w-full h-9 sm:h-10 text-xs sm:text-sm",onClick:o,"data-testid":"reject-request-button",children:[e.jsx(St,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),v&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children: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(Ze,{className:"w-3.5 h-3.5"}),_?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:_?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&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(Ze,{className:"w-3.5 h-3.5"}),"Initiator has requested resume"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Please review and resume if appropriate"})]}):r&&P!==C?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&&P&&P!==C?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:$?'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(Z,{"data-testid":"spectators-card",children:[e.jsx(oe,{className:"pb-2",children:e.jsx(me,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(ee,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((U,B)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${B}`,children:[e.jsx(ls,{className:"h-8 w-8",children:e.jsx(os,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:U.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:U.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:U.role})]})]},B)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),R&&s&&e.jsxs(Z,{"data-testid":"shared-recipients-card",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs(me,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(an,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(ee,{className:"space-y-3",children:S?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):w.length>0?w.map((U,B)=>{const W=(U.displayName||"NA").split(" ").map(J=>J[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${B}`,children:[e.jsx(ls,{className:"h-8 w-8",children:e.jsx(os,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:W})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:U.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:U.email}),U.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},U.userId||B)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),I&&e.jsx(HT,{ioDetails:I.claimRequest.ioDetails,dmsDetails:I.claimRequest.dmsDetails,claimAmount:{amount:I.claimRequest.claimAmount.closed||I.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(L=I.claimRequest.proposalDetails)==null?void 0:L.costBreakup,closedExpensesBreakdown:(M=I.claimRequest.activityInfo)==null?void 0:M.closedExpensesBreakdown,visibility:I.visibility,onEditClaimAmount:b})]})}function KT({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=h.useState(r),[d,m]=h.useState(!1),p=(o==null?void 0:o.length)||0,x=h.useMemo(()=>o.slice(0,500),[o]),u=async()=>{try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(jt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(xt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(yt,{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(Le,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(ht,{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(se,{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(Os,{value:x,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(p,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(Le,{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(Et,{className:"mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(E,{onClick:u,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function QT({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=h.useState(r),[d,m]=h.useState(!1),p=(o==null?void 0:o.length)||0,x=h.useMemo(()=>o.slice(0,500),[o]),u=async()=>{if(!x.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(jt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(xt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(yt,{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(St,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ht,{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(se,{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(Os,{value:x,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(p,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-red-50 border-red-200 text-red-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Ze,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Rejection Guidelines"}),e.jsx("div",{children:"Please provide specific, actionable feedback to help the initiator improve their request."})]})]}),e.jsxs(Et,{className:"mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(E,{variant:"destructive",onClick:u,disabled:d,children:[e.jsx(St,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function XT({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,c]=h.useState(""),[d,m]=h.useState(!1),p=async()=>{if(o.trim())try{m(!0),await a(o.trim()),c(""),s()}catch(u){console.error("Failed to skip approver:",u)}finally{m(!1)}},x=()=>{d||(c(""),s())};return e.jsx(jt,{open:t,onOpenChange:x,children:e.jsxs(xt,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:x,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:d,children:[e.jsx(bt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(yt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center",children:e.jsx(Ze,{className:"w-5 h-5 text-orange-600"})}),e.jsx(ht,{className:"text-xl font-bold text-gray-900",children:"Skip Approver"})]})}),e.jsxs("div",{className:"space-y-4 px-6 py-4 overflow-y-auto flex-1",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ze,{className:"w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-orange-900 mb-1",children:"Important Notice"}),e.jsx("p",{className:"text-sm text-orange-800",children:"You are about to skip the current approver. The request will be moved to the next approval level."})]})]})}),(i||l)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(te,{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(te,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(Os,{id:"skip-reason",placeholder:"Please provide a detailed reason for skipping this approver (e.g., 'Approver is on leave until [date]', 'Approver unavailable - escalating to next level')",value:o,onChange:u=>c(u.target.value),className:"min-h-[100px] border-2 border-gray-300 focus:border-orange-500",disabled:d,autoFocus:!0}),e.jsx("p",{className:"text-xs text-gray-500",children:"This reason will be recorded in the activity log and all participants will be notified."})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:x,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:p,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:d||!o.trim(),children:[e.jsx(Ze,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function JT({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:l,documentError:o,request:c,skipApproverData:d,actionStatus:m,existingParticipants:p,currentLevels:x,maxApprovalLevels:u,onPolicyViolation:g,setShowApproveModal:f,setShowRejectModal:b,setShowAddApproverModal:j,setShowAddSpectatorModal:y,setShowSkipApproverModal:w,setShowActionStatusModal:N,setPreviewDocument:S,setDocumentError:A,setSkipApproverData:_,setActionStatus:D,handleApproveConfirm:R,handleRejectConfirm:v,handleAddApprover:P,handleAddSpectator:C,handleSkipApprover:V,downloadDocument:F,documentPolicy:$}){return e.jsxs(e.Fragment,{children:[e.jsx(KT,{open:t,onClose:()=>f(!1),onConfirm:R,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(QT,{open:s,onClose:()=>b(!1),onConfirm:v,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(s0,{open:a,onClose:()=>j(!1),onConfirm:P,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p,currentLevels:x,maxApprovalLevels:u,onPolicyViolation:g}),e.jsx(t0,{open:r,onClose:()=>y(!1),onConfirm:C,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p}),e.jsx(XT,{open:n,onClose:()=>{w(!1),_(null)},onConfirm:V,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),l&&e.jsx(Mr,{fileName:l.fileName,fileType:l.fileType,fileUrl:mn(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:F,open:!!l,onClose:()=>S(null)}),m&&e.jsx(e0,{open:i,onClose:()=>{N(!1),D(null)},success:m.success,title:m.title,message:m.message}),e.jsx(jt,{open:o.show,onOpenChange:I=>A(T=>({...T,show:I})),children:e.jsxs(xt,{className:"sm:max-w-lg",children:[e.jsxs(yt,{children:[e.jsxs(ht,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Ut,{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((I,T)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:I.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:I.reason})]},T))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",$.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",$.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Et,{children:e.jsx(E,{onClick:()=>A({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const c0={DocumentsTab:AT,ActivityTab:DT,WorkNotesTab:_T,SummaryTab:MT,RequestDetailHeader:OT,QuickActionsSidebar:YT,RequestDetailModals:JT};function Wc({className:t,...s}){return e.jsx(Mf,{"data-slot":"checkbox",className:_e("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(Lf,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(za,{className:"size-3.5"})})})}function d0({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,l]=h.useState(""),[o,c]=h.useState([]),[d,m]=h.useState(new Set),[p,x]=h.useState(!1),[u,g]=h.useState(!1);h.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),x(!1);return}const y=setTimeout(async()=>{var w;try{x(!0);const N=i.slice(1),S=await ja(N,10),A=((w=S==null?void 0:S.data)==null?void 0:w.data)||(S==null?void 0:S.data)||[];c(Array.isArray(A)?A:[])}catch(N){console.error("Failed to search users:",N),X.error("Failed to search users")}finally{x(!1)}},300);return()=>clearTimeout(y)},[i,t]);const f=y=>{m(w=>{const N=new Set(w);return N.has(y)?N.delete(y):N.add(y),N})},b=async()=>{var y,w;if(d.size===0){X.error("Please select at least one user to share with");return}try{g(!0),await $T(a,Array.from(d)),X.success(`Summary shared with ${d.size} user(s)`),m(new Set),l(""),c([]),n==null||n(),s()}catch(N){console.error("Failed to share summary:",N),X.error(((w=(y=N==null?void 0:N.response)==null?void 0:y.data)==null?void 0:w.message)||"Failed to share summary")}finally{g(!1)}},j=()=>{m(new Set),l(""),c([]),s()};return e.jsx(jt,{open:t,onOpenChange:j,children:e.jsxs(xt,{className:"sm:max-w-[500px]",children:[e.jsx(yt,{children:e.jsx(ht,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(te,{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(te,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(ke,{id:"user-search",placeholder:"Type @ to search users...",value:i,onChange:y=>l(y.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)"})]}),p&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Xe,{className:"h-5 w-5 animate-spin text-blue-600"})}),!p&&o.length>0&&e.jsx("div",{className:"border rounded-lg max-h-[300px] overflow-y-auto",children:o.map(y=>{const w=d.has(y.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(y.userId),children:[e.jsx("div",{onClick:N=>N.stopPropagation(),onMouseDown:N=>N.stopPropagation(),className:"flex items-center",children:e.jsx(Wc,{checked:w,onCheckedChange:()=>f(y.userId)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:y.displayName||y.email})]}),(y.designation||y.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:y.designation||y.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:y.email})]})]},y.userId)})}),!p&&i&&i.startsWith("@")&&o.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),!p&&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(y=>{const w=o.find(N=>N.userId===y);return e.jsxs("div",{className:"flex items-center gap-1 bg-white px-2 py-1 rounded-full text-xs",children:[e.jsx("span",{children:(w==null?void 0:w.displayName)||(w==null?void 0:w.email)||y}),e.jsx("button",{onClick:()=>f(y),className:"ml-1 hover:text-red-600",children:e.jsx(bt,{className:"h-3 w-3"})})]},y)})})]})]}),e.jsxs(Et,{children:[e.jsx(E,{variant:"outline",onClick:j,disabled:u,children:"Cancel"}),e.jsx(E,{onClick:b,disabled:u||d.size===0,children:u?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function m0({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=h.useState(""),[o,c]=h.useState(""),[d,m]=h.useState(!1),p=()=>as().add(1,"month").format("YYYY-MM-DD"),x=()=>as().add(1,"month").format("YYYY-MM-DD"),u=()=>as().add(1,"day").format("YYYY-MM-DD");h.useEffect(()=>{t&&!o&&c(p())},[t]);const g=async()=>{var w,N,S,A;if(!i.trim()){X.error("Please provide a reason for pausing");return}if(!o){X.error("Please select a resume date");return}const b=as(o),j=as().add(1,"month"),y=as().add(1,"day");if(b.isAfter(j)){X.error("Resume date cannot be more than 1 month from now");return}if(b.isBefore(y,"day")){X.error("Resume date must be at least 1 day from now");return}try{m(!0),await Aw(a,r,i.trim(),b.toDate()),X.success("Workflow paused successfully"),n&&await n(),l(""),c(p()),s()}catch(_){console.error("Failed to pause workflow:",_),X.error(((N=(w=_==null?void 0:_.response)==null?void 0:w.data)==null?void 0:N.error)||((A=(S=_==null?void 0:_.response)==null?void 0:S.data)==null?void 0:A.message)||"Failed to pause workflow")}finally{m(!1)}},f=()=>{d||(l(""),c(p()),s())};return e.jsx(jt,{open:t,onOpenChange:f,children:e.jsxs(xt,{className:"sm:max-w-[500px]",children:[e.jsx(yt,{children:e.jsxs(ht,{className:"flex items-center gap-2",children:[e.jsx(or,{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(te,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Os,{id:"pause-reason",value:i,onChange:b=>l(b.target.value),placeholder:"Enter the reason for pausing this workflow...",className:"min-h-[100px] text-sm",disabled:d}),e.jsxs("p",{className:"text-xs text-gray-500",children:[i.length," / 1000 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ke,{id:"resume-date",type:"date",value:o,onChange:b=>c(b.target.value),min:u(),max:x(),className:"text-sm",disabled:d}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum 1 month from today. The workflow will automatically resume on this date."})]})]}),e.jsxs(Et,{children:[e.jsx(E,{variant:"outline",onClick:f,disabled:d,children:"Cancel"}),e.jsx(E,{onClick:g,disabled:d||!i.trim()||!o,className:"bg-orange-600 hover:bg-orange-700 text-white",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(or,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function u0({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=h.useState(""),[l,o]=h.useState(!1),c=async()=>{var m,p,x,u;try{o(!0),await Tw(a,n.trim()||void 0),X.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),X.error(((p=(m=g==null?void 0:g.response)==null?void 0:m.data)==null?void 0:p.error)||((u=(x=g==null?void 0:g.response)==null?void 0:x.data)==null?void 0:u.message)||"Failed to resume workflow")}finally{o(!1)}},d=()=>{l||(i(""),s())};return e.jsx(jt,{open:t,onOpenChange:d,children:e.jsxs(xt,{className:"sm:max-w-[500px]",children:[e.jsx(yt,{children:e.jsxs(ht,{className:"flex items-center gap-2",children:[e.jsx(Di,{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(te,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(Os,{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(Et,{children:[e.jsx(E,{variant:"outline",onClick:d,disabled:l,children:"Cancel"}),e.jsx(E,{onClick:c,disabled:l,className:"bg-green-600 hover:bg-green-700 text-white",children:l?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Di,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function x0({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=h.useState(!1),o=async()=>{var c,d,m,p;try{l(!0),await kw(a),X.success("Retrigger request sent to approver"),n&&await n(),s()}catch(x){console.error("Failed to retrigger pause:",x),X.error(((d=(c=x==null?void 0:x.response)==null?void 0:c.data)==null?void 0:d.error)||((p=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:p.message)||"Failed to send retrigger request")}finally{l(!1)}};return e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(xt,{className:"sm:max-w-[450px]",children:[e.jsx(yt,{children:e.jsxs(ht,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-orange-600"}),"Request Resume"]})}),e.jsxs("div",{className:"py-4",children:[e.jsxs("p",{className:"text-sm text-gray-700 mb-4",children:["You are requesting the approver",r?` (${r})`:""," to cancel the pause and resume work on this request."]}),e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-orange-800",children:"A notification will be sent to the approver who paused this workflow, requesting them to resume it."})})]}),e.jsxs(Et,{children:[e.jsx(E,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(E,{onClick:o,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:ZT,ActivityTab:qT,WorkNotesTab:e5,SummaryTab:t5,RequestDetailHeader:s5,QuickActionsSidebar:a5,RequestDetailModals:r5}=c0;let n5=class extends h.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("Custom RequestDetail Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(ts,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(E,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(E,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function i5({requestId:t,onBack:s,dynamicRequests:a=[]}){var Ka,hr,Qa,pr,Xa,Ta,Ja,Za,qa;const n=_a().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=h.useState(l),[d,m]=h.useState(!1),[p,x]=h.useState(null),[u,g]=h.useState(null),[f,b]=h.useState(!1),[j,y]=h.useState(0),[w,N]=h.useState(!1),[S,A]=h.useState(!1),[_,D]=h.useState(!1),[R,v]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[P,C]=h.useState({open:!1,violations:[]}),{user:V}=cs(),{request:F,apiRequest:$,loading:I,refreshing:T,refreshDetails:k,currentApprovalLevel:z,isSpectator:L,isInitiator:M,existingParticipants:U,accessDenied:B}=Vc(n,a,V),{mergedMessages:W,unreadWorkNotes:J,workNoteAttachments:O,setWorkNoteAttachments:H}=Xg(n,$,o,V),{uploadingDocument:Y,triggerFileInput:re,previewDocument:K,setPreviewDocument:ae,documentPolicy:Ne,documentError:Se,setDocumentError:Ge}=Jg($,k),{showApproveModal:Je,setShowApproveModal:Pe,showRejectModal:Oe,setShowRejectModal:ie,showAddApproverModal:pe,setShowAddApproverModal:we,showAddSpectatorModal:Ae,setShowAddSpectatorModal:ne,showSkipApproverModal:q,setShowSkipApproverModal:de,showActionStatusModal:Ye,setShowActionStatusModal:fe,skipApproverData:ye,setSkipApproverData:Ue,actionStatus:nt,setActionStatus:mt,handleApproveConfirm:vt,handleRejectConfirm:xs,handleAddApprover:le,handleSkipApprover:De,handleAddSpectator:ce}=qg(n,z,k),{conclusionRemark:Ke,setConclusionRemark:We,conclusionLoading:tt,conclusionSubmitting:Qe,aiGenerated:rt,handleGenerateConclusion:qe,handleFinalizeConclusion:ot,generationAttempts:$s,generationFailed:ns,maxAttemptsReached:pt}=Zg(F,n,M,k,s,mt,fe);h.useEffect(()=>{(async()=>{var As;try{const qs=await la("SYSTEM_SETTINGS"),gr=await la("WORKFLOW_SHARING"),Rt=[...qs,...gr],Xt={};Rt.forEach(Rs=>{Xt[Rs.configKey]=Rs.configValue}),v({maxApprovalLevels:parseInt(Xt.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Xt.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((As=Xt.ALLOW_ADD_SPECTATOR)==null?void 0:As.toLowerCase())==="true",maxSpectators:parseInt(Xt.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(qs){console.error("Failed to load system policy:",qs)}})()},[]),h.useEffect(()=>{const As=new URLSearchParams(window.location.search).get("tab");As&&c(As)},[n]);const ct=()=>{k()},Ft=()=>{N(!0)},Ss=()=>{A(!0)},ss=async()=>{await k()},Ma=()=>{D(!0)},La=async()=>{await k()},Aa=async()=>{await k()},Ya=async()=>{if(!($!=null&&$.requestId)){X.error("Request ID not found");return}if(!p){X.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},It=((F==null?void 0:F.status)==="approved"||(F==null?void 0:F.status)==="rejected")&&M,Oa=(F==null?void 0:F.status)==="closed"||(F==null?void 0:F.status)==="approved"&&!M||(F==null?void 0:F.status)==="rejected"&&!M,Us=((F==null?void 0:F.templateType)||(F==null?void 0:F.template_type)||"").toString().toUpperCase()==="FORM_16";h.useEffect(()=>{Us&&o==="worknotes"&&c("overview")},[Us,o]),h.useEffect(()=>{(async()=>{if(!Oa||!($!=null&&$.requestId)){g(null),x(null);return}try{b(!0);const As=await n0($.requestId);if(As!=null&&As.summaryId){x(As.summaryId);try{const qs=await Hc(As.summaryId);g(qs)}catch(qs){console.error("Failed to fetch summary details:",qs),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{b(!1)}})()},[Oa,$==null?void 0:$.requestId]);const Lr=((F==null?void 0:F.approvalFlow)||[]).filter(Gt=>Gt&&typeof Gt.step=="number").map(Gt=>({levelNumber:Gt.step||0,approverName:Gt.approver||"Unknown",status:Gt.status||"pending",tatHours:Gt.tatHours||24}));if(I&&!F&&!$)return e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx($t,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading custom request details..."})]})});if(B!=null&&B.denied)return 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(mh,{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:B.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});if(!F)return 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(Ie,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Custom Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The custom request you're looking for doesn't exist or may have been deleted."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});const xr=(V==null?void 0:V.role)==="MANAGEMENT"||(V==null?void 0:V.role)==="ADMIN",Or=((Ka=at.getUserData())==null?void 0:Ka.jobTitle)==="Dealer";return 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:[Us&&e.jsx("p",{className:"text-sm text-emerald-700 font-medium mb-2","data-testid":"form16-details-heading",children:"Form 16 Details"}),e.jsx(s5,{request:F,refreshing:T,onBack:s||(()=>window.history.back()),onRefresh:ct,onShareSummary:Ya,isInitiator:M,slaData:((hr=F==null?void 0:F.summary)==null?void 0:hr.sla)||(F==null?void 0:F.sla)||null,isPaused:((Qa=F==null?void 0:F.pauseInfo)==null?void 0:Qa.isPaused)||!1}),e.jsxs(ai,{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(ri,{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(Mt,{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(uh,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:Us?"Form 16":"Overview"})]}),Oa&&u&&e.jsxs(Mt,{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(Ho,{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(Mt,{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(Hs,{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(Mt,{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(Ie,{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(Mt,{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(Ot,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Activity"})]}),!Us&&e.jsxs(Mt,{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(zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),J>0&&e.jsx(se,{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:J>9?"9+":J})]})]})}),e.jsxs("div",{className:o==="worknotes"&&!Us?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:o==="worknotes"&&!Us?"":"lg:col-span-2",children:[e.jsx(Lt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:Us?e.jsx(Ww,{request:F}):e.jsx(Ow,{request:F,isInitiator:M,needsClosure:It,conclusionRemark:Ke,setConclusionRemark:We,conclusionLoading:tt,conclusionSubmitting:Qe,aiGenerated:rt,handleGenerateConclusion:qe,handleFinalizeConclusion:ot,onPause:Ft,onResume:Ss,onRetrigger:Ma,currentUserIsApprover:!!z,pausedByUserId:(Xa=(pr=F==null?void 0:F.pauseInfo)==null?void 0:pr.pausedBy)==null?void 0:Xa.userId,currentUserId:V==null?void 0:V.userId,generationAttempts:$s,generationFailed:ns,maxAttemptsReached:pt})}),Oa&&e.jsx(Lt,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(t5,{summary:u,loading:f,onShare:Ya,isInitiator:M})}),e.jsx(Lt,{value:"workflow",className:"mt-0",children:Us?e.jsx(Yw,{request:F,requestId:($==null?void 0:$.requestId)||n,isReUser:xr,onRefresh:k}):e.jsx(Vw,{request:F,user:V,isInitiator:M,onSkipApprover:Gt=>{if(!Gt.levelId){alert("Level ID not available");return}Ue(Gt),de(!0)},onRefresh:k})}),e.jsx(Lt,{value:"documents",className:"mt-0",children:e.jsx(ZT,{request:F,workNoteAttachments:O,uploadingDocument:Y,documentPolicy:Ne,triggerFileInput:re,setPreviewDocument:ae,downloadDocument:Ms})}),e.jsx(Lt,{value:"activity",className:"mt-0",children:e.jsx(qT,{request:F})}),!Us&&e.jsx(Lt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(e5,{requestId:n,requestTitle:F.title,mergedMessages:W,setWorkNoteAttachments:H,isInitiator:M,isSpectator:L,currentLevels:Lr,onAddApprover:le,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:Gt=>C({open:!0,violations:Gt})})})]}),!Or&&o!=="worknotes"&&e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[Us&&xr&&e.jsx(CT,{requestId:($==null?void 0:$.requestId)||n,request:F,onRefresh:k}),e.jsx(a5,{request:F,isInitiator:M,isSpectator:L,currentApprovalLevel:z,onAddApprover:()=>we(!0),onAddSpectator:()=>ne(!0),onApprove:()=>Pe(!0),onReject:()=>ie(!0),onPause:Ft,onResume:Ss,onRetrigger:Ma,summaryId:p,refreshTrigger:j,pausedByUserId:(Ja=(Ta=F==null?void 0:F.pauseInfo)==null?void 0:Ta.pausedBy)==null?void 0:Ja.userId,currentUserId:V==null?void 0:V.userId,apiRequest:$,hideApproveReject:Or})]})]})]})]})}),d&&p&&e.jsx(d0,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(F==null?void 0:F.title)||"N/A",onSuccess:()=>{k(),y(Gt=>Gt+1)}}),w&&($==null?void 0:$.requestId)&&e.jsx(m0,{isOpen:w,onClose:()=>N(!1),requestId:$.requestId,levelId:(z==null?void 0:z.levelId)||null,onSuccess:La}),S&&($==null?void 0:$.requestId)&&e.jsx(u0,{isOpen:S,onClose:()=>A(!1),requestId:$.requestId,onSuccess:ss}),_&&($==null?void 0:$.requestId)&&e.jsx(x0,{isOpen:_,onClose:()=>D(!1),requestId:$.requestId,approverName:(qa=(Za=F==null?void 0:F.pauseInfo)==null?void 0:Za.pausedBy)==null?void 0:qa.name,onSuccess:Aa}),e.jsx(r5,{showApproveModal:Je,showRejectModal:Oe,showAddApproverModal:pe,showAddSpectatorModal:Ae,showSkipApproverModal:q,showActionStatusModal:Ye,previewDocument:K,documentError:Se,request:F,skipApproverData:ye,actionStatus:nt,existingParticipants:U,currentLevels:Lr,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:Gt=>C({open:!0,violations:Gt}),setShowApproveModal:Pe,setShowRejectModal:ie,setShowAddApproverModal:we,setShowAddSpectatorModal:ne,setShowSkipApproverModal:de,setShowActionStatusModal:fe,setPreviewDocument:ae,setDocumentError:Ge,setSkipApproverData:Ue,setActionStatus:mt,handleApproveConfirm:vt,handleRejectConfirm:xs,handleAddApprover:le,handleAddSpectator:ce,handleSkipApprover:De,downloadDocument:Ms,documentPolicy:Ne}),e.jsx(si,{open:P.open,onClose:()=>C({open:!1,violations:[]}),violations:P.violations,policyDetails:{maxApprovalLevels:R.maxApprovalLevels,maxParticipants:R.maxParticipants,allowSpectators:R.allowSpectators,maxSpectators:R.maxSpectators}})]})}function l5(t){return e.jsx(n5,{children:e.jsx(i5,{...t})})}const o5=[{value:"Q1",label:"Q1 (April - June)"},{value:"Q2",label:"Q2 (July - September)"},{value:"Q3",label:"Q3 (October - December)"},{value:"Q4",label:"Q4 (January - March)"}];function c5(){const t=new Date().getFullYear(),s=[];for(let a=0;a<4;a++){const r=t-a,n=(r+1).toString().slice(-2);s.push(`${r}-${n}`)}return s}function d5({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,onSearchChange:c,onStatusFilterChange:d,onPriorityFilterChange:m,onTemplateTypeFilterChange:p,onForm16FinancialYearChange:x,onForm16QuarterChange:u,onSortByChange:g,onSortOrderChange:f,onClearFilters:b,activeFiltersCount:j}){const y=c5(),w=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0",children:[e.jsx(oe,{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(Pa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ve,{className:"text-xs sm:text-sm",children:j>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[j," filter",j>1?"s":""," active"]})})]})]}),j>0&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:b,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(bt,{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(ee,{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(Cs,{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(ke,{placeholder:"Search requests, IDs...",value:t,onChange:N=>c(N.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors"})]}),e.jsxs(Be,{value:a,onValueChange:m,children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ve,{placeholder:"All Priorities"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Priorities"}),e.jsx(Q,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(Q,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Be,{value:s,onValueChange:d,children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ve,{placeholder:"All Statuses"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Statuses"}),e.jsx(Q,{value:"pending",children:"Pending (In Approval)"}),e.jsx(Q,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs(Be,{value:r,onValueChange:p,children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ve,{placeholder:"Request type"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(Q,{value:"FORM_16",children:"Form 16"})]})]}),w&&x&&e.jsxs(Be,{value:n||void 0,onValueChange:x,children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ve,{placeholder:"Financial Year"})}),e.jsx(He,{children:y.map(N=>e.jsx(Q,{value:N,children:N},N))})]}),w&&u&&e.jsxs(Be,{value:i||void 0,onValueChange:u,children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ve,{placeholder:"Quarter"})}),e.jsx(He,{children:o5.map(N=>e.jsx(Q,{value:N.value,children:N.label},N.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Be,{value:l,onValueChange:N=>g(N),children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ve,{placeholder:"Sort by"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"due",children:"Due Date"}),e.jsx(Q,{value:"created",children:"Date Created"}),e.jsx(Q,{value:"priority",children:"Priority"}),e.jsx(Q,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>f(o==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:o==="asc"?e.jsx(qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(el,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}const m5=[{value:"Q1",label:"Q1 (April - June)"},{value:"Q2",label:"Q2 (July - September)"},{value:"Q3",label:"Q3 (October - December)"},{value:"Q4",label:"Q4 (January - March)"}];function u5(){const t=new Date().getFullYear(),s=[];for(let a=0;a<4;a++){const r=t-a,n=(r+1).toString().slice(-2);s.push(`${r}-${n}`)}return s}function x5({searchTerm:t,priorityFilter:s,statusFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,activeFiltersCount:c,onSearchChange:d,onPriorityChange:m,onStatusChange:p,onTemplateTypeChange:x,onForm16FinancialYearChange:u,onForm16QuarterChange:g,onSortByChange:f,onSortOrderChange:b,onClearFilters:j}){const y=u5(),w=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(oe,{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(Pa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ve,{className:"text-xs sm:text-sm",children:c>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[c," filter",c>1?"s":""," active"]})})]})]}),c>0&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:j,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(bt,{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(ee,{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(Cs,{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(ke,{placeholder:"Search requests, IDs...",value:t,onChange:N=>d(N.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white transition-colors","data-testid":"closed-requests-search"})]}),e.jsxs(Be,{value:s,onValueChange:m,children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-priority-filter",children:e.jsx(Ve,{placeholder:"All Priorities"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Priorities"}),e.jsx(Q,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(Q,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Be,{value:a,onValueChange:p,children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-status-filter",children:e.jsx(Ve,{placeholder:"Closure Type"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Closures"}),e.jsx(Q,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(Q,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs(Be,{value:r,onValueChange:x,children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-template-type-filter",children:e.jsx(Ve,{placeholder:"Request type"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(Q,{value:"FORM_16",children:"Form 16"})]})]}),w&&u&&e.jsxs(Be,{value:n||void 0,onValueChange:u,children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white",children:e.jsx(Ve,{placeholder:"Financial Year"})}),e.jsx(He,{children:y.map(N=>e.jsx(Q,{value:N,children:N},N))})]}),w&&g&&e.jsxs(Be,{value:i||void 0,onValueChange:g,children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white",children:e.jsx(Ve,{placeholder:"Quarter"})}),e.jsx(He,{children:m5.map(N=>e.jsx(Q,{value:N.value,children:N.label},N.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Be,{value:l,onValueChange:N=>f(N),children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-sort-by",children:e.jsx(Ve,{placeholder:"Sort by"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"due",children:"Due Date"}),e.jsx(Q,{value:"created",children:"Date Created"}),e.jsx(Q,{value:"priority",children:"Priority"})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:b,className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11","data-testid":"closed-requests-sort-order",children:o==="asc"?e.jsx(qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(el,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function h5({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,departmentFilter:n,slaComplianceFilter:i,initiatorFilter:l,approverFilter:o,approverFilterType:c,dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:x,departments:u,loadingDepartments:g,initiatorSearch:f,approverSearch:b,showForm16Filter:j=!1,form16FinancialYear:y="all",form16Quarter:w="all",onForm16FinancialYearChange:N,onForm16QuarterChange:S,onSearchChange:A,onStatusChange:_,onPriorityChange:D,onTemplateTypeChange:R,onDepartmentChange:v,onSlaComplianceChange:P,onInitiatorChange:C,onApproverChange:V,onApproverTypeChange:F,onDateRangeChange:$,onCustomStartDateChange:I,onCustomEndDateChange:T,onShowCustomDatePickerChange:k,onApplyCustomDate:z,onClearFilters:L,hasActiveFilters:M}){return e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"user-all-requests-filters",children:e.jsx(ee,{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(Pa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),M&&e.jsx(se,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),M&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:L,className:"gap-2",children:[e.jsx($t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Qt,{}),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(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(ke,{placeholder:"Search requests...",value:t,onChange:U=>A(U.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Be,{value:s,onValueChange:_,children:[e.jsx(ze,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ve,{placeholder:"All Status"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Status"}),e.jsx(Q,{value:"pending",children:"Pending"}),e.jsx(Q,{value:"paused",children:"Paused"}),e.jsx(Q,{value:"approved",children:"Approved"}),e.jsx(Q,{value:"rejected",children:"Rejected"}),e.jsx(Q,{value:"closed",children:"Closed"})]})]}),e.jsxs(Be,{value:a,onValueChange:D,children:[e.jsx(ze,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ve,{placeholder:"All Priority"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Priority"}),e.jsx(Q,{value:"express",children:"Express"}),e.jsx(Q,{value:"standard",children:"Standard"})]})]}),e.jsxs(Be,{value:r,onValueChange:R,children:[e.jsx(ze,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ve,{placeholder:"All Templates"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Custom"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"}),j&&e.jsx(Q,{value:"FORM_16",children:"Form 16"})]})]}),j&&r==="FORM_16"&&e.jsxs(e.Fragment,{children:[e.jsxs(Be,{value:y,onValueChange:N??(()=>{}),children:[e.jsx(ze,{className:"h-10","data-testid":"form16-financial-year-filter",children:e.jsx(Ve,{placeholder:"Financial Year"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Years"}),e.jsx(Q,{value:"2024-25",children:"2024-25"}),e.jsx(Q,{value:"2023-24",children:"2023-24"}),e.jsx(Q,{value:"2022-23",children:"2022-23"})]})]}),e.jsxs(Be,{value:w,onValueChange:S??(()=>{}),children:[e.jsx(ze,{className:"h-10","data-testid":"form16-quarter-filter",children:e.jsx(Ve,{placeholder:"Quarter"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Quarters"}),e.jsx(Q,{value:"Q1",children:"Q1"}),e.jsx(Q,{value:"Q2",children:"Q2"}),e.jsx(Q,{value:"Q3",children:"Q3"}),e.jsx(Q,{value:"Q4",children:"Q4"})]})]})]}),e.jsxs(Be,{value:n,onValueChange:v,disabled:g||u.length===0,children:[e.jsx(ze,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ve,{placeholder:g?"Loading...":"All Departments"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Departments"}),u.map(U=>e.jsx(Q,{value:U,children:U},U))]})]}),e.jsxs(Be,{value:i,onValueChange:P,children:[e.jsx(ze,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ve,{placeholder:"All SLA Status"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All SLA Status"}),e.jsx(Q,{value:"compliant",children:"Compliant"}),e.jsx(Q,{value:"on-track",children:"On Track"}),e.jsx(Q,{value:"approaching",children:"Approaching"}),e.jsx(Q,{value:"critical",children:"Critical"}),e.jsx(Q,{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(te,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:f.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:f.selectedUser.displayName||f.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:f.handleClear,children:e.jsx(bt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{placeholder:"Search initiator...",value:f.searchQuery,onChange:U=>f.handleSearch(U.target.value),onFocus:()=>{f.searchResults.length>0&&f.setShowResults(!0)},onBlur:()=>setTimeout(()=>f.setShowResults(!1),200),className:"h-10","data-testid":"initiator-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(U=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(U),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:U.displayName||U.email}),U.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:U.email})]})},U.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(te,{className:"text-sm font-medium text-gray-700",children:"Approver"}),o!=="all"&&F&&e.jsxs(Be,{value:c,onValueChange:U=>F(U),children:[e.jsx(ze,{className:"h-7 w-32 text-xs",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Q,{value:"current",children:"Current Only"}),e.jsx(Q,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:b.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:b.selectedUser.displayName||b.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:b.handleClear,children:e.jsx(bt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{placeholder:"Search approver...",value:b.searchQuery,onChange:U=>b.handleSearch(U.target.value),onFocus:()=>{b.searchResults.length>0&&b.setShowResults(!0)},onBlur:()=>setTimeout(()=>b.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),b.showResults&&b.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:b.searchResults.map(U=>e.jsx("button",{type:"button",onClick:()=>b.handleSelect(U),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:U.displayName||U.email}),U.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:U.email})]})},U.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(dt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:d,onValueChange:U=>$(U),children:[e.jsx(ze,{className:"w-[160px] h-10",children:e.jsx(Ve,{placeholder:"Date Range"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Time"}),e.jsx(Q,{value:"today",children:"Today"}),e.jsx(Q,{value:"week",children:"This Week"}),e.jsx(Q,{value:"month",children:"This Month"}),e.jsx(Q,{value:"last7days",children:"Last 7 Days"}),e.jsx(Q,{value:"last30days",children:"Last 30 Days"}),e.jsx(Q,{value:"custom",children:"Custom Range"})]})]}),d==="custom"&&e.jsxs(ra,{open:x,onOpenChange:k,children:[e.jsx(na,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(dt,{className:"w-4 h-4"}),m&&p?`${et(m,"MMM d, yyyy")} - ${et(p,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Xs,{value:m||null,onChange:U=>{const B=U?new Date(U):void 0;B?(I==null||I(B),p&&B>p&&(T==null||T(B))):I==null||I(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"end-date",children:"End Date"}),e.jsx(Xs,{value:p||null,onChange:U=>{const B=U?new Date(U):void 0;B?(T==null||T(B),m&&B<m&&(I==null||I(B))):T==null||T(void 0)},minDate:m||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{size:"sm",onClick:z,disabled:!m||!p,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply Range"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>{k==null||k(!1),I==null||I(void 0),T==null||T(void 0),$("month")},children:"Cancel"})]})]})})]})]})]})})})}function p5({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:p=!1,handleGenerateConclusion:x,handleFinalizeConclusion:u,generationAttempts:g=0,generationFailed:f=!1,maxAttemptsReached:b=!1}){var S,A,_,D,R,v,P,C,V;if(!Hn(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 j=i0(s);if(!j)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 y=l0(s,a),w=o0(y),N={name:((S=s.initiator)==null?void 0:S.name)||((A=s.initiator)==null?void 0:A.displayName)||((_=s.initiator)==null?void 0:_.email)||"Unknown",role:((D=s.initiator)==null?void 0:D.role)||((R=s.initiator)==null?void 0:R.designation)||"Initiator",department:((v=s.initiator)==null?void 0:v.department)||s.department||"",email:((P=s.initiator)==null?void 0:P.email)||"N/A",phone:((C=s.initiator)==null?void 0:C.phone)||((V=s.initiator)==null?void 0:V.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(VT,{activityInfo:j.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(zT,{dealerInfo:j.dealerInfo}),w.showProposalDetails&&j.proposalDetails&&e.jsx(WT,{proposalDetails:j.proposalDetails}),e.jsx(GT,{initiatorInfo:N}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2 text-base",children:[e.jsx(Le,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(ve,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(ee,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Es,{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 ",gs(s.closureDate)]}),e.jsxs("span",{children:["By ",N.name]})]})]})]}),l&&e.jsxs(Z,{"data-testid":"conclusion-remark-card",children:[e.jsx(oe,{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(me,{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(Le,{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(ve,{className:"mt-1 text-xs sm:text-sm",children:((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"This request was rejected. Please review the AI-generated closure remark and finalize it to close this request.":"All approvals are complete. Please review and finalize the conclusion to close this request."})]}),x&&e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:x,disabled:d||b,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx($t,{className:`w-3.5 h-3.5 ${d?"animate-spin":""}`}),p?"Regenerate":"Generate with AI"]}),p&&!b&&!f&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-g," attempts remaining"]})]})]})}),e.jsx(ee,{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(Xe,{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"}),p&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),c&&e.jsx(Jn,{value:o,onChange:F=>c(F),placeholder:"Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals...",className:"text-sm",minHeight:"160px","data-testid":"conclusion-remark-textarea"}),e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"This will be the final summary for this request"}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":"character-count",children:[o?o.replace(/<[^>]*>/g,"").length:0," / 2000 characters"]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-blue-900 mb-1.5",children:"Finalizing this request will:"}),e.jsxs("ul",{className:"text-xs sm:text-sm text-blue-800 space-y-0.5 pl-4",children:[e.jsx("li",{className:"list-disc",children:'Change request status to "CLOSED"'}),e.jsx("li",{className:"list-disc",children:"Notify all participants of closure"}),e.jsx("li",{className:"list-disc",children:"Move request to Closed Requests"}),e.jsx("li",{className:"list-disc",children:"Save conclusion remark permanently"})]})]}),u&&e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(E,{onClick:u,disabled:m||!o.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function g5({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]=h.useState(""),[p,x]=h.useState(!1),[u,g]=h.useState(null),f=async()=>{if(!d.trim()){X.error("Please provide approval comments");return}try{x(!0),g("approve"),await a(d),j(),s()}catch(w){console.error("Failed to approve request:",w),X.error("Failed to approve request. Please try again.")}finally{x(!1),g(null)}},b=async()=>{if(!d.trim()){X.error("Please provide rejection reason");return}try{x(!0),g("reject"),await r(d),j(),s()}catch(w){console.error("Failed to reject request:",w),X.error("Failed to reject request. Please try again.")}finally{x(!1),g(null)}},j=()=>{m(""),g(null)},y=()=>{p||(j(),s())};return t?e.jsx(jt,{open:t,onOpenChange:y,children:e.jsxs(xt,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(yt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(ht,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(Le,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(Ut,{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(Ie,{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(zs,{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(Es,{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(Os,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:d,onChange:w=>m(w.target.value),className:"min-h-[80px] lg:min-h-[90px] text-xs lg:text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[d.length," characters"]})]}),!d.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2",children:[e.jsx(St,{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(Et,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end px-6 pb-6 pt-3 lg:pt-4 flex-shrink-0 border-t bg-gray-50",children:[e.jsx(E,{variant:"outline",onClick:y,disabled:p,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{onClick:b,disabled:!d.trim()||p,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:p&&u==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(St,{className:"w-4 h-4 mr-2"}),"Reject"]})}),e.jsx(E,{onClick:f,disabled:!d.trim()||p,className:"bg-green-600 hover:bg-green-700 text-white",children:p&&u==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function f5({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:c,dueDate:d,taxationType:m}){const[p,x]=h.useState(!1),[u,g]=h.useState(!1),f=m==="Non GST"||m==="Non-GST",b=(n==null?void 0:n.creditNoteNumber)&&(n==null?void 0:n.creditNoteNumber)!=="",j=(n==null?void 0:n.creditNoteNumber)||"",y=n!=null&&n.creditNoteDate?gs(n.creditNoteDate,{includeTime:!1,format:"short"}):"",w=(n==null?void 0:n.creditNoteAmount)||0,N=(n==null?void 0:n.status)||"PENDING",S=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",A=(i==null?void 0:i.dealerCode)||"RE-JP-009",_=l||"Activity",D=o||"RE-REQ-2024-CM-101",R=d?gs(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",v=async()=>{if(a)try{x(!0),await a(),X.success("Credit note downloaded successfully")}catch(V){console.error("Failed to download credit note:",V),X.error("Failed to download credit note. Please try again.")}finally{x(!1)}else X.info("Credit note will be automatically saved to Documents tab")},P=async()=>{if(r)try{g(!0),await r(),X.success("Credit note sent to dealer successfully"),s()}catch(V){console.error("Failed to send credit note to dealer:",V),X.error("Failed to send credit note. Please try again.")}finally{g(!1)}else X.info("Email notification will be sent to dealer with credit note attachment")},C=V=>`₹${V.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(xt,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(yt,{children:[e.jsxs(ht,{className:"font-semibold flex items-center gap-2 text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note from SAP"]}),m&&e.jsx(se,{className:`ml-2 border-none shadow-sm ${f?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:f?"Non-GST Claim":"GST Claim"})]}),e.jsx(Ut,{className:"text-base",children:"Review and send credit note to dealer"})]}),e.jsxs("div",{className:"space-y-5 py-4",children:[b?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(se,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),N==="APPROVED"?"Approved":N==="ISSUED"?"Issued":N==="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(te,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Sb,{className:"w-3 h-3"}),"Credit Note Number"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1 text-lg",children:j})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(te,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(dt,{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(te,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-3",children:[e.jsx(Ha,{className:"w-4 h-4"}),"Credit Note Amount"]}),e.jsx("p",{className:"text-4xl font-bold text-blue-700",children:C(w)})]})]}):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(Pt,{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(Zi,{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(te,{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:S})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(te,{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:A})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(te,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Activity"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:_})]})]})]}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:[e.jsxs("h3",{className:"font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(Ie,{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(te,{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:D})]}),e.jsxs("div",{children:[e.jsx(te,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Due Date"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:R})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Ie,{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(Et,{className:"flex-col-reverse gap-2 sm:flex-row flex items-center justify-between sm:justify-between",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:p||u,className:"border-2",children:"Close"}),e.jsx("div",{className:"flex gap-2",children:b&&e.jsxs(e.Fragment,{children:[e.jsxs(E,{variant:"outline",onClick:v,disabled:p||u,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),p?"Downloading...":"Download"]}),e.jsxs(E,{onClick:P,disabled:p||u,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(ch,{className:"w-4 h-4 mr-2"}),u?"Sending...":"Send to Dealer"]})]})})]})]})})}const Kr=(t,s)=>{if(!t)return{isValid:!0,message:""};const a=t.trim();if(!/^\d+$/.test(a))return{isValid:!1,message:"Code must contain only digits"};if(s){if(!a.startsWith("99"))return{isValid:!1,message:"SAC (Service) code must start with 99"};if(a.length!==6)return{isValid:!1,message:"SAC code must be exactly 6 digits"}}else{if(![4,6,8].includes(a.length))return{isValid:!1,message:"HSN code must be 4, 6, or 8 digits"};if(a.startsWith("99"))return{isValid:!1,message:"HSN code should not start with 99 (use SAC type for services)"}}return{isValid:!0,message:""}},b5={"01":"Jammu and Kashmir","02":"Himachal Pradesh","03":"Punjab","04":"Chandigarh","05":"Uttarakhand","06":"Haryana","07":"Delhi","08":"Rajasthan","09":"Uttar Pradesh",10:"Bihar",11:"Sikkim",12:"Arunachal Pradesh",13:"Nagaland",14:"Manipur",15:"Mizoram",16:"Tripura",17:"Meghalaya",18:"Assam",19:"West Bengal",20:"Jharkhand",21:"Odisha",22:"Chhattisgarh",23:"Madhya Pradesh",24:"Gujarat",25:"Daman and Diu",26:"Dadra and Nagar Haveli",27:"Maharashtra",29:"Karnataka",30:"Goa",31:"Lakshadweep Islands",32:"Kerala",33:"Tamil Nadu",34:"Pondicherry",35:"Andaman and Nicobar",36:"Telangana",37:"Andhra Pradesh",38:"Ladakh",97:"Others"},j5="33",y5=new Set(["04","25","26","31","35","38"]),h0=t=>{if(!t||t.length<2)return null;const s=t.substring(0,2);return b5[s]?s:null},v5=t=>t?y5.has(t):!1,N5=t=>t?t!==j5:!1,p0=t=>{if(!t)return{isIGST:!1,isCGST:!0,isSGST:!0,isUTGST:!1};if(N5(t))return{isIGST:!0,isCGST:!1,isSGST:!1,isUTGST:!1};const a=v5(t);return{isIGST:!1,isCGST:!0,isSGST:!a,isUTGST:a}};function w5({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",dealerGSTIN:n,activityName:i="Activity",requestId:l,defaultGstRate:o=18,documentPolicy:c,taxationType:d}){var we,Ae;const[m,p]=h.useState(""),[x,u]=h.useState(""),g=h.useMemo(()=>{const ne=h0(n);return p0(ne)},[n]),f=h.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),[b,j]=h.useState([]),[y,w]=h.useState([]),[N,S]=h.useState([]),[A,_]=h.useState([]),[D,R]=h.useState(null),[v,P]=h.useState(""),[C,V]=h.useState(!1),[F,$]=h.useState(null),I=h.useRef(null),T=h.useRef(null),k=h.useRef(null),z=h.useRef(null),L=ne=>{const q=ne.type.toLowerCase(),de=ne.name.toLowerCase();return q.includes("image")||q.includes("pdf")||de.endsWith(".pdf")||de.endsWith(".jpg")||de.endsWith(".jpeg")||de.endsWith(".png")||de.endsWith(".gif")||de.endsWith(".webp")};h.useEffect(()=>()=>{F!=null&&F.url&&URL.revokeObjectURL(F.url)},[F]),h.useEffect(()=>{b.length===0&&j([{id:"1",description:"",amount:0,gstRate:o||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},[o]);const M=ne=>{if(!L(ne)){X.error("Preview is only available for images and PDF files");return}F!=null&&F.url&&URL.revokeObjectURL(F.url);const q=URL.createObjectURL(ne);$({file:ne,url:q})},U=ne=>{const q=URL.createObjectURL(ne),de=document.createElement("a");de.href=q,de.download=ne.name,document.body.appendChild(de),de.click(),document.body.removeChild(de),URL.revokeObjectURL(q)},B=h.useMemo(()=>b.reduce((ne,q)=>ne+(q.totalAmt||q.amount||0),0),[b]),W=(ne,q,de=1)=>{const Ye=ne*de,fe=Ye*(q.cgstRate||0)/100,ye=Ye*(q.sgstRate||0)/100,Ue=Ye*(q.utgstRate||0)/100,nt=Ye*(q.igstRate||0)/100,mt=fe+ye+Ue+nt,vt=Ye+mt;return{cgstRate:q.cgstRate,cgstAmt:fe,sgstRate:q.sgstRate,sgstAmt:ye,utgstRate:q.utgstRate,utgstAmt:Ue,igstRate:q.igstRate,igstAmt:nt,gstAmt:mt,gstRate:(q.cgstRate||0)+(q.sgstRate||0)+(q.utgstRate||0)+(q.igstRate||0),totalAmt:vt}},J=h.useMemo(()=>{const ne=m!=="",q=y.length>0,de=N.length>0,Ye=v.trim().length>0,fe=f?!1:b.some(ye=>{const{isValid:Ue}=Kr(ye.hsnCode,ye.isService);return!Ue});return ne&&q&&de&&Ye&&!fe},[m,y,N,v,f,b]),O=new Date().toISOString().split("T")[0],H=()=>{j([...b,{id:Date.now().toString(),description:"",amount:0,gstRate:o||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},Y=(ne,q,de)=>{j(b.map(Ye=>{if(Ye.id===ne){let fe={...Ye,[q]:de};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate","quantity"].includes(q)){const ye=q==="amount"?parseFloat(de)||0:Ye.amount,Ue=q==="quantity"?parseInt(de)||1:Ye.quantity;let nt=Ye.cgstRate,mt=Ye.sgstRate,vt=Ye.utgstRate,xs=Ye.igstRate;if(q==="cgstRate"){if(!g.isCGST)return Ye;nt=parseFloat(de)||0,g.isUTGST?(vt=nt,mt=0):(mt=nt,vt=0),xs=0}else if(q==="sgstRate"){if(!g.isSGST)return Ye;mt=parseFloat(de)||0,nt=mt,vt=0,xs=0}else if(q==="utgstRate"){if(!g.isUTGST)return Ye;vt=parseFloat(de)||0,nt=vt,mt=0,xs=0}else if(q==="igstRate"){if(!g.isIGST)return Ye;xs=parseFloat(de)||0,nt=0,mt=0,vt=0}else if(q==="gstRate"){const De=parseFloat(de)||0;g.isIGST?(xs=De,nt=0,mt=0,vt=0):(nt=De/2,g.isUTGST?(vt=De/2,mt=0):(mt=De/2,vt=0),xs=0)}const le=W(ye,{cgstRate:nt,sgstRate:mt,igstRate:xs,utgstRate:vt},Ue);return{...fe,amount:ye,quantity:Ue,...le}}return fe}return Ye}))},re=ne=>{j(b.filter(q=>q.id!==ne))},K=ne=>{const q=Array.from(ne.target.files||[]);if(q.length>0){const de=[],Ye=c.maxFileSizeMB*1024*1024,fe=[".pdf",".doc",".docx",".zip",".rar"];q.forEach(ye=>{var mt,vt;const Ue="."+((mt=ye.name.split(".").pop())==null?void 0:mt.toLowerCase()),nt=((vt=ye.name.split(".").pop())==null?void 0:vt.toLowerCase())||"";if(ye.size>Ye){X.error(`"${ye.name}" exceeds ${c.maxFileSizeMB}MB limit and was not added.`);return}if(!fe.includes(Ue)){X.error(`"${ye.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!c.allowedFileTypes.includes(nt)){X.error(`"${ye.name}" has an unallowed file type according to system policy.`);return}de.push(ye)}),de.length>0&&w([...y,...de]),I.current&&(I.current.value="")}},ae=ne=>{w(y.filter((q,de)=>de!==ne))},Ne=ne=>{const q=Array.from(ne.target.files||[]);if(q.length>0){const de=[],Ye=c.maxFileSizeMB*1024*1024;q.forEach(fe=>{var Ue;const ye=((Ue=fe.name.split(".").pop())==null?void 0:Ue.toLowerCase())||"";if(fe.size>Ye){X.error(`Photo "${fe.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!fe.type.startsWith("image/")){X.error(`"${fe.name}" is not an image file.`);return}if(!c.allowedFileTypes.includes(ye)){X.error(`"${fe.name}" has an unsupported image format.`);return}de.push(fe)}),de.length>0&&S([...N,...de]),T.current&&(T.current.value="")}},Se=ne=>{S(N.filter((q,de)=>de!==ne))},Ge=ne=>{const q=Array.from(ne.target.files||[]);if(q.length>0){const de=[],Ye=c.maxFileSizeMB*1024*1024,fe=[".pdf",".jpg",".jpeg",".png"];q.forEach(ye=>{var mt,vt;const Ue="."+((mt=ye.name.split(".").pop())==null?void 0:mt.toLowerCase()),nt=((vt=ye.name.split(".").pop())==null?void 0:vt.toLowerCase())||"";if(ye.size>Ye){X.error(`Invoice "${ye.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!fe.includes(Ue)){X.error(`"${ye.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!c.allowedFileTypes.includes(nt)){X.error(`"${ye.name}" format is not allowed by system policy.`);return}de.push(ye)}),de.length>0&&_([...A,...de]),k.current&&(k.current.value="")}},Je=ne=>{_(A.filter((q,de)=>de!==ne))},Pe=ne=>{var de,Ye,fe;const q=(de=ne.target.files)==null?void 0:de[0];if(q){const ye=c.maxFileSizeMB*1024*1024,Ue=[".pdf",".xlsx",".xls",".csv"],nt="."+((Ye=q.name.split(".").pop())==null?void 0:Ye.toLowerCase()),mt=((fe=q.name.split(".").pop())==null?void 0:fe.toLowerCase())||"";if(q.size>ye){X.error(`Attendance file exceeds ${c.maxFileSizeMB}MB limit.`),z.current&&(z.current.value="");return}if(!Ue.includes(nt)){X.error("Please upload PDF, Excel, or CSV files only"),z.current&&(z.current.value="");return}if(!c.allowedFileTypes.includes(mt)){X.error(`"${q.name}" format is not allowed by system policy.`),z.current&&(z.current.value="");return}R(q)}},Oe=async()=>{if(!J){X.error("Please fill all required fields");return}const ne=b.filter(de=>de.description.trim()!==""&&de.amount>0);if(!f&&ne.some(de=>de.description.trim()!==""&&de.amount>0&&(de.gstRate===0||!de.gstRate))&&!window.confirm(`One or more expenses have 0% GST. Are you sure you want to proceed?
|
||
|
||
Note: If these items are taxable, please provide a valid GST rate to ensure correct E-Invoice generation.`)){V(!1);return}try{V(!0),await a({activityCompletionDate:m,numberOfParticipants:x?parseInt(x):void 0,closedExpenses:ne,totalClosedExpenses:B,completionDocuments:y,activityPhotos:N,invoicesReceipts:A.length>0?A:void 0,attendanceSheet:D||void 0,completionDescription:v}),ie(),s()}catch(de){console.error("Failed to submit completion documents:",de),zc(de)||X.error("Failed to submit completion documents. Please try again.")}finally{V(!1)}},ie=()=>{F!=null&&F.url&&URL.revokeObjectURL(F.url),$(null),p(""),u(""),j([{id:"1",description:"",amount:0,gstRate:o||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),w([]),S([]),_([]),R(null),P(""),I.current&&(I.current.value=""),T.current&&(T.current.value=""),k.current&&(k.current.value=""),z.current&&(z.current.value="")},pe=()=>{C||(ie(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(jt,{open:t,onOpenChange:pe,children:e.jsxs(xt,{className:"dealer-completion-documents-modal overflow-hidden flex flex-col",children:[e.jsxs(yt,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs(ht,{className:"font-semibold flex items-center gap-2 text-xl sm:text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]"}),"Activity Completion Documents"]}),d&&e.jsx(se,{className:`ml-2 border-none shadow-sm ${d==="GST"?"bg-emerald-600 text-white hover:bg-emerald-700":"bg-indigo-600 text-white hover:bg-indigo-700"}`,children:d==="GST"?"GST Claim":"Non-GST Claim"})]}),e.jsx(Ut,{className:"text-sm sm:text-base",children:"Step 5: Upload completion proof and final documents"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs sm:text-sm text-gray-600",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",i]}),e.jsx("div",{className:"mt-2",children:"Please upload completion documents, photos, and provide details about the completed activity."})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-6 py-3",children:[e.jsxs("div",{className:"space-y-5 sm:space-y-6",children:[e.jsxs("div",{className:"space-y-1.5 sm:space-y-2",children:[e.jsxs(te,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(dt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Completion Date *"]}),e.jsx(Xs,{value:m||null,onChange:ne=>p(ne||""),maxDate:O,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.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h3",{className:"font-semibold text-base sm:text-lg",children:"Closed Expenses"})}),!f&&e.jsx("div",{className:"text-[10px] text-gray-500 italic mt-0.5",children:"Tax fields are automatically toggled based on the dealer's state (Inter-state vs Intra-state)."}),e.jsxs(E,{type:"button",onClick:H,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(bs,{className:"w-4 h-4 mr-1"}),"Add Expense"]})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 max-h-[400px] overflow-y-auto pr-1",children:b.map(ne=>e.jsxs("div",{className:"p-4 border rounded-lg bg-gray-50/50 space-y-4 relative group",children:[e.jsxs("div",{className:"flex gap-3 items-start w-full",children:[e.jsxs("div",{className:`${f?"flex-[3]":"flex-1"} min-w-0`,children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item description"}),e.jsx(ke,{placeholder:"e.g., Venue rental, Refreshments",value:ne.description,onChange:q=>Y(ne.id,"description",q.target.value),className:"w-full bg-white text-sm"})]}),f&&e.jsxs("div",{className:"w-28 sm:w-36 flex-shrink-0",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(ir,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(ke,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:ne.amount||"",onChange:q=>Y(ne.id,"amount",q.target.value),className:"w-full bg-white text-sm pl-8"})]})]}),!f&&e.jsxs("div",{className:"w-28 sm:w-36 flex-shrink-0",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(ir,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(ke,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:ne.amount||"",onChange:q=>Y(ne.id,"amount",q.target.value),className:"w-full bg-white text-sm pl-8"})]})]}),!f&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"w-20 sm:w-24 flex-shrink-0",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN/SAC Code"}),e.jsx(ke,{placeholder:"HSN/SAC Code",value:ne.hsnCode||"",onChange:q=>Y(ne.id,"hsnCode",q.target.value),className:`w-full bg-white text-sm ${Kr(ne.hsnCode,ne.isService).isValid?"":"border-red-500 focus-visible:ring-red-500"}`}),!Kr(ne.hsnCode,ne.isService).isValid&&e.jsx("span",{className:"text-[9px] text-red-500 mt-1 block leading-tight",children:Kr(ne.hsnCode,ne.isService).message})]}),e.jsxs("div",{className:"w-24 sm:w-28 flex-shrink-0",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item Type"}),e.jsxs("select",{value:ne.isService?"SAC":"HSN",onChange:q=>Y(ne.id,"isService",q.target.value==="SAC"),className:"flex h-9 w-full rounded-md border border-input bg-white px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx("option",{value:"HSN",children:"HSN (Goods)"}),e.jsx("option",{value:"SAC",children:"SAC (Service)"})]})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"CGST %"}),e.jsx(ke,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ne.cgstRate||"",onChange:q=>Y(ne.id,"cgstRate",q.target.value),disabled:!g.isCGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"SGST %"}),e.jsx(ke,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ne.sgstRate||"",onChange:q=>Y(ne.id,"sgstRate",q.target.value),disabled:!g.isSGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"UTGST %"}),e.jsx(ke,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ne.utgstRate||"",onChange:q=>Y(ne.id,"utgstRate",q.target.value),disabled:!g.isUTGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"IGST %"}),e.jsx(ke,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ne.igstRate||"",onChange:q=>Y(ne.id,"igstRate",q.target.value),disabled:!g.isIGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]})]}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"mt-5 hover:bg-red-100 hover:text-red-700 flex-shrink-0 h-9 w-9 p-0",onClick:()=>re(ne.id),children:e.jsx(bt,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:`grid grid-cols-2 sm:grid-cols-5 gap-3 pt-3 border-t border-dashed border-gray-200 ${f?"items-center":""}`,children:[f?e.jsx("div",{className:"col-span-4 invisible"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-gray-500 font-medium",children:[e.jsxs("span",{children:["CGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(ne.cgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),ne.sgstAmt>0&&e.jsxs("span",{children:["SGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(ne.sgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),ne.utgstAmt>0&&e.jsxs("span",{children:["UTGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(ne.utgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs("span",{children:["IGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(ne.igstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 items-center sm:justify-end",children:[e.jsxs("span",{className:"text-gray-500",children:["GST Total: ",e.jsxs("span",{className:"text-gray-900 font-bold",children:["₹",(ne.gstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs(se,{className:"bg-[#2d4a3e] text-white px-3 py-1 text-xs",children:["Item Total: ₹",(ne.totalAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]}),e.jsxs("div",{className:"flex flex-col items-end",children:[e.jsx("span",{className:"text-[10px] text-gray-500 uppercase",children:"Item Total"}),e.jsxs("span",{className:"text-sm font-bold text-[#2d4a3e]",children:["₹",(ne.amount||0).toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]})]},ne.id))}),b.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.'}),b.length>0&&B>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:["₹",B.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(se,{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(te,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Ie,{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 ${y.length>0?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:I,type:"file",multiple:!0,accept:[".pdf",".doc",".docx",".zip",".rar"].filter(ne=>c.allowedFileTypes.includes(ne.replace(".",""))).join(","),className:"hidden",id:"completionDocs",onChange:K}),e.jsx("label",{htmlFor:"completionDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:y.length>0?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"w-8 h-8 text-green-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-green-700",children:[y.length," document",y.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(js,{className:"w-8 h-8 text-gray-400"}),e.jsxs("span",{className:"text-sm text-gray-600",children:["Click to upload documents (Max ",c.maxFileSizeMB,"MB)"]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"PDF, DOC, ZIP allowed"})]})})]}),y.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",y.length,"):"]}),y.map((ne,q)=>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(Ie,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-green-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:ne.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[L(ne)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>M(ne),title:"Preview file",children:e.jsx(Ct,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>U(ne),title:"Download file",children:e.jsx(kt,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>ae(q),title:"Remove document",children:e.jsx(bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},q))]})]}),e.jsxs("div",{children:[e.jsxs(te,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(pi,{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 ${N.length>0?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:T,type:"file",multiple:!0,accept:[".jpg",".jpeg",".png",".gif",".webp"].filter(ne=>c.allowedFileTypes.includes(ne.replace(".",""))).join(","),className:"hidden",id:"completionPhotos",onChange:Ne}),e.jsx("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:N.length>0?e.jsxs(e.Fragment,{children:[e.jsx(us,{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:[N.length," photo",N.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(pi,{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)"})]})})]}),N.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Photos (",N.length,"):"]}),N.map((ne,q)=>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(pi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-green-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:ne.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[L(ne)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>M(ne),title:"Preview photo",children:e.jsx(Ct,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>U(ne),title:"Download photo",children:e.jsx(kt,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>Se(q),title:"Remove photo",children:e.jsx(bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},q))]})]})]})]}),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(se,{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(te,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Pt,{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 ${A.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:k,type:"file",multiple:!0,accept:[".pdf",".jpg",".jpeg",".png"].filter(ne=>c.allowedFileTypes.includes(ne.replace(".",""))).join(","),className:"hidden",id:"invoiceReceipts",onChange:Ge}),e.jsx("label",{htmlFor:"invoiceReceipts",className:"cursor-pointer flex flex-col items-center gap-2",children:A.length>0?e.jsxs(e.Fragment,{children:[e.jsx(us,{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:[A.length," document",A.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(Pt,{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)"})]})})]}),A.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 (",A.length,"):"]}),A.map((ne,q)=>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(Pt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:ne.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[L(ne)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>M(ne),title:"Preview file",children:e.jsx(Ct,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>U(ne),title:"Download file",children:e.jsx(kt,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>Je(q),title:"Remove document",children:e.jsx(bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},q))]})]}),e.jsxs("div",{children:[e.jsx(te,{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 ${D?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:z,type:"file",accept:[".pdf",".xlsx",".xls",".csv"].filter(ne=>c.allowedFileTypes.includes(ne.replace(".",""))).join(","),className:"hidden",id:"attendanceDoc",onChange:Pe}),e.jsx("label",{htmlFor:"attendanceDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:D?e.jsxs(e.Fragment,{children:[e.jsx(us,{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:D.name}),e.jsx("span",{className:"text-xs text-blue-600",children:"Document selected"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(js,{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)"})]})})]}),D&&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(Ie,{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:D.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[L(D)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>M(D),title:"Preview file",children:e.jsx(Ct,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>U(D),title:"Download file",children:e.jsx(kt,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>{R(null),z.current&&(z.current.value="")},title:"Remove document",children:e.jsx(bt,{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(te,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(Os,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:v,onChange:ne=>P(ne.target.value),className:"min-h-[100px] sm:min-h-[120px] text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[v.length," characters"]})]}),!J&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 sm:p-4 flex items-start gap-2 sm:gap-3",children:[e.jsx(Ze,{className:"w-4 h-4 sm:w-5 sm:h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs sm:text-sm text-amber-800",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Missing Required Information"}),e.jsx("p",{children:"Please ensure completion date, at least one document/photo, and description are provided before submitting."})]})]})]}),e.jsxs(Et,{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pt-3 pb-6 border-t flex-shrink-0",children:[e.jsx(E,{variant:"outline",onClick:pe,disabled:C,className:"border-2",children:"Cancel"}),e.jsx(E,{onClick:Oe,disabled:C||!J,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:C?"Submitting...":"Submit Documents"})]})]})}),F&&e.jsx(jt,{open:!!F,onOpenChange:()=>{F!=null&&F.url&&URL.revokeObjectURL(F.url),$(null)},children:e.jsx(xt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(yt,{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(Ct,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ht,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:F.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[F.file.type||"Unknown type"," • ",(F.file.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>U(F.file),className:"gap-2 h-9",children:[e.jsx(kt,{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:(we=F.file.type)!=null&&we.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:F.url,alt:F.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(Ae=F.file.type)!=null&&Ae.includes("pdf")||F.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:F.url,className:"w-full h-full rounded-lg border-0",title:F.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(Ct,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),e.jsxs(E,{onClick:()=>U(F.file),className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",F.file.name]})]})})]})})})]})}function C5({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",dealerGSTIN:n,activityName:i="Activity",requestId:l,previousProposalData:o,defaultGstRate:c=18,documentPolicy:d,taxationType:m,totalBlockedAmount:p=0}){const[x,u]=h.useState(null),g=h.useMemo(()=>{const ie=h0(n);return p0(ie)},[n]),f=h.useMemo(()=>m==="Non GST"||m==="Non-GST",[m]),[b,j]=h.useState([{id:"1",description:"",amount:0,gstRate:c||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),y=(ie,pe,we=1)=>{const Ae=ie*we,ne=Ae*(pe.cgstRate||0)/100,q=Ae*(pe.sgstRate||0)/100,de=Ae*(pe.utgstRate||0)/100,Ye=Ae*(pe.igstRate||0)/100,fe=ne+q+de+Ye,ye=Ae+fe;return{cgstRate:pe.cgstRate,cgstAmt:ne,sgstRate:pe.sgstRate,sgstAmt:q,utgstRate:pe.utgstRate,utgstAmt:de,igstRate:pe.igstRate,igstAmt:Ye,gstAmt:fe,gstRate:(pe.cgstRate||0)+(pe.sgstRate||0)+(pe.utgstRate||0)+(pe.igstRate||0),totalAmt:ye}},[w,N]=h.useState("date"),[S,A]=h.useState(""),[_,D]=h.useState(""),[R,v]=h.useState([]),[P,C]=h.useState(""),[V,F]=h.useState(!1),[$,I]=h.useState(null),[T,k]=h.useState(!1),z=h.useRef(null),L=h.useRef(null),M=ie=>{if(!ie)return!1;const pe=ie.toLowerCase();return pe.endsWith(".pdf")||!!pe.match(/\.(jpg|jpeg|png|gif|webp)$/i)},U=ie=>M(ie.name);h.useEffect(()=>()=>{$!=null&&$.fileUrl&&$.fileUrl.startsWith("blob:")&&URL.revokeObjectURL($.fileUrl)},[$]);const B=ie=>{if(!U(ie)){X.error("Preview is only available for images and PDF files");return}$!=null&&$.fileUrl&&$.fileUrl.startsWith("blob:")&&URL.revokeObjectURL($.fileUrl);const pe=URL.createObjectURL(ie);I({fileName:ie.name,fileType:ie.type,documentId:"",fileUrl:pe,fileSize:ie.size})},W=ie=>{const pe=ie.originalFileName||ie.fileName||ie.name||"Document",we=ie.documentId||ie.id||"",Ae=pe.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let ne="";if(we)ne=mn(we);else if(ne=ie.storageUrl||ie.documentUrl||"",ne&&!ne.startsWith("http")){const q="https://reflow-uat.royalenfield.com",de=q.endsWith("/")?q.slice(0,-1):q,Ye=ne.startsWith("/")?ne:`/${ne}`;ne=`${de}${Ye}`}I({fileName:pe,fileType:Ae,documentId:we,fileUrl:ne})},J=ie=>{const pe=URL.createObjectURL(ie),we=document.createElement("a");we.href=pe,we.download=ie.name,document.body.appendChild(we),we.click(),document.body.removeChild(we),URL.revokeObjectURL(pe)};h.useEffect(()=>{if(t&&o){const ie=p>0;if(o.costItems&&o.costItems.length>0){const pe=o.costItems.map((we,Ae)=>({id:`original-${Ae}`,description:we.itemDescription||we.description||"",amount:Number(we.amount)||0,quantity:Number(we.quantity)||1,hsnCode:we.hsnCode||"",isService:!!we.isService,gstRate:Number(we.gstRate)||c,cgstRate:Number(we.cgstRate)||0,sgstRate:Number(we.sgstRate)||0,utgstRate:Number(we.utgstRate)||0,igstRate:Number(we.igstRate)||0,gstAmt:Number(we.gstAmt)||0,cgstAmt:Number(we.cgstAmt)||0,sgstAmt:Number(we.sgstAmt)||0,utgstAmt:Number(we.utgstAmt)||0,igstAmt:Number(we.igstAmt)||0,cessRate:Number(we.cessRate)||0,cessAmt:Number(we.cessAmt)||0,totalAmt:Number(we.totalAmt)||0,isOriginal:ie}));j(pe)}o.expectedCompletionDate&&(A(o.expectedCompletionDate.split("T")[0]),N("date"))}else t&&!o&&(j([{id:"1",description:"",amount:0,gstRate:c||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),A(""),C(""))},[t,o,c,p]);const O=h.useMemo(()=>b.reduce((ie,pe)=>ie+(pe.totalAmt||pe.amount||0),0),[b]),H=h.useMemo(()=>{const ie=x!==null,pe=b.length>0&&b.every(q=>q.description.trim()!==""&&q.amount>0),we=w==="date"?S!=="":_!==""&&parseInt(_)>0,Ae=P.trim().length>0,ne=f?!1:b.some(q=>{const{isValid:de}=Kr(q.hsnCode,q.isService);return!de});return ie&&pe&&we&&Ae&&!ne},[x,b,w,S,_,P,f]),Y=ie=>{var we,Ae,ne;const pe=(we=ie.target.files)==null?void 0:we[0];if(pe){const q=d.maxFileSizeMB*1024*1024;if(pe.size>q){X.error(`File size exceeds the maximum allowed size of ${d.maxFileSizeMB}MB. Current size: ${(pe.size/(1024*1024)).toFixed(2)}MB`),z.current&&(z.current.value="");return}const de=[".pdf",".doc",".docx"],Ye="."+((Ae=pe.name.split(".").pop())==null?void 0:Ae.toLowerCase()),fe=((ne=pe.name.split(".").pop())==null?void 0:ne.toLowerCase())||"";if(!de.includes(Ye)||!d.allowedFileTypes.includes(fe)){X.error("Please upload a valid PDF, DOC, or DOCX file as per system policy"),z.current&&(z.current.value="");return}u(pe)}},re=ie=>{const pe=Array.from(ie.target.files||[]),we=[],Ae=d.maxFileSizeMB*1024*1024;pe.forEach(ne=>{var de;if(ne.size>Ae){X.error(`"${ne.name}" exceeds ${d.maxFileSizeMB}MB limit and was not added.`);return}const q=((de=ne.name.split(".").pop())==null?void 0:de.toLowerCase())||"";if(!d.allowedFileTypes.includes(q)){X.error(`"${ne.name}" has an unsupported file type and was not added.`);return}we.push(ne)}),we.length>0&&v(ne=>[...ne,...we]),L.current&&(L.current.value="")},K=()=>{j(ie=>[...ie,{id:Date.now().toString(),description:"",amount:0,gstRate:c||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},ae=ie=>{b.length>1&&j(pe=>pe.filter(we=>we.id!==ie))},Ne=(ie,pe,we)=>{j(Ae=>Ae.map(ne=>{if(ne.id===ie){let q={...ne,[pe]:we};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate"].includes(pe)){const de=pe==="amount"?parseFloat(we)||0:ne.amount,Ye=1;let fe=ne.cgstRate,ye=ne.sgstRate,Ue=ne.utgstRate,nt=ne.igstRate;if(pe==="cgstRate"){if(!g.isCGST)return ne;fe=parseFloat(we)||0,g.isUTGST?(Ue=fe,ye=0):(ye=fe,Ue=0),nt=0}else if(pe==="sgstRate"){if(!g.isSGST)return ne;ye=parseFloat(we)||0,fe=ye,Ue=0,nt=0}else if(pe==="utgstRate"){if(!g.isUTGST)return ne;Ue=parseFloat(we)||0,fe=Ue,ye=0,nt=0}else if(pe==="igstRate"){if(!g.isIGST)return ne;nt=parseFloat(we)||0,fe=0,ye=0,Ue=0}else if(pe==="gstRate"){const vt=parseFloat(we)||0;g.isIGST?(nt=vt,fe=0,ye=0,Ue=0):(fe=vt/2,g.isUTGST?(Ue=vt/2,ye=0):(ye=vt/2,Ue=0),nt=0)}const mt=y(de,{cgstRate:fe,sgstRate:ye,igstRate:nt,utgstRate:Ue},Ye);return{...q,amount:de,quantity:Ye,...mt}}return q}return ne}))},Se=ie=>{v(pe=>pe.filter((we,Ae)=>Ae!==ie))},Ge=async()=>{if(!H){X.error("Please fill all required fields");return}let ie=S||"";if(w==="days"&&_){const pe=parseInt(_),we=new Date;we.setDate(we.getDate()+pe),ie=we.toISOString().split("T")[0]}try{if(F(!0),!f&&b.some(ne=>ne.description.trim()!==""&&ne.amount>0&&(ne.gstRate===0||!ne.gstRate))&&!window.confirm(`One or more items have 0% GST. Are you sure you want to proceed?
|
||
|
||
Note: If these items are taxable, please provide a valid GST rate to ensure correct E-Invoice generation.`)){F(!1);return}const we=p>0,Ae=b.filter(ne=>ne.description.trim()!==""&&ne.amount>0).map(ne=>({...ne,description:o&&we&&!ne.isOriginal?`[ADDITIONAL] ${ne.description}`:ne.description}));await a({proposalDocument:x,costBreakup:Ae,totalEstimatedBudget:O,expectedCompletionDate:ie,timelineMode:w,expectedCompletionDays:w==="days"?parseInt(_):0,otherDocuments:R,dealerComments:P}),Je(),s()}catch(pe){console.error("Failed to submit proposal:",pe),zc(pe)||X.error("Failed to submit proposal. Please try again.")}finally{F(!1)}},Je=()=>{$!=null&&$.fileUrl&&$.fileUrl.startsWith("blob:")&&URL.revokeObjectURL($.fileUrl),I(null),u(null),j([{id:"1",description:"",amount:0,gstRate:0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),N("date"),A(""),D(""),v([]),C(""),z.current&&(z.current.value=""),L.current&&(L.current.value="")},Pe=()=>{V||(Je(),s())},Oe=new Date().toISOString().split("T")[0];return e.jsxs(jt,{open:t,onOpenChange:Pe,children:[e.jsxs(xt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(yt,{className:"flex-shrink-0 pb-3 lg:pb-4",children:[e.jsxs(ht,{className:"flex items-center gap-2 text-xl lg:text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-5 h-5 lg:w-6 lg:h-6 text-[--re-green]"}),"Dealer Proposal Submission"]}),m&&e.jsx(se,{className:`ml-2 border-none shadow-sm ${m==="GST"?"bg-emerald-600 text-white hover:bg-emerald-700":"bg-indigo-600 text-white hover:bg-indigo-700"}`,children:m==="GST"?"GST Claim":"Non-GST Claim"})]}),e.jsx(Ut,{className:"text-sm lg:text-base",children:"Step 1: Upload proposal and planning details"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs lg:text-sm text-gray-600",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",i]})]}),e.jsx("div",{className:"mt-1",children:"Please upload proposal document, provide cost breakdown, timeline, and detailed comments."})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden min-h-0 py-3 lg:py-4",children:[o&&e.jsx("div",{className:"mb-6 mx-1",children:e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg overflow-hidden cursor-pointer hover:bg-amber-100/50 transition-colors",onClick:()=>k(!T),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(Ie,{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(se,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(o.totalEstimatedBudget||o.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:T?e.jsx(Vo,{className:"w-4 h-4"}):e.jsx(bs,{className:"w-4 h-4"})})]}),T&&e.jsxs("div",{className:"px-4 pb-4 border-t border-amber-200 space-y-4 bg-white/50",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-xs",children:[o.expectedCompletionDate&&e.jsxs("div",{className:"flex items-center gap-1.5 text-gray-700",children:[e.jsx(dt,{className:"w-3.5 h-3.5 text-gray-500"}),e.jsx("span",{className:"font-medium",children:"Expected Completion:"}),e.jsx("span",{children:new Date(o.expectedCompletionDate).toLocaleDateString("en-IN")})]}),o.documentUrl&&e.jsx("div",{className:"flex items-center gap-1.5",children:M(o.documentUrl)?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:o.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"View Previous Document"})]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:o.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"Download Previous Document"})]})}),o.otherDocuments&&o.otherDocuments.length>0&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1.5 flex items-center gap-1",children:[e.jsx(Ie,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:o.otherDocuments.map((ie,pe)=>e.jsx(Pr,{document:{documentId:ie.documentId||ie.id||"",name:ie.originalFileName||ie.fileName||ie.name||"Supporting Document",fileType:(ie.originalFileName||ie.fileName||ie.name||"").split(".").pop()||"file",uploadedAt:ie.uploadedAt||new Date().toISOString()},onPreview:M(ie.originalFileName||ie.fileName||ie.name||"")?()=>W(ie):void 0,onDownload:async we=>{if(we)await Ms(we);else{let Ae=ie.storageUrl||ie.documentUrl;if(Ae&&!Ae.startsWith("http")){const ne="https://reflow-uat.royalenfield.com",q=ne.endsWith("/")?ne.slice(0,-1):ne,de=Ae.startsWith("/")?Ae:`/${Ae}`;Ae=`${q}${de}`}Ae&&window.open(Ae,"_blank")}}},pe))})]})]}),(o.costItems||o.costBreakup)&&(o.costItems||o.costBreakup).length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-xs font-semibold text-gray-700 mb-2",children:"Previous Cost Breakdown:"}),e.jsx("div",{className:"border rounded-md overflow-hidden text-xs",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-600",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-2 font-medium",children:"Description"}),e.jsx("th",{className:"p-2 font-medium text-right",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y",children:[(o.costItems||o.costBreakup).map((ie,pe)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:ie.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(ie.amount).toLocaleString("en-IN")]})]},pe)),e.jsxs("tr",{className:"bg-gray-50 font-bold",children:[e.jsx("td",{colSpan:1,className:"p-2 text-gray-900",children:"Total"}),e.jsxs("td",{className:"p-2 text-right text-gray-900",children:["₹",Number(o.totalEstimatedBudget||o.totalBudget||0).toLocaleString("en-IN")]})]})]})]})})]}),(o.comments||o.dealerComments)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-700 mb-1",children:"Previous Comments:"}),e.jsxs("div",{className:"bg-white border rounded p-2 text-xs text-gray-600 italic",children:['"',o.comments||o.dealerComments,'"']})]})]})]})}),e.jsxs("div",{className:"space-y-6 lg:space-y-0 lg:grid lg:grid-cols-2 lg:gap-x-8 lg:gap-y-6 lg:items-start",children:[e.jsxs("div",{className:"space-y-2 lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Proposal Document"}),e.jsx(se,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${x?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:[e.jsx("input",{ref:z,type:"file",accept:[".pdf",".doc",".docx"].filter(ie=>d.allowedFileTypes.includes(ie.replace(".",""))).join(","),className:"hidden",id:"proposalDoc",onChange:Y}),e.jsx("label",{htmlFor:"proposalDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:x?e.jsxs("div",{className:"flex flex-col items-center gap-2 w-full text-center",children:[e.jsx(us,{className:"w-8 h-8 text-green-600"}),e.jsx("span",{className:"text-sm font-semibold text-green-700 truncate w-full px-2",children:x.name}),e.jsxs("div",{className:"flex gap-2",children:[U(x)&&e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>B(x),className:"h-7 text-[10px]",children:"Preview"}),e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>J(x),className:"h-7 text-[10px]",children:"Download"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(js,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Upload Proposal (PDF, DOC)"})]})})]})]}),e.jsxs("div",{className:"space-y-2 lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Timeline for Closure"}),e.jsx(se,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{type:"button",onClick:()=>N("date"),className:w==="date"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Date"}),e.jsx(E,{type:"button",onClick:()=>N("days"),className:w==="days"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Days"})]}),w==="date"?e.jsx(Xs,{value:S||null,onChange:ie=>A(ie||""),minDate:Oe,placeholderText:"dd/mm/yyyy",className:"w-full"}):e.jsx(ke,{type:"number",placeholder:"Enter number of days",min:"1",value:_,onChange:ie=>D(ie.target.value),className:"h-10 w-full"})]})]}),e.jsxs("div",{className:"lg:col-span-2 space-y-3 py-4 border-y border-gray-100 mt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg text-[#2d4a3e]",children:"Cost Breakup"}),e.jsx(se,{variant:"outline",className:"text-xs border-[#2d4a3e] text-[#2d4a3e] bg-green-50 font-medium",children:"Required"})]}),!f&&e.jsx("div",{className:"text-[10px] text-gray-500 italic mt-0.5",children:"Tax fields are automatically toggled based on the dealer's state (Inter-state vs Intra-state)."}),e.jsxs(E,{type:"button",onClick:K,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(bs,{className:"w-4 h-4 mr-1"}),"Add Item"]})]}),e.jsx("div",{className:"space-y-4 max-h-[400px] overflow-y-auto pr-1",children:b.map(ie=>e.jsx("div",{className:"p-4 border rounded-xl bg-gray-50/50 hover:bg-gray-50 transition-colors shadow-sm relative group",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex gap-3 items-start",children:[e.jsxs("div",{className:`${f?"flex-[3]":"flex-1"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold",children:"Item Description"}),ie.isOriginal?e.jsx(se,{className:"text-[9px] h-4 bg-gray-200 text-gray-700 hover:bg-gray-200 border-none",children:"ORIGINAL"}):o&&p>0?e.jsx(se,{className:"text-[9px] h-4 bg-amber-100 text-amber-700 hover:bg-amber-100 border-none",children:"ADDITIONAL"}):null]}),e.jsx(ke,{placeholder:"e.g., Venue branding, Logistics, etc.",value:ie.description,onChange:pe=>Ne(ie.id,"description",pe.target.value),className:`w-full bg-white shadow-sm ${ie.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:ie.isOriginal})]}),f&&e.jsxs("div",{className:"flex-1 min-w-[140px]",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(ir,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(ke,{type:"number",value:ie.amount||"",onChange:pe=>Ne(ie.id,"amount",pe.target.value),className:`pl-8 bg-white shadow-sm ${ie.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:ie.isOriginal})]})]}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"mt-6 hover:bg-red-50 hover:text-red-600 h-9 w-9 p-0 rounded-full",onClick:()=>ae(ie.id),disabled:b.length===1||ie.isOriginal,children:e.jsx(bt,{className:"w-4 h-4"})})]}),!f&&e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-3 items-start",children:[e.jsxs("div",{className:"flex-1 min-w-[140px]",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(ir,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(ke,{type:"number",value:ie.amount||"",onChange:pe=>Ne(ie.id,"amount",pe.target.value),className:`pl-8 bg-white shadow-sm ${ie.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:ie.isOriginal})]})]}),e.jsxs("div",{className:"w-28 sm:w-32",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN/SAC Code"}),e.jsx(ke,{value:ie.hsnCode||"",onChange:pe=>Ne(ie.id,"hsnCode",pe.target.value),className:`bg-white shadow-sm ${Kr(ie.hsnCode,ie.isService).isValid?"":"border-red-500"} ${ie.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:ie.isOriginal})]}),e.jsxs("div",{className:"w-28 sm:w-32",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Type"}),e.jsxs("select",{value:ie.isService?"SAC":"HSN",onChange:pe=>Ne(ie.id,"isService",pe.target.value==="SAC"),className:`flex h-10 w-full rounded-md border border-input bg-white px-3 py-2 text-sm shadow-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-[#2d4a3e] ${ie.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:ie.isOriginal,children:[e.jsx("option",{value:"HSN",children:"HSN (Goods)"}),e.jsx("option",{value:"SAC",children:"SAC (Service)"})]})]}),e.jsxs("div",{className:"w-16",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"CGST %"}),e.jsx(ke,{type:"number",value:ie.cgstRate||"",onChange:pe=>Ne(ie.id,"cgstRate",pe.target.value),disabled:!g.isCGST,className:"bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-16",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"SGST %"}),e.jsx(ke,{type:"number",value:ie.sgstRate||"",onChange:pe=>Ne(ie.id,"sgstRate",pe.target.value),disabled:!g.isSGST,className:"bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-16",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"UTGST %"}),e.jsx(ke,{type:"number",value:ie.utgstRate||"",onChange:pe=>Ne(ie.id,"utgstRate",pe.target.value),disabled:!g.isUTGST,className:"bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-16",children:[e.jsx(te,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"IGST %"}),e.jsx(ke,{type:"number",value:ie.igstRate||"",onChange:pe=>Ne(ie.id,"igstRate",pe.target.value),disabled:!g.isIGST,className:"bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"})]})]}),!f&&e.jsxs("div",{className:"flex flex-wrap gap-4 pt-3 border-t border-dashed items-center justify-between text-xs",children:[e.jsxs("div",{className:"flex gap-4 text-gray-500 font-medium",children:[e.jsxs("span",{children:["CGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",ie.cgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),ie.sgstAmt>0&&e.jsxs("span",{children:["SGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",ie.sgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),ie.utgstAmt>0&&e.jsxs("span",{children:["UTGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",ie.utgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs("span",{children:["IGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",ie.igstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]}),e.jsxs("div",{className:"flex gap-4 items-center",children:[e.jsxs("span",{className:"text-gray-500",children:["GST Total: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",ie.gstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs("span",{className:"text-sm font-bold text-[#2d4a3e] bg-green-50 px-3 py-1 rounded-lg",children:["Item Total: ₹",ie.totalAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]})]})},ie.id))}),e.jsxs("div",{className:"bg-[#2d4a3e] rounded-xl p-5 text-white flex items-center justify-between shadow-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-white/20 rounded-lg",children:e.jsx(ir,{className:"w-6 h-6"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-white/70 uppercase font-bold tracking-wider",children:"Estimated Total Budget"}),!f&&e.jsx("p",{className:"text-sm text-white/90",children:"Inclusive of all applicable taxes"})]})]}),e.jsxs("div",{className:"text-3xl font-bold border-l border-white/20 pl-6",children:["₹",O.toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Other Documents"}),e.jsx(se,{variant:"outline",className:"text-xs border-gray-300 text-gray-500 bg-gray-50 font-medium",children:"Optional"})]}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${R.length>0?"border-blue-500 bg-blue-50":"border-gray-300 bg-white"}`,children:[e.jsx("input",{ref:L,type:"file",multiple:!0,accept:d.allowedFileTypes.map(ie=>`.${ie}`).join(","),className:"hidden",id:"otherDocs",onChange:re}),e.jsxs("label",{htmlFor:"otherDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(js,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:R.length>0?`${R.length} files selected`:"Upload supporting files"}),e.jsx("span",{className:"text-[10px] text-gray-400",children:"Click to add documents"})]})]}),R.length>0&&e.jsx("div",{className:"mt-2 space-y-2 max-h-[120px] overflow-y-auto",children:R.map((ie,pe)=>e.jsxs("div",{className:"flex items-center justify-between bg-blue-50 border border-blue-100 p-2 rounded-lg text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(Ie,{className:"w-3.5 h-3.5 text-blue-600 flex-shrink-0"}),e.jsx("span",{className:"text-gray-700 font-medium truncate",children:ie.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[U(ie)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",onClick:()=>B(ie),children:e.jsx(Ct,{className:"w-3 h-3"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",onClick:()=>J(ie),children:e.jsx(kt,{className:"w-3 h-3"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100 hover:text-red-600",onClick:()=>Se(pe),children:e.jsx(bt,{className:"w-3 h-3"})})]})]},pe))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"font-semibold text-base lg:text-lg",children:"Dealer Comments *"}),e.jsx(Os,{placeholder:"Details about execution, special requirements, etc.",value:P,onChange:ie=>C(ie.target.value),className:"min-h-[100px] bg-white shadow-sm"})]})]}),!H&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 lg:p-4 flex items-start gap-2 lg:gap-3 lg:col-span-2 mt-4",children:[e.jsx(Ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs lg:text-sm text-amber-800",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Missing Required Information"}),e.jsx("p",{children:"Please ensure proposal document, cost breakup, timeline, and dealer comments are provided before submitting."})]})]})]}),e.jsxs(Et,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end flex-shrink-0 pt-3 lg:pt-4 border-t",children:[e.jsx(E,{variant:"outline",onClick:Pe,disabled:V,className:"border-2",children:"Cancel"}),e.jsx(E,{onClick:Ge,disabled:!H||V,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:V?"Submitting...":"Submit Documents"})]})]}),$&&e.jsx(Mr,{fileName:$.fileName||"",fileType:$.fileType||"",fileUrl:$.fileUrl||"",fileSize:$.fileSize||0,attachmentId:$.documentId||"",onDownload:Ms,open:!!$,onClose:()=>I(null)})]})}function S5({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n,requestId:i,preFilledIONumber:l,preFilledBlockedAmount:o,preFilledRemainingBalance:c,taxationType:d}){const[m,p]=h.useState("approve"),[x,u]=h.useState(""),[g,f]=h.useState(!1),b=h.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),j=l||"";h.useEffect(()=>{t&&(u(""),p("approve"))},[t]);const y=x.length,w=500,N=h.useMemo(()=>(m==="reject"||j.trim().length>0)&&x.trim().length>0,[m,j,x]),S=async()=>{if(!N){if(m==="approve"&&!j.trim()){X.error("IO number is required. Please block amount from IO tab first.");return}if(!x.trim()){X.error("Please provide comments");return}return}try{f(!0),m==="approve"?await a({ioNumber:j.trim(),comments:x.trim()}):await r(x.trim()),A(),s()}catch(D){console.error(`Failed to ${m} request:`,D),X.error(`Failed to ${m} request. Please try again.`)}finally{f(!1)}},A=()=>{p("approve"),u("")},_=()=>{g||(A(),s())};return e.jsx(jt,{open:t,onOpenChange:_,children:e.jsxs(xt,{className:"dept-lead-io-modal overflow-hidden flex flex-col",children:[e.jsxs(yt,{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(Le,{className:"w-5 h-5 lg:w-6 lg:h-6 text-green-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ht,{className:"font-semibold text-lg lg:text-xl flex items-center gap-2 flex-wrap",children:["Review and Approve",d&&e.jsx(se,{className:`ml-2 border-none shadow-sm ${b?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:b?"Non-GST Claim":"GST Claim"})]}),e.jsx(Ut,{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(se,{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(se,{className:"bg-green-100 text-green-800 border-green-200 text-xs",children:[e.jsx(Le,{className:"w-3 h-3 mr-1"}),"APPROVE"]})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden py-3 lg:py-4 px-6",children:e.jsxs("div",{className:"space-y-3 lg:space-y-4",children:[e.jsxs("div",{className:"flex gap-2 p-1 bg-gray-100 rounded-lg",children:[e.jsxs(E,{type:"button",onClick:()=>p("approve"),className:`flex-1 text-sm lg:text-base ${m==="approve"?"bg-green-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:m==="approve"?"default":"ghost",children:[e.jsx(Le,{className:"w-4 h-4 mr-1"}),"Approve"]}),e.jsxs(E,{type:"button",onClick:()=>p("reject"),className:`flex-1 text-sm lg:text-base ${m==="reject"?"bg-red-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:m==="reject"?"destructive":"ghost",children:[e.jsx(St,{className:"w-4 h-4 mr-1"}),"Reject"]})]}),e.jsxs("div",{className:"space-y-3 lg:space-y-0 lg:grid lg:grid-cols-2 lg:gap-6",children:[m==="approve"&&e.jsxs("div",{className:"p-3 lg:p-4 bg-blue-50 border border-blue-200 rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{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(te,{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(ke,{id:"ioNumber",value:j||"—",disabled:!0,readOnly:!0,className:"bg-gray-100 h-8 lg:h-9 cursor-not-allowed text-xs lg:text-sm"}),!j&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:"⚠️ IO number not found. Please block amount from IO tab first."}),j&&e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"✓ Loaded from IO table"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o!==void 0&&o>0&&e.jsx("div",{className:"p-2 bg-green-50 border border-green-200 rounded",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs font-semibold text-gray-700",children:"Blocked Amount:"}),e.jsxs("span",{className:"text-xs lg:text-sm font-bold text-green-700 mt-1",children:["₹",o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})}),c!=null&&e.jsx("div",{className:"p-2 bg-blue-50 border border-blue-200 rounded",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs font-semibold text-gray-700",children:"Remaining Balance:"}),e.jsxs("span",{className:"text-xs lg:text-sm font-bold text-blue-700 mt-1",children:["₹",c.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]})]}),e.jsxs("div",{className:`space-y-1.5 ${m==="approve"?"":"lg:col-span-2"}`,children:[e.jsxs(te,{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(Os,{id:"comment",placeholder:m==="approve"?"Enter your approval comments and any conditions or notes...":"Enter detailed reasons for rejection...",value:x,onChange:D=>{const R=D.target.value;R.length<=w&&u(R)},rows:4,className:"text-xs lg:text-sm min-h-[80px] lg:min-h-[100px] resize-none"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ts,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[y,"/",w]})]})]})]})]})}),e.jsxs(Et,{className:"flex-shrink-0 flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pb-6 pt-3 border-t",children:[e.jsx(E,{variant:"outline",onClick:_,disabled:g,className:"text-sm lg:text-base",children:"Cancel"}),e.jsx(E,{onClick:S,disabled:!N||g,className:`text-sm lg:text-base ${m==="approve"?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700"} text-white`,children:g?`${m==="approve"?"Approving":"Rejecting"}...`:e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),m==="approve"?"Approve Request":"Reject Request"]})})]})]})})}function A5({isOpen:t,onClose:s,onPush:a,onReQuotation:r,completionDetails:n,ioDetails:i,completionDocuments:l,requestTitle:o,requestNumber:c,taxationType:d}){var F,$;const m=h.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),[p,x]=h.useState(""),[u,g]=h.useState(!1),[f,b]=h.useState(null),[j,y]=h.useState(!1),w=p.length,N=500,S=h.useMemo(()=>n!=null&&n.totalClosedExpenses?n.totalClosedExpenses:n!=null&&n.closedExpenses&&Array.isArray(n.closedExpenses)?n.closedExpenses.reduce((I,T)=>{const k=typeof T=="object"&&T.amount||0,z=typeof T=="object"&&T.gstAmt||0,L=T.totalAmt||k+z;return I+(Number(L)||0)},0):0,[n]),A=I=>{if(!I)return"—";try{return new Date(I).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return I}},_=I=>`₹${I.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,D=I=>{if(!I.name)return!1;const T=I.name.toLowerCase();return T.endsWith(".pdf")||T.endsWith(".jpg")||T.endsWith(".jpeg")||T.endsWith(".png")||T.endsWith(".gif")||T.endsWith(".webp")},R=async I=>{if(!I.id){X.error("Document preview not available - document ID missing");return}y(!0);try{const T=mn(I.id),k=I.name.toLowerCase(),z=k.endsWith(".pdf"),L=k.match(/\.(jpg|jpeg|png|gif|webp)$/i),M=!0,U=M?null:localStorage.getItem("accessToken"),W=await fetch(T,{headers:{Accept:z?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!W.ok)throw new Error(`Failed to load file: ${W.status} ${W.statusText}`);const J=await W.blob();if(J.size===0)throw new Error("File is empty or could not be loaded");const O=window.URL.createObjectURL(J);b({name:I.name,url:O,type:J.type||(z?"application/pdf":L?"image":void 0),size:J.size})}catch(T){console.error("Failed to load document preview:",T),X.error("Failed to load document preview")}finally{y(!1)}};h.useEffect(()=>()=>{f!=null&&f.url&&f.url.startsWith("blob:")&&window.URL.revokeObjectURL(f.url)},[f]);const v=async()=>{if(!p.trim()){X.error("Please provide comments before proceeding");return}try{g(!0),await a(p.trim()),P(),s()}catch(I){console.error("Failed to generate e-invoice:",I),X.error("Failed to generate e-invoice. Please try again.")}finally{g(!1)}},P=()=>{x("")},C=async()=>{if(!p.trim()){X.error("Please provide comments (reason) for re-quotation request");return}if(!r){X.error("Re-quotation handler not provided");return}try{g(!0),await r(p.trim()),P(),s()}catch(I){console.error("Failed to request re-quotation:",I)}finally{g(!1)}},V=()=>{u||(P(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(jt,{open:t,onOpenChange:V,children:e.jsxs(xt,{className:"settlement-push-modal overflow-hidden flex flex-col w-full max-w-none",children:[e.jsxs(yt,{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(Ot,{className:"w-4 h-4 sm:w-5 sm:h-5 sm:w-6 sm:h-6 text-indigo-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ht,{className:"font-semibold text-lg sm:text-xl flex items-center gap-2 flex-wrap",children:["E-Invoice Generation & Sync",d&&e.jsx(se,{className:`ml-2 border-none shadow-sm ${m?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:m?"Non-GST Claim":"GST Claim"})]}),e.jsx(Ut,{className:"text-xs sm:text-sm mt-1",children:"Review completion details and expenses before generating e-invoice and initiating SAP settlement"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 p-3 sm:p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between sm:flex-col sm:items-start sm:gap-1",children:[e.jsx("span",{className:"font-medium text-xs sm:text-sm text-gray-600",children:"Workflow Step:"}),e.jsx(se,{variant:"outline",className:"font-mono text-xs",children:"Requestor Claim Approval"})]}),c&&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:c})]}),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:o||"—"})]}),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(se,{className:"bg-indigo-100 text-indigo-800 border-indigo-200 text-xs",children:[e.jsx(Ot,{className:"w-3 h-3 mr-1"}),"SYNC TO SAP"]})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-6 py-3",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6",children:[n&&e.jsxs(Z,{children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs(me,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(us,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Details"]}),e.jsx(ve,{className:"text-xs sm:text-sm",children:"Review activity completion information"})]}),e.jsxs(ee,{className:"space-y-2 sm:space-y-3",children:[n.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(n.activityCompletionDate)})]}),n.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:n.numberOfParticipants})]}),n.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:n.completionDescription})]})]})]}),i&&i.ioNumber&&e.jsxs(Z,{children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs(me,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Pt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"IO Details"]}),e.jsx(ve,{className:"text-xs sm:text-sm",children:"Internal Order information for budget reference"})]}),e.jsxs(ee,{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:i.ioNumber})]}),i.blockedAmount!==void 0&&i.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:_(i.blockedAmount)})]}),i.remainingBalance!==void 0&&i.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:_(i.remainingBalance)})]})]})]}),(n==null?void 0:n.closedExpenses)&&n.closedExpenses.length>0&&e.jsxs(Z,{className:"md:col-span-2 lg:col-span-3",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs(me,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Ha,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Expense Breakdown"]}),e.jsx(ve,{className:"text-xs sm:text-sm",children:"Review closed expenses breakdown (Base + GST)"})]}),e.jsxs(ee,{children:[e.jsxs("div",{className:"grid grid-cols-12 gap-2 mb-2 px-3 text-xs font-medium text-gray-500 uppercase tracking-wider hidden sm:grid",children:[e.jsx("div",{className:`${m?"col-span-8":"col-span-4"}`,children:"Description"}),e.jsx("div",{className:"col-span-2 text-right",children:"Base"}),!m&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"col-span-2 text-right",children:"GST Rate"}),e.jsx("div",{className:"col-span-2 text-right",children:"GST Amt"})]}),e.jsx("div",{className:"col-span-2 text-right",children:"Total"})]}),e.jsx("div",{className:"space-y-2 max-h-[300px] overflow-y-auto",children:n.closedExpenses.map((I,T)=>{const k=typeof I=="object"&&I.amount||0,z=typeof I=="object"&&I.gstRate||0,L=typeof I=="object"&&I.gstAmt||0,M=typeof I=="object"?I.totalAmt||k+L:0;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-12 gap-2 items-center py-2 px-3 bg-gray-50 rounded border text-xs sm:text-sm",children:[e.jsxs("div",{className:"sm:hidden flex justify-between w-full mb-1",children:[e.jsx("span",{className:"font-semibold text-gray-900",children:I.description||`Expense ${T+1}`}),e.jsx("span",{className:"font-bold text-gray-900",children:_(M)})]}),e.jsxs("div",{className:"sm:hidden flex justify-between w-full text-xs text-gray-500",children:[e.jsxs("span",{children:["Base: ",_(k)]}),!m&&e.jsxs("span",{children:["GST: ",z,"% (",_(L),")"]})]}),e.jsx("div",{className:`hidden sm:block ${m?"col-span-8":"col-span-4"} min-w-0`,children:e.jsx("p",{className:"font-medium text-gray-900 truncate",title:I.description,children:I.description||`Expense ${T+1}`})}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:_(k)}),!m&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:[z,"%"]}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:_(L)})]}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right font-semibold text-gray-900",children:_(M)})]},T)})}),e.jsxs("div",{className:"flex items-center justify-between py-2 sm:py-3 px-3 sm:px-4 bg-blue-50 rounded border-2 border-blue-200 mt-3 sm:mt-4",children:[e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:"Total Closed Expenses:"}),e.jsx("span",{className:"text-sm sm:text-base font-bold text-blue-700",children:_(S)})]})]})]})]}),l&&e.jsxs("div",{className:"space-y-4",children:[l.completionDocuments&&l.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(us,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Documents"]}),e.jsxs(se,{variant:"secondary",className:"text-xs",children:[l.completionDocuments.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:l.completionDocuments.map((I,T)=>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(us,{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:I.name,children:I.name})})]}),I.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[D(I)&&e.jsx("button",{type:"button",onClick:()=>R(I),disabled:j,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:j?e.jsx(Xe,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(Ct,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{I.id&&await Ms(I.id)}catch(k){console.error("Failed to download document:",k),X.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(kt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},T))})]}),l.activityPhotos&&l.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(Ot,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Activity Photos"]}),e.jsxs(se,{variant:"secondary",className:"text-xs",children:[l.activityPhotos.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:l.activityPhotos.map((I,T)=>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(Ot,{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:I.name,children:I.name})})]}),I.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[D(I)&&e.jsx("button",{type:"button",onClick:()=>R(I),disabled:j,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview photo",children:j?e.jsx(Xe,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(Ct,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{I.id&&await Ms(I.id)}catch(k){console.error("Failed to download document:",k),X.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download photo",children:e.jsx(kt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},T))})]}),l.invoicesReceipts&&l.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(Pt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Invoices / Receipts"]}),e.jsxs(se,{variant:"secondary",className:"text-xs",children:[l.invoicesReceipts.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:l.invoicesReceipts.map((I,T)=>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-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:I.name,children:I.name})})]}),I.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[D(I)&&e.jsx("button",{type:"button",onClick:()=>R(I),disabled:j,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:j?e.jsx(Xe,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(Ct,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{I.id&&await Ms(I.id)}catch(k){console.error("Failed to download document:",k),X.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(kt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},T))})]}),l.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(Ot,{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(Ot,{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:l.attendanceSheet.name,children:l.attendanceSheet.name})})]}),l.attendanceSheet.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[D(l.attendanceSheet)&&e.jsx("button",{type:"button",onClick:()=>R(l.attendanceSheet),disabled:j,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:j?e.jsx(Xe,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(Ct,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var I;try{(I=l.attendanceSheet)!=null&&I.id&&await Ms(l.attendanceSheet.id)}catch(T){console.error("Failed to download document:",T),X.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(kt,{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(ts,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-yellow-900",children:"Please verify all details before generation"}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1",children:"Once submitted, the system will generate an e-invoice and initiate the SAP settlement process."})]})]})}),e.jsxs("div",{className:"space-y-1.5 max-w-2xl",children:[e.jsxs(te,{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(Os,{id:"comment",placeholder:"Enter your comments about e-invoice generation (e.g., verified expenses, ready for settlement)...",value:p,onChange:I=>{const T=I.target.value;T.length<=N&&x(T)},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(ts,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[w,"/",N]})]})]})]})}),e.jsxs(Et,{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pt-3 pb-6 border-t flex-shrink-0",children:[e.jsx(E,{variant:"outline",onClick:V,disabled:u,children:"Cancel"}),r&&e.jsxs(E,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:C,disabled:!p.trim()||u,children:[u?e.jsx(Xe,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx($t,{className:"w-4 h-4 mr-2"}),"Request Re-quotation"]}),e.jsx(E,{onClick:v,disabled:!p.trim()||u,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:u?"Processing...":e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"w-4 h-4 mr-2"}),"Generate & Sync"]})})]})]})}),f&&e.jsx(jt,{open:!!f,onOpenChange:()=>b(null),children:e.jsx(xt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(yt,{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(Ct,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ht,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:f.name}),f.type&&e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[f.type," ",f.size&&`• ${(f.size/1024).toFixed(1)} KB`]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>{const I=document.createElement("a");I.href=f.url,I.download=f.name,I.click()},className:"gap-2 h-9",children:[e.jsx(kt,{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:j?e.jsx("div",{className:"flex items-center justify-center h-full min-h-[70vh]",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Xe,{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..."})]})}):f.name.toLowerCase().endsWith(".pdf")||(F=f.type)!=null&&F.includes("pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:f.url,className:"w-full h-full rounded-lg border-0",title:f.name,style:{minHeight:"70vh",height:"100%"}})}):f.name.match(/\.(jpg|jpeg|png|gif|webp)$/i)||($=f.type)!=null&&$.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:f.url,alt:f.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(Ct,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),e.jsxs(E,{onClick:()=>{const I=document.createElement("a");I.href=f.url,I.download=f.name,I.click()},className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",f.name]})]})})]})})})]})}function T5({isOpen:t,onClose:s,stepNumber:a,stepName:r,requestNumber:n="RE-REQ-2024-CM-101",recipientEmail:i="system@undefined",subject:l,emailBody:o}){const c=`System Notification: Activity Created - ${n}`,d=l||c,m=`System Notification
|
||
|
||
Activity has been automatically created for claim ${n}.
|
||
|
||
All stakeholders have been notified.
|
||
|
||
This is an automated message.`,p=o||m;return e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(xt,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(yt,{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(ba,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ht,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(Ut,{className:"text-sm",children:["Step ",a,": ",r]})]})]})})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-4 border border-blue-200",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-gray-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-gray-600",children:"To:"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:i})]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ba,{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(Zi,{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:p})}),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(dt,{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(se,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(se,{className:"bg-purple-50 text-purple-700 border-purple-200",children:"Auto-triggered"})]})]}),e.jsx("div",{className:"flex justify-end gap-2 pt-2",children:e.jsxs(E,{variant:"outline",onClick:s,className:"h-9",children:[e.jsx(bt,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function k5({isOpen:t,onClose:s,onApprove:a,onReject:r,onRequestRevision:n,proposalData:i,dealerName:l="Dealer",activityName:o="Activity",requestId:c,request:d,previousProposalData:m,taxationType:p}){const x=h.useMemo(()=>p==="Non GST"||p==="Non-GST",[p]),[u,g]=h.useState(""),[f,b]=h.useState(!1),[j,y]=h.useState(null),[w,N]=h.useState(!1),S=h.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const L=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(L)?L.reduce((M,U)=>{const B=typeof U=="object"&&U.amount||0,W=typeof U=="object"&&U.quantity||1,J=B*W,O=typeof U=="object"&&U.gstAmt||0,H=U.totalAmt||J+O;return M+(Number(H)||0)},0):0},[i]),A=h.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const L=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(L)?L.reduce((M,U)=>{const B=typeof U=="object"&&U.amount||0,W=typeof U=="object"&&U.quantity||1;return M+Number(B)*Number(W)},0):0},[i]),_=h.useMemo(()=>{const L=(d==null?void 0:d.internalOrders)||(d==null?void 0:d.internal_orders)||[];if(Array.isArray(L)&&L.length>0)return L.reduce((U,B)=>{const W=Number(B.ioBlockedAmount||B.io_blocked_amount||0);return U+W},0);const M=(d==null?void 0:d.internalOrder)||(d==null?void 0:d.internal_order);return Number((M==null?void 0:M.ioBlockedAmount)||(M==null?void 0:M.io_blocked_amount)||0)},[d==null?void 0:d.internalOrders,d==null?void 0:d.internal_orders,d==null?void 0:d.internalOrder,d==null?void 0:d.internal_order]),D=_>=A-.01,R=Math.max(0,A-_),[v,P]=h.useState(null),C=L=>{if(!L)return"—";try{return new Date(L).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return L}},V=L=>{if(!L.name)return!1;const M=L.name.toLowerCase();return M.endsWith(".pdf")||M.endsWith(".jpg")||M.endsWith(".jpeg")||M.endsWith(".png")||M.endsWith(".gif")||M.endsWith(".webp")},F=L=>{let M=L.url||L.storageUrl||"";const U=L.id||L.documentId||"";if(!U&&!M){X.error("Document preview not available");return}if(M&&!M.startsWith("http")&&!M.startsWith("blob:")){const B="https://reflow-uat.royalenfield.com",W=B.endsWith("/")?B.slice(0,-1):B,J=M.startsWith("/")?M:`/${M}`;M=`${W}${J}`}P({name:L.name||"Document",url:M||(U?mn(U):""),type:(L.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:U})};h.useEffect(()=>()=>{v!=null&&v.url&&v.url.startsWith("blob:")&&window.URL.revokeObjectURL(v.url)},[v]);const $=async()=>{if(!u.trim()){X.error("Please provide approval comments");return}try{b(!0),y("approve"),await a(u),k(),s()}catch(L){console.error("Failed to approve proposal:",L),X.error("Failed to approve proposal. Please try again.")}finally{b(!1),y(null)}},I=async()=>{if(!u.trim()){X.error("Please provide rejection reason");return}try{b(!0),y("reject"),await r(u),k(),s()}catch(L){console.error("Failed to reject proposal:",L),X.error("Failed to reject proposal. Please try again.")}finally{b(!1),y(null)}},T=async()=>{if(!u.trim()){X.error("Please provide reasons for requesting a revision");return}if(!n){X.error("Revision feature is not available");return}try{b(!0),y("revision"),await n(u),k(),s()}catch(L){console.error("Failed to request revision:",L),X.error("Failed to request revision. Please try again.")}finally{b(!1),y(null)}},k=()=>{g(""),y(null)},z=()=>{f||(k(),s())};return t?e.jsxs(jt,{open:t,onOpenChange:z,children:[e.jsxs(xt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(yt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(ht,{className:"flex items-center gap-2 text-lg lg:text-xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),p&&e.jsx(se,{className:`ml-2 border-none shadow-sm ${x?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:x?"Non-GST Claim":"GST Claim"})]}),e.jsx(Ut,{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:()=>N(!w),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(Ie,{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(se,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(m.totalEstimatedBudget||m.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:w?e.jsx(Vo,{className:"w-4 h-4"}):e.jsx(bs,{className:"w-4 h-4"})})]}),w&&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(dt,{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:V({name:m.documentUrl})?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:m.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"View Previous Document"})]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{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(ir,{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((L,M)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:L.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(L.amount).toLocaleString("en-IN")]})]},M)),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(Ie,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:m.otherDocuments.map((L,M)=>e.jsx(Pr,{document:{documentId:L.documentId||L.id||"",name:L.originalFileName||L.fileName||L.name||"Supporting Document",fileType:(L.originalFileName||L.fileName||L.name||"").split(".").pop()||"file",uploadedAt:L.uploadedAt||new Date().toISOString()},onPreview:V({name:L.originalFileName||L.fileName||L.name||""})?()=>F(L):void 0,onDownload:async U=>{if(U)await Ms(U);else{let B=L.storageUrl||L.documentUrl;if(B&&!B.startsWith("http")){const W="https://reflow-uat.royalenfield.com",J=W.endsWith("/")?W.slice(0,-1):W,O=B.startsWith("/")?B:`/${B}`;B=`${J}${O}`}B&&window.open(B,"_blank")}}},M))})]}),(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(zs,{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(Ie,{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(Ie,{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 ",C(i.submittedAt)]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:i.proposalDocument.id&&e.jsxs(e.Fragment,{children:[V(i.proposalDocument)&&e.jsx("button",{type:"button",onClick:()=>F(i.proposalDocument),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(Ct,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var L;try{(L=i.proposalDocument)!=null&&L.id&&await Ms(i.proposalDocument.id)}catch(M){console.error("Failed to download document:",M),X.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(kt,{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(Ie,{className:"w-4 h-4 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(se,{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((L,M)=>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(Ie,{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:L.name,children:L.name})]}),L.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[V(L)&&e.jsx("button",{type:"button",onClick:()=>F(L),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(Ct,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{L.id&&await Ms(L.id)}catch(U){console.error("Failed to download document:",U),X.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(kt,{className:"w-5 h-5 text-gray-600"})})]})]},M))})]})]}),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(ir,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const L=i!=null&&i.costBreakup?Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[]:[];return L&&Array.isArray(L)&&L.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden max-h-[200px] lg:max-h-[180px] overflow-y-auto",children:[e.jsx("div",{className:"bg-gray-50 px-3 lg:px-4 py-2 border-b sticky top-0",children:e.jsxs("div",{className:`grid ${x?"grid-cols-3":"grid-cols-4"} gap-4 text-xs lg:text-sm font-semibold text-gray-700`,children:[e.jsx("div",{className:"col-span-1",children:"Item Description"}),e.jsx("div",{className:"text-right",children:"Base"}),!x&&e.jsx("div",{className:"text-right",children:"GST"}),e.jsx("div",{className:"text-right",children:"Total"})]})}),e.jsx("div",{className:"divide-y",children:L.map((M,U)=>{var B,W;return e.jsxs("div",{className:`px-3 lg:px-4 py-2 lg:py-3 grid ${x?"grid-cols-3":"grid-cols-4"} gap-4`,children:[e.jsxs("div",{className:"col-span-1 text-xs lg:text-sm text-gray-700",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[e.jsx("span",{className:"font-medium",children:(B=M==null?void 0:M.description)!=null&&B.startsWith("[ADDITIONAL]")?M.description.replace("[ADDITIONAL]","").trim():(M==null?void 0:M.description)||"N/A"}),L.some(J=>{var O;return(O=J==null?void 0:J.description)==null?void 0:O.startsWith("[ADDITIONAL]")})&&((W=M==null?void 0:M.description)!=null&&W.startsWith("[ADDITIONAL]")?e.jsx(se,{className:"text-[9px] h-3.5 px-1 bg-amber-100 text-amber-700 hover:bg-amber-100 border-none leading-none",children:"ADDITIONAL"}):e.jsx(se,{className:"text-[9px] h-3.5 px-1 bg-gray-100 text-gray-600 hover:bg-gray-100 border-none leading-none",children:"ORIGINAL"}))]}),!x&&(M!=null&&M.gstRate)?e.jsxs("span",{className:"block text-[10px] text-gray-400",children:[M.gstRate,"% GST"]}):null]}),e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(M==null?void 0:M.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!x&&e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(M==null?void 0:M.gstAmt)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsxs("div",{className:"text-xs lg:text-sm font-semibold text-gray-900 text-right",children:["₹",(Number((M==null?void 0:M.totalAmt)||((M==null?void 0:M.amount)||0)*((M==null?void 0:M.quantity)||1)+((M==null?void 0:M.gstAmt)||0))||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(M==null?void 0:M.id)||(M==null?void 0:M.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(ir,{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:["₹",S.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(dt,{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?C(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(zs,{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(Os,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:u,onChange:L=>g(L.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(St,{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(Et,{className:"flex flex-col gap-2 sm:flex-row sm:justify-end px-6 pb-6 pt-3 lg:pt-4 flex-shrink-0 border-t bg-gray-50",children:[e.jsx(E,{variant:"outline",onClick:z,disabled:f,className:"border-2 w-full sm:w-auto",children:"Cancel"}),e.jsxs("div",{className:"flex flex-col gap-2 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(E,{onClick:T,disabled:!u.trim()||f,variant:"secondary",className:"bg-amber-100 hover:bg-amber-200 text-amber-900 border border-amber-200 w-full sm:w-auto",children:f&&j==="revision"?"Requesting...":e.jsxs(e.Fragment,{children:[e.jsx(zs,{className:"w-4 h-4 mr-2"}),"Request Revised Quotation"]})}),e.jsx(E,{onClick:I,disabled:!u.trim()||f,variant:"destructive",className:"bg-red-600 hover:bg-red-700 w-full sm:w-auto",children:f&&j==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(St,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(E,{onClick:$,disabled:!u.trim()||!D||f,className:"bg-green-600 hover:bg-green-700 text-white disabled:opacity-50 disabled:cursor-not-allowed w-full sm:w-auto",title:D?"":"Please block IO budget before approving",children:f&&j==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Approve (Continue to Dept Lead)"]})})]}),!D&&e.jsx("p",{className:"text-xs text-red-600 text-center sm:text-left font-medium",children:_>0?`Pending block: ₹${R.toLocaleString("en-IN",{minimumFractionDigits:2})} more needs to be blocked in the IO Tab.`:"Please block IO budget in the IO Tab before approving."})]})]})]}),v&&e.jsx(Mr,{fileName:v.name,fileType:v.type||"",fileUrl:v.url,fileSize:v.size,attachmentId:v.id,onDownload:Ms,open:!!v,onClose:()=>P(null)})]}):null}function R5({isOpen:t,onClose:s,snapshot:a,type:r,title:n}){const[i,l]=h.useState(null);if(!a)return null;const o=r==="PROPOSAL",c=u=>Number(u||0).toLocaleString("en-IN",{maximumFractionDigits:2,style:"currency",currency:"INR"}),d=u=>{if(!u)return null;try{return new Date(u).toLocaleDateString("en-IN",{day:"numeric",month:"short",year:"numeric"})}catch{return u}},m=u=>{if(!u)return!1;const g=u.toLowerCase();return g.endsWith(".pdf")||!!g.match(/\.(jpg|jpeg|png|gif|webp)$/i)},p=u=>{var f;const g=(f=(u||"").split(".").pop())==null?void 0:f.toLowerCase();return g==="pdf"?"pdf":["jpg","jpeg","png","gif","webp"].includes(g||"")?"image":"file"},x=u=>{const g=u.fileName||u.originalFileName||(o?"Proposal Document":"Completion Document"),f=u.documentId||"",b=g.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let j="";if(f)j=mn(f);else if(j=u.storageUrl||u.documentUrl||"",j&&!j.startsWith("http")){const y="https://reflow-uat.royalenfield.com",w=y.endsWith("/")?y.slice(0,-1):y,N=j.startsWith("/")?j:`/${j}`;j=`${w}${N}`}l({fileName:g,fileType:b,documentId:f,fileUrl:j,fileSize:u.sizeBytes})};return e.jsxs(e.Fragment,{children:[e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(xt,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs(yt,{className:"px-6 py-4 border-b",children:[e.jsxs(ht,{className:"flex items-center gap-2",children:[o?e.jsx(Ie,{className:"w-5 h-5 text-blue-600"}):e.jsx(Pt,{className:"w-5 h-5 text-green-600"}),n||(o?"Proposal Snapshot Details":"Completion Snapshot Details")]}),e.jsxs(Ut,{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(dt,{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(Pr,{document:{documentId:"",name:o?"Proposal Document":"Completion Document",fileType:p(a.documentUrl),uploadedAt:new Date().toISOString()},onPreview:m(a.documentUrl)?()=>x({fileName:o?"Proposal Document":"Completion Document",documentUrl:a.documentUrl}):void 0,onDownload:async()=>{let u=a.documentUrl;if(!u.startsWith("http")){const g="https://reflow-uat.royalenfield.com",f=g.endsWith("/")?g.slice(0,-1):g,b=u.startsWith("/")?u:`/${u}`;u=`${f}${b}`}window.open(u,"_blank")}})]}),a.otherDocuments&&a.otherDocuments.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1 flex items-center justify-between",children:[e.jsx("span",{children:"Supporting Documents"}),e.jsxs(se,{variant:"secondary",className:"text-[10px] h-5",children:[a.otherDocuments.length," Files"]})]}),e.jsx("div",{className:"space-y-2",children:a.otherDocuments.map((u,g)=>e.jsx(Pr,{document:{documentId:u.documentId||"",name:u.originalFileName||u.fileName||"Supporting Document",fileType:p(u.originalFileName||u.fileName||""),uploadedAt:u.uploadedAt||new Date().toISOString()},onPreview:m(u.originalFileName||u.fileName||"")?()=>x(u):void 0,onDownload:u.documentId?Ms:async()=>{let f=u.storageUrl||u.documentUrl;if(f&&!f.startsWith("http")){const b="https://reflow-uat.royalenfield.com",j=b.endsWith("/")?b.slice(0,-1):b,y=f.startsWith("/")?f:`/${f}`;f=`${j}${y}`}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((u,g)=>e.jsxs("tr",{className:"bg-white hover:bg-gray-50/50",children:[e.jsx("td",{className:"p-3 text-gray-800",children:u.description}),e.jsx("td",{className:"p-3 text-right text-gray-900 font-medium tabular-nums",children:c(u.amount)})]},g)):e.jsx("tr",{children:e.jsx("td",{colSpan:2,className:"p-4 text-center text-gray-500 italic text-xs",children:"No breakdown items available"})}),e.jsxs("tr",{className:"bg-gray-50/80 font-semibold text-gray-900 border-t-2 border-gray-100",children:[e.jsx("td",{className:"p-3",children:"Total"}),e.jsx("td",{className:"p-3 text-right tabular-nums",children:c(a.totalBudget||a.totalExpenses)})]})]})]})})]}),a.comments&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1 flex items-center gap-1",children:[e.jsx(sh,{className:"w-4 h-4"}),"Comments"]}),e.jsx("div",{className:"bg-gray-50 rounded-lg p-3 text-sm text-gray-700 italic border border-gray-100",children:a.comments})]})]})}),e.jsx("div",{className:"px-6 py-4 border-t bg-gray-50 flex justify-end",children:e.jsx(E,{onClick:s,children:"Close"})})]})}),i&&e.jsx(Mr,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:Ms,open:!!i,onClose:()=>l(null)})]})}async function D5(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 F5(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 I5(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 P5(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 E5(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 g0(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 _5(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 M5(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 L5(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}}async function O5(t){var s;try{const a=await je.post(`/dealer-claims/${t}/wfm/retrigger`);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error re-triggering WFM push:",a),a}}const Br=t=>{if(!t)return"";try{return gs(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}}},$5=t=>{switch(t){case"approved":return e.jsx(Le,{className:"w-5 h-5 text-green-600"});case"skipped":return e.jsx(Le,{className:"w-5 h-5 text-green-600"});case"pending":return e.jsx(st,{className:"w-5 h-5 text-blue-600"});case"rejected":return e.jsx(Le,{className:"w-5 h-5 text-red-600"});default:return e.jsx(st,{className:"w-5 h-5 text-gray-400"})}},U5=t=>{switch(t){case"approved":return"bg-green-100 text-green-800 border-green-200";case"skipped":return"bg-green-50 text-green-700 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"}},B5=(t,s)=>s&&(t==="pending"||t==="in_progress")?"border-purple-500 bg-purple-50 shadow-md":t==="approved"||t==="skipped"?"border-green-500 bg-green-50":t==="rejected"?"border-red-500 bg-red-50":"border-gray-200 bg-white",V5=t=>{switch(t){case"approved":return"bg-green-100";case"skipped":return"bg-green-100";case"pending":return"bg-purple-100";case"rejected":return"bg-red-100";default:return"bg-gray-100"}};function z5({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i}){var pr,Xa,Ta,Ja,Za,qa,Gt,As,qs,gr,Rt,Xt,Rs,ma,$r,ya,er,pn,gn,fn,Kc,Qc,Xc,Jc,Zc,qc,ed,td,sd,ad,rd,nd,id,ld,od,cd,dd,md,ud,xd,hd,pd,gd,fd,bd,jd,yd,vd,Nd,wd,Cd,Sd,Ad,Td,kd,Rd,Dd,Fd,Id,Pd,Ed,_d,Md,Ld,Od,$d,Ud,Bd,Vd,zd,Hd,Wd,Gd,Yd,Kd,Qd,Xd,Jd,Zd,qd,em,tm,sm,am,rm,nm,im,lm,om,cm,dm,mm,um,xm,hm,pm,gm,fm,bm,jm,ym,vm,Nm;const[l,o]=h.useState(!1),[c,d]=h.useState(!1),[m,p]=h.useState(!1),[x,u]=h.useState(!1),[g,f]=h.useState(!1),[b,j]=h.useState(!1),[y,w]=h.useState(!1),[N,S]=h.useState(null),[A,_]=h.useState(!1),[D,R]=h.useState(null),[v,P]=h.useState([]),[C,V]=h.useState(!1),[F,$]=h.useState(new Set),[I,T]=h.useState(null),[k,z]=h.useState(null),[L,M]=h.useState(!1),[U,B]=h.useState(!1),[W,J]=h.useState([]),[O,H]=h.useState(0);h.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Me=t.id||t.requestId;try{const be=await Ps(Me),ue=(be==null?void 0:be.approvalLevels)||(be==null?void 0:be.approvals)||[];if(ue&&ue.length>0){const ge=ue.map(xe=>{var Re;return{step:xe.levelNumber||xe.level_number||0,levelNumber:xe.levelNumber||xe.level_number||0,levelName:xe.levelName||xe.level_name,approver:xe.approverName||xe.approver_name||"",approverEmail:(xe.approverEmail||xe.approver_email||"").toLowerCase(),status:((Re=xe.status)==null?void 0:Re.toLowerCase())||"waiting",tatHours:xe.tatHours||xe.tat_hours||24,elapsedHours:xe.elapsedHours||xe.elapsed_hours,approvedAt:xe.actionDate||xe.action_date,comment:xe.comments||xe.comment,levelId:xe.levelId||xe.level_id}}).sort((xe,Re)=>(xe.levelNumber||0)-(Re.levelNumber||0));J(xe=>xe.length!==ge.length||xe.some((Fe,Ce)=>{const Nt=ge[Ce];return!Nt||Fe.levelNumber!==Nt.levelNumber||Fe.levelName!==Nt.levelName||Fe.approverEmail!==Nt.approverEmail||Fe.status!==Nt.status})?ge:xe)}else J([])}catch(be){console.warn("Failed to load approval flows from API:",be),t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&J(t.approvalFlow)}}else t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&J(t.approvalFlow)})()},[t==null?void 0:t.id,t==null?void 0:t.requestId,t==null?void 0:t.totalLevels,O]),h.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const G=t.id||t.requestId;(async()=>{try{const be=await Ps(G),ue=(be==null?void 0:be.approvalLevels)||(be==null?void 0:be.approvals)||[];if(ue&&ue.length>0){const ge=ue.map(xe=>{var Re;return{step:xe.levelNumber||xe.level_number||0,levelNumber:xe.levelNumber||xe.level_number||0,levelName:xe.levelName||xe.level_name,approver:xe.approverName||xe.approver_name||"",approverEmail:(xe.approverEmail||xe.approver_email||"").toLowerCase(),status:((Re=xe.status)==null?void 0:Re.toLowerCase())||"waiting",tatHours:xe.tatHours||xe.tat_hours||24,elapsedHours:xe.elapsedHours||xe.elapsed_hours,approvedAt:xe.actionDate||xe.action_date,comment:xe.comments||xe.comment,levelId:xe.levelId||xe.level_id}}).sort((xe,Re)=>(xe.levelNumber||0)-(Re.levelNumber||0));J(ge)}}catch(be){console.warn("Failed to load approval flows from API:",be)}})()}},[t==null?void 0:t.currentStep,t==null?void 0:t.totalLevels]);const Y=async()=>{H(G=>G+1),await new Promise(G=>setTimeout(G,500)),n==null||n(),re()},re=async()=>{if(t!=null&&t.id||t!=null&&t.requestId)try{const Me=[...await Pw(t.id||t.requestId)||[]].sort((be,ue)=>new Date(ue.createdAt).getTime()-new Date(be.createdAt).getTime());P(Me)}catch(G){console.warn("Failed to load version history:",G)}};h.useEffect(()=>{re()},[t==null?void 0:t.id,t==null?void 0:t.requestId,O]);const K=(G,Me,be)=>{var xe;const ue=((t==null?void 0:t.totalLevels)||0)>5||(((xe=t==null?void 0:t.approvalLevels)==null?void 0:xe.length)||0)>5;if(Me&&Me.trim()&&(Me.toLowerCase().includes("additional approver")||!/^step\s+\d+$/i.test(Me)))return Me;const ge=ue?{1:"Dealer - Proposal Submission",2:"Requestor Evaluation & Confirmation",3:"Department Lead Approval",4:"Activity Creation",5:"Dealer - Completion Documents",6:"Requestor - Claim Approval",7:"E-Invoice Generation",8:"Credit Note from SAP"}:{1:"Dealer - Proposal Submission",2:"Requestor Evaluation & Confirmation",3:"Department Lead Approval",4:"Dealer - Completion Documents",5:"Requestor - Claim Approval",6:"E-Invoice Generation",7:"Credit Note from SAP"};return ge[G]?ge[G]:be&&be!=="Unknown"&&be!=="System"?`Additional Approver - ${be}`:`Additional Approver - Step ${G}`},ae=(G,Me,be)=>{var Re;if(Me&&Me.toLowerCase().includes("additional approver"))return be&&be!=="Unknown"&&be!=="System"?`${be} will review and approve this request as an additional approver.`:"Additional approver will review and approve this request.";const ge=((t==null?void 0:t.totalLevels)||0)>5||(((Re=t==null?void 0:t.approvalLevels)==null?void 0:Re.length)||0)>5;if(Me&&Me.trim()){const Fe=Me.toLowerCase();if(Fe.includes("dealer")&&Fe.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(Fe.includes("requestor")&&(Fe.includes("evaluation")||Fe.includes("confirmation")))return"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)";if(Fe.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(Fe.includes("activity creation"))return"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.";if(Fe.includes("dealer")&&(Fe.includes("completion")||Fe.includes("documents")))return"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description";if(Fe.includes("requestor")&&(Fe.includes("claim")||Fe.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(Fe.includes("e-invoice")||Fe.includes("invoice generation")||Fe.includes("dms"))return"E-Invoice will be generated upon settlement initiation.";if(Fe.includes("credit note")||Fe.includes("sap"))return"Got credit note from SAP. Review and send to dealer to complete the claim management process."}const xe=ge?{1:"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests",2:"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)",3:"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)",4:"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.",5:"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description",6:"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.",7:"E-Invoice will be generated upon settlement initiation.",8:"Got credit note from SAP. Review and send to dealer to complete the claim management process."}:{1:"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests",2:"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)",3:"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)",4:"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description",5:"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.",6:"E-Invoice will be generated upon settlement initiation.",7:"Got credit note from SAP. Review and send to dealer to complete the claim management process."};return xe[G]?xe[G]:be&&be!=="Unknown"&&be!=="System"?`${be} will review and approve this request.`:`Step ${G} approval required.`},Ne=G=>{if(!v||v.length===0||!G)return{current:null,previous:null};const ue=[...v.filter(Re=>{var Fe;return!!(Re.levelName&&Re.levelName.trim()===G.trim()||(Fe=Re.snapshotData)!=null&&Fe.levelName&&Re.snapshotData.levelName.trim()===G.trim())})].sort((Re,Fe)=>{if(Fe.version!==Re.version)return Fe.version-Re.version;const Ce=Re.snapshotType==="APPROVE"?1:Re.snapshotType==="PROPOSAL"||Re.snapshotType==="COMPLETION"?2:3,Nt=Fe.snapshotType==="APPROVE"?1:Fe.snapshotType==="PROPOSAL"||Fe.snapshotType==="COMPLETION"?2:3;return Ce-Nt}).filter((Re,Fe,Ce)=>Re.snapshotType==="WORKFLOW"?!Ce.some(wt=>wt.snapshotType==="APPROVE"&&wt.levelName===Re.levelName&&wt.version>=Re.version):!0),ge=ue.length>0?ue[0]:null,xe=ue.length>1?ue[1]:null;return{current:ge,previous:xe,all:ue}},Se=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),Ge=Se!=null?Number(Se):null,Je=((t==null?void 0:t.status)||"").toUpperCase(),Pe=Je==="REJECTED",Oe=Je==="CLOSED",ie=!Pe&&!Oe&&(Je==="PENDING"||Je==="IN_PROGRESS"||Je==="IN-PROGRESS"),pe=W.find(G=>{var ue,ge;const Me=G.levelId||G.level_id,be=(ue=t==null?void 0:t.approvals)==null?void 0:ue.find(xe=>xe.levelId===Me);return((ge=be==null?void 0:be.status)==null?void 0:ge.toLowerCase())==="rejected"}),we=pe?Number(pe.levelNumber||pe.level_number||pe.step||0):null,Ae=W.map((G,Me)=>{var va,Ds,he,gt,zt,vs,At;const be=Number(G.levelNumber||G.level_number||G.step||Me+1),ue=G.levelName||G.level_name,ge=(va=t==null?void 0:t.approvals)==null?void 0:va.find($e=>$e.levelId===G.levelId);let xe;if(ue&&ue.toLowerCase().includes("department lead")||be===3){const $e=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);($e!=null&&$e.ioNumber||$e!=null&&$e.io_number)&&(xe={ioNumber:$e.ioNumber||$e.io_number||"",blockedAmount:$e.ioBlockedAmount||$e.io_blocked_amount||0,availableBalance:$e.ioAvailableBalance||$e.io_available_balance||0,remainingBalance:$e.ioRemainingBalance||$e.io_remaining_balance||0,organizedBy:((Ds=$e.organizer)==null?void 0:Ds.displayName)||((he=$e.organizer)==null?void 0:he.name)||$e.organizedBy||G.approver||"N/A",organizedAt:$e.organizedAt||$e.organized_at||G.approvedAt||(t==null?void 0:t.updatedAt)||""})}let Fe;be===6&&(ge!=null&&ge.dmsDetails?Fe={dmsNumber:ge.dmsDetails.dmsNumber||"",dmsRemarks:ge.dmsDetails.dmsRemarks||"",pushedBy:ge.dmsDetails.pushedBy||G.approver,pushedAt:ge.dmsDetails.pushedAt||G.approvedAt||""}:t!=null&&t.dmsNumber&&(Fe={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((gt=t.dmsDetails)==null?void 0:gt.dmsRemarks)||"",pushedBy:G.approver,pushedAt:G.approvedAt||t.updatedAt||""}));let Ce;if(Pe||Oe)((zt=ge==null?void 0:ge.status)==null?void 0:zt.toLowerCase())==="rejected"?Ce="rejected":we!==null&&be>we?Ce="waiting":((vs=ge==null?void 0:ge.status)==null?void 0:vs.toLowerCase())==="approved"?Ce="approved":we!==null&&be<we?((At=ge==null?void 0:ge.status)==null?void 0:At.toLowerCase())==="approved"?Ce="approved":Ce="waiting":(Ge!==null&&be>Ge,Ce="waiting");else if(ie&&Ge!==null&&Ge>0)if(be>Ge)Ce="waiting";else if(be<Ge)if(ge!=null&&ge.status){const $e=ge.status.toLowerCase();$e==="approved"?Ce="approved":$e==="skipped"?Ce="skipped":$e==="rejected"?Ce="rejected":Ce="waiting"}else Ce="waiting";else if(ge!=null&&ge.status){const $e=ge.status.toLowerCase();$e==="approved"?Ce="approved":$e==="rejected"?Ce="rejected":Ce="in_progress"}else{const $e=(G.status||"pending").toLowerCase();$e==="in-review"||$e==="in_review"||$e==="in review"||$e==="pending"?Ce="in_progress":Ce=$e}else if(ge!=null&&ge.status){const $e=ge.status.toLowerCase();$e==="approved"?Ce="approved":$e==="rejected"?Ce="rejected":$e==="pending"||$e==="in_progress"||$e==="in-progress"?Ce="in_progress":Ce=(G.status||"waiting").toLowerCase()}else{const $e=(G.status||"waiting").toLowerCase();$e==="in-review"||$e==="in_review"||$e==="in review"||$e==="pending"?Ce="in_progress":Ce=$e}const wt=Ce==="waiting"?0:G.elapsedHours||0,Ts=G.approver||G.approverName||"Unknown",Tt=ue?Ne(ue):{current:null,previous:null};return{step:be,title:K(be,ue,Ts),approver:Ts,description:ae(be,ue,Ts)||G.description||"",tatHours:G.tatHours||24,status:Ce,comment:G.comment||(ge==null?void 0:ge.comment),approvedAt:G.approvedAt||(ge==null?void 0:ge.timestamp),elapsedHours:wt,ioDetails:xe,dmsDetails:Fe,einvoiceUrl:be===7?ge==null?void 0:ge.einvoiceUrl:void 0,emailTemplateUrl:(ge==null?void 0:ge.emailTemplateUrl)||void 0,versionHistory:Tt}});let ne=null,q=1;if(Pe||Oe)we!==null?q=we:Ge!==null?q=Ge:q=(t==null?void 0:t.currentStep)||1;else if(ie){const G=Ge!==null?Ae.find(Me=>Me.step===Ge):null;ne=G&&(G.status==="pending"||G.status==="in_progress")?G:Ae.find(Me=>{var ue;const be=((ue=Me.status)==null?void 0:ue.toLowerCase())||"";return be==="pending"||be==="in_progress"||be==="in-review"||be==="in_review"}),q=ne?ne.step:Ge||(t==null?void 0:t.currentStep)||1}else q=Ge||(t==null?void 0:t.currentStep)||1;const de=((pr=s==null?void 0:s.email)==null?void 0:pr.toLowerCase())||"",Ye=((Xa=t==null?void 0:t.dealerEmail)==null?void 0:Xa.toLowerCase())||((Ja=(Ta=t==null?void 0:t.dealer)==null?void 0:Ta.email)==null?void 0:Ja.toLowerCase())||((qa=(Za=t==null?void 0:t.claimDetails)==null?void 0:Za.dealerEmail)==null?void 0:qa.toLowerCase())||((As=(Gt=t==null?void 0:t.claimDetails)==null?void 0:Gt.dealer_email)==null?void 0:As.toLowerCase())||"",fe=Ye&&de===Ye,ye=W.find(G=>(G.step||G.levelNumber||G.level_number)===q),Ue=((ye==null?void 0:ye.approverEmail)||"").toLowerCase(),nt=Ue&&de===Ue,mt=((gr=(qs=t==null?void 0:t.initiator)==null?void 0:qs.email)==null?void 0:gr.toLowerCase())||((Rt=t==null?void 0:t.initiatorEmail)==null?void 0:Rt.toLowerCase())||"",vt=W.find(G=>{const Me=(G.approverEmail||"").toLowerCase(),be=(G.levelName||"").toLowerCase();return mt&&Me===mt||be.includes("requestor evaluation")||be.includes("requestor")&&be.includes("confirmation")}),xs=vt&&(vt.step||vt.levelNumber||vt.level_number)||2,le=vt||W.find(G=>(G.step||G.levelNumber||G.level_number)===2),De=((le==null?void 0:le.approverEmail)||"").toLowerCase(),ce=De&&de===De,Ke=W.find(G=>(G.step||G.levelNumber||G.level_number)===1),We=((Ke==null?void 0:Ke.approverEmail)||"").toLowerCase(),tt=We&&de===We,Qe=W.find(G=>(G.levelName||"").toLowerCase().includes("department lead")),rt=((Qe==null?void 0:Qe.approverEmail)||"").toLowerCase(),qe=rt&&de===rt,ot=async G=>{var Me,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ue=t.id||t.requestId;G.proposalDocument&&await Rn(G.proposalDocument,ue,"APPROVAL");for(const xe of G.otherDocuments)await Rn(xe,ue,"SUPPORTING");const ge=G.costBreakup.reduce((xe,Re)=>xe+(Re.totalAmt||Re.amount||0),0);await I5(ue,{proposalDocument:G.proposalDocument||void 0,costBreakup:G.costBreakup.map(xe=>({description:xe.description,amount:xe.amount,gstRate:xe.gstRate,gstAmt:xe.gstAmt,cgstRate:xe.cgstRate,cgstAmt:xe.cgstAmt,sgstRate:xe.sgstRate,sgstAmt:xe.sgstAmt,igstRate:xe.igstRate,igstAmt:xe.igstAmt,utgstRate:xe.utgstRate,utgstAmt:xe.utgstAmt,cessRate:xe.cessRate,cessAmt:xe.cessAmt,totalAmt:xe.totalAmt,quantity:xe.quantity,hsnCode:xe.hsnCode,isService:xe.isService})),totalEstimatedBudget:ge,expectedCompletionDate:G.expectedCompletionDate,dealerComments:G.dealerComments}),X.success("Proposal submitted successfully"),Y()}catch(ue){console.error("Failed to submit proposal:",ue);const ge=((be=(Me=ue==null?void 0:ue.response)==null?void 0:Me.data)==null?void 0:be.message)||(ue==null?void 0:ue.message)||"Failed to submit proposal. Please try again.";throw X.error(ge),ue}},$s=async G=>{var Me,be,ue,ge,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Re=t.id||t.requestId,Fe=await Ps(Re),Ce=(Fe==null?void 0:Fe.approvalLevels)||(Fe==null?void 0:Fe.approvals)||[],Nt=((be=(Me=t==null?void 0:t.initiator)==null?void 0:Me.email)==null?void 0:be.toLowerCase())||((ue=t==null?void 0:t.initiatorEmail)==null?void 0:ue.toLowerCase())||"",wt=Ce.find(Tt=>{const va=(Tt.approverEmail||Tt.approver_email||"").toLowerCase(),Ds=(Tt.levelName||Tt.level_name||"").toLowerCase(),he=Tt.levelNumber||Tt.level_number;return Nt&&va===Nt||Ds.includes("requestor evaluation")||Ds.includes("requestor")&&Ds.includes("confirmation")||he===xs})||Ce.find(Tt=>(Tt.levelNumber||Tt.level_number)===2);if(!(wt!=null&&wt.levelId)&&!(wt!=null&&wt.level_id))throw new Error("Initiator approval level not found");const Ts=wt.levelId||wt.level_id;await Tn(Re,Ts,G),X.success("Proposal approved successfully"),Y()}catch(Re){console.error("Failed to approve proposal:",Re);const Fe=((xe=(ge=Re==null?void 0:Re.response)==null?void 0:ge.data)==null?void 0:xe.message)||(Re==null?void 0:Re.message)||"Failed to approve proposal. Please try again.";throw X.error(Fe),Re}},ns=async G=>{var Me,be,ue,ge,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Re=t.id||t.requestId,Fe=await Ps(Re),Ce=(Fe==null?void 0:Fe.approvalLevels)||(Fe==null?void 0:Fe.approvals)||[],Nt=((be=(Me=t==null?void 0:t.initiator)==null?void 0:Me.email)==null?void 0:be.toLowerCase())||((ue=t==null?void 0:t.initiatorEmail)==null?void 0:ue.toLowerCase())||"",wt=Ce.find(Tt=>{const va=(Tt.approverEmail||Tt.approver_email||"").toLowerCase(),Ds=(Tt.levelName||Tt.level_name||"").toLowerCase(),he=Tt.levelNumber||Tt.level_number;return Nt&&va===Nt||Ds.includes("requestor evaluation")||Ds.includes("requestor")&&Ds.includes("confirmation")||he===xs})||Ce.find(Tt=>(Tt.levelNumber||Tt.level_number)===2);if(!(wt!=null&&wt.levelId)&&!(wt!=null&&wt.level_id))throw new Error("Initiator approval level not found");const Ts=wt.levelId||wt.level_id;await Nr(Re,Ts,"Proposal rejected by requestor",G),X.success("Proposal rejected. Request has been cancelled."),Y()}catch(Re){console.error("Failed to reject proposal:",Re);const Fe=((xe=(ge=Re==null?void 0:Re.response)==null?void 0:ge.data)==null?void 0:xe.message)||(Re==null?void 0:Re.message)||"Failed to reject proposal. Please try again.";throw X.error(Fe),Re}},pt=async G=>{var Me,be,ue,ge,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Re=t.id||t.requestId,Fe=await Ps(Re),Ce=(Fe==null?void 0:Fe.approvalLevels)||(Fe==null?void 0:Fe.approvals)||[],Nt=((be=(Me=t==null?void 0:t.initiator)==null?void 0:Me.email)==null?void 0:be.toLowerCase())||((ue=t==null?void 0:t.initiatorEmail)==null?void 0:ue.toLowerCase())||"",wt=Ce.find(Tt=>{const va=(Tt.approverEmail||Tt.approver_email||"").toLowerCase(),Ds=(Tt.levelName||Tt.level_name||"").toLowerCase(),he=Tt.levelNumber||Tt.level_number;return Nt&&va===Nt||Ds.includes("requestor evaluation")||Ds.includes("requestor")&&Ds.includes("confirmation")||he===xs})||Ce.find(Tt=>(Tt.levelNumber||Tt.level_number)===2);if(!(wt!=null&&wt.levelId)&&!(wt!=null&&wt.level_id))throw new Error("Initiator approval level not found");const Ts=wt.levelId||wt.level_id;await Nr(Re,Ts,"Revised Quotation Requested",G),X.success("Revision requested. Request returned to dealer."),Y()}catch(Re){console.error("Failed to request revision:",Re);const Fe=((xe=(ge=Re==null?void 0:Re.response)==null?void 0:ge.data)==null?void 0:xe.message)||(Re==null?void 0:Re.message)||"Failed to request revision. Please try again.";throw X.error(Fe),Re}},ct=async G=>{var Me,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ue=t.id||t.requestId,ge=await Ps(ue),Re=((ge==null?void 0:ge.approvalLevels)||(ge==null?void 0:ge.approvals)||[]).find(Ce=>{const Nt=(Ce.levelName||Ce.level_name||"").toLowerCase();return Nt.includes("requestor claim")||Nt.includes("requestor - claim")});if(!(Re!=null&&Re.levelId)&&!(Re!=null&&Re.level_id))throw new Error("Claim approval level not found");const Fe=Re.levelId||Re.level_id;await Nr(ue,Fe,"Revised Quotation Requested",G),X.success("Re-quotation requested. Request returned to dealer."),Y()}catch(ue){console.error("Failed to request re-quotation:",ue);const ge=((be=(Me=ue==null?void 0:ue.response)==null?void 0:Me.data)==null?void 0:be.message)||(ue==null?void 0:ue.message)||"Failed to request re-quotation. Please try again.";throw X.error(ge),ue}},Ft=async G=>{var Me,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ue=t.id||t.requestId,ge=await Ps(ue),xe=(ge==null?void 0:ge.approvalLevels)||(ge==null?void 0:ge.approvals)||[],Re=xe.find(Ce=>(Ce.levelName||Ce.level_name||"").toLowerCase().includes("department lead"))||xe.find(Ce=>(Ce.levelNumber||Ce.level_number)===3);if(!(Re!=null&&Re.levelId)&&!(Re!=null&&Re.level_id))throw new Error("Department Lead approval level not found");const Fe=Re.levelId||Re.level_id;await g0(ue,{ioNumber:G.ioNumber}),await Tn(ue,Fe,G.comments),X.success("Request approved and IO organized successfully"),Y()}catch(ue){console.error("Failed to approve and organize IO:",ue);const ge=((be=(Me=ue==null?void 0:ue.response)==null?void 0:Me.data)==null?void 0:be.message)||(ue==null?void 0:ue.message)||"Failed to approve request. Please try again.";throw X.error(ge),ue}},Ss=async G=>{var Me,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ue=t.id||t.requestId,ge=G.closedExpenses.map(xe=>({description:xe.description,amount:xe.amount,gstRate:xe.gstRate,gstAmt:xe.gstAmt,cgstRate:xe.cgstRate,cgstAmt:xe.cgstAmt,sgstRate:xe.sgstRate,sgstAmt:xe.sgstAmt,igstRate:xe.igstRate,igstAmt:xe.igstAmt,utgstRate:xe.utgstRate,utgstAmt:xe.utgstAmt,cessRate:xe.cessRate,cessAmt:xe.cessAmt,totalAmt:xe.totalAmt,quantity:xe.quantity,hsnCode:xe.hsnCode,isService:xe.isService}));if(await P5(ue,{activityCompletionDate:G.activityCompletionDate,numberOfParticipants:G.numberOfParticipants,closedExpenses:ge,totalClosedExpenses:G.totalClosedExpenses,completionDocuments:G.completionDocuments,activityPhotos:G.activityPhotos,completionDescription:G.completionDescription}),G.invoicesReceipts&&G.invoicesReceipts.length>0)for(const xe of G.invoicesReceipts)await Rn(xe,ue,"SUPPORTING");G.attendanceSheet&&await Rn(G.attendanceSheet,ue,"SUPPORTING"),X.success("Completion documents submitted successfully"),Y()}catch(ue){console.error("Failed to submit completion documents:",ue);const ge=((be=(Me=ue==null?void 0:ue.response)==null?void 0:Me.data)==null?void 0:be.message)||(ue==null?void 0:ue.message)||"Failed to submit completion documents. Please try again.";throw X.error(ge),ue}},ss=async G=>{var Me,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ue=t.id||t.requestId,ge=new Date().toISOString().slice(0,10);await _5(ue,{eInvoiceDate:ge}),X.success("E-Invoice generation initiated successfully."),Y()}catch(ue){console.error("[DealerClaimWorkflowTab] Error generating e-invoice:",ue);let xe=((be=(Me=ue==null?void 0:ue.response)==null?void 0:Me.data)==null?void 0:be.message)||(ue==null?void 0:ue.message)||"E-Invoice generation failed. Please try again.";throw xe.length>300&&(xe=xe.substring(0,300)+"..."),X.error(xe),ue}},Ma=async G=>{var Me,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ue=t.id||t.requestId,ge=await Ps(ue),xe=(ge==null?void 0:ge.approvalLevels)||(ge==null?void 0:ge.approvals)||[],Re=xe.find(Ce=>(Ce.levelName||Ce.level_name||"").toLowerCase().includes("department lead"))||xe.find(Ce=>(Ce.levelNumber||Ce.level_number)===3);if(!(Re!=null&&Re.levelId)&&!(Re!=null&&Re.level_id))throw new Error("Department Lead approval level not found");const Fe=Re.levelId||Re.level_id;await Nr(ue,Fe,"Dept Lead rejected - More clarification required",G),X.success("Request rejected. Request has been cancelled."),Y()}catch(ue){console.error("Failed to reject request:",ue);const ge=((be=(Me=ue==null?void 0:ue.response)==null?void 0:Me.data)==null?void 0:be.message)||(ue==null?void 0:ue.message)||"Failed to reject request. Please try again.";throw X.error(ge),ue}},[La,Aa]=h.useState(null);h.useEffect(()=>{if(!t){Aa(null);return}(async()=>{try{const Me=t.id||t.requestId;if(!Me){Aa(null);return}const be=await Ps(Me),ue=(be==null?void 0:be.documents)||[],ge=t.proposalDetails||(be==null?void 0:be.proposalDetails)||{},xe=ue.find(Ce=>Ce.category==="APPROVAL"||Ce.type==="proposal"||Ce.documentCategory==="APPROVAL"),Re=ue.filter(Ce=>Ce.category==="SUPPORTING"||Ce.type==="supporting"||Ce.documentCategory==="SUPPORTING");let Fe=ge.costBreakup||[];if(typeof Fe=="string")try{Fe=JSON.parse(Fe)}catch(Ce){console.warn("Failed to parse costBreakup JSON:",Ce),Fe=[]}Array.isArray(Fe)||(Fe=[]),Aa({proposalDocument:xe?{name:xe.fileName||xe.file_name||xe.name,id:xe.documentId||xe.document_id||xe.id}:void 0,costBreakup:Fe,expectedCompletionDate:ge.expectedCompletionDate||"",otherDocuments:Re.map(Ce=>({name:Ce.fileName||Ce.file_name||Ce.name,id:Ce.documentId||Ce.document_id||Ce.id})),dealerComments:ge.dealerComments||"",submittedAt:ge.submittedAt})}catch(Me){console.warn("Failed to load proposal data:",Me);const be=t.proposalDetails||{};let ue=be.costBreakup||[];if(typeof ue=="string")try{ue=JSON.parse(ue)}catch(ge){console.warn("Failed to parse costBreakup JSON:",ge),ue=[]}Array.isArray(ue)||(ue=[]),Aa({proposalDocument:void 0,costBreakup:ue,expectedCompletionDate:be.expectedCompletionDate||"",otherDocuments:[],dealerComments:be.dealerComments||"",submittedAt:be.submittedAt})}})()},[t]);const[Ya,It]=h.useState(null);h.useEffect(()=>{if(!t){It(null);return}(async()=>{try{const Me=t.id||t.requestId;if(!Me){It(null);return}const be=await Ps(Me),ue=(be==null?void 0:be.documents)||[],ge=[],xe=[],Re=[];let Fe=null;ue.forEach(Ce=>{const Nt=(Ce.category||Ce.documentCategory||Ce.type||"").toUpperCase(),wt=(Ce.fileName||Ce.file_name||Ce.name||"").toLowerCase(),Ts={name:Ce.fileName||Ce.file_name||Ce.name,id:Ce.documentId||Ce.document_id||Ce.id,url:Ce.url||Ce.storageUrl||Ce.storage_url};Nt==="COMPLETION"||Nt==="COMPLETION_DOCUMENT"?ge.push(Ts):Nt==="ACTIVITY_PHOTO"||Nt==="PHOTO"||Nt==="IMAGE"?xe.push(Ts):Nt==="ATTENDANCE"||Nt==="ATTENDANCE_SHEET"?Fe=Ts:(Nt==="SUPPORTING"||Nt==="INVOICE"||Nt==="RECEIPT")&&(!Fe&&(wt.includes("attendance")||wt.includes("participant"))?Fe=Ts:Re.push(Ts))}),ge.length===0&&xe.length===0&&t.completionDetails,It({completionDocuments:ge,activityPhotos:xe,invoicesReceipts:Re,attendanceSheet:Fe})}catch(Me){console.warn("Failed to load completion documents:",Me),It(null)}})()},[t]);const Oa=async()=>{try{X.loading("Retriggering WFM push...",{id:"wfm-retrigger"}),await O5(t.id),X.success("WFM push re-triggered successfully",{id:"wfm-retrigger"}),n?n():window.location.reload()}catch(G){console.error("Error retriggering WFM push:",G),X.error(G.message||"Failed to re-trigger WFM push",{id:"wfm-retrigger"})}},Us=async()=>{try{const G=t.id||t.requestId;if(!G){X.error("Request ID not found");return}const be=await fetch(`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${G}/e-invoice/csv`,{headers:{Authorization:`Bearer ${at.getAccessToken()||""}`},credentials:"include"});if(!be.ok)throw new Error("Failed to download CSV");const ue=await be.blob(),ge=window.URL.createObjectURL(ue),xe=document.createElement("a");xe.href=ge,xe.download=`Invoice_${t.requestNumber||"Export"}.csv`,document.body.appendChild(xe),xe.click(),window.URL.revokeObjectURL(ge),document.body.removeChild(xe),X.success("CSV downloaded successfully")}catch(G){console.error("Error downloading CSV:",G),X.error("Failed to download CSV")}},Lr=async()=>{try{const G=t.id||t.requestId;if(!G){X.error("Request ID not found");return}if(!t.invoice&&!t.irn){X.error("Invoice not generated yet");return}B(!0),M(!0);const be=await fetch(`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${G}/e-invoice/pdf`,{headers:{Authorization:`Bearer ${at.getAccessToken()||""}`},credentials:"include"});if(!be.ok)throw new Error("Failed to fetch invoice PDF");const ue=await be.blob(),ge=window.URL.createObjectURL(ue);k&&window.URL.revokeObjectURL(k),z(ge)}catch(G){console.error("Failed to preview invoice:",G),X.error("Failed to load invoice preview"),M(!1)}finally{B(!1)}},xr=()=>{M(!1),k&&(window.URL.revokeObjectURL(k),z(null))},Or=()=>{if(k){const G=document.createElement("a");G.href=k,G.download=`Invoice_${t.requestNumber||"Download"}.pdf`,document.body.appendChild(G),G.click(),document.body.removeChild(G),X.success("Invoice PDF downloaded")}},Ka=((Xt=t==null?void 0:t.claimDetails)==null?void 0:Xt.dealerName)||((Rs=t==null?void 0:t.dealerInfo)==null?void 0:Rs.name)||"Dealer",hr=((ma=t==null?void 0:t.claimDetails)==null?void 0:ma.dealerGstin)||(($r=t==null?void 0:t.dealerInfo)==null?void 0:$r.gstin)||((ya=t==null?void 0:t.dealerInfo)==null?void 0:ya.dealerGSTIN),Qa=((er=t==null?void 0:t.claimDetails)==null?void 0:er.activityName)||((pn=t==null?void 0:t.activityInfo)==null?void 0:pn.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(Z,{children:[e.jsx(oe,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(ve,{className:"mt-2",children:"Approval process for dealer claim management"})]})})}),e.jsxs(ee,{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(ts,{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((G,Me)=>{var wt,Ts,Tt,va,Ds;const ue=(((wt=G.status)==null?void 0:wt.toLowerCase())||"")==="in_progress",ge=G.step===q,xe=ie&&ue&&ge,Re=G.status==="approved"||G.status==="skipped",Fe=W.find(he=>(he.step||he.levelNumber||he.level_number)===G.step),Ce=Fe!=null&&Fe.levelId?(Ts=t==null?void 0:t.approvals)==null?void 0:Ts.find(he=>he.levelId===Fe.levelId||he.level_id===Fe.levelId):null,Nt=(Ce==null?void 0:Ce.status)==="PAUSED"||((Tt=t==null?void 0:t.pauseInfo)==null?void 0:Tt.isPaused)&&(((va=t==null?void 0:t.pauseInfo)==null?void 0:va.levelId)===(Ce==null?void 0:Ce.levelId)||((Ds=t==null?void 0:t.pauseInfo)==null?void 0:Ds.level_id)===(Ce==null?void 0:Ce.levelId));return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${B5(G.status,xe)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${V5(G.status)}`,children:$5(G.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:G.title}),e.jsx(se,{className:U5(G.status),children:G.status.toLowerCase()}),G.emailTemplateUrl&&G.status==="approved"&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>{S({stepNumber:G.step,stepName:G.title}),w(!0)},children:e.jsx(ba,{className:"w-3.5 h-3.5 text-blue-600"})}),G.step===7&&G.einvoiceUrl&&Re&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",title:"Download E-Invoice",onClick:()=>window.open(G.einvoiceUrl,"_blank"),children:e.jsx(kt,{className:"w-3.5 h-3.5 text-green-600"})}),(()=>{const he=(G.levelName||G.title||"").toLowerCase().includes("requestor claim")||(G.levelName||G.title||"").toLowerCase().includes("requestor - claim"),gt=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&G.status==="approved";return he&>&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-amber-100",title:"Preview Invoice",onClick:Lr,children:e.jsx(Pt,{className:"w-3.5 h-3.5 text-amber-600"})})})(),(()=>{var At,$e,Ns,Bt;const he=(G.levelName||G.title||"").toLowerCase().includes("requestor claim")||(G.levelName||G.title||"").toLowerCase().includes("requestor - claim"),gt=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&G.status==="approved",zt=((At=t==null?void 0:t.invoice)==null?void 0:At.wfmPushStatus)||(($e=t==null?void 0:t.invoice)==null?void 0:$e.wfmPushStatus),vs=((Ns=t==null?void 0:t.invoice)==null?void 0:Ns.wfmPushError)||((Bt=t==null?void 0:t.invoice)==null?void 0:Bt.wfmPushError);return he&>&&e.jsxs("div",{className:"flex items-center gap-1 ml-1",children:[e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-emerald-100",title:"Export CSV",onClick:Us,children:e.jsx(dh,{className:"w-3.5 h-3.5 text-emerald-600"})}),zt==="SUCCESS"?e.jsx("div",{title:"Pushed to WFM successfully",children:e.jsx(us,{className:"w-3.5 h-3.5 text-green-500"})}):zt==="FAILED"?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{title:`WFM Push Failed: ${vs||"Unknown error"}`,children:e.jsx(St,{className:"w-3.5 h-3.5 text-red-500"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[10px] text-red-600 hover:text-red-700 hover:bg-red-50 border border-red-200 h-auto py-0",onClick:Oa,children:"Retry Push"})]}):e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{title:"WFM Push Pending",children:e.jsx(st,{className:"w-3.5 h-3.5 text-amber-500"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[10px] text-amber-600 hover:text-amber-700 hover:bg-amber-50 border border-amber-200 h-auto py-0",onClick:Oa,children:"Push Now"})]})]})})()]}),e.jsx("p",{className:"text-sm text-gray-600",children:G.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:G.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",Kt(G.tatHours)]}),G.elapsedHours&&(xe||Re)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",Kt(G.elapsedHours)]})]})]}),G.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:G.comment})}),G.versionHistory&&G.versionHistory.all&&G.versionHistory.all.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsxs(E,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs text-amber-700 hover:text-amber-800 hover:bg-amber-50",onClick:()=>{const he=new Set(F);he.has(G.step)?he.delete(G.step):he.add(G.step),$(he)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xh,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"font-medium",children:"Version History"}),G.versionHistory.all&&G.versionHistory.all.length>0&&e.jsxs(se,{className:"bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0",children:[G.versionHistory.all.length," Versions"]})]}),F.has(G.step)?e.jsx(Wi,{className:"w-4 h-4"}):e.jsx(rn,{className:"w-4 h-4"})]}),F.has(G.step)&&G.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:G.versionHistory.all.map((he,gt)=>{var zt,vs,At,$e;return e.jsxs("div",{className:`space-y-2 ${gt>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(se,{className:`${gt===0?"bg-amber-500":"bg-gray-400"} text-white text-[10px] px-2 py-0.5`,children:[gt===0?"Current":"Previous",": v",he.version]}),e.jsx("span",{className:"text-[10px] text-gray-600 font-medium",children:Br(he.createdAt)})]})}),e.jsx("p",{className:"text-xs text-gray-700 font-medium",children:he.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${gt===0?"bg-blue-100":"bg-gray-100"} flex items-center justify-center`,children:e.jsx("span",{className:`text-[8px] font-bold ${gt===0?"text-blue-600":"text-gray-600"}`,children:((vs=(zt=he.changer)==null?void 0:zt.displayName)==null?void 0:vs.charAt(0))||"U"})}),e.jsxs("span",{className:"text-[10px] text-gray-600",children:["By ",((At=he.changer)==null?void 0:At.displayName)||(($e=he.changer)==null?void 0:$e.email)||"Unknown User"]})]}),he.snapshotType==="PROPOSAL"&&he.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(he.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>T({data:he.snapshotData,type:"PROPOSAL",title:`Proposal (v${he.version})`}),children:[e.jsx(Ct,{className:"w-3 h-3"}),"View Details"]})]}),he.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",he.snapshotData.comments]})]}),he.snapshotType==="INTERNAL_ORDER"&&he.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: ",he.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Blocked Amount: ₹",Number(he.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),he.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-[10px] text-gray-600",children:["SAP Doc: ",he.snapshotData.sapDocumentNumber]})]}),he.snapshotType==="COMPLETION"&&he.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(he.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>T({data:he.snapshotData,type:"COMPLETION",title:`Completion (v${he.version})`}),children:[e.jsx(Ct,{className:"w-3 h-3"}),"View Details"]})]}),he.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",he.snapshotData.comments]})]}),he.snapshotType==="APPROVE"&&he.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:[he.snapshotData.action==="APPROVE"?"Approval":"Rejection"," Snapshot:"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["By: ",he.snapshotData.approverName||he.snapshotData.approverEmail||"Unknown"]}),he.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1",children:["Comments: ",he.snapshotData.comments.substring(0,100),he.snapshotData.comments.length>100?"...":""]}),he.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-[10px] text-red-600 mt-1",children:["Rejection Reason: ",he.snapshotData.rejectionReason.substring(0,100),he.snapshotData.rejectionReason.length>100?"...":""]})]}),he.snapshotType==="WORKFLOW"&&he.snapshotData&&he.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:[he.snapshotData.comments.substring(0,100),he.snapshotData.comments.length>100?"...":""]})]})]},gt)})})]}),xe&&(Ce==null?void 0:Ce.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:Ce.sla.deadline?Ca(Ce.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${Nt?"bg-gray-100 border-gray-300":(Ce.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(Ce.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(Ce.sla.percentageUsed||0)>=50?"bg-amber-50 border-amber-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(st,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",Nt&&"(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:Ce.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:[Ce.sla.elapsedText||"0 hours"," / ",Kt(G.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const he=Ce.sla.percentageUsed||0,gt=()=>Nt?"bg-gray-500":he>=100?"bg-red-600":he>=75?"bg-orange-500":he>=50?"bg-amber-500":"bg-green-600",zt=()=>Nt?"text-gray-600":he>=100?"text-red-600":he>=75?"text-orange-600":he>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(Zs,{value:he,className:"h-3",indicatorClassName:gt()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${zt()}`,children:["Progress: ",Math.min(100,he),"% of TAT used"]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[Ce.sla.remainingText||"0 hours"," remaining"]})]})]})})(),Ce.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(Fi,{className:"w-4 h-4"}),"Deadline Breached"]}),Ce.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(ts,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),(()=>{const he=G.levelName||G.level_name;return(he&&he.toLowerCase().includes("department lead")||G.title&&G.title.toLowerCase().includes("department lead"))&&G.status==="approved"&&G.ioDetails&&G.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(Pt,{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:G.ioDetails.ioNumber})]}),G.ioDetails.blockedAmount!==void 0&&G.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:["₹",G.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),G.ioDetails.remainingBalance!==void 0&&G.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:["₹",G.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 ",G.ioDetails.organizedBy||G.approver||"N/A"," on"," ",G.ioDetails.organizedAt?Br(G.ioDetails.organizedAt):G.approvedAt?Br(G.approvedAt):"N/A"]})]})]})})(),G.step===6&&G.dmsDetails&&G.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(Ot,{className:"w-4 h-4 text-purple-600"}),e.jsx("p",{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice & Settlement Details"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"Settlement ID:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:G.dmsDetails.dmsNumber})]}),G.dmsDetails.dmsRemarks&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Settlement Remarks:"}),e.jsx("p",{className:"text-sm text-gray-900",children:G.dmsDetails.dmsRemarks})]}),G.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Initiated by ",G.dmsDetails.pushedBy," on"," ",Br(G.dmsDetails.pushedAt)]})]})]}),(()=>{const he=W.find($e=>($e.step||$e.levelNumber||$e.level_number)===G.step),gt=((he==null?void 0:he.approverEmail)||"").toLowerCase(),zt=gt&&de===gt,vs=G.step===1||(he==null?void 0:he.levelName)&&he.levelName.toLowerCase().includes("dealer");return xe&&(zt||vs&&fe)})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[(()=>{const he=((Fe==null?void 0:Fe.levelName)||G.title||"").toLowerCase();return(G.step===1||he.includes("proposal")||he.includes("submission"))&&(fe||tt)})()&&e.jsxs(E,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{o(!0)},children:[e.jsx(js,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),(()=>{const he=((Fe==null?void 0:Fe.levelName)||G.title||"").toLowerCase();return(he.includes("requestor evaluation")||he.includes("confirmation")||G.step===xs)&&(a||ce)})()&&e.jsxs(E,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{d(!0)},children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const he=W.find($e=>($e.step||$e.levelNumber||$e.level_number)===G.step);if(!((he==null?void 0:he.levelName)||G.title||"").toLowerCase().includes("initiator action")||!(a||de===mt))return null;const At=async $e=>{var Ns,Bt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Fs=t.requestId||t.id;await dp(Fs,$e,{reason:""}),X.success(`Action "${$e==="REVISE"?"Revision Requested":"Request Reopened"}" performed successfully`),Y()}catch(Fs){console.error("Failed to perform initiator action:",Fs);const L0=((Bt=(Ns=Fs==null?void 0:Fs.response)==null?void 0:Ns.data)==null?void 0:Bt.message)||(Fs==null?void 0:Fs.message)||"Failed to perform action";X.error(L0)}};return e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(E,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:()=>At("REVISE"),children:[e.jsx($t,{className:"w-4 h-4 mr-2"}),"Request Re-quotation"]}),e.jsxs(E,{variant:"outline",className:"border-blue-500 text-blue-600 hover:bg-blue-50",onClick:()=>At("REOPEN"),children:[e.jsx(ih,{className:"w-4 h-4 mr-2"}),"Reopen"]})]})})(),(()=>{const he=W.find(Bt=>(Bt.levelName||"").toLowerCase().includes("department lead"));if(!(he&&G.step===(he.step||he.levelNumber||he.level_number)))return null;const zt=((he==null?void 0:he.approverEmail)||"").toLowerCase();if(!(zt&&de===zt||qe||nt))return null;const At=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),$e=(At==null?void 0:At.ioNumber)||(At==null?void 0:At.io_number)||(t==null?void 0:t.ioNumber)||"",Ns=$e&&$e.trim()!=="";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(E,{className:"bg-green-600 hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>{p(!0)},disabled:!Ns,children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Review and Approve"]}),!Ns&&e.jsx("p",{className:"text-xs text-amber-600",children:"Please add an IO number in the IO tab before approving this step."})]})})(),(()=>{const he=W.find($e=>($e.step||$e.levelNumber||$e.level_number)===G.step),gt=((he==null?void 0:he.approverEmail)||"").toLowerCase(),zt=fe&>===Ye,vs=((he==null?void 0:he.levelName)||G.title||"").toLowerCase(),At=vs.includes("dealer completion")||vs.includes("completion documents");return zt&&At})()&&e.jsxs(E,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{u(!0)},children:[e.jsx(js,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const he=W.find(At=>{const $e=(At.levelName||"").toLowerCase();return $e.includes("requestor claim")||$e.includes("requestor - claim")});if(!(he&&G.step===(he.step||he.levelNumber||he.level_number)))return null;const zt=((he==null?void 0:he.approverEmail)||"").toLowerCase();return a||zt&&de===zt?e.jsxs(E,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{f(!0)},children:[e.jsx(Ot,{className:"w-4 h-4 mr-2"}),"Generate E-Invoice & Sync"]}):null})(),(()=>{var Ns;const he=((Fe==null?void 0:Fe.levelName)||G.title||"").toLowerCase(),gt=he.includes("credit note")||he.includes("sap")||G.step===8&&!he.includes("additional"),zt=((Fe==null?void 0:Fe.approverEmail)||"").toLowerCase(),vs=zt&&de===zt,At=((Ns=s==null?void 0:s.role)==null?void 0:Ns.toUpperCase())||"";return gt&&(vs||(At==="FINANCE"||At==="ADMIN"))})()&&e.jsxs(E,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{j(!0)},children:[e.jsx(Pt,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]}),(()=>{const he=W.find(At=>(At.step||At.levelNumber||At.level_number)===G.step),gt=((he==null?void 0:he.levelName)||G.title||"").toLowerCase(),zt=gt.includes("additional approver"),vs=G.step===1||gt.includes("proposal")||gt.includes("submission")||gt.includes("requestor evaluation")||gt.includes("confirmation")||gt.includes("department lead")||gt.includes("dealer completion")||gt.includes("completion documents")||gt.includes("requestor claim")||gt.includes("requestor - claim")||gt.includes("credit note")||gt.includes("sap");if(zt||!vs){const At=(he==null?void 0:he.levelId)||(he==null?void 0:he.level_id);if(At){const $e=(he==null?void 0:he.levelName)||(he==null?void 0:he.level_name)||G.title||"Approval Level",Ns=(he==null?void 0:he.approverName)||(he==null?void 0:he.approver_name)||G.approver||"Approver";return e.jsxs(E,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{R({levelId:At,levelName:$e,approverName:Ns}),_(!0)},children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Review Request"]})}return e.jsxs(e.Fragment,{children:[e.jsxs(E,{className:"bg-green-600 hover:bg-green-700",onClick:async()=>{var $e,Ns;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Bt=t.id||t.requestId;if(!At){X.error("Approval level not found");return}await Tn(Bt,At,""),X.success("Request approved successfully"),Y()}catch(Bt){console.error("Failed to approve:",Bt);const Fs=((Ns=($e=Bt==null?void 0:Bt.response)==null?void 0:$e.data)==null?void 0:Ns.message)||(Bt==null?void 0:Bt.message)||"Failed to approve request. Please try again.";X.error(Fs)}},children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(E,{variant:"destructive",onClick:async()=>{var $e,Ns;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Bt=t.id||t.requestId;if(!At){X.error("Approval level not found");return}const Fs=prompt("Please provide a reason for rejection:");if(Fs===null)return;await Nr(Bt,At,"Request rejected",Fs),X.success("Request rejected successfully"),Y()}catch(Bt){console.error("Failed to reject:",Bt);const Fs=((Ns=($e=Bt==null?void 0:Bt.response)==null?void 0:$e.data)==null?void 0:Ns.message)||(Bt==null?void 0:Bt.message)||"Failed to reject request. Please try again.";X.error(Fs)}},children:[e.jsx(St,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),G.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",Br(G.approvedAt)]})]})]})},Me)})})]})]}),e.jsx(C5,{isOpen:l,onClose:()=>o(!1),onSubmit:ot,dealerName:Ka,dealerGSTIN:hr,activityName:Qa,defaultGstRate:(gn=t==null?void 0:t.claimDetails)==null?void 0:gn.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),previousProposalData:(fn=v==null?void 0:v.find(G=>G.snapshotType==="PROPOSAL"))==null?void 0:fn.snapshotData,documentPolicy:i,taxationType:(Kc=t==null?void 0:t.claimDetails)==null?void 0:Kc.taxationType,totalBlockedAmount:((t==null?void 0:t.internalOrders)||[]).reduce((G,Me)=>G+Number(Me.ioBlockedAmount||Me.io_blocked_amount||Me.blockedAmount||0),0)}),e.jsx(k5,{isOpen:c,onClose:()=>{d(!1)},onApprove:$s,onReject:ns,onRequestRevision:pt,proposalData:La,dealerName:Ka,activityName:Qa,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const G=(v==null?void 0:v.filter(Me=>Me.snapshotType==="PROPOSAL"))||[];return G.length>1?G[1].snapshotData:null})(),taxationType:(Qc=t==null?void 0:t.claimDetails)==null?void 0:Qc.taxationType}),e.jsx(S5,{isOpen:m,onClose:()=>p(!1),onApprove:Ft,onReject:Ma,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((Xc=t==null?void 0:t.internalOrder)==null?void 0:Xc.ioNumber)||((Jc=t==null?void 0:t.internalOrder)==null?void 0:Jc.io_number)||((Zc=t==null?void 0:t.internal_order)==null?void 0:Zc.ioNumber)||((qc=t==null?void 0:t.internal_order)==null?void 0:qc.io_number)||void 0,preFilledBlockedAmount:((ed=t==null?void 0:t.internalOrder)==null?void 0:ed.ioBlockedAmount)||((td=t==null?void 0:t.internalOrder)==null?void 0:td.io_blocked_amount)||((sd=t==null?void 0:t.internal_order)==null?void 0:sd.ioBlockedAmount)||((ad=t==null?void 0:t.internal_order)==null?void 0:ad.io_blocked_amount)||void 0,preFilledRemainingBalance:((rd=t==null?void 0:t.internalOrder)==null?void 0:rd.ioRemainingBalance)||((nd=t==null?void 0:t.internalOrder)==null?void 0:nd.io_remaining_balance)||((id=t==null?void 0:t.internal_order)==null?void 0:id.ioRemainingBalance)||((ld=t==null?void 0:t.internal_order)==null?void 0:ld.io_remaining_balance)||void 0,taxationType:(od=t==null?void 0:t.claimDetails)==null?void 0:od.taxationType}),e.jsx(w5,{isOpen:x,onClose:()=>u(!1),onSubmit:Ss,dealerName:Ka,dealerGSTIN:hr,activityName:Qa,defaultGstRate:(cd=t==null?void 0:t.claimDetails)==null?void 0:cd.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i,taxationType:(dd=t==null?void 0:t.claimDetails)==null?void 0:dd.taxationType}),e.jsx(A5,{isOpen:g,onClose:()=>f(!1),onPush:ss,completionDetails:{activityCompletionDate:((md=t==null?void 0:t.completionDetails)==null?void 0:md.activityCompletionDate)||((ud=t==null?void 0:t.completionDetails)==null?void 0:ud.activity_completion_date),numberOfParticipants:((xd=t==null?void 0:t.completionDetails)==null?void 0:xd.numberOfParticipants)||((hd=t==null?void 0:t.completionDetails)==null?void 0:hd.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((pd=t==null?void 0:t.completionDetails)==null?void 0:pd.closedExpenses)||((gd=t==null?void 0:t.completionDetails)==null?void 0:gd.closed_expenses),totalClosedExpenses:((fd=t==null?void 0:t.budgetTracking)==null?void 0:fd.closedExpenses)||((bd=t==null?void 0:t.budgetTracking)==null?void 0:bd.closed_expenses)||((jd=t==null?void 0:t.completionDetails)==null?void 0:jd.totalClosedExpenses)||((yd=t==null?void 0:t.completionDetails)==null?void 0:yd.total_closed_expenses),completionDescription:((vd=t==null?void 0:t.completionDetails)==null?void 0:vd.completionDescription)||((Nd=t==null?void 0:t.completionDetails)==null?void 0:Nd.completion_description)},ioDetails:{ioNumber:((wd=t==null?void 0:t.internalOrder)==null?void 0:wd.ioNumber)||((Cd=t==null?void 0:t.internalOrder)==null?void 0:Cd.io_number)||((Sd=t==null?void 0:t.internal_order)==null?void 0:Sd.ioNumber)||((Ad=t==null?void 0:t.internal_order)==null?void 0:Ad.io_number),blockedAmount:((Td=t==null?void 0:t.internalOrder)==null?void 0:Td.ioBlockedAmount)||((kd=t==null?void 0:t.internalOrder)==null?void 0:kd.io_blocked_amount)||((Rd=t==null?void 0:t.internal_order)==null?void 0:Rd.ioBlockedAmount)||((Dd=t==null?void 0:t.internal_order)==null?void 0:Dd.io_blocked_amount),availableBalance:((Fd=t==null?void 0:t.internalOrder)==null?void 0:Fd.ioAvailableBalance)||((Id=t==null?void 0:t.internalOrder)==null?void 0:Id.io_available_balance)||((Pd=t==null?void 0:t.internal_order)==null?void 0:Pd.ioAvailableBalance)||((Ed=t==null?void 0:t.internal_order)==null?void 0:Ed.io_available_balance),remainingBalance:((_d=t==null?void 0:t.internalOrder)==null?void 0:_d.ioRemainingBalance)||((Md=t==null?void 0:t.internalOrder)==null?void 0:Md.io_remaining_balance)||((Ld=t==null?void 0:t.internal_order)==null?void 0:Ld.ioRemainingBalance)||((Od=t==null?void 0:t.internal_order)==null?void 0:Od.io_remaining_balance)},completionDocuments:Ya,requestTitle:t==null?void 0:t.title,requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.request_number)||(t==null?void 0:t.id),taxationType:($d=t==null?void 0:t.claimDetails)==null?void 0:$d.taxationType,onReQuotation:ct}),e.jsx(f5,{isOpen:b,onClose:()=>j(!1),taxationType:(Ud=t==null?void 0:t.claimDetails)==null?void 0:Ud.taxationType,onDownload:async()=>{X.info("Download functionality will be implemented")},onSendToDealer:async()=>{var G,Me;try{const be=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!be){X.error("Request ID not found");return}await M5(be),X.success("Credit note sent to dealer successfully. Step 8 has been approved."),n&&n()}catch(be){console.error("Failed to send credit note to dealer:",be);const ue=((Me=(G=be==null?void 0:be.response)==null?void 0:G.data)==null?void 0:Me.message)||(be==null?void 0:be.message)||"Failed to send credit note to dealer";X.error(ue)}},creditNoteData:{creditNoteNumber:((Bd=t==null?void 0:t.creditNote)==null?void 0:Bd.creditNoteNumber)||((Vd=t==null?void 0:t.creditNote)==null?void 0:Vd.credit_note_number)||((Hd=(zd=t==null?void 0:t.claimDetails)==null?void 0:zd.creditNote)==null?void 0:Hd.creditNoteNumber)||((Wd=t==null?void 0:t.claimDetails)==null?void 0:Wd.creditNoteNumber)||((Gd=t==null?void 0:t.claimDetails)==null?void 0:Gd.credit_note_number),creditNoteDate:((Yd=t==null?void 0:t.creditNote)==null?void 0:Yd.creditNoteDate)||((Kd=t==null?void 0:t.creditNote)==null?void 0:Kd.credit_note_date)||((Xd=(Qd=t==null?void 0:t.claimDetails)==null?void 0:Qd.creditNote)==null?void 0:Xd.creditNoteDate)||((Jd=t==null?void 0:t.claimDetails)==null?void 0:Jd.creditNoteDate)||((Zd=t==null?void 0:t.claimDetails)==null?void 0:Zd.credit_note_date),creditNoteAmount:(qd=t==null?void 0:t.creditNote)!=null&&qd.creditNoteAmount?Number((em=t==null?void 0:t.creditNote)==null?void 0:em.creditNoteAmount):(tm=t==null?void 0:t.creditNote)!=null&&tm.credit_note_amount?Number((sm=t==null?void 0:t.creditNote)==null?void 0:sm.credit_note_amount):(rm=(am=t==null?void 0:t.claimDetails)==null?void 0:am.creditNote)!=null&&rm.creditNoteAmount?Number((im=(nm=t==null?void 0:t.claimDetails)==null?void 0:nm.creditNote)==null?void 0:im.creditNoteAmount):(lm=t==null?void 0:t.claimDetails)!=null&&lm.creditNoteAmount?Number((om=t==null?void 0:t.claimDetails)==null?void 0:om.creditNoteAmount):(cm=t==null?void 0:t.claimDetails)!=null&&cm.credit_note_amount?Number((dm=t==null?void 0:t.claimDetails)==null?void 0:dm.credit_note_amount):void 0,status:((mm=t==null?void 0:t.creditNote)==null?void 0:mm.status)||((xm=(um=t==null?void 0:t.claimDetails)==null?void 0:um.creditNote)==null?void 0:xm.status)||((hm=t==null?void 0:t.creditNote)!=null&&hm.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((pm=t==null?void 0:t.claimDetails)==null?void 0:pm.dealerName)||((gm=t==null?void 0:t.claimDetails)==null?void 0:gm.dealer_name),dealerCode:((fm=t==null?void 0:t.claimDetails)==null?void 0:fm.dealerCode)||((bm=t==null?void 0:t.claimDetails)==null?void 0:bm.dealer_code),dealerEmail:((jm=t==null?void 0:t.claimDetails)==null?void 0:jm.dealerEmail)||((ym=t==null?void 0:t.claimDetails)==null?void 0:ym.dealer_email)},activityName:((vm=t==null?void 0:t.claimDetails)==null?void 0:vm.activityName)||((Nm=t==null?void 0:t.claimDetails)==null?void 0:Nm.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(T5,{isOpen:y,onClose:()=>{w(!1),S(null)},stepNumber:(N==null?void 0:N.stepNumber)||4,stepName:(N==null?void 0:N.stepName)||"Activity Creation",requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.id)||(t==null?void 0:t.request_number),recipientEmail:"system@undefined"}),D&&e.jsx(g5,{isOpen:A,onClose:()=>{_(!1),R(null)},onApprove:async G=>{var Me,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ue=t.id||t.requestId,ge=D.levelId;if(!ge){X.error("Approval level not found");return}await Tn(ue,ge,G),X.success("Request approved successfully"),Y(),_(!1),R(null)}catch(ue){console.error("Failed to approve:",ue);const ge=((be=(Me=ue==null?void 0:ue.response)==null?void 0:Me.data)==null?void 0:be.message)||(ue==null?void 0:ue.message)||"Failed to approve request. Please try again.";throw X.error(ge),ue}},onReject:async G=>{var Me,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ue=t.id||t.requestId,ge=D.levelId;if(!ge){X.error("Approval level not found");return}await Nr(ue,ge,"Request rejected",G),X.success("Request rejected successfully"),Y(),_(!1),R(null)}catch(ue){console.error("Failed to reject:",ue);const ge=((be=(Me=ue==null?void 0:ue.response)==null?void 0:Me.data)==null?void 0:be.message)||(ue==null?void 0:ue.message)||"Failed to reject request. Please try again.";throw X.error(ge),ue}},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}),v&&v.length>0&&e.jsxs(Z,{className:"mt-6 border-amber-100 bg-amber-50/30",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(me,{className:"text-sm font-bold flex items-center gap-2 text-amber-900",children:[e.jsx(Ot,{className:"w-4 h-4"}),"Revision History & Audit Trail"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>V(!C),className:"text-amber-700 hover:text-amber-800 hover:bg-amber-100",children:C?"Hide History":"View History"})]}),e.jsx(ve,{className:"text-xs text-amber-700",children:"Records of all revisions and actions taken on this request"})]}),C&&e.jsx(ee,{children:e.jsx("div",{className:"space-y-4",children:v.map((G,Me)=>{var be,ue,ge,xe;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 ",G.version]}),G.snapshotType&&e.jsx(se,{className:"bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0",children:G.snapshotType}),G.levelNumber&&e.jsxs(se,{className:"bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0",children:["Step ",G.levelNumber]})]}),e.jsx("span",{className:"text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full",children:Br(G.createdAt)})]}),e.jsx("p",{className:"text-xs font-medium text-gray-800",children:G.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:((ue=(be=G.changer)==null?void 0:be.displayName)==null?void 0:ue.charAt(0))||"U"})}),e.jsxs("span",{className:"text-xs text-gray-500",children:["By ",((ge=G.changer)==null?void 0:ge.displayName)||((xe=G.changer)==null?void 0:xe.email)||"Unknown User"]})]}),G.snapshotType==="PROPOSAL"&&G.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:"}),G.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(E,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-small flex items-center gap-1",onClick:()=>T({data:G.snapshotData,type:"PROPOSAL",title:`Historical Proposal (Version ${G.version})`}),children:["View Details",e.jsx(Ct,{className:"w-2 h-2"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Budget: ₹",Number(G.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),G.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",G.snapshotData.comments.substring(0,80),G.snapshotData.comments.length>80?"...":""]})]}),G.snapshotType==="COMPLETION"&&G.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:"}),G.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(E,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-medium flex items-center gap-1",onClick:()=>T({data:G.snapshotData,type:"COMPLETION",title:`Historical Completion (Version ${G.version})`}),children:["View Details",e.jsx(Ct,{className:"w-3 h-3"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Total Expenses: ₹",Number(G.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),G.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",G.snapshotData.comments.substring(0,80),G.snapshotData.comments.length>80?"...":""]})]}),G.snapshotType==="INTERNAL_ORDER"&&G.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: ",G.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-gray-600",children:["Blocked: ₹",Number(G.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),G.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-gray-600",children:["SAP Doc: ",G.snapshotData.sapDocumentNumber]})]}),G.snapshotType==="APPROVE"&&G.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:[G.snapshotData.action==="APPROVE"?"Approval":"Rejection",":"]}),e.jsxs("p",{className:"text-gray-600",children:["By: ",G.snapshotData.approverName||G.snapshotData.approverEmail||"Unknown"]}),G.snapshotData.levelName&&e.jsxs("p",{className:"text-gray-600",children:["Level: ",G.snapshotData.levelName]}),G.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",G.snapshotData.comments.substring(0,80),G.snapshotData.comments.length>80?"...":""]}),G.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-red-600 mt-1",children:["Rejection Reason: ",G.snapshotData.rejectionReason.substring(0,80),G.snapshotData.rejectionReason.length>80?"...":""]})]}),G.snapshotType==="WORKFLOW"&&G.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: ",G.snapshotData.status||"N/A"]}),G.snapshotData.currentLevel&&e.jsxs("p",{className:"text-gray-600",children:["Current Level: ",G.snapshotData.currentLevel]})]})]})]},G.historyId||Me)})})})]}),e.jsx(R5,{isOpen:!!I,onClose:()=>T(null),snapshot:I==null?void 0:I.data,type:(I==null?void 0:I.type)||"PROPOSAL",title:I==null?void 0:I.title}),L&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:xr}),e.jsxs("div",{className:"relative w-[95vw] max-w-5xl h-[90vh] bg-white rounded-xl shadow-2xl flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b bg-gray-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Invoice Preview"}),e.jsx(se,{className:"bg-amber-100 text-amber-800 text-xs",children:t.requestNumber})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[k&&e.jsxs(E,{variant:"outline",size:"sm",onClick:Or,className:"gap-1.5 text-xs",children:[e.jsx(kt,{className:"w-3.5 h-3.5"}),"Download"]}),e.jsx(E,{variant:"ghost",size:"icon",onClick:xr,className:"h-8 w-8 hover:bg-gray-200",children:e.jsx(bt,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:U?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3",children:[e.jsx(Xe,{className:"w-8 h-8 text-amber-600 animate-spin"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading invoice..."})]}):k?e.jsx("iframe",{src:k,className:"w-full h-full border-0",title:"Invoice PDF Preview"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Failed to load invoice"})})})]})]})]})}function H5({request:t,apiRequest:s,onRefresh:a}){const{user:r}=cs(),n=(s==null?void 0:s.requestId)||(t==null?void 0:t.requestId),i=(s==null?void 0:s.proposalDetails)||{},l=(s==null?void 0:s.claimDetails)||s||{},c=h.useMemo(()=>{const P=(i==null?void 0:i.costBreakup)||(l==null?void 0:l.costBreakup)||[],C=Array.isArray(P)?P:typeof P=="string"?JSON.parse(P):[];return!Array.isArray(C)||C.length===0?Number((l==null?void 0:l.totalProposedTaxableAmount)||(i==null?void 0:i.totalEstimatedBudget)||(i==null?void 0:i.total_estimated_budget)||0):C.reduce((V,F)=>{const $=typeof F=="object"&&F.amount||0,I=typeof F=="object"&&F.quantity||1;return V+Number($)*Number(I)},0)},[i==null?void 0:i.costBreakup,l==null?void 0:l.costBreakup,l==null?void 0:l.totalProposedTaxableAmount,i==null?void 0:i.totalEstimatedBudget]),d=(s==null?void 0:s.budgetTracking)||(t==null?void 0:t.budgetTracking)||{},m=(d==null?void 0:d.budgetStatus)||(d==null?void 0:d.budget_status)||"",p=(s==null?void 0:s.internalOrders)||(s==null?void 0:s.internal_orders)||(t==null?void 0:t.internalOrders)||[],x=m==="PROPOSED"&&p.length>0,[u,g]=h.useState(""),[f,b]=h.useState(!1),[j,y]=h.useState(null),[w,N]=h.useState(""),[S,A]=h.useState([]),[_,D]=h.useState(!1);h.useEffect(()=>{if(p.length>0){const P=p.map(C=>{const V=C.organizer||null,F=(V==null?void 0:V.displayName)||(V==null?void 0:V.display_name)||(V==null?void 0:V.name)||(V!=null&&V.firstName&&(V!=null&&V.lastName)?`${V.firstName} ${V.lastName}`.trim():null)||(V==null?void 0:V.email)||"Unknown User";return{ioNumber:C.ioNumber||C.io_number,blockedAmount:Number(C.ioBlockedAmount||C.io_blocked_amount||0),availableBalance:Number(C.ioAvailableBalance||C.io_available_balance||0),remainingBalance:Number(C.ioRemainingBalance||C.io_remaining_balance||0),blockedDate:C.organizedAt||C.organized_at||new Date().toISOString(),blockedBy:F,sapDocumentNumber:C.sapDocumentNumber||C.sap_document_number||"",status:C.status==="BLOCKED"?"blocked":C.status==="RELEASED"?"released":C.status==="PENDING"?"pending":"blocked"}});A(P),!x&&P.length>0&&g(P[P.length-1].ioNumber)}},[s,t,x,p]);const R=async()=>{var P,C;if(!u.trim()){X.error("Please enter an IO number");return}if(!n){X.error("Request ID not found");return}b(!0);try{const V=await E5(n,u.trim());if(V.isValid&&V.availableBalance>0){y(V.availableBalance);const F=S.reduce((I,T)=>I+T.blockedAmount,0),$=Math.max(0,c-F);$>0?N(String($.toFixed(2))):c>0&&F===0?N(String(c.toFixed(2))):N(String(V.availableBalance.toFixed(2))),X.success(`IO fetched from SAP. Available balance: ₹${V.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)}else X.error("Invalid IO number or no available balance found"),y(null),N("")}catch(V){console.error("Failed to fetch IO budget:",V);const F=((C=(P=V==null?void 0:V.response)==null?void 0:P.data)==null?void 0:C.message)||(V==null?void 0:V.message)||"Failed to validate IO number or fetch budget from SAP";X.error(F),y(null)}finally{b(!1)}},v=async()=>{var $,I;if(!u.trim()||j===null){X.error("Please fetch IO amount first");return}if(!n){X.error("Request ID not found");return}const P=parseFloat(w);if(!w||isNaN(P)||P<=0){X.error("Please enter a valid amount to block");return}const C=parseFloat(P.toFixed(2));if(C>j){X.error("Amount to block exceeds available IO budget");return}const F=S.reduce((T,k)=>T+k.blockedAmount,0)+C;if(c>0){const T=parseFloat(c.toFixed(2)),k=parseFloat(F.toFixed(2));if(Math.abs(k-T)>.01){X.error(`Total blocked amount (₹${k.toLocaleString("en-IN")}) must be exactly equal to the estimated budget (₹${T.toLocaleString("en-IN")})`);return}}D(!0);try{const T=parseFloat(j.toFixed(2)),k=parseFloat((T-C).toFixed(2)),z={ioNumber:u.trim(),ioAvailableBalance:T,ioBlockedAmount:C,ioRemainingBalance:k};await g0(n,z);const L=await F5(n),M=(L==null?void 0:L.internalOrder)||(L==null?void 0:L.internal_order);if(M){const U=Number(M.ioBlockedAmount||M.io_blocked_amount||C),B=Number(M.ioRemainingBalance||M.io_remaining_balance||0),W=j-U;Math.abs(U-C)>.01&&console.warn("[IOTab] ⚠️ Amount mismatch! Sent:",C,"Saved:",U),Math.abs(B-W)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:j,blockedAmount:U,expectedRemaining:W,backendRemaining:B,difference:B-W});const J=r,O=(J==null?void 0:J.displayName)||(J==null?void 0:J.display_name)||(J==null?void 0:J.name)||(J!=null&&J.firstName&&(J!=null&&J.lastName)?`${J.firstName} ${J.lastName}`.trim():null)||(J==null?void 0:J.email)||"Current User",H={ioNumber:M.ioNumber||M.io_number||u,blockedAmount:U,availableBalance:j,remainingBalance:B,blockedDate:M.organizedAt||M.organized_at||new Date().toISOString(),blockedBy:O,sapDocumentNumber:M.sapDocumentNumber||M.sap_document_number||"",status:"blocked"};A(Y=>[...Y,H]),N(""),y(null),X.success("IO budget blocked successfully in SAP"),a==null||a()}else X.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(T){console.error("Failed to block IO budget:",T);const k=((I=($=T==null?void 0:T.response)==null?void 0:$.data)==null?void 0:I.message)||(T==null?void 0:T.message)||"Failed to block IO budget in SAP";X.error(k)}finally{D(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(ve,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:u,onChange:P=>g(P.target.value),disabled:f||S.length>0&&!x,className:"flex-1"}),e.jsxs(E,{onClick:R,disabled:!u.trim()||f||S.length>0&&!x,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),f?"Fetching...":"Fetch Amount"]})]})]}),!j&&S.length===0&&u.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.']})}),j!==null&&(S.length===0||x)&&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:["₹",j.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsx(Le,{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:"})," ",u]}),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(te,{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(ke,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:w,onChange:P=>N(P.target.value),className:"pl-8"})]}),c>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:["₹",c.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs(E,{onClick:v,disabled:_||!w||parseFloat(w)<=0||parseFloat(w)>j||c>0&&Math.abs(S.reduce((P,C)=>P+C.blockedAmount,0)+parseFloat(w)-c)>.01,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(es,{className:"w-4 h-4 mr-2"}),_?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(Le,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(ve,{children:"Details of IO blocked in SAP system"})]}),e.jsx(ee,{children:S.length>0?e.jsxs("div",{className:"space-y-6",children:[x&&e.jsx("div",{className:"bg-amber-50 border-2 border-amber-500 rounded-lg p-4 animate-pulse",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ze,{className:"w-6 h-6 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-amber-900",children:"Additional Budget Blocking Required"}),e.jsxs("p",{className:"text-sm text-amber-700 mt-1",children:["Actual expenses exceed the previously blocked amount. Please block an additional ₹",(c-S.reduce((P,C)=>P+C.blockedAmount,0)).toLocaleString("en-IN",{minimumFractionDigits:2}),"."]})]})]})}),S.slice().reverse().map((P,C)=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:`p-3 flex justify-between items-center ${C===0?"bg-green-50":"bg-gray-50"}`,children:[e.jsxs("span",{className:"font-semibold text-sm",children:["IO: ",P.ioNumber]}),e.jsx(se,{className:P.status==="blocked"?"bg-green-100 text-green-800":P.status==="pending"?"bg-amber-100 text-amber-800":"bg-blue-100 text-blue-800",children:P.status==="blocked"?"Blocked":P.status==="pending"?"Provisioned":"Released"})]}),e.jsxs("div",{className:"grid grid-cols-2 divide-x divide-y",children:[e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Amount"}),e.jsxs("p",{className:"text-sm font-bold text-green-700",children:["₹",P.blockedAmount.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"SAP Doc"}),e.jsx("p",{className:"text-sm font-medium",children:P.sapDocumentNumber||"N/A"})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Blocked By"}),e.jsx("p",{className:"text-xs",children:P.blockedBy})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Date"}),e.jsx("p",{className:"text-[10px]",children:new Date(P.blockedDate).toLocaleString()})]})]})]},C)),e.jsxs("div",{className:"mt-4 p-4 bg-[#2d4a3e] text-white rounded-lg flex justify-between items-center",children:[e.jsx("span",{className:"font-bold",children:"Total Blocked:"}),e.jsxs("span",{className:"text-xl font-bold",children:["₹",S.reduce((P,C)=>P+C.blockedAmount,0).toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ha,{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 W5(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)}}async function G5(t){var s;try{const a=await je.get(`/dealers-external/search/${t}`);return((s=a.data)==null?void 0:s.data)||a.data||null}catch(a){return console.error("[DealerAPI] Error searching external dealer:",a),null}}const Ys=[{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 Y5({formData:t,updateFormData:s,onValidationError:a,currentUserEmail:r="",currentUserId:n="",currentUserName:i="",onValidate:l,maxApprovalLevels:o,onPolicyViolation:c}){const{userSearchResults:d,userSearchLoading:m,searchUsersForIndex:p,clearSearchForIndex:x}=Qg(),[u,g]=h.useState(!1),[f,b]=h.useState(""),[j,y]=h.useState(24),[w,N]=h.useState("hours"),[S,A]=h.useState(3),[_,D]=h.useState([]),[R,v]=h.useState(!1),[P,C]=h.useState(null),V=h.useRef(null),F=()=>{const O=t.approvers||[],H=[];return Ys.forEach(Y=>{if(Y.isAuto||Y.approverType==="dealer"||Y.approverType==="initiator")return;const re=O.find(K=>K.level===Y.level);(!re||!re.email||!re.userId||!re.tat)&&H.push(`${Y.name}`)}),{isValid:H.length===0,missingSteps:H}};h.useEffect(()=>{if(l){const O=F();l(O.isValid)}},[t.approvers]),h.useEffect(()=>{const O=t.approvers||[];if(O.length>0){const H=[],Y=O.filter(K=>K.isAdditional);Ys.forEach(K=>{const ae=O.find(Ne=>Ne.originalStepLevel===K.level||!Ne.originalStepLevel&&!Ne.isAdditional&&Ne.level===K.level);if(ae)H.push(ae);else if(K.isAuto){const Ne=K.level===8?"finance@royalenfield.com":"system@royalenfield.com",Se=K.level===8?"System/Finance":"System";H.push({email:Ne,name:Se,level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level})}else K.approverType==="dealer"?H.push({email:t.dealerEmail||"",name:t.dealerName||"",level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level}):K.approverType==="initiator"?H.push({email:r||"",name:i||r||"User",userId:n,level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level}):H.push({email:"",name:"",level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level})}),Y.forEach(K=>{H.push(K)}),H.sort((K,ae)=>K.level-ae.level),JSON.stringify(O.map(K=>({level:K.level,originalStepLevel:K.originalStepLevel})))!==JSON.stringify(H.map(K=>({level:K.level,originalStepLevel:K.originalStepLevel})))&&s("approvers",H)}else{const H=[];Ys.forEach(Y=>{Y.isAuto||(Y.approverType==="dealer"?H.push({email:t.dealerEmail||"",name:t.dealerName||"",level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level}):Y.approverType==="initiator"?H.push({email:r||"",name:i||r||"User",userId:n,level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level}):H.push({email:"",name:"",level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level}))}),s("approvers",H)}},[t.dealerEmail,t.dealerName,r,n,i]);const $=(O,H)=>{const Y=[...t.approvers||[]],re=Y.findIndex(K=>K.originalStepLevel===O||!K.originalStepLevel&&K.level===O&&!K.isAdditional);if(re===-1){const K=Ys.find(ae=>ae.level===O);Y.push({email:H,name:"",level:O,tat:(K==null?void 0:K.defaultTat)||48,tatType:"hours",originalStepLevel:O})}else{const K=Y[re];if(K){const ae=K.email;Y[re]={...K,email:H,name:H!==ae?"":K.name,userId:H!==ae?void 0:K.userId}}}if(s("approvers",Y),!H||!H.startsWith("@")||H.length<2){x(O-1);return}p(O-1,H,10)},I=async(O,H)=>{var Y,re;try{const K=Ys.find(Pe=>Pe.level===O);if(K&&!K.isAuto&&K.approverType!=="initiator"&&((Y=H.email)==null?void 0:Y.toLowerCase())===(r==null?void 0:r.toLowerCase())){X.error(`You cannot assign yourself as ${K.name} approver.`),a&&a({type:"self-assign",email:H.email,message:`You cannot assign yourself as ${K.name} approver.`});return}if((t.approvers||[]).some(Pe=>{var Oe,ie;return Pe.level!==O&&(Pe.userId===H.userId||((Oe=Pe.email)==null?void 0:Oe.toLowerCase())===((ie=H.email)==null?void 0:ie.toLowerCase()))})){X.error("This user is already assigned to another step."),a&&a({type:"error",email:H.email,message:"This user is already assigned to another step."});return}const Se=await fa({userId:H.userId,email:H.email,displayName:H.displayName,firstName:H.firstName,lastName:H.lastName,department:H.department,phone:H.phone,mobilePhone:H.mobilePhone,designation:H.designation,jobTitle:H.jobTitle,manager:H.manager,employeeId:H.employeeId,employeeNumber:H.employeeNumber,secondEmail:H.secondEmail,location:H.location}),Ge=[...t.approvers||[]],Je=Ge.findIndex(Pe=>Pe.originalStepLevel===O||!Pe.originalStepLevel&&Pe.level===O&&!Pe.isAdditional);if(Je===-1){const Pe=Ys.find(Oe=>Oe.level===O);Ge.push({email:H.email,name:H.displayName||[H.firstName,H.lastName].filter(Boolean).join(" "),userId:Se.userId,level:O,tat:(Pe==null?void 0:Pe.defaultTat)||48,tatType:"hours",originalStepLevel:O})}else{const Pe=Ge[Je];Pe&&(Ge[Je]={...Pe,email:H.email,name:H.displayName||[H.firstName,H.lastName].filter(Boolean).join(" "),userId:Se.userId,originalStepLevel:Pe.originalStepLevel||O})}s("approvers",Ge),x(O-1),X.success(`Approver for ${(re=Ys.find(Pe=>Pe.level===O))==null?void 0:re.name} selected successfully.`)}catch(K){console.error("Failed to ensure user exists:",K),X.error("Failed to validate user. Please try again."),a&&a({type:"error",email:H.email,message:"Failed to validate user. Please try again."})}},T=(O,H)=>{const Y=[...t.approvers||[]],re=Y.findIndex(K=>K.originalStepLevel===O||!K.originalStepLevel&&K.level===O&&!K.isAdditional);if(re!==-1){const K=Y[re];K&&(Y[re]={...K,tat:H},s("approvers",Y))}},k=(O,H)=>{const Y=[...t.approvers||[]],re=Y.findIndex(K=>K.originalStepLevel===O||!K.originalStepLevel&&K.level===O&&!K.isAdditional);if(re!==-1){const K=Y[re];K&&(Y[re]={...K,tatType:H,tat:""},s("approvers",Y))}},z=O=>{if(b(O),P&&P.email.toLowerCase()!==O.toLowerCase()&&C(null),V.current&&clearTimeout(V.current),!O||!O.startsWith("@")||O.length<2){D([]),v(!1);return}v(!0),V.current=setTimeout(async()=>{var H;try{const Y=O.slice(1),K=((H=(await ja(Y,10)).data)==null?void 0:H.data)||[];D(K)}catch(Y){console.error("Search failed:",Y),D([])}finally{v(!1)}},300)},L=async O=>{try{await fa({userId:O.userId,email:O.email,displayName:O.displayName,firstName:O.firstName,lastName:O.lastName,department:O.department,phone:O.phone,mobilePhone:O.mobilePhone,designation:O.designation,jobTitle:O.jobTitle,manager:O.manager,employeeId:O.employeeId,employeeNumber:O.employeeNumber,secondEmail:O.secondEmail,location:O.location}),b(O.email),C(O),D([]),v(!1)}catch(H){console.error("Failed to ensure user exists:",H),X.error("Failed to verify user. Please try again.")}},M=async()=>{var Oe,ie;const O=f.trim().toLowerCase();if(!O){X.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(O)){X.error("Please enter a valid email address");return}const Y=typeof j=="string"?Number(j):j;if(!Y||Y<=0||isNaN(Y)){X.error("Please enter valid TAT (minimum 1)");return}const re=w==="days"?30:720;if((w==="days"?Y*24:Y)>720){X.error(`TAT cannot exceed ${re} ${w==="days"?"days":"hours"}`);return}const ae=Ys.find(pe=>pe.name==="Requestor Claim Approval");if(ae&&S>=ae.level){X.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if(O===(r==null?void 0:r.toLowerCase())){X.error("You cannot add yourself as an additional approver.");return}const Ne=t.approvers||[];if(Ne.some(pe=>{var we;return pe.userId&&(P==null?void 0:P.userId)&&pe.userId===P.userId||((we=pe.email)==null?void 0:we.toLowerCase())===O})){X.error("This user is already assigned as an approver.");return}const Ge=Ne.find(pe=>pe.originalStepLevel===S||!pe.originalStepLevel&&!pe.isAdditional&&pe.level===S),Pe=(Ge?Ge.level:S)+1;if(o){const we=new Set(Ne.map(Ae=>Ae.level)).size+1;if(we>o){const Ae=[{type:"max_approval_levels",message:`Adding this approver would create ${we} approval levels, which exceeds the maximum allowed (${o}). Please remove some approvers before adding a new one.`,currentValue:we,maxValue:o}];c?c(Ae):X.error(((Oe=Ae[0])==null?void 0:Oe.message)||"Maximum approval levels exceeded");return}}if(!P||P.email.toLowerCase()!==O)try{const we=((ie=(await ja(O,1)).data)==null?void 0:ie.data)||[];if(we.length===0){X.error("User not found in organization directory. Please use @ to search for users.");return}const Ae=we[0];await fa({userId:Ae.userId,email:Ae.email,displayName:Ae.displayName,firstName:Ae.firstName,lastName:Ae.lastName,department:Ae.department,phone:Ae.phone,mobilePhone:Ae.mobilePhone,designation:Ae.designation,jobTitle:Ae.jobTitle,manager:Ae.manager,employeeId:Ae.employeeId,employeeNumber:Ae.employeeNumber,secondEmail:Ae.secondEmail,location:Ae.location});const ne={email:Ae.email,name:Ae.displayName||[Ae.firstName,Ae.lastName].filter(Boolean).join(" "),userId:Ae.userId,level:Pe,tat:typeof j=="string"?Number(j):j,tatType:w,isAdditional:!0,insertAfterLevel:S,stepName:`Additional Approver - ${Ae.displayName||Ae.email}`},q=Ne.map(de=>de.level>=Pe?{...de,level:de.level+1}:de);q.push(ne),q.sort((de,Ye)=>de.level-Ye.level),s("approvers",q),X.success("Additional approver added and subsequent steps shifted")}catch(pe){console.error("Failed to validate approver:",pe),X.error("Failed to validate user. Please try again.");return}else{const pe={email:P.email,name:P.displayName||[P.firstName,P.lastName].filter(Boolean).join(" "),userId:P.userId,level:Pe,tat:j,tatType:w,isAdditional:!0,insertAfterLevel:S,stepName:`Additional Approver - ${P.displayName||P.email}`},we=Ne.map(Ae=>Ae.level>=Pe?{...Ae,level:Ae.level+1}:Ae);we.push(pe),we.sort((Ae,ne)=>Ae.level-ne.level),s("approvers",we),X.success("Additional approver added and subsequent steps shifted")}b(""),y(24),N("hours"),A(3),C(null),D([]),g(!1)},U=O=>{const H=[...t.approvers||[]];if(!H.find(ae=>ae.level===O))return;const K=H.filter(ae=>ae.level!==O).map(ae=>ae.level>O&&!ae.isAdditional?{...ae,level:ae.level-1}:ae);K.sort((ae,Ne)=>ae.level-Ne.level),s("approvers",K),X.success("Additional approver removed and subsequent steps shifted back")},B=()=>[...t.approvers||[]].sort((H,Y)=>H.level-Y.level),W=t.approvers||[],J=B();return e.jsxs(Ht.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(Zt,{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(Z,{className:"border-2 border-blue-200 bg-blue-50",children:e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(Er,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsxs(ve,{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 O=t.approvers||[],Y=new Set(O.map(re=>re.level)).size;return Y>0?e.jsxs("span",{children:[" (",Y,"/",o,")"]}):null})()]})]})]})}),e.jsxs(Z,{className:"border-2",children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx(ve,{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(ee,{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 O=t.approvers||[],Y=new Set(O.map(re=>re.level)).size;return Y>0?e.jsxs("span",{children:[" (",Y,"/",o,")"]}):null})()]}),e.jsxs(E,{type:"button",variant:"outline",onClick:()=>g(!0),className:"flex items-center gap-2",children:[e.jsx(bs,{className:"w-4 h-4"}),"Add Additional Approver"]})]}),e.jsx("div",{className:"p-3 rounded-lg border-2 border-blue-200 bg-blue-50",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center flex-shrink-0",children:e.jsx(Vt,{className:"w-4 h-4 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-blue-900 text-sm",children:"Request Initiator"}),e.jsx(se,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-xs text-blue-700",children:"Creates and submits the request"})]})]})}),(()=>{const O=J.filter(Y=>Y.isAdditional&&Y.insertAfterLevel===0);let H=O.length;return Ys.filter(Y=>!Y.isAuto).map((Y,re,K)=>{const ae=W.find(Oe=>Oe.originalStepLevel===Y.level||!Oe.originalStepLevel&&Oe.level===Y.level&&!Oe.isAdditional)||{email:"",name:"",level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level},Ne=re===K.length-1,Se=Y.isAuto||Y.approverType==="dealer"||Y.approverType==="initiator",Ge=!Y.isAuto,Je=J.filter(Oe=>Oe.isAdditional&&Oe.insertAfterLevel===Y.level).sort((Oe,ie)=>Oe.level-ie.level),Pe=H+1;return H++,H+=Je.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"})}),re===0&&O.map((Oe,ie)=>{const pe=ie+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:pe})}),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(se,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>U(Oe.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(bt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:Oe.name||Oe.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",Oe.email]}),e.jsxs("div",{children:["TAT: ",Oe.tat," ",Oe.tatType]})]})]})]})})]},`additional-${Oe.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${ae.email&&ae.userId?"border-green-200 bg-green-50":Se?"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 ${ae.email&&ae.userId?"bg-green-600":Se?"bg-blue-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold text-sm",children:Pe})}),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:Y.name}),Ne&&e.jsx(se,{variant:"destructive",className:"text-xs",children:"FINAL"}),Se&&e.jsx(se,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:Y.description}),Ge&&(()=>{var pe,we;const Oe=!!(ae.email&&ae.userId),ie=!ae.email&&!Se;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs(te,{htmlFor:`approver-${Y.level}`,className:`text-xs font-bold ${ie?"text-blue-900":Oe?"text-green-900":"text-gray-900"}`,children:["Approver Email ",!Se&&"*",ie&&e.jsx("span",{className:"ml-2 text-[10px] font-semibold italic text-blue-600",children:"(Required)"})]}),Oe&&e.jsxs(se,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Le,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{id:`approver-${Y.level}`,type:"text",placeholder:Se?ae.email:"@username or email...",value:ae.email||"",onChange:Ae=>{const ne=Ae.target.value;Se||$(Y.level,ne)},disabled:Se||Y.isAuto,className:`h-9 border-2 transition-all mt-1 w-full text-sm ${Se?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":Oe?"bg-green-50/50 border-green-600 focus:border-green-700 ring-offset-green-50 focus:ring-1 focus:ring-green-100 font-semibold text-gray-900":"bg-white border-blue-300 shadow-sm shadow-blue-100/50 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`}),!Se&&!Y.isAuto&&(m[Y.level-1]||(((pe=d[Y.level-1])==null?void 0:pe.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:m[Y.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:(we=d[Y.level-1])==null?void 0:we.map(Ae=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>I(Y.level,Ae),children:[e.jsx("div",{className:"font-medium text-gray-900",children:Ae.displayName||Ae.email}),e.jsx("div",{className:"text-xs text-gray-600",children:Ae.email}),Ae.department&&e.jsx("div",{className:"text-xs text-gray-500",children:Ae.department})]},Ae.userId))})})]}),ae.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:ae.name})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:`tat-${Y.level}`,className:`text-xs font-bold ${ie?"text-blue-900":Oe?"text-green-900":"text-gray-900"}`,children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ke,{id:`tat-${Y.level}`,type:"number",placeholder:ae.tatType==="days"?"7":"24",min:"1",max:ae.tatType==="days"?"30":"720",value:ae.tat||"",onChange:Ae=>T(Y.level,parseInt(Ae.target.value)||""),disabled:Y.isAuto,className:`h-9 border-2 transition-all flex-1 text-sm ${Se?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":Oe?"bg-green-50/50 border-green-600 focus:border-green-700 focus:ring-1 focus:ring-green-100 font-semibold text-gray-900":"bg-white border-blue-300 shadow-sm shadow-blue-100/50 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`}),e.jsxs(Be,{value:ae.tatType||"hours",onValueChange:Ae=>k(Y.level,Ae),disabled:Y.isAuto,children:[e.jsx(ze,{className:`w-20 h-9 border-2 transition-all text-sm ${Se?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed":Oe?"bg-green-50/50 border-green-600 focus:border-green-700 focus:ring-1 focus:ring-green-100 text-gray-900 font-medium":"bg-white border-blue-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`,children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Q,{value:"hours",children:"Hours"}),e.jsx(Q,{value:"days",children:"Days"})]})]})]})]})]})})()]})]})}),Je.map((Oe,ie)=>{const pe=Pe+ie+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:pe})}),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:Oe.stepName||"Additional Approver"}),e.jsx(se,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),Oe.email&&Oe.userId&&e.jsxs(se,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Le,{className:"w-3 h-3 mr-1"}),"Verified"]}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>U(Oe.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(bt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:Oe.name||Oe.email||"No approver assigned"}),Oe.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",Oe.email]}),Oe.tat&&e.jsxs("div",{children:["TAT: ",Oe.tat," ",Oe.tatType]})]})]})]})})]},`additional-${Oe.level}`)})]},Y.level)})})()]})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(oe,{children:e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(st,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3",children:J.map(O=>{const H=O.originalStepLevel?Ys.find(ae=>ae.level===O.originalStepLevel):Ys.find(ae=>ae.level===O.level&&!O.isAdditional);if(H!=null&&H.isAuto)return null;const Y=Number(O.tat||0),K=(O.tatType||"hours")==="days"?Y*24:Y;if(!Y)return null;if(O.isAdditional){const ae=Ys.find(Ne=>Ne.level===O.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:O.stepName||`Additional Approver (after "${(ae==null?void 0:ae.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[K," hours"]})]},O.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:(H==null?void 0:H.name)||"Unknown"}),e.jsxs("span",{className:"text-sm text-gray-600",children:[K," hours"]})]},O.level)})})})]})]}),e.jsx(jt,{open:u,onOpenChange:g,children:e.jsxs(xt,{className:"sm:max-w-md",children:[e.jsxs(yt,{children:[e.jsxs(ht,{className:"flex items-center gap-2",children:[e.jsx(bs,{className:"w-5 h-5 text-blue-600"}),"Add Additional Approver"]}),e.jsx(Ut,{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(te,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(Be,{value:S.toString(),onValueChange:O=>A(Number(O)),children:[e.jsx(ze,{className:"h-11 border-gray-300",children:e.jsx(Ve,{placeholder:"Select step"})}),e.jsx(He,{children:Ys.filter(O=>{if(O.isAuto)return!1;const H=Ys.find(Y=>Y.name==="Requestor Claim Approval");return!(H&&O.level>=H.level)}).map(O=>e.jsx(Q,{value:O.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:O.name})]})},O.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 O=t.approvers||[],Y=new Set(O.map(re=>re.level)).size;return Y>0?e.jsxs("span",{children:[" (",Y,"/",o,")"]}):null})()]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{type:"number",min:"1",max:w==="days"?"30":"720",value:j,onChange:O=>{const H=O.target.value;if(H==="")y("");else{const Y=Number(H);!isNaN(Y)&&Y>=0&&y(Y)}},onBlur:O=>{const H=O.target.value;(!H||H===""||Number(H)<=0)&&y(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(Be,{value:w,onValueChange:O=>N(O),children:[e.jsx(ze,{className:"w-24 h-11 border-gray-300",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Q,{value:"hours",children:"Hours"}),e.jsx(Q,{value:"days",children:"Days"})]})]})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum time for this approver to respond (1-",w==="days"?"30 days":"720 hours",")"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ji,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(ke,{type:"text",placeholder:"@username or user@example.com",value:f,onChange:O=>z(O.target.value),className:"pl-10 h-11 border-gray-300",autoFocus:!0}),(R||_.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:R?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):_.length>0?e.jsx("ul",{className:"divide-y",children:_.map(O=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>L(O),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:O.displayName||[O.firstName,O.lastName].filter(Boolean).join(" ")||O.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:O.email}),O.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:O.designation})]})})},O.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(Et,{children:[e.jsx(E,{type:"button",variant:"outline",onClick:()=>{g(!1),b(""),y(24),N("hours"),A(3),C(null),D([])},className:"flex-1",children:"Cancel"}),e.jsxs(E,{type:"button",onClick:M,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!f.trim()||!j,children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const Yl=[{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"}],Kl=["Claim Details","Approver Selection","Review & Submit"];function K5({onBack:t,onSubmit:s}){const{user:a}=cs(),[r,n]=h.useState(1),[i,l]=h.useState(!1),[o,c]=h.useState([]),[d,m]=h.useState(!1),[p,x]=h.useState(""),u=h.useRef(null),[g,f]=h.useState(!1),b=h.useRef(null),[j,y]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[w,N]=h.useState({open:!1,violations:[]}),[S,A]=h.useState([]),[_,D]=h.useState(!0);h.useEffect(()=>{(async()=>{try{D(!0);const U=await MA();A(U)}catch(U){console.error("Failed to load activity types:",U),X.error("Failed to load activity types. Please refresh the page.")}finally{D(!1)}})()},[]),h.useEffect(()=>{(async()=>{var U;try{const B=await la("SYSTEM_SETTINGS"),W=await la("WORKFLOW_SHARING"),J=[...B,...W],O={};J.forEach(H=>{O[H.configKey]=H.configValue}),y({maxApprovalLevels:parseInt(O.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(O.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((U=O.ALLOW_ADD_SPECTATOR)==null?void 0:U.toLowerCase())==="true",maxSpectators:parseInt(O.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(B){console.error("Failed to load system policy:",B)}})()},[]),h.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const[R,v]=h.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",dealerItemGroup:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),P=Kl.length,C=M=>{if(x(M),u.current&&clearTimeout(u.current),!M||M.trim().length<2){c([]),m(!1);return}m(!0),u.current=setTimeout(async()=>{try{const U=await G5(M);if(U){const B={dealerId:U.dealer||U.dealer_code||M,dealerCode:U.dealer||U.dealer_code||M,dealerName:U["dealer name"]||U.dealer_name||"Unknown Dealer",displayName:U["dealer name"]||U.dealer_name||"Unknown Dealer",email:U["dealer email"]||"",phone:U["dealer phone"]||"",city:U["re city"]||U.city||"",state:U["re state code"]||U.state||"",isLoggedIn:!0};c([B])}else c([])}catch(U){console.error("Error searching external dealer:",U),c([])}finally{m(!1)}},300)},V=(M,U)=>{v(B=>{const W={...B,[M]:U};if(M==="periodStartDate")U&&W.periodEndDate&&U>W.periodEndDate&&(W.periodEndDate=void 0,X.error("End date must be on or after the start date. End date has been cleared."));else if(M==="periodEndDate"&&U&&W.periodStartDate&&U<W.periodStartDate)return X.error("End date must be on or after the start date."),B;if(M==="activityType"&&W.dealerCode){const J=S.find(O=>O.title===U);if(J)if(J.creditPostingOn){const O=J.creditPostingOn.toLowerCase(),H=(W.dealerItemGroup||"").toLowerCase();if(H){let Y=!1;if((O==="vehicle"&&H==="vehicle"||O==="spares"&&H==="spares"||O==="gma"&&H==="gma"||O==="apparel"&&H==="apparel"||O===H)&&(Y=!0),!Y)return X.error("incorrect Delercode for selected service group",{description:`Activity requires ${J.creditPostingOn}, but already selected dealer is ${W.dealerItemGroup}`,duration:6e3}),B}}else console.warn(`[ClaimWizard] Activity type "${U}" is missing creditPostingOn configuration.`)}return W})},F=M=>{v(U=>({...U,...M}))},$=()=>{switch(r){case 1:return R.activityName&&R.activityType&&R.dealerCode&&R.dealerName&&R.activityDate&&R.location&&R.requestDescription;case 2:const U=(R.approvers||[]).find(B=>B.originalStepLevel===3||!B.originalStepLevel&&B.level===3&&!B.isAdditional);return(U==null?void 0:U.email)&&(U==null?void 0:U.userId)&&(U==null?void 0:U.tat);case 3:return!0;default:return!1}},I=()=>{if(r<P){if(!$()){if(r===2){const U=(R.approvers||[]).find(W=>W.originalStepLevel===3||!W.originalStepLevel&&W.level===3&&!W.isAdditional),B=[];(!(U!=null&&U.email)||!(U!=null&&U.userId)||!(U!=null&&U.tat))&&B.push("Department Lead Approval"),B.length>0?X.error(`Please add missing approvers: ${B.join(", ")}`):X.error("Please complete all required approver selections (email, user verification, and TAT) before proceeding.")}else X.error("Please complete all required fields before proceeding.");return}n(r+1)}},T=()=>{r>1&&n(r-1)},k=async M=>{l(!0);try{const U=await W5(M.dealerCode);if(!U.isLoggedIn){X.error(`Dealer "${U.dealerName||U.displayName}" (${U.dealerCode}) is not mapped to the system.`,{duration:5e3}),x(""),c([]),V("dealerCode",""),V("dealerName",""),V("dealerEmail",""),V("dealerPhone",""),V("dealerAddress",""),l(!1);return}if(R.activityType){const B=S.find(W=>W.title===R.activityType);if(B&&B.creditPostingOn){const W=B.creditPostingOn.toLowerCase(),J=(U.itemGroup||"").toLowerCase();let O=!1;if((W==="vehicle"&&J==="vehicle"||W==="spares"&&J==="spares"||W==="gma"&&J==="gma"||W==="apparel"&&J==="apparel"||W===J)&&(O=!0),!O){X.error("incorrect Delercode for selected service group",{description:`Activity requires ${B.creditPostingOn}, but dealer is ${U.itemGroup||"N/A"}`,duration:6e3}),x(""),c([]),l(!1);return}}}F({dealerCode:U.dealerCode,dealerName:U.dealerName||U.displayName,dealerEmail:U.email||"",dealerPhone:U.phone||"",dealerAddress:"",dealerItemGroup:U.itemGroup||""}),x(U.dealerName||U.displayName),c([]),X.success(`Dealer "${U.dealerName||U.displayName}" verified and mapped to the System`)}catch{X.error("Dealer is not mapped to the system",{duration:5e3}),x(""),c([]),V("dealerCode",""),V("dealerName",""),V("dealerEmail",""),V("dealerPhone",""),V("dealerAddress","")}finally{l(!1)}},z=()=>{if(g)return;const U=[...R.approvers||[]].sort((H,Y)=>H.level-Y.level),B=new Map,W=[];if(U.forEach(H=>{B.has(H.level)?W.push(H.level):B.set(H.level,H)}),W.length>0){X.error(`Duplicate approver levels detected: ${W.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",W,U);return}const J=U.map(H=>{const Y={email:H.email,name:H.name,userId:H.userId,level:H.level,tat:H.tat,tatType:H.tatType};return H.isAdditional&&H.stepName&&(Y.stepName=H.stepName,Y.isAdditional=!0),H.originalStepLevel&&(Y.originalStepLevel=H.originalStepLevel),Y}),O={...R,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:J};if(f(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{f(!1),b.current=null},3e4),s)try{s(O)}catch(H){b.current&&(clearTimeout(b.current),b.current=null),f(!1),console.error("Error submitting claim:",H)}else b.current&&(clearTimeout(b.current),b.current=null),f(!1)},L=()=>{switch(r){case 1:return e.jsxs(Ht.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(Pt,{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(te,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(ke,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:R.activityName,onChange:M=>V("activityName",M.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(Be,{value:R.activityType,onValueChange:M=>V("activityType",M),disabled:_,children:[e.jsx(ze,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(Ve,{placeholder:_?"Loading activity types...":"Select activity type"})}),e.jsx(He,{children:S.length>0?S.map(M=>e.jsx(Q,{value:M.title,children:M.title},M.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(te,{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(ke,{placeholder:"Type dealer code, name, or email to search...",value:R.dealerCode?`${R.dealerName} (${R.dealerCode})`:p,onChange:M=>{R.dealerCode?(V("dealerCode",""),V("dealerName",""),V("dealerEmail",""),V("dealerPhone",""),V("dealerAddress",""),x(M.target.value)):C(M.target.value)},onFocus:()=>{p&&p.length>=2&&C(p)},className:"h-12 border-2 border-gray-300 focus:border-blue-500",disabled:i}),R.dealerCode&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsxs(se,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Le,{className:"w-3 h-3 mr-1"}),"Verified"]})}),(d||o.length>0)&&!R.dealerCode&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:d?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:o.map(M=>e.jsx("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>k(M),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:M.dealerName||M.displayName}),e.jsxs("div",{className:"text-xs text-gray-600",children:[e.jsx("span",{className:"font-mono",children:M.dealerCode}),M.email&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1",children:"•"}),e.jsx("span",{children:M.email})]})]}),M.city&&M.state&&e.jsxs("div",{className:"text-xs text-gray-500",children:[M.city,", ",M.state]})]}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:M.isLoggedIn?e.jsx(Le,{className:"w-4 h-4 text-green-600"}):e.jsx(St,{className:"w-4 h-4 text-red-500"})})]})},M.dealerId))})})]})}),R.dealerCode&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:R.dealerName})," (",R.dealerCode,")"]}),R.dealerEmail&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Email: ",R.dealerEmail]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(dt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.activityDate?et(R.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(fi,{mode:"single",selected:R.activityDate,onSelect:M=>V("activityDate",M),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(ke,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:R.location,onChange:M=>V("location",M.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(te,{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(Jn,{value:R.requestDescription||"",onChange:M=>V("requestDescription",M),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(te,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(se,{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(te,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(dt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.periodStartDate?et(R.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(fi,{mode:"single",selected:R.periodStartDate,onSelect:M=>V("periodStartDate",M),initialFocus:!0,toDate:R.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",disabled:!R.periodStartDate,children:[e.jsx(dt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.periodEndDate?et(R.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(fi,{mode:"single",selected:R.periodEndDate,onSelect:M=>V("periodEndDate",M),initialFocus:!0,fromDate:R.periodStartDate||void 0})})]}),!R.periodStartDate&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Please select start date first"})]})]}),(R.periodStartDate||R.periodEndDate)&&e.jsx("div",{className:"mt-2",children:R.periodStartDate&&R.periodEndDate?e.jsxs("p",{className:"text-xs text-gray-600",children:["Period: ",et(R.periodStartDate,"d MMM yyyy")," - ",et(R.periodEndDate,"d MMM yyyy")]}):e.jsx("p",{className:"text-xs text-gray-500",children:R.periodStartDate?"Please select end date for the period":"Please select start date first"})})]})]})]});case 2:return e.jsx(Y5,{formData:R,updateFormData:V,currentUserEmail:(a==null?void 0:a.email)||"",currentUserId:(a==null?void 0:a.userId)||"",currentUserName:(a==null?void 0:a.displayName)||(a==null?void 0:a.name)||(a!=null&&a.firstName&&(a!=null&&a.lastName)?`${a.firstName} ${a.lastName}`.trim():(a==null?void 0:a.email)||"User"),maxApprovalLevels:j.maxApprovalLevels,onPolicyViolation:M=>N({open:!0,violations:M})});case 3:return e.jsxs(Ht.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(Le,{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(Z,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.activityName})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(se,{variant:"secondary",className:"mt-1",children:R.activityType})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(Zi,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1 font-mono",children:R.dealerCode})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.dealerName})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerPhone})]}),R.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerAddress})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"w-5 h-5 text-purple-600"}),"Selected Approvers"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsx("div",{className:"space-y-3",children:[...R.approvers||[]].filter(U=>{var B,W;return!((B=U.email)!=null&&B.includes("system@"))&&!((W=U.email)!=null&&W.includes("finance@"))}).sort((U,B)=>U.level-B.level).map(U=>{const B=Number(U.tat||0),J=(U.tatType||"hours")==="days"?B*24:B;let O="Unknown",H="";if(U.isAdditional){O=U.stepName||"Additional Approver";const Y=Yl.find(re=>re.level===U.insertAfterLevel);H=U.stepName||`Additional Approver (after "${(Y==null?void 0:Y.name)||"Unknown"}")`}else{const Y=U.originalStepLevel?Yl.find(re=>re.level===U.originalStepLevel):Yl.find(re=>re.level===U.level&&!re.isAuto);O=(Y==null?void 0:Y.name)||"Unknown",H=O}return e.jsx("div",{className:`p-3 rounded-lg border ${U.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(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:H}),U.isAdditional&&e.jsx(se,{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:U.name||U.email||"Not selected"}),U.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:U.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[J," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${U.level}-${U.email}`)})})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.activityDate?et(R.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(te,{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(zo,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:R.location})]})]}),R.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Estimated Budget"}),e.jsx("p",{className:"text-xl font-bold text-blue-900 mt-1",children:R.estimatedBudget})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(te,{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(Es,{content:R.requestDescription||"",className:"text-sm"})})]})})]}),(R.periodStartDate||R.periodEndDate)&&e.jsxs(Z,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(st,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.periodStartDate?et(R.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.periodEndDate?et(R.periodEndDate,"PPP"):"Not specified"})]})]})})]}),e.jsx("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-6",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Er,{className:"w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-blue-900 mb-1",children:"Ready to Submit"}),e.jsx("p",{className:"text-sm text-blue-800",children:"Please review all the information above. Once submitted, your claim request will enter the approval workflow."})]})]})})]})]});default:return null}};return e.jsxs("div",{className:"w-full bg-gradient-to-br from-gray-50 to-gray-100 py-4 sm:py-6 lg:py-8 px-3 sm:px-4 lg:px-6 overflow-y-auto",children:[e.jsxs("div",{className:"max-w-6xl mx-auto pb-8",children:[e.jsxs("div",{className:"mb-6 sm:mb-8",children:[e.jsxs(E,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(ws,{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(se,{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:Kl[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(Zs,{value:r/P*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:Kl.map((M,U)=>e.jsx("span",{className:`text-xs sm:text-sm ${U+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:U+1},U))})]})]}),e.jsx(Z,{className:"mb-6 sm:mb-8",children:e.jsx(ee,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(ol,{mode:"wait",children:L()})})}),e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between gap-3 sm:gap-0 pb-4 sm:pb-0",children:[e.jsxs(E,{variant:"outline",onClick:T,disabled:r===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(ws,{className:"w-4 h-4"}),"Previous"]}),r<P?e.jsxs(E,{onClick:I,className:`gap-2 w-full sm:w-auto order-1 sm:order-2 ${$()?"":"opacity-50 cursor-pointer hover:opacity-60"}`,children:["Next",e.jsx(fs,{className:"w-4 h-4"})]}):e.jsx(E,{onClick:z,disabled:!$()||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(Xe,{className:"w-4 h-4 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(za,{className:"w-4 h-4"}),"Submit Claim Request"]})})]})]}),e.jsx(si,{open:w.open,onClose:()=>N({open:!1,violations:[]}),violations:w.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}const{DocumentsTab:Q5,ActivityTab:X5,WorkNotesTab:J5,SummaryTab:Z5,RequestDetailHeader:q5,QuickActionsSidebar:ek,RequestDetailModals:tk}=c0;let sk=class extends h.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("Dealer Claim RequestDetail Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(ts,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(E,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(E,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function ak({requestId:t,onBack:s,dynamicRequests:a=[]}){var Za,qa,Gt,As,qs,gr;const n=_a().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=h.useState(l),[d,m]=h.useState(!1),[p,x]=h.useState(null),[u,g]=h.useState(null),[f,b]=h.useState(!1),[j,y]=h.useState(0),[w,N]=h.useState(!1),[S,A]=h.useState(!1),[_,D]=h.useState(!1),[R,v]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[P,C]=h.useState({open:!1,violations:[]}),{user:V}=cs(),{request:F,apiRequest:$,loading:I,refreshing:T,refreshDetails:k,currentApprovalLevel:z,isSpectator:L,isInitiator:M,existingParticipants:U,accessDenied:B}=Vc(n,a,V),W=(V==null?void 0:V.userId)||"",J=(V==null?void 0:V.jobTitle)==="Dealer"||(V==null?void 0:V.designation)==="Dealer",H=((F==null?void 0:F.workflowType)==="CLAIM_MANAGEMENT"||($==null?void 0:$.workflowType)==="CLAIM_MANAGEMENT"||(F==null?void 0:F.templateType)==="claim-management")&&!J,{mergedMessages:Y,unreadWorkNotes:re,workNoteAttachments:K,setWorkNoteAttachments:ae}=Xg(n,$,o,V),{uploadingDocument:Ne,triggerFileInput:Se,previewDocument:Ge,setPreviewDocument:Je,documentPolicy:Pe,documentError:Oe,setDocumentError:ie}=Jg($,k),[pe,we]=h.useState(null),Ae=pe||z,{showApproveModal:ne,setShowApproveModal:q,showRejectModal:de,setShowRejectModal:Ye,showAddApproverModal:fe,setShowAddApproverModal:ye,showAddSpectatorModal:Ue,setShowAddSpectatorModal:nt,showSkipApproverModal:mt,setShowSkipApproverModal:vt,showActionStatusModal:xs,setShowActionStatusModal:le,skipApproverData:De,setSkipApproverData:ce,actionStatus:Ke,setActionStatus:We,handleApproveConfirm:tt,handleRejectConfirm:Qe,handleAddApprover:rt,handleSkipApprover:qe,handleAddSpectator:ot}=qg(n,Ae,k),$s=async Rt=>{await tt(Rt),we(null)},ns=async Rt=>{await Qe(Rt),we(null)},pt=((F==null?void 0:F.status)||($==null?void 0:$.status)||"").toLowerCase(),ct=(pt==="approved"||pt==="rejected")&&M,{conclusionRemark:Ft,setConclusionRemark:Ss,conclusionLoading:ss,conclusionSubmitting:Ma,aiGenerated:La,handleGenerateConclusion:Aa,handleFinalizeConclusion:Ya,generationAttempts:It,generationFailed:Oa,maxAttemptsReached:Us}=Zg(F,n,M,k,s,We,le);h.useEffect(()=>{(async()=>{var Xt;try{const Rs=await la("SYSTEM_SETTINGS"),ma=await la("WORKFLOW_SHARING"),$r=[...Rs,...ma],ya={};$r.forEach(er=>{ya[er.configKey]=er.configValue}),v({maxApprovalLevels:parseInt(ya.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(ya.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((Xt=ya.ALLOW_ADD_SPECTATOR)==null?void 0:Xt.toLowerCase())==="true",maxSpectators:parseInt(ya.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Rs){console.error("Failed to load system policy:",Rs)}})()},[]),h.useEffect(()=>{const Xt=new URLSearchParams(window.location.search).get("tab");Xt&&c(Xt)},[n]);const Lr=()=>{k()},xr=()=>{N(!0)},Or=()=>{A(!0)},Ka=async()=>{await k()},hr=()=>{D(!0)},Qa=async()=>{await k()},pr=async()=>{await k()},Xa=async()=>{if(!($!=null&&$.requestId)){X.error("Request ID not found");return}if(!p){X.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Ta=(F==null?void 0:F.status)==="closed";h.useEffect(()=>{(async()=>{if(!Ta||!($!=null&&$.requestId)){g(null),x(null);return}try{b(!0);const Xt=await n0($.requestId);if(Xt!=null&&Xt.summaryId){x(Xt.summaryId);try{const Rs=await Hc(Xt.summaryId);g(Rs)}catch(Rs){console.error("Failed to fetch summary details:",Rs),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{b(!1)}})()},[Ta,$==null?void 0:$.requestId]),h.useEffect(()=>{if(!W||!($!=null&&$.requestId))return;const Rt=en();if(!Rt)return;Wh(Rt,W);const Xt=Rs=>{var er,pn,gn,fn;const ma=Rs==null?void 0:Rs.notification;if(!ma)return;const $r=ma.requestId||ma.request_id,ya=((er=ma.metadata)==null?void 0:er.requestNumber)||((pn=ma.metadata)==null?void 0:pn.request_number);$r!==$.requestId&&ya!==n&&ya!==$.requestNumber||((gn=ma.metadata)!=null&&gn.creditNoteNumber||(fn=ma.metadata)!=null&&fn.credit_note_number)&&k()};return Rt.on("notification:new",Xt),()=>{Rt.off("notification:new",Xt)}},[W,$==null?void 0:$.requestId,n,k]);const Ja=((F==null?void 0:F.approvalFlow)||[]).filter(Rt=>Rt&&typeof Rt.step=="number").map(Rt=>({levelNumber:Rt.step||0,approverName:Rt.approver||"Unknown",status:Rt.status||"pending",tatHours:Rt.tatHours||24}));return I&&!F&&!$?e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx($t,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading dealer claim request details..."})]})}):B!=null&&B.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(mh,{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:B.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):F?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"dealer-claim-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(q5,{request:F,refreshing:T,onBack:s||(()=>window.history.back()),onRefresh:Lr,onShareSummary:Xa,isInitiator:M,slaData:((Za=F==null?void 0:F.summary)==null?void 0:Za.sla)||(F==null?void 0:F.sla)||null,isPaused:((qa=F==null?void 0:F.pauseInfo)==null?void 0:qa.isPaused)||!1}),e.jsxs(ai,{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(ri,{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(Mt,{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(uh,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Ta&&u&&e.jsxs(Mt,{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(Ho,{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(Mt,{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(Hs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),H&&e.jsxs(Mt,{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(Ha,{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(Mt,{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(Ie,{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(Mt,{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(Ot,{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(Mt,{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(zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),re>0&&e.jsx(se,{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:re>9?"9+":re})]})]})}),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(Lt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(p5,{request:F,apiRequest:$,currentUserId:W,isInitiator:M,needsClosure:ct,conclusionRemark:Ft,setConclusionRemark:Ss,conclusionLoading:ss,conclusionSubmitting:Ma,aiGenerated:La,handleGenerateConclusion:Aa,handleFinalizeConclusion:Ya,generationAttempts:It,generationFailed:Oa,maxAttemptsReached:Us})}),Ta&&e.jsx(Lt,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(Z5,{summary:u,loading:f,onShare:Xa,isInitiator:M})}),e.jsx(Lt,{value:"workflow",className:"mt-0",children:e.jsx(z5,{request:F,user:V,isInitiator:M,onSkipApprover:Rt=>{if(!Rt.levelId){alert("Level ID not available");return}ce(Rt),vt(!0)},onRefresh:k,documentPolicy:Pe})}),H&&e.jsx(Lt,{value:"io",className:"mt-0",children:e.jsx(H5,{request:F,apiRequest:$,onRefresh:k})}),e.jsx(Lt,{value:"documents",className:"mt-0",children:e.jsx(Q5,{request:F,workNoteAttachments:K,uploadingDocument:Ne,documentPolicy:Pe,triggerFileInput:Se,setPreviewDocument:Je,downloadDocument:Ms})}),e.jsx(Lt,{value:"activity",className:"mt-0",children:e.jsx(X5,{request:F})}),e.jsx(Lt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(J5,{requestId:n,requestTitle:F.title,mergedMessages:Y,setWorkNoteAttachments:ae,isInitiator:M,isSpectator:L,currentLevels:Ja,onAddApprover:rt,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:Rt=>C({open:!0,violations:Rt})})})]}),o!=="worknotes"&&e.jsx(ek,{request:F,isInitiator:M,isSpectator:L,currentApprovalLevel:z,onAddApprover:()=>ye(!0),onAddSpectator:()=>nt(!0),onApprove:()=>q(!0),onReject:()=>Ye(!0),onPause:xr,onResume:Or,onRetrigger:hr,summaryId:p,refreshTrigger:j,pausedByUserId:(As=(Gt=F==null?void 0:F.pauseInfo)==null?void 0:Gt.pausedBy)==null?void 0:As.userId,currentUserId:W,apiRequest:$,hideApproveReject:J})]})]})]})}),d&&p&&e.jsx(d0,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(F==null?void 0:F.title)||"N/A",onSuccess:()=>{k(),y(Rt=>Rt+1)}}),w&&($==null?void 0:$.requestId)&&e.jsx(m0,{isOpen:w,onClose:()=>N(!1),requestId:$.requestId,levelId:(z==null?void 0:z.levelId)||null,onSuccess:Qa}),S&&($==null?void 0:$.requestId)&&e.jsx(u0,{isOpen:S,onClose:()=>A(!1),requestId:$.requestId,onSuccess:Ka}),_&&($==null?void 0:$.requestId)&&e.jsx(x0,{isOpen:_,onClose:()=>D(!1),requestId:$.requestId,approverName:(gr=(qs=F==null?void 0:F.pauseInfo)==null?void 0:qs.pausedBy)==null?void 0:gr.name,onSuccess:pr}),e.jsx(tk,{showApproveModal:ne,showRejectModal:de,showAddApproverModal:fe,showAddSpectatorModal:Ue,showSkipApproverModal:mt,showActionStatusModal:xs,previewDocument:Ge,documentError:Oe,request:F,skipApproverData:De,actionStatus:Ke,existingParticipants:U,currentLevels:Ja,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:Rt=>C({open:!0,violations:Rt}),setShowApproveModal:q,setShowRejectModal:Ye,setShowAddApproverModal:ye,setShowAddSpectatorModal:nt,setShowSkipApproverModal:vt,setShowActionStatusModal:le,setPreviewDocument:Je,setDocumentError:ie,setSkipApproverData:ce,setActionStatus:We,handleApproveConfirm:$s,handleRejectConfirm:ns,handleAddApprover:rt,handleAddSpectator:ot,handleSkipApprover:qe,downloadDocument:Ms,documentPolicy:Pe}),e.jsx(si,{open:P.open,onClose:()=>C({open:!1,violations:[]}),violations:P.violations,policyDetails:{maxApprovalLevels:R.maxApprovalLevels,maxParticipants:R.maxParticipants,allowSpectators:R.allowSpectators,maxSpectators:R.maxSpectators}})]}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"not-found-state",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(Ie,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Dealer Claim Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The dealer claim request you're looking for doesn't exist or may have been deleted."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function rk(t){return e.jsx(sk,{children:e.jsx(ak,{...t})})}function nk({onNavigate:t,onNewRequest:s}){const[a,r]=h.useState(!0),[n,i]=h.useState(!1),[l,o]=h.useState({totalClaims:0,totalValue:0,approved:0,rejected:0,pending:0,credited:0,pendingCredit:0,approvedValue:0,rejectedValue:0,pendingValue:0,creditedValue:0,pendingCreditValue:0}),[c,d]=h.useState([]),[m,p]=h.useState("all"),[x,u]=h.useState(),[g,f]=h.useState(),b=async(C=!1)=>{try{C?i(!0):r(!0);const V=await L5(m||"all",x,g);o(V.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(V.categoryData||[])}catch(V){console.error("[DealerDashboard] Error fetching data:",V),X.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)}};h.useEffect(()=>{b()},[]);const j=(C,V=!1)=>{if(C==null||isNaN(C))return"₹0";const F=typeof C=="string"?parseFloat(C):Number(C);return F<=0?"₹0":V||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")}`},y=C=>C.toLocaleString("en-IN"),w=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),N=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),S=h.useMemo(()=>{const C=c.reduce((V,F)=>V+F.raised,0);return C===0?[]:c.map(V=>({name:V.activityType.length>20?V.activityType.substring(0,20)+"...":V.activityType,value:V.raised,fullName:V.activityType,percentage:(V.raised/C*100).toFixed(0)}))},[c]),A=h.useMemo(()=>c.map(C=>({name:C.activityType.length>15?C.activityType.substring(0,15)+"...":C.activityType,fullName:C.activityType,Raised:C.raised,Approved:C.approved,Rejected:C.rejected,Pending:C.pending})),[c]),_=h.useMemo(()=>c.map(C=>({name:C.activityType.length>15?C.activityType.substring(0,15)+"...":C.activityType,fullName:C.activityType,Raised:C.raisedValue,Approved:C.approvedValue,Credited:C.creditedValue})),[c]),D=["#166534","#15803d","#16a34a","#22c55e","#4ade80","#86efac","#bbf7d0"],R=h.useMemo(()=>c.length===0?null:c.reduce((C,V)=>V.approvalRate>((C==null?void 0:C.approvalRate)||0)?V:C),[c]),v=h.useMemo(()=>c.length===0?null:c.reduce((C,V)=>V.raisedValue>((C==null?void 0:C.raisedValue)||0)?V:C),[c]);return a?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx($t,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):l.totalClaims===0&&c.length===0?e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(Z,{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(ee,{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(ps,{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.jsx("div",{className:"flex flex-wrap gap-4 mt-8",children:e.jsxs(E,{onClick:()=>{i(!0),b(!0)},disabled:n,variant:"outline",className:"bg-white/10 hover:bg-white/20 text-white border-white/20",children:[e.jsx($t,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh"]})})]})})})]}),e.jsx(Z,{className:"shadow-lg",children:e.jsxs(ee,{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(no,{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.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:e.jsxs(E,{onClick:()=>{i(!0),b(!0)},disabled:n,variant:"outline",children:[e.jsx($t,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh Data"]})})]})})]}):e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(Z,{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(ee,{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(ps,{className:"w-8 h-8 text-slate-900"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-4xl text-white font-bold",children:"Claims Analytics Dashboard"}),e.jsx("p",{className:"text-xl text-gray-200 mt-1",children:"Comprehensive insights into approval workflows"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 mt-8",children:[e.jsxs(E,{onClick:()=>t==null?void 0:t("/requests?status=pending"),className:"bg-blue-600 hover:bg-blue-700 text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200",children:[e.jsx(st,{className:"w-5 h-5 mr-2"}),"View Pending Claims"]}),e.jsxs(E,{onClick:()=>t==null?void 0:t("/requests"),className:"bg-emerald-600 hover:bg-emerald-700 text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200",children:[e.jsx(Ie,{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(Z,{className:"border-l-4 border-l-blue-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{className:"text-sm text-muted-foreground",children:"Raised Claims"}),e.jsx("div",{className:"p-2 rounded-lg bg-blue-50",children:e.jsx(Ie,{className:"h-4 w-4 text-blue-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.totalClaims)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j(l.totalValue,!0)})]})]}),e.jsxs(Z,{className:"border-l-4 border-l-green-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{className:"text-sm text-muted-foreground",children:"Approved"}),e.jsx("div",{className:"p-2 rounded-lg bg-green-50",children:e.jsx(Le,{className:"h-4 w-4 text-green-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.approved)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Hs,{className:"h-3 w-3 text-green-600"}),e.jsxs("p",{className:"text-xs text-green-600",children:[w(),"% approval rate"]})]})]})]}),e.jsxs(Z,{className:"border-l-4 border-l-red-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{className:"text-sm text-muted-foreground",children:"Rejected"}),e.jsx("div",{className:"p-2 rounded-lg bg-red-50",children:e.jsx(St,{className:"h-4 w-4 text-red-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.rejected)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Ab,{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(Z,{className:"border-l-4 border-l-orange-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{className:"text-sm text-muted-foreground",children:"Pending"}),e.jsx("div",{className:"p-2 rounded-lg bg-orange-50",children:e.jsx(st,{className:"h-4 w-4 text-orange-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.pending)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j(l.pendingValue)})]})]}),e.jsxs(Z,{className:"border-l-4 border-l-emerald-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{className:"text-sm text-muted-foreground",children:"Credited"}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-50",children:e.jsx(Tb,{className:"h-4 w-4 text-emerald-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.credited)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Hs,{className:"h-3 w-3 text-emerald-600"}),e.jsxs("p",{className:"text-xs text-emerald-600",children:[N(),"% credit rate"]})]})]})]}),e.jsxs(Z,{className:"border-l-4 border-l-amber-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{className:"text-sm text-muted-foreground",children:"Pending Credit"}),e.jsx("div",{className:"p-2 rounded-lg bg-amber-50",children:e.jsx(ts,{className:"h-4 w-4 text-amber-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.pendingCredit)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j(l.pendingCreditValue)})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(Z,{className:"shadow-lg",children:[e.jsx(oe,{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(no,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(me,{children:"Claims Distribution by Activity Type"}),e.jsx(ve,{children:"Total claims raised across activity types"})]})]})}),e.jsxs(ee,{children:[e.jsx(Qr,{width:"100%",height:300,children:e.jsxs(Yx,{children:[e.jsx(Kx,{data:S,cx:"50%",cy:"50%",labelLine:!1,label:({name:C,percentage:V})=>`${C}: ${V}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:S.map((C,V)=>e.jsx(Qx,{fill:D[V%D.length]},`cell-${V}`))}),e.jsx(Xr,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:S.slice(0,3).map((C,V)=>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[V%D.length]}}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600",children:C.name}),e.jsx("p",{className:"text-sm text-gray-900",children:y(C.value)})]})]},V))})]})]}),e.jsxs(Z,{className:"shadow-lg",children:[e.jsx(oe,{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(me,{children:"Claims Status by Activity Type"}),e.jsx(ve,{children:"Count comparison across workflow stages"})]})]})}),e.jsx(ee,{children:e.jsx(Qr,{width:"100%",height:300,children:e.jsxs(so,{data:A,children:[e.jsx(Ai,{strokeDasharray:"3 3"}),e.jsx(Ti,{dataKey:"name"}),e.jsx(ki,{}),e.jsx(Xr,{}),e.jsx(Ri,{}),e.jsx(ka,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(ka,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(ka,{dataKey:"Rejected",fill:"#ef4444"}),e.jsx(ka,{dataKey:"Pending",fill:"#f59e0b"})]})})})]})]}),e.jsxs(Z,{className:"shadow-lg",children:[e.jsx(oe,{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(Ot,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(me,{children:"Detailed Activity Type Breakdown"}),e.jsx(ve,{children:"In-depth analysis of claims by type and status"})]})]})}),e.jsx(ee,{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(Qr,{width:"100%",height:350,children:e.jsxs(so,{data:_,children:[e.jsx(Ai,{strokeDasharray:"3 3"}),e.jsx(Ti,{dataKey:"name"}),e.jsx(ki,{tickFormatter:C=>j(C)}),e.jsx(Xr,{formatter:C=>j(C),labelFormatter:C=>C}),e.jsx(Ri,{}),e.jsx(ka,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(ka,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(ka,{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((C,V)=>e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow",children:[e.jsx(oe,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{className:"text-base",children:C.activityType}),e.jsxs(se,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[C.approvalRate.toFixed(1),"% approved"]})]})}),e.jsxs(ee,{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:[y(C.raised)," (",j(C.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:[y(C.approved)," (",j(C.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:[y(C.rejected)," (",j(C.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:[y(C.pending)," (",j(C.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:[y(C.credited)," (",j(C.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:[y(C.pendingCredit)," (",j(C.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:[C.creditRate.toFixed(1),"%"]})]}),e.jsx(Zs,{value:C.creditRate,className:"h-2"})]})]})]},V))})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(Z,{className:"border-t-4 border-t-green-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(es,{className:"h-6 w-6 text-green-600"})}),e.jsx(Hs,{className:"h-5 w-5 text-green-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Best Performing"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:(R==null?void 0:R.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-green-600",children:[(R==null?void 0:R.approvalRate.toFixed(2))||0,"% approval rate"]})]})}),e.jsx(Z,{className:"border-t-4 border-t-blue-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(Ha,{className:"h-6 w-6 text-blue-600"})}),e.jsx(Ot,{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:(v==null?void 0:v.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-blue-600",children:[v?j(v.raisedValue,!0):"₹0"," raised"]})]})}),e.jsx(Z,{className:"border-t-4 border-t-emerald-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(Yi,{className:"h-6 w-6 text-emerald-600"})}),e.jsx(Le,{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:[N(),"%"]}),e.jsxs("p",{className:"text-sm text-emerald-600",children:[y(l.credited)," claims credited"]})]})}),e.jsx(Z,{className:"border-t-4 border-t-amber-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(nh,{className:"h-6 w-6 text-amber-600"})}),e.jsx(ts,{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:y(l.pendingCredit)}),e.jsxs("p",{className:"text-sm text-amber-600",children:[j(l.pendingCreditValue)," awaiting credit"]})]})})]})]})}function ik({searchTerm:t,sortBy:s,sortOrder:a,onSearchChange:r,onSortByChange:n,onSortOrderChange:i,onClearFilters:l,activeFiltersCount:o,...c}){return e.jsxs(Z,{className:"shadow-lg border-0",children:[e.jsx(oe,{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(Pa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ve,{className:"text-xs sm:text-sm",children:o>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[o," filter",o>1?"s":""," active"]})})]})]}),o>0&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:l,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(bt,{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(ee,{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(Cs,{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(ke,{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(Be,{value:s,onValueChange:d=>n(d),children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ve,{placeholder:"Sort by"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"due",children:"Due Date"}),e.jsx(Q,{value:"created",children:"Date Created"}),e.jsx(Q,{value:"priority",children:"Priority"}),e.jsx(Q,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>i(a==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:a==="asc"?e.jsx(qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(el,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function lk({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(Z,{className:"shadow-lg border-0","data-testid":"dealer-closed-requests-filters",children:[e.jsx(oe,{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(Pa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ve,{className:"text-xs sm:text-sm",children:d>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[d," filter",d>1?"s":""," active"]})})]})]}),d>0&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:c,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3","data-testid":"dealer-closed-requests-clear-filters",children:[e.jsx(bt,{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(ee,{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(Cs,{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(ke,{placeholder:"Search requests, IDs...",value:t,onChange:p=>n(p.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors","data-testid":"dealer-closed-requests-search"})]}),i&&e.jsxs(Be,{value:s,onValueChange:i,children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200","data-testid":"dealer-closed-requests-status-filter",children:e.jsx(Ve,{placeholder:"Closure Type"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Closures"}),e.jsx(Q,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(Q,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{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(Be,{value:a,onValueChange:p=>l(p),children:[e.jsx(ze,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200","data-testid":"dealer-closed-requests-sort-by",children:e.jsx(Ve,{placeholder:"Sort by"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"due",children:"Due Date"}),e.jsx(Q,{value:"created",children:"Date Created"}),e.jsx(Q,{value:"priority",children:"Priority"})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:o,className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11","data-testid":"dealer-closed-requests-sort-order",children:r==="asc"?e.jsx(qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(el,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function ok({searchTerm:t,statusFilter:s,initiatorFilter:a,approverFilter:r,approverFilterType:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,initiatorSearch:d,approverSearch:m,onSearchChange:p,onStatusChange:x,onInitiatorChange:u,onApproverChange:g,onApproverTypeChange:f,onDateRangeChange:b,onCustomStartDateChange:j,onCustomEndDateChange:y,onShowCustomDatePickerChange:w,onApplyCustomDate:N,onClearFilters:S,hasActiveFilters:A,..._}){return e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"dealer-user-all-requests-filters",children:e.jsx(ee,{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(Pa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),A&&e.jsx(se,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),A&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:S,className:"gap-2",children:[e.jsx($t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Qt,{}),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(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(ke,{placeholder:"Search requests...",value:t,onChange:D=>p(D.target.value),className:"pl-10 h-10","data-testid":"dealer-search-input"})]}),e.jsxs(Be,{value:s,onValueChange:x,children:[e.jsx(ze,{className:"h-10","data-testid":"dealer-status-filter",children:e.jsx(Ve,{placeholder:"All Status"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Status"}),e.jsx(Q,{value:"pending",children:"Pending"}),e.jsx(Q,{value:"paused",children:"Paused"}),e.jsx(Q,{value:"approved",children:"Approved"}),e.jsx(Q,{value:"rejected",children:"Rejected"}),e.jsx(Q,{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(te,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:d.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:d.selectedUser.displayName||d.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:d.handleClear,children:e.jsx(bt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{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(te,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r!=="all"&&f&&e.jsxs(Be,{value:n,onValueChange:D=>f(D),children:[e.jsx(ze,{className:"h-7 w-32 text-xs",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Q,{value:"current",children:"Current Only"}),e.jsx(Q,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:m.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:m.selectedUser.displayName||m.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:m.handleClear,children:e.jsx(bt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{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(dt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:i,onValueChange:D=>b(D),children:[e.jsx(ze,{className:"w-[160px] h-10",children:e.jsx(Ve,{placeholder:"Date Range"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Time"}),e.jsx(Q,{value:"today",children:"Today"}),e.jsx(Q,{value:"week",children:"This Week"}),e.jsx(Q,{value:"month",children:"This Month"}),e.jsx(Q,{value:"last7days",children:"Last 7 Days"}),e.jsx(Q,{value:"last30days",children:"Last 30 Days"}),e.jsx(Q,{value:"custom",children:"Custom Range"})]})]}),i==="custom"&&e.jsxs(ra,{open:c,onOpenChange:w,children:[e.jsx(na,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(dt,{className:"w-4 h-4"}),l&&o?`${et(l,"MMM d, yyyy")} - ${et(o,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Xs,{value:l||null,onChange:D=>{const R=D?new Date(D):void 0;R?(j==null||j(R),o&&R>o&&(y==null||y(R))):j==null||j(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"end-date",children:"End Date"}),e.jsx(Xs,{value:o||null,onChange:D=>{const R=D?new Date(D):void 0;R?(y==null||y(R),l&&R<l&&(j==null||j(R))):y==null||y(void 0)},minDate:l||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{size:"sm",onClick:N,disabled:!l||!o,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>{w==null||w(!1),j==null||j(void 0),y==null||y(void 0),b("month")},children:"Cancel"})]})]})})]})]})]})})})}function ck(t){switch(t){case"DEALER_CLAIM":return rk;case"CUSTOM":default:return l5}}function dk(t){switch(t){case"DEALER":return ik;case"STANDARD":default:return d5}}function mk(t){switch(t){case"DEALER":return lk;case"STANDARD":default:return x5}}function uk(t){switch(t){case"DEALER":return ok;case"STANDARD":default:return h5}}const xk=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Sa,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:es,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:es,iconColor:"text-gray-600"}}},hk=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ze,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:St,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Le,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ze,iconColor:"text-gray-600",label:t}}};function pk({onViewRequest:t}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState(1),[d,m]=h.useState(0),[p]=h.useState(10),x=h.useRef(null),u=fw(),g=h.useMemo(()=>{try{const R=at.getUserData();return lc(R)}catch(R){return console.error("[OpenRequests] Error getting user filter type:",R),"STANDARD"}},[]),f=h.useMemo(()=>dk(g),[g]),b=g==="DEALER",j=R=>{const v={search:u.searchTerm||void 0,status:R&&!b&&u.statusFilter!=="all"?u.statusFilter:void 0,priority:!b&&u.priorityFilter!=="all"?u.priorityFilter:void 0,templateType:u.templateTypeFilter!=="all"?u.templateTypeFilter:void 0,sortBy:u.sortBy,sortOrder:u.sortOrder};return v.templateType==="FORM_16"&&(u.form16FinancialYear&&(v.financialYear=u.form16FinancialYear),u.form16Quarter&&(v.quarter=u.form16Quarter)),v},y=h.useCallback(async(R=1,v)=>{try{R===1&&(n(!0),a([]));const P=await Ws.listOpenForMe({page:R,limit:p,search:v==null?void 0:v.search,status:v==null?void 0:v.status,priority:v==null?void 0:v.priority,templateType:v==null?void 0:v.templateType,financialYear:v==null?void 0:v.financialYear,quarter:v==null?void 0:v.quarter,sortBy:v==null?void 0:v.sortBy,sortOrder:v==null?void 0:v.sortOrder}),C=Array.isArray(P==null?void 0:P.data)?P.data:[],V=P==null?void 0:P.pagination;V&&(u.setCurrentPage(V.page||1),c(V.totalPages||1),m(V.total||0));const F=C.map($=>{var T,k,z,L;const I=$.submittedAt||$.submitted_at||$.createdAt||$.created_at;return{id:$.requestNumber||$.request_number||$.requestId,requestId:$.requestId,displayId:$.requestNumber||$.request_number||$.requestId,title:$.title,description:$.description,status:($.status||"").toString().toLowerCase().replace("_","-"),priority:($.priority||"").toString().toLowerCase(),initiator:{name:((T=$.initiator)==null?void 0:T.displayName)||((k=$.initiator)==null?void 0:k.email)||"—",avatar:(((z=$.initiator)==null?void 0:z.displayName)||((L=$.initiator)==null?void 0:L.email)||"NA").split(" ").map(M=>M[0]).join("").slice(0,2).toUpperCase()},currentApprover:$.currentApprover?{name:$.currentApprover.name||$.currentApprover.email||"—",avatar:($.currentApprover.name||$.currentApprover.email||"CA").split(" ").map(M=>M[0]).join("").slice(0,2).toUpperCase(),sla:$.currentApprover.sla}:void 0,createdAt:I||"—",approvalStep:$.currentLevel?`Step ${$.currentLevel} of ${$.totalLevels||"?"}`:void 0,department:$.department,currentLevelSLA:$.currentLevelSLA,templateType:$.templateType||$.template_type,form16Submission:$.form16Submission??null}});a(F)}finally{n(!1),l(!1)}},[p,u]);x.current=y;const w=h.useCallback(()=>{l(!0),y(u.currentPage,j(!0))},[u.currentPage,y]),N=h.useCallback(R=>{R>=1&&R<=o&&(u.setCurrentPage(R),y(R,j(!0)))},[o,u,y]),S=()=>{const R=[];let P=Math.max(1,u.currentPage-Math.floor(2.5)),C=Math.min(o,P+5-1);C-P<4&&(P=Math.max(1,C-5+1));for(let V=P;V<=C;V++)R.push(V);return R},A=h.useRef(!1);h.useEffect(()=>{if(!A.current){A.current=!0;const R=u.currentPage||1;y(R,j(!0))}},[]);const _=h.useRef({searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:b});h.useEffect(()=>{if(!A.current)return;const R=_.current;if(!(R.searchTerm!==u.searchTerm||R.statusFilter!==u.statusFilter||R.priorityFilter!==u.priorityFilter||R.templateTypeFilter!==u.templateTypeFilter||R.sortBy!==u.sortBy||R.sortOrder!==u.sortOrder||R.isDealer!==b))return;const P=setTimeout(()=>{u.setCurrentPage(1),y(1,j(!0)),_.current={searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:b}},u.searchTerm?500:0);return()=>clearTimeout(P)},[u.searchTerm,u.statusFilter,u.priorityFilter,u.templateTypeFilter,u.form16FinancialYear,u.form16Quarter,u.sortBy,u.sortOrder,b]);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(Ie,{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(se,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold",children:[r?"Loading…":`${d||s.length} open`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:w,disabled:i,children:[e.jsx($t,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:i?"Refreshing...":"Refresh"})]})]})]}),e.jsx(f,{searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,form16FinancialYear:u.form16FinancialYear,form16Quarter:u.form16Quarter,sortBy:u.sortBy,sortOrder:u.sortOrder,onSearchChange:u.setSearchTerm,onStatusFilterChange:u.setStatusFilter,onPriorityFilterChange:u.setPriorityFilter,onTemplateTypeFilterChange:u.setTemplateTypeFilter,onForm16FinancialYearChange:u.setForm16FinancialYear,onForm16QuarterChange:u.setForm16Quarter,onSortByChange:u.setSortBy,onSortOrderChange:u.setSortOrder,onClearFilters:u.clearFilters,activeFiltersCount:u.activeFiltersCount}),e.jsx("div",{className:"space-y-3",children:D.map(R=>{const v=xk(R.priority),P=(R.templateType||R.template_type||"").toString().toUpperCase()==="FORM_16",C=R.form16Submission,V=C==null?void 0:C.displayStatus,F=V&&/balance mismatch|failed/i.test(String(V)),$=P&&V?{color:F?"bg-red-100 text-red-800 border-red-200":V==="Completed"?"bg-green-100 text-green-800 border-green-200":"bg-gray-100 text-gray-700 border-gray-200",icon:Ze,label:V}:hk(R.status);return e.jsx(Z,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>t==null?void 0:t(R.id,R.title),children:e.jsx(ee,{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 ${v.color} border shadow-sm`,children:e.jsx(v.icon,{className:`w-5 h-5 ${v.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:R.displayId||R.id}),e.jsxs(se,{variant:"outline",className:`${$.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx($.icon,{className:"w-3.5 h-3.5 mr-1"}),$.label||R.status]}),R.department&&e.jsx(se,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:R.department}),e.jsx(se,{variant:"outline",className:`${v.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:R.priority}),(()=>{const I=(R==null?void 0:R.templateType)||(R==null?void 0:R.template_type)||"",T=(I==null?void 0:I.toUpperCase())||"";let k="Non-Templatized",z="bg-purple-100 !text-purple-600 border-purple-200";return T==="DEALER CLAIM"?(k="Dealer Claim",z="bg-blue-100 !text-blue-700 border-blue-200"):T==="FORM_16"?(k="Form 16",z="bg-emerald-100 !text-emerald-700 border-emerald-200"):T==="TEMPLATE"&&(k="Template"),e.jsx(se,{variant:"outline",className:`${z} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:k})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:R.title}),(R.templateType||"").toString().toUpperCase()==="FORM_16"&&R.form16Submission&&e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-600 mt-1",children:[R.form16Submission.dealerCode&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Dealer:"})," ",R.form16Submission.dealerCode]}),R.form16Submission.form16aNumber&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Form 16A:"})," ",R.form16Submission.form16aNumber]}),R.form16Submission.financialYear&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"FY:"})," ",R.form16Submission.financialYear]}),R.form16Submission.quarter&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Q:"})," ",R.form16Submission.quarter]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Total amount:"})," ",R.form16Submission.totalAmount!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(R.form16Submission.totalAmount):"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Credit note:"})," ",R.form16Submission.creditNoteNumber||"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Status:"})," ",R.form16Submission.displayStatus||R.form16Submission.status||"—"]})]}),R.currentLevelSLA&&(()=>{var L;const I=!!(R.isPaused||(L=R.pauseInfo)!=null&&L.isPaused||R.status==="paused"),T=R.currentLevelSLA.percentageUsed||0,z=I?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:T>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:T>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:T>=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 ${z.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:[I?e.jsx(rr,{className:`w-3.5 h-3.5 ${z.icon}`}):e.jsx(st,{className:`w-3.5 h-3.5 ${z.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",T,"% ",I&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:R.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${z.text}`,children:[R.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(Zs,{value:T,className:"h-1.5",indicatorClassName:z.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(ls,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(os,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:R.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:R.initiator.name})]}),R.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ls,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(os,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:R.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:R.currentApprover.name})]}),R.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ze,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:R.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(dt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",R.createdAt!=="—"?Ca(R.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(fs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},R.id)})}),D.length===0&&e.jsx(Z,{className:"shadow-lg border-0",children:e.jsxs(ee,{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(Ie,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:u.searchTerm||u.activeFiltersCount>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),u.activeFiltersCount>0&&e.jsx(E,{variant:"outline",className:"mt-4",onClick:u.clearFilters,children:"Clear all filters"})]})}),o>1&&!r&&e.jsx(Z,{className:"shadow-md",children:e.jsx(ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(u.currentPage-1)*p+1," to ",Math.min(u.currentPage*p,d)," of ",d," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>N(u.currentPage-1),disabled:u.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(fs,{className:"h-4 w-4 rotate-180"})}),u.currentPage>3&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>N(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),S().map(R=>e.jsx(E,{variant:R===u.currentPage?"default":"outline",size:"sm",onClick:()=>N(R),className:`h-8 w-8 p-0 ${R===u.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:R},R)),u.currentPage<o-2&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>N(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>N(u.currentPage+1),disabled:u.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(fs,{className:"h-4 w-4"})})]})]})})})]})}function gk({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(Ie,{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(se,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold","data-testid":"closed-requests-count",children:[s?"Loading…":`${t} closed`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:r,disabled:a,"data-testid":"closed-requests-refresh",children:[e.jsx($t,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${a?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:a?"Refreshing...":"Refresh"})]})]})]})}function fk(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Sa,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:es,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:es,iconColor:"text-gray-600"}}}function bk(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:Le,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:St,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ze,iconColor:"text-gray-600",label:t,description:""}}}function jk({request:t,onViewRequest:s}){var l;const a=fk(t.priority),r=bk(t.status),n=a.icon,i=r.icon;return e.jsx(Z,{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(ee,{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(se,{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(se,{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(se,{variant:"outline",className:`${a.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:t.priority}),(()=>{const o=t.templateType||"",c=(o==null?void 0:o.toUpperCase())||"";let d="Non-Templatized",m="bg-purple-100 !text-purple-600 border-purple-200";return c==="DEALER CLAIM"?(d="Dealer Claim",m="bg-blue-100 !text-blue-700 border-blue-200"):c==="FORM_16"?(d="Form 16",m="bg-emerald-100 !text-emerald-700 border-emerald-200"):c==="TEMPLATE"&&(d="Template"),e.jsx(se,{variant:"outline",className:`${m} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:d})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:t.title}),((l=t.templateType)==null?void 0:l.toUpperCase())==="FORM_16"&&t.form16Submission&&e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-600",children:[t.form16Submission.dealerCode&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Dealer:"})," ",t.form16Submission.dealerCode]}),t.form16Submission.form16aNumber&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Form 16A:"})," ",t.form16Submission.form16aNumber]}),t.form16Submission.financialYear&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"FY:"})," ",t.form16Submission.financialYear]}),t.form16Submission.quarter&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Q:"})," ",t.form16Submission.quarter]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Total amount:"})," ",t.form16Submission.totalAmount!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t.form16Submission.totalAmount):"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Credit note:"})," ",t.form16Submission.creditNoteNumber||"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Status:"})," ",t.form16Submission.displayStatus||t.form16Submission.status||"—"]})]}),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(ls,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(os,{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(Le,{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(dt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?Ca(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Le,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",Ca(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(fs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function yk({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(jk,{request:r,onViewRequest:a},r.id))})}function vk({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(Z,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(ee,{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(Ie,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:t||s>0?"Try adjusting your filters or search terms to see more results.":"No closed requests available at the moment."}),s>0&&e.jsx(E,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function Nk(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 wk({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=Nk(a,r);return e.jsx(Z,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(a-1)*i+1," to ",Math.min(a*i,n)," of ",n," closed requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>s(a-1),disabled:a===1,className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-prev",children:e.jsx(fs,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>s(1),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-first",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),l.map(o=>e.jsx(E,{variant:o===a?"default":"outline",size:"sm",onClick:()=>s(o),className:`h-8 w-8 p-0 ${o===a?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`closed-requests-pagination-page-${o}`,children:o},o)),a<r-2&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>s(a+1),disabled:a===r,className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-next",children:e.jsx(fs,{className:"h-4 w-4"})})]})]})})})}function Ck(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,form16Submission:t.form16Submission??null}}function Sk(t){return t.map(Ck)}function Ak({itemsPerPage:t=10}={}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=h.useCallback(async(p=1,x)=>{try{p===1&&(n(!0),a([]));const u=await Ws.listClosedByMe({page:p,limit:t,search:x==null?void 0:x.search,status:x!=null&&x.status&&x.status!=="all"?x.status:void 0,priority:x==null?void 0:x.priority,templateType:x==null?void 0:x.templateType,financialYear:x==null?void 0:x.financialYear,quarter:x==null?void 0:x.quarter,sortBy:x==null?void 0:x.sortBy,sortOrder:x==null?void 0:x.sortOrder}),g=Array.isArray(u==null?void 0:u.data)?u.data:[],f=Sk(g);a(f);const b=u==null?void 0:u.pagination;b&&c({currentPage:b.page||1,totalPages:b.totalPages||1,totalRecords:b.total||0,itemsPerPage:t})}catch(u){console.error("[ClosedRequests] Error fetching requests:",u),a([])}finally{n(!1),l(!1)}},[t]),m=h.useCallback(p=>{l(!0),d(o.currentPage,p)},[d,o.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:o,fetchRequests:d,handleRefresh:m}}const Tk={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},f0=on({name:"closedRequests",initialState:Tk,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},setForm16FinancialYear:(t,s)=>{t.form16FinancialYear=s.payload},setForm16Quarter:(t,s)=>{t.form16Quarter=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.form16FinancialYear="",t.form16Quarter="",t.currentPage=1}}}),{setSearchTerm:kk,setStatusFilter:Rk,setPriorityFilter:Dk,setTemplateTypeFilter:Fk,setForm16FinancialYear:Ik,setForm16Quarter:Pk,setSortBy:Ek,setSortOrder:_k,setCurrentPage:Mk,clearFilters:Lk}=f0.actions;function Ok({onFiltersChange:t,debounceMs:s=500}={}){const a=Yn(),r=h.useRef(null),n=h.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,form16FinancialYear:d,form16Quarter:m,sortBy:p,sortOrder:x,currentPage:u}=dn(v=>v.closedRequests),g=h.useCallback(v=>a(kk(v)),[a]),f=h.useCallback(v=>a(Rk(v)),[a]),b=h.useCallback(v=>a(Dk(v)),[a]),j=h.useCallback(v=>a(Fk(v)),[a]),y=h.useCallback(v=>a(Ik(v)),[a]),w=h.useCallback(v=>a(Pk(v)),[a]),N=h.useCallback(v=>a(Ek(v)),[a]),S=h.useCallback(v=>a(_k(v)),[a]),A=h.useCallback(v=>a(Mk(v)),[a]),_=h.useCallback(()=>({search:i,status:l,priority:o,templateType:c!=="all"?c:void 0,financialYear:c==="FORM_16"&&d?d:void 0,quarter:c==="FORM_16"&&m?m:void 0,sortBy:p,sortOrder:x}),[i,l,o,c,d,m,p,x]);h.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const v=setTimeout(()=>{t&&t(_())},i?s:0);return r.current=v,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,p,x,t,_,s]);const D=h.useCallback(()=>{a(Lk())},[a]),R=[i,o!=="all"?o:null,l!=="all"?l:null,c!=="all"?c:null,c==="FORM_16"&&d?"fy":null,c==="FORM_16"&&m?"q":null].filter(Boolean).length;return{searchTerm:i,priorityFilter:o,statusFilter:l,templateTypeFilter:c,form16FinancialYear:d,form16Quarter:m,sortBy:p,sortOrder:x,currentPage:u,setSearchTerm:g,setPriorityFilter:b,setStatusFilter:f,setTemplateTypeFilter:j,setForm16FinancialYear:y,setForm16Quarter:w,setSortBy:N,setSortOrder:S,setCurrentPage:A,clearFilters:D,activeFiltersCount:R,getFilters:_}}function $k({onViewRequest:t}){const s=Ak({itemsPerPage:10}),a=h.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=Ok(),n=h.useMemo(()=>{try{const x=at.getUserData();return lc(x)}catch(x){return console.error("[ClosedRequests] Error getting user filter type:",x),"STANDARD"}},[]),i=h.useMemo(()=>mk(n),[n]),l=n==="DEALER",o=h.useCallback(()=>{const x=r.getFilters();return{search:x.search||void 0,status:x.status!=="all"?x.status:void 0,priority:!l&&x.priority?x.priority:void 0,templateType:x.templateType,financialYear:x.financialYear,quarter:x.quarter,sortBy:x.sortBy,sortOrder:x.sortOrder}},[r,l]),c=h.useRef({searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,form16FinancialYear:r.form16FinancialYear,form16Quarter:r.form16Quarter,sortBy:r.sortBy,sortOrder:r.sortOrder}),d=h.useRef(!1);h.useEffect(()=>{const x=r.currentPage||1;a.current(x,o()),d.current=!0},[l]),h.useEffect(()=>{if(!d.current)return;const x=c.current;if(!(x.searchTerm!==r.searchTerm||x.statusFilter!==r.statusFilter||x.priorityFilter!==r.priorityFilter||x.templateTypeFilter!==r.templateTypeFilter||x.form16FinancialYear!==r.form16FinancialYear||x.form16Quarter!==r.form16Quarter||x.sortBy!==r.sortBy||x.sortOrder!==r.sortOrder))return;const g=setTimeout(()=>{r.setCurrentPage(1),a.current(1,o()),c.current={searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,form16FinancialYear:r.form16FinancialYear,form16Quarter:r.form16Quarter,sortBy:r.sortBy,sortOrder:r.sortOrder}},r.searchTerm!==x.searchTerm?500:0);return()=>clearTimeout(g)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.templateTypeFilter,r.form16FinancialYear,r.form16Quarter,r.sortBy,r.sortOrder,l]);const m=h.useCallback(x=>{x>=1&&x<=s.pagination.totalPages&&(r.setCurrentPage(x),s.fetchRequests(x,o()))},[s,r,o]),p=h.useCallback(()=>{s.handleRefresh(o())},[s,o]);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(gk,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:p}),e.jsx(i,{searchTerm:r.searchTerm,priorityFilter:r.priorityFilter,statusFilter:r.statusFilter,templateTypeFilter:r.templateTypeFilter,form16FinancialYear:r.form16FinancialYear,form16Quarter:r.form16Quarter,sortBy:r.sortBy,sortOrder:r.sortOrder,activeFiltersCount:r.activeFiltersCount,onSearchChange:r.setSearchTerm,onPriorityChange:r.setPriorityFilter,onStatusChange:r.setStatusFilter,onTemplateTypeChange:r.setTemplateTypeFilter,onForm16FinancialYearChange:r.setForm16FinancialYear,onForm16QuarterChange:r.setForm16Quarter,onSortByChange:r.setSortBy,onSortOrderChange:()=>r.setSortOrder(r.sortOrder==="asc"?"desc":"asc"),onClearFilters:r.clearFilters}),e.jsx(yk,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(vk,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(wk,{pagination:s.pagination,onPageChange:m})]})}function Uk(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 Bk(t){return Uk(t)?"DEALER_CLAIM":"CUSTOM"}function Vk(t,s){return`/request/${t}`}class zk extends h.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("RequestDetail Router Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(ts,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(E,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(E,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function Hk({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=_a().requestId||t||"",{user:i}=cs(),{apiRequest:l,loading:o}=Vc(n,a,i);if(o&&!l)return e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx($t,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading request details..."})]})});const c=Bk(l),d=ck(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function Wk(t){return e.jsx(zk,{children:e.jsx(Hk,{...t})})}function Gk({onViewSummary:t}){const s=ys(),[a,r]=h.useState([]),[n,i]=h.useState(!0),[l,o]=h.useState(""),[c,d]=h.useState(1),[m,p]=h.useState(1),[x,u]=h.useState(0),g=10,f=h.useCallback(async(w=1)=>{try{i(!0);const N=await UT({page:w,limit:g});r(N.data||[]),p(N.pagination.totalPages||1),u(N.pagination.total||0),d(N.pagination.page||1)}catch(N){console.error("Failed to fetch shared summaries:",N),X.error("Failed to load shared summaries")}finally{i(!1)}},[]);h.useEffect(()=>{f(1)},[f]);const b=async w=>{try{await r0(w),r(N=>N.map(S=>S.sharedSummaryId===w?{...S,isRead:!0,viewedAt:new Date().toISOString()}:S)),t?t(w):s(`/shared-summaries/${w}`)}catch(N){console.error("Failed to mark as viewed:",N),t?t(w):s(`/shared-summaries/${w}`)}},j=w=>{w>=1&&w<=m&&f(w)},y=a.filter(w=>{var S,A,_,D;if(!l)return!0;const N=l.toLowerCase();return((S=w.title)==null?void 0:S.toLowerCase().includes(N))||((A=w.requestNumber)==null?void 0:A.toLowerCase().includes(N))||((_=w.initiatorName)==null?void 0:_.toLowerCase().includes(N))||((D=w.sharedByName)==null?void 0:D.toLowerCase().includes(N))});return e.jsx("div",{className:"min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden",children:e.jsxs("div",{className:"max-w-7xl mx-auto w-full",children:[e.jsxs("div",{className:"mb-4 sm:mb-6",children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900 mb-1 sm:mb-2",children:"Shared Summaries"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600",children:"View summaries of closed requests shared with you"})]}),e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs("div",{className:"relative",children:[e.jsx(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(ke,{placeholder:"Search by title, request number, or user...",value:l,onChange:w=>o(w.target.value),className:"pl-10 text-sm sm:text-base"})]})}),n&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Xe,{className:"h-8 w-8 animate-spin text-blue-600"})}),!n&&y.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(Ie,{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&&y.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-3 sm:gap-4 mb-4 sm:mb-6",children:y.map(w=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${w.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>b(w.sharedSummaryId),children:e.jsx("div",{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[w.isRead?e.jsx(kb,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(Ct,{className:"h-4 w-4 text-blue-600 flex-shrink-0"}),e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900 truncate flex-1 min-w-0",children:w.title}),!w.isRead&&e.jsx("span",{className:"px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded-full flex-shrink-0",children:"New"})]}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 break-words",children:["Request: ",e.jsx("span",{className:"font-medium",children:w.requestNumber})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap items-start sm:items-center gap-2 sm:gap-3 md:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Vt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Initiator: ",e.jsx("span",{className:"font-medium",children:w.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Vt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared by: ",e.jsx("span",{className:"font-medium",children:w.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(dt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",et(new Date(w.sharedAt),"MMM dd, yyyy HH:mm")]})]}),w.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Ct,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",et(new Date(w.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(E,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:N=>{N.stopPropagation(),b(w.sharedSummaryId)},children:"View"})]})})},w.sharedSummaryId))}),m>1&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 sm:gap-4 bg-white rounded-lg shadow-sm border border-gray-200 p-3 sm:p-4",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-gray-600 text-center sm:text-left",children:["Showing ",(c-1)*g+1," to ",Math.min(c*g,x)," of ",x," summaries"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>j(c-1),disabled:c===1,className:"text-xs sm:text-sm",children:"Previous"}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 whitespace-nowrap",children:["Page ",c," of ",m]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>j(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function Yk(){const{sharedSummaryId:t}=_a(),s=ys(),[a,r]=h.useState(null),[n,i]=h.useState(!0);h.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,p;try{i(!0);try{await r0(t)}catch(u){console.warn("Failed to mark as viewed:",u)}const x=await Hc(t);r(x)}catch(x){console.error("Failed to fetch summary details:",x),X.error(((p=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:p.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(Le,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(St,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(st,{className:"h-4 w-4 text-orange-600"}):e.jsx(Ie,{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(Xe,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):a?e.jsx("div",{className:"min-h-screen bg-gray-50 p-4 sm:p-6",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs(E,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(ws,{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(se,{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(Es,{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:et(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:et(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(se,{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(Es,{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(Ie,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Summary Not Found"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"The summary you're looking for doesn't exist."}),e.jsx(E,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function Kk(){const{requestId:t}=_a(),s=ys(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(Jt,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(a0,{requestId:t||""})})})}function b0({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(se,{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 ta({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:l,testId:o="stats-card",onClick:c}){return e.jsx(Z,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":o,onClick:c,children:e.jsx(ee,{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 Qk({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(ta,{label:"Total",value:t.total,icon:Ie,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(ta,{label:"Pending",value:t.pending,icon:st,iconColor:"text-orange-600",gradient:"bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200",textColor:"text-orange-700",valueColor:"text-orange-900",testId:"stat-pending",onClick:s?()=>a("pending"):void 0}),e.jsx(ta,{label:"Paused",value:t.paused,icon:or,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(ta,{label:"Approved",value:t.approved,icon:Le,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(ta,{label:"Rejected",value:t.rejected,icon:St,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(ta,{label:"Draft",value:t.draft,icon:tl,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(ta,{label:"Closed",value:t.closed,icon:sl,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 Xk({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,onSearchChange:n,onStatusChange:i,onPriorityChange:l,onTemplateTypeChange:o}){return e.jsx(Z,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(ee,{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(Cs,{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(ke,{placeholder:"Search requests by title, description, or ID...",value:t,onChange:c=>n(c.target.value),className:"pl-9 text-sm sm:text-base bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"search-input"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 w-full md:w-auto",children:[e.jsxs(Be,{value:s,onValueChange:i,children:[e.jsx(ze,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"status-filter",children:e.jsx(Ve,{placeholder:"Status"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Status"}),e.jsx(Q,{value:"draft",children:"Draft"}),e.jsx(Q,{value:"pending",children:"Pending"}),e.jsx(Q,{value:"paused",children:"Paused"}),e.jsx(Q,{value:"approved",children:"Approved"}),e.jsx(Q,{value:"rejected",children:"Rejected"}),e.jsx(Q,{value:"closed",children:"Closed"})]})]}),e.jsxs(Be,{value:a,onValueChange:l,children:[e.jsx(ze,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"priority-filter",children:e.jsx(Ve,{placeholder:"Priority"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Priority"}),e.jsx(Q,{value:"express",children:"Express"}),e.jsx(Q,{value:"standard",children:"Standard"})]})]}),e.jsxs(Be,{value:r,onValueChange:o,children:[e.jsx(ze,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"template-type-filter",children:e.jsx(Ve,{placeholder:"Template Type"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]})]})]})})})}function Jk(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Sa,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:es,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:es,iconColor:"text-gray-600"}}}function Zk(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Le,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:St,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Le,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:tl,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ze,iconColor:"text-gray-600"}}}const qk=t=>{if(!t)return"";let s=t.replace(/<(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|tfoot|ul|video)[^>]*>/gi," ");return s=s.replace(/<br\s*\/?>/gi," "),s=s.replace(/<[^>]*>/g,""),s=s.replace(/\s+/g," ").trim(),s=s.replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'"),s};function e4({request:t,index:s,onViewRequest:a}){var o;const r=Zk(t.status),n=Jk(t.priority),i=r.icon,l=n.icon;return e.jsx(Ht.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(Z,{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(ee,{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(se,{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(se,{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(or,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(se,{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",p="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",p="bg-blue-100 !text-blue-700 border-blue-200"):d==="FORM_16"?(m="Form 16",p="bg-emerald-100 !text-emerald-700 border-emerald-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(se,{variant:"outline",className:`${p} 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:qk(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:"})," ",Ca(t.submittedDate)]})]})]}),e.jsx(fs,{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.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16"?e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Hs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-emerald-600 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm font-medium text-emerald-700","data-testid":"form16-ocr-flow",children:"Form 16 OCR FLOW"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm truncate","data-testid":"current-approver",children:[e.jsx("span",{className:"text-gray-500",children:"Current Approver:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.currentApprover})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm","data-testid":"approval-level",children:[e.jsx("span",{className:"text-gray-500",children:"Approval Level:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.approverLevel})]})]})]})}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-500",children:[e.jsx(st,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",Ca(t.submittedDate)]})]})]})]})})})})}function t4({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(Z,{"data-testid":"loading-state",children:e.jsx(ee,{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(Z,{"data-testid":"empty-state",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(Ie,{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(e4,{request:l,index:o,onViewRequest:i},l.id))})}function s4(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 j0(t){return Array.isArray(t)?t.map(s4):[]}function a4({itemsPerPage:t=10}={}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=h.useCallback(async(m=1,p)=>{try{m===1&&(n(!0),a([]));const x=await Ws.listMyInitiatedWorkflows({page:m,limit:t,search:p==null?void 0:p.search,status:p==null?void 0:p.status,priority:p==null?void 0:p.priority,templateType:p==null?void 0:p.templateType}),u=Array.isArray(x==null?void 0:x.data)?x.data:[],g=j0(u);a(g),l(!0);const f=x==null?void 0:x.pagination;f&&c({currentPage:f.page||1,totalPages:f.totalPages||1,totalRecords:f.total||0,itemsPerPage:t})}catch(x){console.error("[MyRequests] Error fetching requests:",x),a([]),l(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:o,fetchMyRequests:d}}const r4={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},y0=on({name:"myRequests",initialState:r4,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:n4,setStatusFilter:i4,setPriorityFilter:l4,setTemplateTypeFilter:o4,setCurrentPage:c4,clearFilters:d4}=y0.actions;function m4({onFiltersChange:t,debounceMs:s=500}={}){const a=Yn(),r=h.useRef(null),n=h.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d}=dn(j=>j.myRequests),m=h.useCallback(j=>a(n4(j)),[a]),p=h.useCallback(j=>a(i4(j)),[a]),x=h.useCallback(j=>a(l4(j)),[a]),u=h.useCallback(j=>a(o4(j)),[a]),g=h.useCallback(j=>a(c4(j)),[a]),f=h.useCallback(()=>({search:i,status:l,priority:o,templateType:c}),[i,l,o,c]);h.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const j=setTimeout(()=>{t&&t(f())},i?s:0);return r.current=j,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,t,f,s]);const b=h.useCallback(()=>{a(d4())},[a]);return{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d,setSearchTerm:m,setStatusFilter:p,setPriorityFilter:x,setTemplateTypeFilter:u,setCurrentPage:g,getFilters:f,resetFilters:b}}function u4({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=cs(),r=a4({itemsPerPage:10}),n=h.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=m4(),l=h.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}),o=h.useRef(!1);h.useEffect(()=>{const j=i.currentPage||1;n.current(j,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),o.current=!0},[]),h.useEffect(()=>{if(!o.current)return;const j=l.current;if(!(j.searchTerm!==i.searchTerm||j.statusFilter!==i.statusFilter||j.priorityFilter!==i.priorityFilter||j.templateTypeFilter!==i.templateTypeFilter))return;const w=setTimeout(()=>{i.setCurrentPage(1),n.current(1,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),l.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}},i.searchTerm!==j.searchTerm?500:0);return()=>clearTimeout(w)},[i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter]);const[c,d]=h.useState(null),[m,p]=h.useState(!1),x=h.useCallback(async()=>{if(a!=null&&a.userId)try{p(!0);const j=await _t.getRequestStats("all",void 0,void 0,void 0,i.priorityFilter!=="all"?i.priorityFilter:void 0,i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0,void 0,a.userId,void 0,void 0,i.searchTerm||void 0,void 0,!0);d({total:j.totalRequests||0,pending:j.openRequests||0,paused:j.pausedRequests||0,approved:j.approvedRequests||0,rejected:j.rejectedRequests||0,draft:j.draftRequests||0,closed:j.closedRequests||0})}catch(j){console.error("Failed to fetch backend stats:",j),d(null)}finally{p(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter,i.templateTypeFilter]);h.useEffect(()=>{const j=setTimeout(()=>{x()},i.searchTerm?500:0);return()=>clearTimeout(j)},[i.searchTerm,i.priorityFilter,i.templateTypeFilter,x]);const u=j0(s),g=r.hasFetchedFromApi?r.requests:u,f=h.useMemo(()=>c?{total:c.total||0,pending:c.pending||0,paused:c.paused||0,approved:c.approved||0,rejected:c.rejected||0,draft:c.draft||0,closed:c.closed||0}:{total:0,pending:0,paused:0,approved:0,rejected:0,draft:0,closed:0},[c]),b=h.useCallback(j=>{j>=1&&j<=r.pagination.totalPages&&(i.setCurrentPage(j),r.fetchMyRequests(j,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}))},[r,i]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"my-requests-page",children:[e.jsx(b0,{icon:Ie,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(Qk,{stats:f,onStatusFilter:j=>{i.setStatusFilter(j)}}),e.jsx(Xk,{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(t4,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(_r,{currentPage:i.currentPage||r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:b,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function v0({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(b0,{icon:Ie,title:i(),description:l(),testId:"requests-header"}),e.jsx(se,{variant:"outline",className:t?"bg-blue-50 text-blue-700 border-blue-200":"bg-green-50 text-green-700 border-green-200",children:t?"Organization":"Personal"})]}),e.jsx(E,{onClick:n,disabled:r||a,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-button",children:r?e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function N0({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(ta,{label:"Total",value:t.total,icon:Ie,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(ta,{label:"Pending",value:t.pending,icon:st,iconColor:"text-orange-600",gradient:"bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200",textColor:"text-orange-700",valueColor:"text-orange-900",testId:"stat-pending",onClick:s?()=>a("pending"):void 0}),e.jsx(ta,{label:"Paused",value:t.paused,icon:or,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(ta,{label:"Approved",value:t.approved,icon:Le,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(ta,{label:"Rejected",value:t.rejected,icon:St,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(ta,{label:"Closed",value:t.closed,icon:sl,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 x4=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Sa,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:es,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:es,iconColor:"text-gray-600"}}},wx=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Le,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected",icon:St,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending",icon:st,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"closed",icon:Le,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"draft",icon:tl,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:Ze,iconColor:"text-gray-600"}}},h4=t=>{if(!t)return"";let s=t.replace(/<(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|tfoot|ul|video)[^>]*>/gi," ");return s=s.replace(/<br\s*\/?>/gi," "),s=s.replace(/<[^>]*>/g,""),s=s.replace(/\s+/g," ").trim(),s=s.replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'"),s};function p4(t){return t==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function g4({request:t,index:s,onViewRequest:a}){var p;const r=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",n=t==null?void 0:t.form16Submission,i=n==null?void 0:n.displayStatus,l=i&&/balance mismatch|failed/i.test(String(i)),o=r&&i?{color:l?"bg-red-100 !text-red-800 border-red-200":i==="Completed"?"bg-green-100 !text-green-800 border-green-200":"bg-gray-100 !text-gray-700 border-gray-200",icon:wx(t.status).icon,label:i}:wx(t.status),c=x4(t.priority),d=o.icon,m=c.icon;return e.jsx(Ht.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(Z,{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(ee,{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(se,{variant:"outline",className:`${o.color} border font-medium text-xs shrink-0`,"data-testid":"status-badge",children:[e.jsx(d,{className:"w-3 h-3 mr-1"}),e.jsx("span",{className:"capitalize",children:o.label})]}),(((p=t.pauseInfo)==null?void 0:p.isPaused)||t.isPaused)&&e.jsxs(se,{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(or,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(se,{variant:"outline",className:`${c.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(m,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const x=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",u=(x==null?void 0:x.toUpperCase())||"";let g="Non-Templatized",f="bg-purple-100 !text-purple-600 border-purple-200";return u==="DEALER CLAIM"?(g="Dealer Claim",f="bg-blue-100 !text-blue-700 border-blue-200"):u==="FORM_16"?(g="Form 16",f="bg-emerald-100 !text-emerald-700 border-emerald-200"):u==="TEMPLATE"&&(g="Template"),e.jsx(se,{variant:"outline",className:`${f} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:g})})(),t.department&&e.jsx(se,{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:h4(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:"})," ",Ca(t.submittedDate)]}),r&&n&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"truncate","data-testid":"form16-total-amount",children:[e.jsx("span",{className:"font-medium",children:"Total amount:"})," ",n.totalAmount!=null?p4(n.totalAmount):"—"]}),e.jsxs("span",{className:"truncate","data-testid":"form16-credit-note",children:[e.jsx("span",{className:"font-medium",children:"Credit note:"})," ",n.creditNoteNumber||"—"]})]})]})]}),e.jsx(fs,{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.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16"?e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Hs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-emerald-600 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm font-medium text-emerald-700","data-testid":"form16-ocr-flow",children:"Form 16 OCR FLOW"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm truncate","data-testid":"current-approver",children:[e.jsx("span",{className:"text-gray-500",children:"Current Approver:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.currentApprover})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm","data-testid":"approval-level",children:[e.jsx("span",{className:"text-gray-500",children:"Approval Level:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.approverLevel})]})]})]})}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-500",children:[e.jsx(st,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",Ca(t.submittedDate)]})]})]})]})})})})}function w0({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(Z,{"data-testid":"loading-state",children:e.jsx(ee,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(Z,{"data-testid":"empty-state",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(Ie,{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(g4,{request:n,index:i,onViewRequest:r},n.id))})}const f4={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",requestTypeFilter:"all",form16FinancialYear:"all",form16Quarter:"all",slaComplianceFilter:"all",departmentFilter:"all",initiatorFilter:"all",approverFilter:"all",approverFilterType:"current",dateRange:"all",customStartDate:void 0,customEndDate:void 0,showCustomDatePicker:!1,currentPage:1},C0=on({name:"requests",initialState:f4,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,s.payload!=="FORM_16"&&(t.form16FinancialYear="all",t.form16Quarter="all")},setRequestTypeFilter:(t,s)=>{t.requestTypeFilter=s.payload,s.payload!=="form_16"&&(t.form16FinancialYear="all",t.form16Quarter="all")},setForm16FinancialYear:(t,s)=>{t.form16FinancialYear=s.payload},setForm16Quarter:(t,s)=>{t.form16Quarter=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.requestTypeFilter="all",t.form16FinancialYear="all",t.form16Quarter="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:b4,setStatusFilter:j4,setPriorityFilter:y4,setTemplateTypeFilter:v4,setRequestTypeFilter:N4,setForm16FinancialYear:w4,setForm16Quarter:C4,setSlaComplianceFilter:S4,setDepartmentFilter:A4,setInitiatorFilter:T4,setApproverFilter:k4,setApproverFilterType:R4,setDateRange:Cx,setCustomStartDate:Ql,setCustomEndDate:Xl,setShowCustomDatePicker:mi,setCurrentPage:D4,clearFilters:F4}=C0.actions;function S0(){const t=Yn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,requestTypeFilter:i,form16FinancialYear:l,form16Quarter:o,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:m,approverFilter:p,approverFilterType:x,dateRange:u,customStartDate:g,customEndDate:f,showCustomDatePicker:b,currentPage:j}=dn(J=>J.requests),y=h.useCallback(J=>t(b4(J)),[t]),w=h.useCallback(J=>t(j4(J)),[t]),N=h.useCallback(J=>t(y4(J)),[t]),S=h.useCallback(J=>t(v4(J)),[t]),A=h.useCallback(J=>t(N4(J)),[t]),_=h.useCallback(J=>t(w4(J)),[t]),D=h.useCallback(J=>t(C4(J)),[t]),R=h.useCallback(J=>t(S4(J)),[t]),v=h.useCallback(J=>t(A4(J)),[t]),P=h.useCallback(J=>t(T4(J)),[t]),C=h.useCallback(J=>t(k4(J)),[t]),V=h.useCallback(J=>t(R4(J)),[t]),F=h.useCallback(J=>t(Cx(J)),[t]),$=h.useCallback(J=>t(Ql(J)),[t]),I=h.useCallback(J=>t(Xl(J)),[t]),T=h.useCallback(J=>t(mi(J)),[t]),k=h.useCallback(J=>t(D4(J)),[t]),z=h.useCallback(()=>n==="FORM_16"?{templateType:"FORM_16",financialYear:l!=="all"?l:void 0,quarter:o!=="all"?o:void 0}:{search:s||void 0,status:a!=="all"?a:void 0,priority:r!=="all"?r:void 0,templateType:n!=="all"?n:void 0,slaCompliance:c!=="all"?c:void 0,department:d!=="all"?d:void 0,initiator:m!=="all"?m:void 0,approver:p!=="all"?p:void 0,approverType:p!=="all"?x:void 0,dateRange:u,startDate:g,endDate:f},[s,a,r,n,l,o,c,d,m,p,x,u,g,f]),L=h.useCallback(()=>{t(F4())},[t]),M=h.useCallback(J=>{const O=J;t(Cx(O)),O!=="custom"?(t(Ql(void 0)),t(Xl(void 0)),t(mi(!1))):t(mi(!0))},[t]),U=h.useCallback(()=>{g&&f&&(g>f&&(t(Ql(f)),t(Xl(g))),t(mi(!1)))},[g,f,t]),B=n==="FORM_16";return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,requestTypeFilter:i,form16FinancialYear:l,form16Quarter:o,isForm16:B,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:m,approverFilter:p,approverFilterType:x,dateRange:u,customStartDate:g,customEndDate:f,showCustomDatePicker:b,currentPage:j,hasActiveFilters:B?n==="FORM_16"&&(l!=="all"||o!=="all"):!!(s||a!=="all"||r!=="all"||n!=="all"||i!=="all"||i==="form_16"&&(l!=="all"||o!=="all")||c!=="all"||d!=="all"||m!=="all"||p!=="all"||u!=="all"||g||f),setSearchTerm:y,setStatusFilter:w,setPriorityFilter:N,setTemplateTypeFilter:S,setRequestTypeFilter:A,setForm16FinancialYear:_,setForm16Quarter:D,setSlaComplianceFilter:R,setDepartmentFilter:v,setInitiatorFilter:P,setApproverFilter:C,setApproverFilterType:V,setDateRange:F,setCustomStartDate:$,setCustomEndDate:I,setShowCustomDatePicker:T,setCurrentPage:k,getFilters:z,clearFilters:L,handleDateRangeChange:M,handleApplyCustomDate:U}}function Bi({filterValue:t,onFilterChange:s,source:a="default"}){const[r,n]=h.useState(""),[i,l]=h.useState([]),[o,c]=h.useState(!1),[d,m]=h.useState(null),[p,x]=h.useState(!1),u=h.useRef(null);h.useEffect(()=>{async function j(){if(t!=="all"&&!d)try{const y=await sa.getUserById(t);y&&(m(y),n(y.displayName||y.email))}catch(y){console.error("Failed to fetch user detail for search:",y)}else t==="all"&&(m(null),n(""))}j()},[t]),h.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const g=h.useCallback(j=>{if(n(j),u.current&&clearTimeout(u.current),!j||j.trim().length<2){l([]),c(!1);return}u.current=setTimeout(async()=>{var y;x(!0);try{const N=((y=(await sa.searchUsers(j.trim(),10,a)).data)==null?void 0:y.data)||[];l(N),c(N.length>0)}catch(w){console.error("Search API failed:",w),l([]),c(!1)}finally{x(!1)}},400)},[a]),f=h.useCallback(j=>{m(j),s(j.userId),n(j.displayName||j.email),c(!1),l([])},[s]),b=h.useCallback(()=>{m(null),s("all"),n(""),c(!1),l([])},[s]);return{searchQuery:r,searchResults:i,showResults:o,selectedUser:d,searching:p,handleSearch:g,handleSelect:f,handleClear:b,setShowResults:c}}function I4(t){var d,m,p,x,u,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 b=t.approvals.find(j=>{const y=(j.status||"").toString().toUpperCase();return y==="PENDING"||y==="IN_PROGRESS"});if(b)n=b.approverName||((d=b.approver)==null?void 0:d.name)||((m=b.approver)==null?void 0:m.displayName)||b.approverEmail||((p=b.approver)==null?void 0:p.email)||"—";else{const y=[...t.approvals].sort((w,N)=>{const S=w.levelNumber||w.level_number||0;return(N.levelNumber||N.level_number||0)-S})[0];y&&(n=y.approverName||((x=y.approver)==null?void 0:x.name)||((u=y.approver)==null?void 0:u.displayName)||y.approverEmail||((g=y.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 b=t.approvals.find(j=>{const y=(j.status||"").toString().toUpperCase();return y==="PENDING"||y==="IN_PROGRESS"});if(b){const j=b.levelNumber||b.level_number||0,y=c||t.approvals.length;i=`${j} of ${y}`}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,form16Submission:t.form16Submission??null}}function A0(t){return Array.isArray(t)?t.map(I4):[]}function P4(t,s,a,r,n,i){if(t.length>0){const l=t.length,o=t.filter(u=>{const g=(u.status||"").toString().toUpperCase();return g==="PENDING"||g==="IN_PROGRESS"}).length,c=t.filter(u=>(u.status||"").toString().toUpperCase()==="APPROVED").length,d=t.filter(u=>(u.status||"").toString().toUpperCase()==="REJECTED").length,m=t.filter(u=>(u.status||"").toString().toUpperCase()==="DRAFT").length,p=t.filter(u=>(u.status||"").toString().toUpperCase()==="CLOSED").length,x=t.filter(u=>(u.status||"").toString().toUpperCase()==="PAUSED").length;return{total:l,pending:o,paused:x,approved:c,rejected:d,draft:m,closed:p}}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 T0={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(zi,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(T0);var E4=T0.exports;const k0=Hi(E4);var R0={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(zi,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(R0);var _4=R0.exports;const D0=Hi(_4);as.extend(D0);as.extend(k0);function M4(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,p;return(((l=n.currentApprover)==null?void 0:l.userId)||((o=n.currentApprover)==null?void 0:o.user_id)||((d=(c=n.approvals)==null?void 0:c.find(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:d.approverId)||((p=(m=n.approvals)==null?void 0:m.find(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:p.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,p,x,u,g,f,b,j,y,w;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const N=(r.status||"").toString().toUpperCase();if(!(N==="APPROVED"||N==="REJECTED"||N==="CLOSED"))return!1;const A=((c=r.currentLevelSLA)==null?void 0:c.status)||((m=(d=r.currentApprover)==null?void 0:d.sla)==null?void 0:m.status)||((p=r.sla)==null?void 0:p.status)||((u=(x=r.summary)==null?void 0:x.sla)==null?void 0:u.status);return A?A!=="breached"&&A.toLowerCase()!=="breached":!0}const i=((g=r.currentLevelSLA)==null?void 0:g.status)||((b=(f=r.currentApprover)==null?void 0:f.sla)==null?void 0:b.status)||((j=r.sla)==null?void 0:j.status)||((w=(y=r.summary)==null?void 0:y.sla)==null?void 0:w.status);if(!i)return n==="on-track"||n==="on_track";const o={"on-track":"on_track",on_track:"on_track",approaching:"approaching",critical:"critical",breached:"breached"}[n.toLowerCase()]||n.toLowerCase();return i===o||i.toLowerCase()===o})),s.dateRange){let r=null,n=null;if(s.dateRange==="custom"&&s.startDate&&s.endDate)r=as(s.startDate).startOf("day").toDate(),n=as(s.endDate).endOf("day").toDate();else{const i=as();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 p=as(m).startOf("day").toDate(),x=as(r).startOf("day").toDate(),u=as(n).endOf("day").toDate();return p>=x&&p<=u}const o=as(l).startOf("day").toDate(),c=as(r).startOf("day").toDate(),d=as(n).endOf("day").toDate();return o>=c&&o<=d}))}return a}as.extend(k0);as.extend(D0);function L4(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return et(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function F0(t,s){const a=M4(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var y,w,N,S,A;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),p=((y=c.initiator)==null?void 0:y.displayName)||((w=c.initiator)==null?void 0:w.email)||c.initiatorName||"N/A",x=c.department||((N=c.initiator)==null?void 0:N.department)||"N/A",u=((S=c.currentApprover)==null?void 0:S.displayName)||((A=c.currentApprover)==null?void 0:A.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",f=L4(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),b=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),j=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${p.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,`"${u.replace(/"/g,'""')}"`,g,f,`"${b}"`];r.push(j.join(","))});const n=r.join(`
|
||
`),i=new Blob([n],{type:"text/csv;charset=utf-8;"}),l=document.createElement("a"),o=URL.createObjectURL(i);l.setAttribute("href",o),l.setAttribute("download",`requests-export-${new Date().toISOString().split("T")[0]}.csv`),l.style.visibility="hidden",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o)}async function O4({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?void 0:a.templateType)==="FORM_16"&&(a!=null&&a.financialYear&&(c.financialYear=a.financialYear),a!=null&&a.quarter&&(c.quarter=a.quarter)),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.approver&&a.approver!=="all"&&(c.approver=a.approver,c.approverType=a.approverType||"current"),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(n=a.startDate)==null?void 0:n.toISOString()),a!=null&&a.endDate&&(c.endDate=(i=a.endDate)==null?void 0:i.toISOString());const d=await Ws.listWorkflows({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const p=m.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:p.length,totalPages:1};return{data:p,allData:[],filteredData:p,pagination:{page:x.page,limit:x.limit||s,total:x.total||p.length,totalPages:x.totalPages||1}}}else{const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),(a==null?void 0:a.templateType)==="FORM_16"&&(a!=null&&a.financialYear&&(c.financialYear=a.financialYear),a!=null&&a.quarter&&(c.quarter=a.quarter)),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(l=a.startDate)==null?void 0:l.toISOString()),a!=null&&a.endDate&&(c.endDate=(o=a.endDate)==null?void 0:o.toISOString());const d=await Ws.listParticipantRequests({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const p=m.filter(u=>(u.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:p.length,totalPages:1};return{data:p,allData:[],filteredData:p,pagination:x}}}async function $4(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const l=t?await Ws.listWorkflows({page:r,limit:100}):await Ws.listParticipantRequests({page:r,limit:100});let o=[];if(Array.isArray(l==null?void 0:l.data)?o=l.data:Array.isArray(l)&&(o=l),o.length>0){const c=o.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");a.push(...c),r++,l!=null&&l.pagination?n=r<=l.pagination.totalPages:n=o.length===100}else n=!1}return a}function U4({onViewRequest:t}){const{user:s}=cs(),a=dn(L=>L.dashboard.viewAsUser),r=h.useMemo(()=>al(s),[s]),n=h.useMemo(()=>r&&!a,[r,a]),i=S0(),[l,o]=h.useState([]),[c,d]=h.useState(!1),[m,p]=h.useState(!1),[x,u]=h.useState(null),[g,f]=h.useState([]),[b,j]=h.useState(!1),[y,w]=h.useState(1),[N,S]=h.useState(0),[A]=h.useState(10),_=Bi({filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter,source:"local"}),D=Bi({filterValue:i.approverFilter,onFilterChange:i.setApproverFilter,source:"local"}),R=h.useCallback(async(L,M,U,B)=>{try{const W=B==null?void 0:B.slaCompliance;if(W&&W!=="all"&&W!=="breached"&&W!=="compliant"){const O={};B!=null&&B.search&&(O.search=B.search),B!=null&&B.priority&&B.priority!=="all"&&(O.priority=B.priority),B!=null&&B.department&&B.department!=="all"&&(O.department=B.department),B!=null&&B.initiator&&B.initiator!=="all"&&(O.initiator=B.initiator),B!=null&&B.approver&&B.approver!=="all"&&(O.approver=B.approver,O.approverType=B.approverType||"current"),O.slaCompliance=W,L&&(O.dateRange=L),M&&(O.startDate=M.toISOString()),U&&(O.endDate=U.toISOString());const H=n?await Ws.listWorkflows({page:1,limit:1e3,...O}):await Ws.listParticipantRequests({page:1,limit:1e3,...O}),Y=Array.isArray(H==null?void 0:H.data)?H.data:[],re=Y.length,K=Y.filter(Ge=>{const Je=(Ge.status||"").toString().toUpperCase();return Je==="PENDING"||Je==="IN_PROGRESS"}).length,ae=Y.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="APPROVED").length,Ne=Y.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="REJECTED").length,Se=Y.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="CLOSED").length;u({total:re,pending:K,paused:0,approved:ae,rejected:Ne,draft:0,closed:Se})}else{const O=await _t.getRequestStats(L,M?M.toISOString():void 0,U?U.toISOString():void 0,void 0,B==null?void 0:B.priority,B==null?void 0:B.templateType,B==null?void 0:B.department,B==null?void 0:B.initiator,B==null?void 0:B.approver,B==null?void 0:B.approverType,B==null?void 0:B.search,B==null?void 0:B.slaCompliance,!n);u({total:O.totalRequests||0,pending:O.openRequests||0,paused:O.pausedRequests||0,approved:O.approvedRequests||0,rejected:O.rejectedRequests||0,draft:O.draftRequests||0,closed:O.closedRequests||0})}}catch(W){console.error("Failed to fetch backend stats:",W)}finally{}},[n]),v=h.useCallback(async()=>{try{j(!0);const L=await _t.getDepartments();f(L)}catch{}finally{j(!1)}},[]),P=h.useRef(i),C=h.useRef(R);h.useEffect(()=>{P.current=i,C.current=R},[i,R]),h.useEffect(()=>{const L=new URLSearchParams(window.location.search),M=L.get("approver"),U=L.get("approverType"),B=L.get("slaCompliance"),W=L.get("dateRange"),J=L.get("startDate"),O=L.get("endDate");M&&i.setApproverFilter(M),(U==="current"||U==="any")&&i.setApproverFilterType(U),B&&i.setSlaComplianceFilter(B),W&&i.setDateRange(W),J&&i.setCustomStartDate(new Date(J)),O&&i.setCustomEndDate(new Date(O))},[]);const V=h.useCallback(async(L=1)=>{try{L===1&&(d(!0),o([]));const M=P.current.getFilters(),U=await O4({page:L,itemsPerPage:A,filters:M,isOrgLevel:n});o(U.data),i.setCurrentPage(U.pagination.page),w(U.pagination.totalPages),S(U.pagination.total)}catch{o([])}finally{d(!1)}},[A,n]),F=h.useCallback(async()=>{try{p(!0);const L=await $4(n);await F0(L,i.getFilters())}catch(L){console.error("Failed to export requests:",L),alert("Failed to export requests. Please try again.")}finally{p(!1)}},[n,i]);h.useEffect(()=>{v()},[v]),h.useEffect(()=>{const L=setTimeout(()=>{const M={priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0,department:i.departmentFilter!=="all"?i.departmentFilter:void 0,initiator:i.initiatorFilter!=="all"?i.initiatorFilter:void 0,approver:i.approverFilter!=="all"?i.approverFilter:void 0,approverType:i.approverFilter!=="all"?i.approverFilterType:void 0,search:i.searchTerm||void 0,slaCompliance:i.slaComplianceFilter!=="all"?i.slaComplianceFilter:void 0},U=i.dateRange||"all";C.current(U,i.customStartDate,i.customEndDate,M)},i.searchTerm?500:0);return()=>clearTimeout(L)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.templateTypeFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const $=h.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,form16FinancialYear:i.form16FinancialYear,form16Quarter:i.form16Quarter,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=h.useRef(!1);h.useEffect(()=>{const L=i.currentPage||1;V(L),I.current=!0},[]),h.useEffect(()=>{if(!I.current)return;const L=$.current;if(!(L.searchTerm!==i.searchTerm||L.statusFilter!==i.statusFilter||L.priorityFilter!==i.priorityFilter||L.templateTypeFilter!==i.templateTypeFilter||L.form16FinancialYear!==i.form16FinancialYear||L.form16Quarter!==i.form16Quarter||L.slaComplianceFilter!==i.slaComplianceFilter||L.departmentFilter!==i.departmentFilter||L.initiatorFilter!==i.initiatorFilter||L.approverFilter!==i.approverFilter||L.approverFilterType!==i.approverFilterType||L.dateRange!==i.dateRange||L.customStartDate!==i.customStartDate||L.customEndDate!==i.customEndDate||L.isOrgLevel!==n))return;const U=setTimeout(()=>{i.setCurrentPage(1),V(1),$.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,form16FinancialYear:i.form16FinancialYear,form16Quarter:i.form16Quarter,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!==L.searchTerm?500:0);return()=>clearTimeout(U)},[n,i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter,i.form16FinancialYear,i.form16Quarter,i.slaComplianceFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.dateRange,i.customStartDate,i.customEndDate]);const T=h.useCallback(L=>{L>=1&&L<=y&&(i.setCurrentPage(L),V(L))},[y,V,i]),k=h.useMemo(()=>A0(l),[l]),z=h.useMemo(()=>x?{total:x.total||0,pending:x.pending||0,paused:x.paused||0,approved:x.approved||0,rejected:x.rejected||0,draft:x.draft||0,closed:x.closed||0}:P4([],n,x,!1,N,k),[n,x,N,k]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(v0,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:F}),e.jsx(N0,{stats:z,onStatusFilter:L=>{i.setStatusFilter(L)}}),e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(ee,{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(Pa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(se,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx($t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Qt,{}),i.isForm16?e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(te,{className:"text-sm font-medium text-gray-700",children:"All Templates"}),e.jsxs(Be,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(ze,{className:"h-10 w-[180px]","data-testid":"template-type-filter",children:e.jsx(Ve,{placeholder:"All Templates"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Custom"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(Q,{value:"FORM_16",children:"Form 16"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(te,{className:"text-sm font-medium text-gray-700",children:"Financial Year"}),e.jsxs(Be,{value:i.form16FinancialYear,onValueChange:i.setForm16FinancialYear,children:[e.jsx(ze,{className:"h-10 w-[140px]","data-testid":"form16-financial-year-filter",children:e.jsx(Ve,{placeholder:"Financial Year"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Years"}),e.jsx(Q,{value:"2024-25",children:"2024-25"}),e.jsx(Q,{value:"2023-24",children:"2023-24"}),e.jsx(Q,{value:"2022-23",children:"2022-23"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(te,{className:"text-sm font-medium text-gray-700",children:"Quarter"}),e.jsxs(Be,{value:i.form16Quarter,onValueChange:i.setForm16Quarter,children:[e.jsx(ze,{className:"h-10 w-[130px]","data-testid":"form16-quarter-filter",children:e.jsx(Ve,{placeholder:"Quarter"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Quarters"}),e.jsx(Q,{value:"Q1",children:"Q1"}),e.jsx(Q,{value:"Q2",children:"Q2"}),e.jsx(Q,{value:"Q3",children:"Q3"}),e.jsx(Q,{value:"Q4",children:"Q4"})]})]})]})]}):e.jsxs(e.Fragment,{children:[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(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(ke,{placeholder:"Search requests...",value:i.searchTerm,onChange:L=>i.setSearchTerm(L.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Be,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ve,{placeholder:"All Status"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Status"}),e.jsx(Q,{value:"pending",children:"Pending"}),e.jsx(Q,{value:"paused",children:"Paused"}),e.jsx(Q,{value:"approved",children:"Approved"}),e.jsx(Q,{value:"rejected",children:"Rejected"}),e.jsx(Q,{value:"closed",children:"Closed"})]})]}),e.jsxs(Be,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ve,{placeholder:"All Priority"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Priority"}),e.jsx(Q,{value:"express",children:"Express"}),e.jsx(Q,{value:"standard",children:"Standard"})]})]}),e.jsxs(Be,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ve,{placeholder:"All Templates"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(Q,{value:"FORM_16",children:"Form 16"})]})]}),e.jsxs(Be,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:b||g.length===0,children:[e.jsx(ze,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ve,{placeholder:b?"Loading...":"All Departments"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Departments"}),g.map(L=>e.jsx(Q,{value:L,children:L},L))]})]}),e.jsxs(Be,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ve,{placeholder:"All SLA Status"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All SLA Status"}),e.jsx(Q,{value:"compliant",children:"Compliant"}),e.jsx(Q,{value:"on-track",children:"On Track"}),e.jsx(Q,{value:"approaching",children:"Approaching"}),e.jsx(Q,{value:"critical",children:"Critical"}),e.jsx(Q,{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(te,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:_.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:_.selectedUser.displayName||_.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:_.handleClear,children:e.jsx(bt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{placeholder:"Search initiator...",value:_.searchQuery,onChange:L=>_.handleSearch(L.target.value),onFocus:()=>{_.searchResults.length>0&&_.setShowResults(!0)},onBlur:()=>setTimeout(()=>_.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),_.showResults&&_.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:_.searchResults.map(L=>e.jsx("button",{type:"button",onClick:()=>_.handleSelect(L),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:L.displayName||L.email}),L.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:L.email})]})},L.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(te,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(Be,{value:i.approverFilterType,onValueChange:L=>i.setApproverFilterType(L),children:[e.jsx(ze,{className:"h-7 w-32 text-xs",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Q,{value:"current",children:"Current Only"}),e.jsx(Q,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:D.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:D.selectedUser.displayName||D.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:D.handleClear,children:e.jsx(bt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{placeholder:"Search approver...",value:D.searchQuery,onChange:L=>D.handleSearch(L.target.value),onFocus:()=>{D.searchResults.length>0&&D.setShowResults(!0)},onBlur:()=>setTimeout(()=>D.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),D.showResults&&D.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:D.searchResults.map(L=>e.jsx("button",{type:"button",onClick:()=>D.handleSelect(L),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:L.displayName||L.email}),L.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:L.email})]})},L.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(dt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(ze,{className:"w-[160px] h-10",children:e.jsx(Ve,{placeholder:"Date Range"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Time"}),e.jsx(Q,{value:"today",children:"Today"}),e.jsx(Q,{value:"week",children:"This Week"}),e.jsx(Q,{value:"month",children:"This Month"}),e.jsx(Q,{value:"last7days",children:"Last 7 Days"}),e.jsx(Q,{value:"last30days",children:"Last 30 Days"}),e.jsx(Q,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(ra,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(na,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(dt,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${et(i.customStartDate,"MMM d, yyyy")} - ${et(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Xs,{value:i.customStartDate||null,onChange:L=>{const M=L?new Date(L):void 0;M?(i.setCustomStartDate(M),i.customEndDate&&M>i.customEndDate&&i.setCustomEndDate(M)):i.setCustomStartDate(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"end-date",children:"End Date"}),e.jsx(Xs,{value:i.customEndDate||null,onChange:L=>{const M=L?new Date(L):void 0;M?(i.setCustomEndDate(M),i.customStartDate&&M<i.customStartDate&&i.setCustomStartDate(M)):i.setCustomEndDate(void 0)},minDate:i.customStartDate||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsx(E,{className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329] text-white",onClick:i.handleApplyCustomDate,disabled:!i.customStartDate||!i.customEndDate,children:"Apply Range"})]}),e.jsx("div",{className:"flex gap-2 pt-2 border-t",children:e.jsx(E,{size:"sm",variant:"outline",onClick:()=>{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})})]})})]})]})]})]})})}),e.jsx(w0,{requests:k,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(_r,{currentPage:i.currentPage||1,totalPages:y,totalRecords:N,itemsPerPage:A,onPageChange:T,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function B4({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.financialYear&&(r.financialYear=a.financialYear),a!=null&&a.quarter&&(r.quarter=a.quarter),a!=null&&a.department&&a.department!=="all"&&(r.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(r.initiator=a.initiator),a!=null&&a.approver&&a.approver!=="all"&&(r.approver=a.approver,r.approverType=a.approverType||"current"),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(r.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(r.dateRange=a.dateRange),a!=null&&a.startDate&&(r.startDate=a.startDate instanceof Date?a.startDate.toISOString():a.startDate),a!=null&&a.endDate&&(r.endDate=a.endDate instanceof Date?a.endDate.toISOString():a.endDate);const n=await Ws.listParticipantRequests({page:t,limit:s,...r});let i=[];Array.isArray(n==null?void 0:n.data)?i=n.data:Array.isArray(n)&&(i=n);const l=i.filter(c=>(c.status||"").toString().toUpperCase()!=="DRAFT"),o=(n==null?void 0:n.pagination)||{page:t,limit:s,total:l.length,totalPages:1};return{data:l,allData:[],filteredData:l,pagination:{page:o.page,limit:o.limit||s,total:o.total||l.length,totalPages:o.totalPages||1}}}const Sx=100;async function V4(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.financialYear&&(i.financialYear=t.financialYear),t!=null&&t.quarter&&(i.quarter=t.quarter),t!=null&&t.department&&t.department!=="all"&&(i.department=t.department),t!=null&&t.initiator&&t.initiator!=="all"&&(i.initiator=t.initiator),t!=null&&t.approver&&t.approver!=="all"&&(i.approver=t.approver,i.approverType=t.approverType||"current"),t!=null&&t.slaCompliance&&t.slaCompliance!=="all"&&(i.slaCompliance=t.slaCompliance),t!=null&&t.dateRange&&(i.dateRange=t.dateRange),t!=null&&t.startDate&&(i.startDate=t.startDate instanceof Date?t.startDate.toISOString():t.startDate),t!=null&&t.endDate&&(i.endDate=t.endDate instanceof Date?t.endDate.toISOString():t.endDate);a&&r<=n;){const l=await Ws.listParticipantRequests({page:r,limit:Sx,...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===Sx}}return s}function z4({onViewRequest:t}){const s=S0(),a=h.useMemo(()=>{try{const W=at.getUserData();return lc(W)}catch(W){return console.error("[UserAllRequests] Error getting user filter type:",W),"STANDARD"}},[]),r=h.useMemo(()=>uk(a),[a]),n=a==="DEALER",i=h.useCallback(()=>{const W=s.getFilters();if(!n)return W;const J=s.requestTypeFilter;if(J==="form_16")return{templateType:"FORM_16",financialYear:s.form16FinancialYear!=="all"?s.form16FinancialYear:void 0,quarter:s.form16Quarter!=="all"?s.form16Quarter:void 0};if(J==="claim_management")return{templateType:"DEALER CLAIM",search:W.search,status:W.status!=="all"?W.status:void 0,dateRange:W.dateRange,startDate:W.startDate,endDate:W.endDate,initiator:W.initiator,approver:W.approver,approverType:W.approverType};const{priority:O,templateType:H,department:Y,slaCompliance:re,...K}=W;return K},[s,n]),l=h.useCallback(()=>{if(n){const W=s.requestTypeFilter;return W==="form_16"?s.form16FinancialYear!=="all"||s.form16Quarter!=="all":W==="claim_management"?s.statusFilter!=="all"||s.dateRange!=="all"||!!s.customStartDate||!!s.customEndDate:!!(s.searchTerm||s.statusFilter!=="all"||s.initiatorFilter!=="all"||s.approverFilter!=="all"||s.dateRange!=="all"||s.customStartDate||s.customEndDate)}return s.hasActiveFilters},[n,s]),[o,c]=h.useState([]),[d,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(null),[f,b]=h.useState([]),[j,y]=h.useState(!1),[w,N]=h.useState(!1),[S,A]=h.useState(1),[_,D]=h.useState(0),[R]=h.useState(10),v=Bi({filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter,source:"local"}),P=Bi({filterValue:s.approverFilter,onFilterChange:s.setApproverFilter,source:"local"}),C=h.useCallback(async(W,J,O,H)=>{try{const Y=await _t.getRequestStats(W,J?J.toISOString():void 0,O?O.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:Y.totalRequests||0,pending:Y.openRequests||0,paused:Y.pausedRequests||0,approved:Y.approvedRequests||0,rejected:Y.rejectedRequests||0,draft:Y.draftRequests||0,closed:Y.closedRequests||0})}catch(Y){console.error("Failed to fetch backend stats:",Y)}},[]),V=h.useCallback(async()=>{try{y(!0);const W=await _t.getDepartments();b(W)}catch{}finally{y(!1)}},[]);h.useEffect(()=>{a==="STANDARD"&&Bh().then(W=>N(!!(W.canViewForm16Submission||W.canView26AS))).catch(()=>N(!1))},[a]);const F=h.useRef(s),$=h.useRef(C),I=h.useRef(i);h.useEffect(()=>{F.current=s,$.current=C,I.current=i},[s,C,i]);const T=h.useCallback(async(W=1)=>{try{W===1&&(m(!0),c([]));const J=I.current(),O=await B4({page:W,itemsPerPage:R,filters:J});c(O.data),s.setCurrentPage(O.pagination.page),A(O.pagination.totalPages),D(O.pagination.total)}catch{c([])}finally{m(!1)}},[R,s]),k=h.useCallback(async()=>{try{x(!0);const W=i(),J=await V4(W);await F0(J,W)}catch(W){console.error("Failed to export requests:",W),alert("Failed to export requests. Please try again.")}finally{x(!1)}},[i]);h.useEffect(()=>{V()},[V]),h.useEffect(()=>{const W=setTimeout(()=>{const J={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"&&(J.priority=s.priorityFilter),s.templateTypeFilter!=="all"&&(J.templateType=s.templateTypeFilter),s.departmentFilter!=="all"&&(J.department=s.departmentFilter),s.slaComplianceFilter!=="all"&&(J.slaCompliance=s.slaComplianceFilter));const O=s.dateRange==="all"?"all":s.dateRange||"month";$.current(O,s.customStartDate,s.customEndDate,J)},s.searchTerm?500:0);return()=>clearTimeout(W)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter,n]);const z=h.useRef({searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}),L=h.useRef(!1);h.useEffect(()=>{const W=s.currentPage||1;T(W),L.current=!0},[]),h.useEffect(()=>{if(!L.current)return;const W=z.current;if(!(W.searchTerm!==s.searchTerm||W.statusFilter!==s.statusFilter||W.priorityFilter!==s.priorityFilter||W.templateTypeFilter!==s.templateTypeFilter||W.slaComplianceFilter!==s.slaComplianceFilter||W.departmentFilter!==s.departmentFilter||W.initiatorFilter!==s.initiatorFilter||W.approverFilter!==s.approverFilter||W.approverFilterType!==s.approverFilterType||W.dateRange!==s.dateRange||W.customStartDate!==s.customStartDate||W.customEndDate!==s.customEndDate))return;const O=setTimeout(()=>{s.setCurrentPage(1),T(1),z.current={searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}},s.searchTerm!==W.searchTerm?500:0);return()=>clearTimeout(O)},[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 M=h.useCallback(W=>{W>=1&&W<=S&&(s.setCurrentPage(W),T(W))},[S,T,s]),U=h.useMemo(()=>A0(o),[o]),B=h.useMemo(()=>{if(u)return{total:u.total||0,pending:u.pending||0,paused:u.paused||0,approved:u.approved||0,rejected:u.rejected||0,draft:u.draft||0,closed:u.closed||0};const W=U.filter(re=>{const K=(re.status||"").toString().toLowerCase();return K==="pending"||K==="in-progress"}).length,J=U.filter(re=>(re.status||"").toString().toLowerCase()==="paused").length,O=U.filter(re=>(re.status||"").toString().toLowerCase()==="approved").length,H=U.filter(re=>(re.status||"").toString().toLowerCase()==="rejected").length,Y=U.filter(re=>(re.status||"").toString().toLowerCase()==="closed").length;return{total:_>0?_:U.length,pending:W,paused:J,approved:O,rejected:H,draft:0,closed:Y}},[u,_,U]);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(v0,{isOrgLevel:!1,isAdmin:!1,loading:d,exporting:p,onExport:k}),e.jsx(N0,{stats:B,onStatusFilter:W=>{s.setStatusFilter(W)}}),e.jsx(r,{requestTypeFilter:s.requestTypeFilter,onRequestTypeChange:W=>s.setRequestTypeFilter(W),showForm16Filter:w,form16FinancialYear:s.form16FinancialYear,form16Quarter:s.form16Quarter,onForm16FinancialYearChange:s.setForm16FinancialYear,onForm16QuarterChange:s.setForm16Quarter,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:j,initiatorSearch:v,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(w0,{requests:U,loading:d,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(_r,{currentPage:s.currentPage||1,totalPages:S,totalRecords:_,itemsPerPage:R,onPageChange:M,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function H4(){const t=ys();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(Z,{children:e.jsxs(ee,{className:"p-8 text-center",children:[e.jsx(Ze,{className:"w-12 h-12 text-yellow-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Approver ID Required"}),e.jsx("p",{className:"text-gray-600",children:"Please select an approver to view their performance details."}),e.jsxs(E,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(ws,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function W4({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(Zt,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Approver Performance Report"}),e.jsx("p",{className:"text-sm text-gray-600",children:t})]})]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx($t,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function G4({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(Z,{children:[e.jsx(oe,{className:"pb-3",children:e.jsx(me,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(ee,{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(es,{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(Zs,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(Z,{children:[e.jsx(oe,{className:"pb-3",children:e.jsx(me,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(ee,{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(Le,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(Z,{children:[e.jsx(oe,{className:"pb-3",children:e.jsx(me,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(ee,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[t.avgResponseHours.toFixed(1),"h"]}),e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(Wo,{className:"w-5 h-5 text-purple-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:t.avgResponseHours<24?`${(t.avgResponseHours/8).toFixed(1)} working days`:`${(t.avgResponseHours/24).toFixed(1)} days`})]})]}),e.jsxs(Z,{children:[e.jsx(oe,{className:"pb-3",children:e.jsx(me,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(ee,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.pendingCount}),e.jsx("div",{className:"p-2 bg-orange-100 rounded-lg",children:e.jsx(st,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function Y4({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(Z,{"data-testid":"approver-actions-stats",children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Approver's Actions"}),e.jsxs(ve,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?JN(a,r,n,""):"(all time)"]})]}),e.jsxs(ee,{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(Zt,{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(Le,{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(St,{className:"w-5 h-5 text-red-600"}),e.jsx("span",{className:"text-xs text-red-600 font-medium",children:s&&s.approvedCount+s.rejectedCount>0?`${Math.round(s.rejectedCount/(s.approvedCount+s.rejectedCount)*100)}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:(s==null?void 0:s.rejectedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Rejected by Approver"})]}),e.jsxs("div",{className:"p-4 bg-yellow-50 rounded-lg border border-yellow-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(st,{className:"w-5 h-5 text-yellow-600"})}),e.jsx("div",{className:"text-2xl font-bold text-yellow-700",children:(s==null?void 0:s.pendingCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Pending Actions"})]}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg border border-gray-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(sl,{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(Ie,{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(es,{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(Rb,{className:"w-5 h-5 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:(s==null?void 0:s.tatCompliancePercent)!==void 0?`${s.tatCompliancePercent}%`:"N/A"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:(s==null?void 0:s.withinTatCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Compliant"})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Ze,{className:"w-5 h-5 text-red-600"})}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:(s==null?void 0:s.breachedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Breached"})]}),e.jsxs("div",{className:"p-4 bg-purple-50 rounded-lg border border-purple-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(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 K4({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:l,showCustomDatePicker:o,tempCustomStartDate:c,tempCustomEndDate:d,onSearchChange:m,onStatusChange:p,onPriorityChange:x,onSlaComplianceChange:u,onDateRangeChange:g,onShowCustomDatePickerChange:f,onTempStartDateChange:b,onTempEndDateChange:j,onApplyCustomDate:y,onClearFilters:w}){return e.jsxs(Z,{"data-testid":"approver-performance-filters",children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{children:"Filters"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:w,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(ke,{placeholder:"Search requests...",value:t,onChange:N=>m(N.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(Be,{value:s,onValueChange:p,children:[e.jsx(ze,{"data-testid":"status-filter",children:e.jsx(Ve,{placeholder:"Status"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Status"}),e.jsx(Q,{value:"pending",children:"Pending"}),e.jsx(Q,{value:"approved",children:"Approved"}),e.jsx(Q,{value:"rejected",children:"Rejected"}),e.jsx(Q,{value:"closed",children:"Closed"})]})]}),e.jsxs(Be,{value:a,onValueChange:x,children:[e.jsx(ze,{"data-testid":"priority-filter",children:e.jsx(Ve,{placeholder:"Priority"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Priority"}),e.jsx(Q,{value:"express",children:"Express"}),e.jsx(Q,{value:"standard",children:"Standard"})]})]}),e.jsxs(Be,{value:r,onValueChange:u,children:[e.jsx(ze,{"data-testid":"sla-compliance-filter",children:e.jsx(Ve,{placeholder:"SLA Compliance"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All SLA"}),e.jsx(Q,{value:"compliant",children:"Compliant"}),e.jsx(Q,{value:"on-track",children:"On Track"}),e.jsx(Q,{value:"approaching",children:"Approaching"}),e.jsx(Q,{value:"critical",children:"Critical"}),e.jsx(Q,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:n,onValueChange:g,children:[e.jsx(ze,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Ve,{placeholder:"Date Range"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Time"}),e.jsx(Q,{value:"today",children:"Today"}),e.jsx(Q,{value:"week",children:"This Week"}),e.jsx(Q,{value:"month",children:"This Month"}),e.jsx(Q,{value:"last7days",children:"Last 7 Days"}),e.jsx(Q,{value:"last30days",children:"Last 30 Days"}),e.jsx(Q,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(ra,{open:o,onOpenChange:f,children:[e.jsx(na,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(dt,{className:"w-4 h-4"}),c&&d?`${et(c,"MMM d")} - ${et(d,"MMM d")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(ke,{id:"start-date",type:"date",value:c?et(c,"yyyy-MM-dd"):"",onChange:N=>{const S=N.target.value?new Date(N.target.value):void 0;S?(b(S),d&&S>d&&j(S)):b(void 0)},max:et(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(ke,{id:"end-date",type:"date",value:d?et(d,"yyyy-MM-dd"):"",onChange:N=>{const S=N.target.value?new Date(N.target.value):void 0;S?(j(S),c&&S<c&&b(S)):j(void 0)},min:c?et(c,"yyyy-MM-dd"):void 0,max:et(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{size:"sm",onClick:y,disabled:!c||!d,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-date-button",children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>{f(!1),b(i),j(l),(!i||!l)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const Q4=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Hs,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:es,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:es,iconColor:"text-gray-600"}}},X4=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Le,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:St,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:st,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Le,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ie,iconColor:"text-gray-600"}}},J4=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 Z4(t){if(!t)return"N/A";try{return et(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function q4(t){if(!t)return"N/A";try{return et(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function Vi(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=Vk(s);n(l)}function e6({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const c=ys();return e.jsxs(Z,{"data-testid":"approver-performance-request-list",children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Request Details"}),e.jsxs(ve,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(ee,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx($t,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading requests..."})]}):t.length===0?e.jsxs("div",{className:"text-center py-12 text-gray-500","data-testid":"empty-state",children:[e.jsx(Ie,{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=Q4(d.priority),p=X4(d.status),x=J4(d.slaStatus||""),u=m.icon,g=p.icon;return e.jsx(Z,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{Vi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(ee,{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(se,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(u,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(se,{className:p.color,"data-testid":"status-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${p.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(se,{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(Le,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(St,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(st,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(se,{className:x.color,"data-testid":"sla-status-badge",children:x.label})]}),e.jsx("h3",{className:"font-medium text-gray-900 mb-1 truncate","data-testid":"request-title",children:d.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-500 mt-2",children:[e.jsxs("span",{className:"flex items-center gap-1","data-testid":"initiator-info",children:[e.jsx(Vt,{className:"w-3 h-3"}),d.initiatorName,d.initiatorDepartment&&e.jsxs("span",{className:"ml-1",children:["(",d.initiatorDepartment,")"]})]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"submission-date",children:[e.jsx(st,{className:"w-3 h-3"}),"Submitted: ",Z4(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(Le,{className:"w-3 h-3"}),"Action: ",q4(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(es,{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(Wo,{className:"w-3 h-3"}),Kt(d.levelElapsedHours)," / ",Kt(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:f=>{f.stopPropagation(),Vi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(fs,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(_r,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function t6(){const[t]=fh(),[s,a]=h.useState(""),[r,n]=h.useState(t.get("status")||"all"),[i,l]=h.useState(t.get("priority")||"all"),[o,c]=h.useState(t.get("slaCompliance")||"all"),[d,m]=h.useState(t.get("dateRange")||"all"),[p,x]=h.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[u,g]=h.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[f,b]=h.useState(!1),[j,y]=h.useState(void 0),[w,N]=h.useState(void 0),S=h.useCallback(()=>{a(""),n("all"),l("all"),c("all"),m("all"),x(void 0),g(void 0),y(void 0),N(void 0),b(!1)},[]),A=h.useCallback(D=>{const R=D;m(R),R!=="custom"?(x(void 0),g(void 0),y(void 0),N(void 0),b(!1)):(y(p),N(u),b(!0))},[p,u]),_=h.useCallback(()=>{if(j&&w){if(j>w){const D=j;x(w),g(D),y(w),N(D)}else x(j),g(w);b(!1)}},[j,w]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:d,customStartDate:p,customEndDate:u,showCustomDatePicker:f,tempCustomStartDate:j,tempCustomEndDate:w,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:x,setCustomEndDate:g,setShowCustomDatePicker:b,setTempCustomStartDate:y,setTempCustomEndDate:N,clearFilters:S,handleDateRangeChange:A,handleApplyCustomDate:_}}function s6({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:l,searchTerm:o,itemsPerPage:c}){const[d,m]=h.useState([]),[p,x]=h.useState(null),[u,g]=h.useState([]),[f,b]=h.useState(!0),[j,y]=h.useState(!1),[w,N]=h.useState(1),[S,A]=h.useState(1),[_,D]=h.useState(0),R=h.useRef(!0),v=h.useCallback(async()=>{if(t)try{const F=s==="all"?void 0:s,$=await _t.getSingleApproverStats(t,F,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);x($)}catch(F){console.error("[ApproverPerformance] Failed to fetch approver stats:",F),x(null)}},[t,s,a,r,i,l]),P=h.useCallback(async(F=1)=>{if(!t){b(!1);return}try{b(!0);const $=await _t.getRequestsByApprover(t,F,c,s==="all"?void 0:s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,l!=="all"?l:void 0,o||void 0);m($.requests),D($.pagination.totalRecords),A($.pagination.totalPages),N($.pagination.currentPage),g($.requests)}catch($){console.error("Failed to fetch requests:",$)}finally{b(!1),y(!1)}},[t,s,a,r,n,i,l,o,c]);h.useEffect(()=>{R.current&&(R.current=!1,v(),P(1))},[]),h.useEffect(()=>{R.current||v()},[s,a,r,i,l]),h.useEffect(()=>{R.current||P(1)},[s,a,r,n,i,l,o]);const C=h.useCallback(()=>{y(!0),v(),P(1)},[v,P]),V=h.useCallback(F=>{P(F)},[P]);return{requests:d,approverStats:p,allFilteredRequests:u,loading:f,refreshing:j,currentPage:w,totalPages:S,totalRecords:_,handleRefresh:C,handlePageChange:V}}const Ax=10;function a6(){const[t]=fh(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=t6(),n=s6({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:Ax});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(W4,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(G4,{approverStats:n.approverStats}),n.approverStats&&e.jsx(Y4,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(K4,{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(e6,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:Ax,onPageChange:n.handlePageChange})]}):e.jsx(H4,{})}function r6(){const{user:t}=cs(),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(Z,{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(ee,{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(ls,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(nl,{src:(t==null?void 0:t.picture)||""}),e.jsx(os,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),vr(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(ps,{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:[vr(t)&&e.jsxs(se,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(ps,{className:"w-3 h-3 mr-1"}),"Administrator"]}),bn(t)&&e.jsxs(se,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(Zt,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(se,{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(Z,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(oe,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Vt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(ve,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(ee,{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(ba,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Email"}),e.jsx("p",{className:"text-base text-gray-900 break-words",children:(t==null?void 0:t.email)||"Not provided"})]})]}),(t==null?void 0:t.firstName)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Vt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"First Name"}),e.jsx("p",{className:"text-base text-gray-900",children:t.firstName})]})]}),(t==null?void 0:t.lastName)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Vt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Last Name"}),e.jsx("p",{className:"text-base text-gray-900",children:t.lastName})]})]}),(t==null?void 0:t.displayName)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Vt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Display Name"}),e.jsx("p",{className:"text-base text-gray-900",children:t.displayName})]})]}),(t==null?void 0:t.phone)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Wn,{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(Z,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(oe,{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(Tm,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(ve,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(ee,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[(t==null?void 0:t.employeeId)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Vt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Employee ID"}),e.jsx("p",{className:"text-base text-gray-900 font-medium",children:t.employeeId})]})]}),(t==null?void 0:t.department)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx($o,{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(Tm,{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(ps,{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(se,{variant:vr(t)||bn(t)?"default":"secondary",className:vr(t)?"bg-yellow-400 text-slate-900":bn(t)?"bg-blue-400 text-slate-900":"",children:vr(t)?"Administrator":bn(t)?"Management":"User"}),(vr(t)||bn(t))&&e.jsx(Le,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(oe,{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(dt,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(ve,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(ee,{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(Le,{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(se,{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 ui="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",n6="https://reflow-uat.royalenfield.com";function Jl(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 i6(){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 l6(t){if(ui.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:Jl(ui)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Jl(ui)})}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:Jl(ui)})}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(`${n6}/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 o6(){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 i6()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await l6(s)}catch(a){throw a}}function Po({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const l=h.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(Of,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:_e("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($f,{"data-slot":"slider-track",className:_e("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(Uf,{"data-slot":"slider-range",className:_e("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,c)=>e.jsx(Bf,{"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 c6({onConfigUpdate:t}){const[s,a]=h.useState([]),[r,n]=h.useState(!0),[i,l]=h.useState(null),[o,c]=h.useState(null),[d,m]=h.useState({}),[p,x]=h.useState(null);h.useEffect(()=>{u()},[]);const u=async()=>{var v,P;try{n(!0),c(null);const C=await ul();a(C)}catch(C){c(((P=(v=C.response)==null?void 0:v.data)==null?void 0:P.error)||"Failed to load configurations")}finally{n(!1)}},g=async v=>{var P,C;try{l(v.configKey),c(null);const V=d[v.configKey]??v.configValue;if(v.validationRules){const F=parseFloat(V);if(v.valueType==="NUMBER"){if(v.validationRules.min!==void 0&&F<v.validationRules.min)throw new Error(`Value must be at least ${v.validationRules.min}`);if(v.validationRules.max!==void 0&&F>v.validationRules.max)throw new Error(`Value must be at most ${v.validationRules.max}`)}}await Bs(v.configKey,V),a(F=>F.map($=>$.configKey===v.configKey?{...$,configValue:V}:$)),m(F=>{const $={...F};return delete $[v.configKey],$}),x(`${v.displayName} updated successfully`),setTimeout(()=>x(null),3e3),t&&t()}catch(V){c(V.message||((C=(P=V.response)==null?void 0:P.data)==null?void 0:C.error)||"Failed to save configuration")}finally{l(null)}},f=async v=>{var P,C;if(confirm(`Reset "${v.displayName}" to default value?`))try{l(v.configKey),c(null),await RA(v.configKey),a(V=>V.map(F=>F.configKey===v.configKey?{...F,configValue:F.defaultValue||""}:F)),m(V=>{const F={...V};return delete F[v.configKey],F}),x(`${v.displayName} reset to default`),setTimeout(()=>x(null),3e3)}catch(V){c(((C=(P=V.response)==null?void 0:P.data)==null?void 0:C.error)||"Failed to reset configuration")}finally{l(null)}},b=(v,P)=>{m(C=>({...C,[v]:P}))},j=v=>d[v.configKey]??v.configValue,y=v=>d[v.configKey]!==void 0&&d[v.configKey]!==v.configValue,w=v=>{var V,F,$,I;const P=j(v),C=i===v.configKey;if(!v.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:v.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Ze,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(v.uiComponent||v.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(ms,{checked:P==="true",onCheckedChange:L=>b(v.configKey,L?"true":"false"),disabled:C})]});case"slider":const T=parseInt(P)||0,k=((V=v.validationRules)==null?void 0:V.min)||0,z=((F=v.validationRules)==null?void 0:F.max)||100;return e.jsxs("div",{className:"space-y-3 p-3 bg-slate-50 border border-slate-200 rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-lg font-semibold text-slate-900",children:[T,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",k,"-",z]})]}),e.jsx(Po,{value:[T],min:k,max:z,step:1,onValueChange:([L])=>{L!==void 0&&b(v.configKey,L.toString())},disabled:C,className:"w-full"})]});case"number":return e.jsx(ke,{type:"number",value:P,onChange:L=>b(v.configKey,L.target.value),disabled:C,min:($=v.validationRules)==null?void 0:$.min,max:(I=v.validationRules)==null?void 0:I.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(ke,{type:"text",value:P,onChange:L=>b(v.configKey,L.target.value),disabled:C,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},N=v=>{switch(v){case"TAT_SETTINGS":return e.jsx(st,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Ie,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(_s,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Ki,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(an,{className:"w-5 h-5"});default:return e.jsx(lr,{className:"w-5 h-5"})}},S=["DASHBOARD_LAYOUT"],A=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],_=s.filter(v=>!S.includes(v.configCategory)&&!A.includes(v.configKey)),D=_.reduce((v,P)=>(v[P.configCategory]||(v[P.configCategory]=[]),v[P.configCategory].push(P),v),{});if(Object.keys(D).forEach(v=>{const P=D[v];P&&P.sort((C,V)=>C.sortOrder-V.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Xe,{className:"w-8 h-8 animate-spin text-gray-400"})});if(_.length===0)return e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{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(lr,{className:"w-10 h-10 text-slate-400"})}),e.jsx("p",{className:"text-slate-700 font-medium text-lg",children:"No configurations found"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 max-w-md mx-auto",children:"System configurations will appear here once they are initialized"})]})});const R=Object.keys(D);return e.jsxs("div",{className:"space-y-6",children:[p&&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(Le,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:p})]}),o&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:o}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(ai,{defaultValue:R[0],className:"w-full",children:[e.jsx(ri,{className:"flex flex-wrap w-full bg-slate-100/80 backdrop-blur-sm p-1 gap-1 rounded-md h-auto border border-slate-200 shadow-sm",children:R.map(v=>e.jsx(Mt,{value:v,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:v.replace(/_/g," ")})},v))}),R.map(v=>{var P,C,V;return e.jsx(Lt,{value:v,className:"space-y-4 mt-6",children:e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{className:"pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx("div",{className:"text-white",children:N(v)})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-slate-900",children:v.replace(/_/g," ")}),e.jsxs(ve,{className:"text-sm",children:[((P=D[v])==null?void 0:P.length)||0," setting",(((C=D[v])==null?void 0:C.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(ee,{className:"space-y-6",children:(V=D[v])==null?void 0:V.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(te,{className:"text-sm font-semibold text-slate-900",children:F.displayName}),y(F)&&e.jsx(se,{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(se,{variant:"outline",className:"text-xs bg-gradient-to-r from-orange-50 to-red-50 text-orange-800 border-orange-400 font-medium shadow-sm",children:"Requires Restart"})]}),F.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:F.description}),F.defaultValue&&e.jsxs("p",{className:"text-xs text-slate-500 mt-2",children:["Default: ",e.jsx("code",{className:"px-2 py-0.5 bg-slate-100 text-slate-700 rounded-sm font-mono text-xs border border-slate-200",children:F.defaultValue})]})]})}),w(F),F.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(E,{size:"sm",onClick:()=>g(F),disabled:!y(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(Xe,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"w-4 h-4"}),"Save Changes"]})}),F.defaultValue&&e.jsxs(E,{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(oh,{className:"w-4 h-4"}),"Reset to Default"]})]})]},F.configKey))})]})},v)})]})]})}function d6(){const[t,s]=h.useState([]),[a,r]=h.useState(!0),[n,i]=h.useState(new Date().getFullYear()),[l,o]=h.useState(!1),[c,d]=h.useState(null),[m,p]=h.useState(null),[x,u]=h.useState(null),[g,f]=h.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});h.useEffect(()=>{b()},[n]);const b=async()=>{var v,P;try{r(!0),p(null);const C=await IA(n);s(C)}catch(C){p(((P=(v=C.response)==null?void 0:v.data)==null?void 0:P.error)||"Failed to load holidays")}finally{r(!1)}},j=()=>{f({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),o(!0)},y=v=>{f({holidayDate:v.holidayDate,holidayName:v.holidayName,description:v.description||"",holidayType:v.holidayType,isRecurring:v.isRecurring}),d(v),o(!0)},w=()=>{if(c)return;const v=new Date;return v.setDate(v.getDate()+1),v.toISOString().split("T")[0]},N=async()=>{var v,P;try{if(p(null),!g.holidayDate||!g.holidayName){p("Holiday date and name are required");return}c?(await EA(c.holidayId,g),X.success("Holiday updated successfully")):(await PA(g),X.success("Holiday created successfully")),await b(),o(!1),setTimeout(()=>u(null),3e3)}catch(C){p(((P=(v=C.response)==null?void 0:v.data)==null?void 0:P.error)||"Failed to save holiday")}},S=async v=>{var P,C;if(confirm(`Delete "${v.holidayName}"?`))try{p(null),await _A(v.holidayId),X.success("Holiday deleted successfully"),await b()}catch(V){const F=((C=(P=V.response)==null?void 0:P.data)==null?void 0:C.error)||"Failed to delete holiday";p(F),X.error(F)}},A=v=>{switch(v){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";default:return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300"}},_=Array.from({length:5},(v,P)=>new Date().getFullYear()-1+P),D=t.reduce((v,P)=>{const C=new Date(P.holidayDate).toLocaleString("default",{month:"long"});return v[C]||(v[C]=[]),v[C].push(P),v},{}),R=Object.keys(D).sort((v,P)=>{const C=new Date(Date.parse(v+" 1, 2000")).getMonth(),V=new Date(Date.parse(P+" 1, 2000")).getMonth();return C-V});return e.jsxs("div",{className:"space-y-6",children:[x&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(Le,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:x})]}),m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:m}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>p(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsx(oe,{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(dt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(ve,{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(Be,{value:n.toString(),onValueChange:v=>i(parseInt(v)),children:[e.jsx(ze,{className:"w-24 sm:w-32 border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm",children:e.jsx(Ve,{})}),e.jsx(He,{className:"rounded-md",children:_.map(v=>e.jsx(Q,{value:v.toString(),children:v},v))})]}),e.jsxs(E,{onClick:j,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(bs,{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(Xe,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{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(dt,{className:"w-10 h-10 text-slate-400"})}),e.jsxs("p",{className:"text-slate-700 font-medium text-lg",children:["No holidays found for ",n]}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:"Add holidays to exclude them from TAT calculations"}),e.jsxs(E,{onClick:j,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(bs,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:R.map(v=>{var P,C,V;return e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{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(me,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[v," ",n]}),e.jsxs(ve,{className:"text-xs sm:text-sm",children:[((P=D[v])==null?void 0:P.length)||0," holiday",(((C=D[v])==null?void 0:C.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(dt,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(ee,{className:"space-y-3 pt-4",children:(V=D[v])==null?void 0:V.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(se,{variant:"outline",className:`${A(F.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:F.holidayType}),F.isRecurring&&e.jsx(se,{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:mp(F.holidayDate)}),F.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:F.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>y(F),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>S(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(ln,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},F.holidayId))})]},v)})}),e.jsx(jt,{open:l,onOpenChange:o,children:e.jsxs(xt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(yt,{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(dt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ht,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(Ut,{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(te,{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(ke,{id:"date",type:"date",value:g.holidayDate,onChange:v=>f({...g,holidayDate:v.target.value}),min:w(),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:c?"Select the holiday date":"Select the holiday date (minimum: tomorrow)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{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(ke,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:v=>f({...g,holidayName:v.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(te,{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(ke,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:v=>f({...g,description:v.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(te,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(Be,{value:g.holidayType,onValueChange:v=>f({...g,holidayType:v}),children:[e.jsx(ze,{id:"type",className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm",children:e.jsx(Ve,{})}),e.jsxs(He,{className:"rounded-lg",children:[e.jsx(Q,{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(Q,{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(Q,{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(Q,{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:v=>f({...g,isRecurring:v.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(te,{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(Et,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(E,{variant:"outline",onClick:()=>o(!1),className:"h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:"Cancel"}),e.jsxs(E,{onClick:N,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(dt,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function m6(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function u6(){const[t,s]=h.useState(""),[a,r]=h.useState([]),[n,i]=h.useState(!1),[l,o]=h.useState(null),[c,d]=h.useState("USER"),[m,p]=h.useState(!1),[x,u]=h.useState(null),[g,f]=h.useState([]),[b,j]=h.useState(!1),[y,w]=h.useState({admins:0,management:0,users:0}),[N,S]=h.useState("ELEVATED"),[A,_]=h.useState(1),[D,R]=h.useState(1),[v,P]=h.useState(0),C=10,V=h.useRef(null),F=h.useRef(null),$=h.useCallback(m6(async O=>{var H,Y,re;if(!O||!O.startsWith("@")||O.length<2){r([]),i(!1);return}i(!0);try{const K=O.slice(1),Ne=((H=(await sa.searchUsers(K,20)).data)==null?void 0:H.data)||[];r(Ne)}catch(K){console.error("Search failed:",K),u({type:"error",text:((re=(Y=K.response)==null?void 0:Y.data)==null?void 0:re.message)||"Failed to search users"})}finally{i(!1)}},300),[]),I=O=>{const H=O.target.value;s(H),$(H)},T=async O=>{o(O),s(O.email),r([]);const H=g.find(Y=>Y.email.toLowerCase()===O.email.toLowerCase()||Y.userId===O.userId);if(H&&H.role)d(H.role);else try{const re=(await sa.getAllUsers()).find(K=>K.email&&K.email.toLowerCase()===O.email.toLowerCase()||K.userId&&K.userId===O.userId);re&&re.role?d(re.role):d("USER")}catch(Y){console.error("Failed to check user role:",Y),d("USER")}},k=async()=>{var O,H;if(!l||!c){u({type:"error",text:"Please select a user and role"});return}p(!0),u(null);try{await sa.assignRole(l.email,c),u({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await z(),await L()}catch(Y){console.error("Role assignment failed:",Y),u({type:"error",text:((H=(O=Y.response)==null?void 0:O.data)==null?void 0:H.error)||"Failed to assign role"})}finally{p(!1)}},z=async(O=A)=>{var H,Y,re,K,ae,Ne;j(!0);try{const Se=await sa.getUsersByRole(N,O,C),Ge=((Y=(H=Se.data)==null?void 0:H.data)==null?void 0:Y.users)||[],Je=(K=(re=Se.data)==null?void 0:re.data)==null?void 0:K.pagination,Pe=(Ne=(ae=Se.data)==null?void 0:ae.data)==null?void 0:Ne.summary;f(Ge),Je&&(_(Je.currentPage),R(Je.totalPages),P(Je.totalUsers)),Pe&&w({admins:Pe.ADMIN||0,management:Pe.MANAGEMENT||0,users:Pe.USER||0})}catch(Se){console.error("Failed to fetch users:",Se)}finally{j(!1)}},L=async()=>{var O,H,Y,re,K,ae;try{const Ne=await sa.getRoleStatistics(),Se=((H=(O=Ne.data)==null?void 0:O.data)==null?void 0:H.statistics)||((Y=Ne.data)==null?void 0:Y.statistics)||[];w({admins:parseInt(((re=Se.find(Ge=>Ge.role==="ADMIN"))==null?void 0:re.count)||"0"),management:parseInt(((K=Se.find(Ge=>Ge.role==="MANAGEMENT"))==null?void 0:K.count)||"0"),users:parseInt(((ae=Se.find(Ge=>Ge.role==="USER"))==null?void 0:ae.count)||"0")})}catch(Ne){console.error("Failed to fetch statistics:",Ne)}};h.useEffect(()=>{z(1),L()},[N]);const M=O=>{S(O),_(1)},U=O=>{z(O)},B=O=>{S(O),_(1),requestAnimationFrame(()=>{const H=F.current;H&&H.scrollIntoView({behavior:"smooth",block:"start"})})};h.useEffect(()=>{const O=H=>{V.current&&!V.current.contains(H.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",O),()=>{document.removeEventListener("mousedown",O)}},[a]);const W=O=>{switch(O){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"}},J=O=>{switch(O){case"ADMIN":return e.jsx(Vr,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(Zt,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(Vt,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{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(Db,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(ee,{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(Z,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${N==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>B("ADMIN"),children:e.jsx(ee,{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:y.admins}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1 font-semibold",children:N==="ADMIN"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-xl shadow-md",children:e.jsx(Vr,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(Z,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${N==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>B("MANAGEMENT"),children:e.jsx(ee,{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:y.management}),e.jsx("p",{className:"text-xs text-blue-700 mt-1 font-semibold",children:N==="MANAGEMENT"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-blue-400 to-blue-500 rounded-xl shadow-md",children:e.jsx(Zt,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(Z,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${N==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>B("USER"),children:e.jsx(ee,{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:y.users}),e.jsx("p",{className:"text-xs text-gray-700 mt-1 font-semibold",children:N==="USER"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-gray-400 to-gray-500 rounded-xl shadow-md",children:e.jsx(Vt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(Qt,{}),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:V,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(ke,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:I,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(Xe,{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(O=>e.jsxs("button",{onClick:()=>T(O),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${O.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:O.displayName||O.email}),e.jsx("p",{className:"text-xs text-gray-600",children:O.email}),O.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[O.department,O.designation?` • ${O.designation}`:""]})]},O.userId))})]})]}),l&&e.jsx("div",{className:"border-2 border-slate-300 bg-gradient-to-br from-slate-100 to-slate-50 rounded-lg p-4 shadow-sm",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-gradient-to-br from-slate-700 to-slate-500 flex items-center justify-center text-white font-bold shadow-md",children:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-slate-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-slate-600",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[l.department,l.designation?` • ${l.designation}`:""]})]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>{o(null),s("")},className:"hover:bg-slate-200",children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Select Role"}),e.jsxs(Be,{value:c,onValueChange:O=>d(O),children:[e.jsx(ze,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Ve,{placeholder:"Select role"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(Q,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(Q,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(E,{onClick:k,disabled:!l||m,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"assign-role-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ps,{className:"w-4 h-4 mr-2"}),"Assign Role"]})}),x&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${x.type==="success"?"border-green-200 bg-green-50":"border-red-200 bg-red-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.type==="success"?e.jsx(Le,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Ze,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${x.type==="success"?"text-green-800":"text-red-800"}`,children:x.text})]})})]})]}),e.jsx(Qt,{}),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 (",v," ",N!=="ALL"&&N!=="ELEVATED"?N.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Be,{value:N,onValueChange:M,children:[e.jsx(ze,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Ve,{placeholder:"Filter by role"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",y.admins+y.management,")"]})]})}),e.jsx(Q,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",y.admins,")"]})]})}),e.jsx(Q,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",y.management,")"]})]})}),e.jsx(Q,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",y.users,")"]})]})}),e.jsx(Q,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",y.admins+y.management+y.users,")"]})]})})]})]})})]}),e.jsx("div",{className:"pt-2",children:b?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Xe,{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(Zt,{className:"w-6 h-6 text-gray-400"})}),e.jsx("p",{className:"font-medium text-gray-700",children:"No users found"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:N==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2","data-testid":"users-list",children:g.map(O=>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-${O.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 ${W(O.role)} flex items-center justify-center shadow-sm`,children:J(O.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:O.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:O.email}),O.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[O.department,O.designation?` • ${O.designation}`:""]})]})]}),e.jsx(se,{className:`${W(O.role)} shrink-0`,"data-testid":`role-badge-${O.role}`,children:O.role})]})},O.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 ",(A-1)*C+1," to ",Math.min(A*C,v)," of ",v," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>U(A-1),disabled:A===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)},(O,H)=>{let Y;return D<=5||A<=3?Y=H+1:A>=D-2?Y=D-4+H:Y=A-2+H,e.jsx(E,{variant:A===Y?"default":"outline",size:"sm",onClick:()=>U(Y),className:`w-9 h-9 p-0 ${A===Y?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${Y}-button`,children:Y},Y)})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>U(A+1),disabled:A===D,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function x6(){const[t,s]=h.useState([]),[a,r]=h.useState(!0),[n,i]=h.useState(!1),[l,o]=h.useState(null),[c,d]=h.useState(null),[m,p]=h.useState(null),[x,u]=h.useState({title:"",itemCode:"",taxationType:"",sapRefNo:"",creditPostingOn:""});h.useEffect(()=>{g()},[]);const g=async()=>{var S,A;try{r(!0),d(null);const _=await LA(!1);s(_)}catch(_){const D=((A=(S=_.response)==null?void 0:S.data)==null?void 0:A.error)||"Failed to load activity types";d(D),X.error(D)}finally{r(!1)}},f=()=>{u({title:"",itemCode:"",taxationType:"",sapRefNo:"",creditPostingOn:""}),o(null),i(!0)},b=S=>{u({title:S.title,itemCode:S.itemCode||"",taxationType:S.taxationType||"",sapRefNo:S.sapRefNo||"",creditPostingOn:S.creditPostingOn||""}),o(S),i(!0)},j=async()=>{var S,A;try{if(d(null),!x.title.trim()||!x.taxationType.trim()||!x.sapRefNo.trim()||!x.creditPostingOn.trim()){d("Title, Taxation Type, Credit Posting On, and Claim Document Type (SAP Ref) are required"),X.error("Please fill in all mandatory fields");return}const _={title:x.title.trim(),itemCode:x.itemCode.trim()||null,taxationType:x.taxationType.trim(),sapRefNo:x.sapRefNo.trim(),creditPostingOn:x.creditPostingOn.trim()};l?(await $A(l.activityTypeId,_),X.success("Activity type updated successfully")):(await OA(_),X.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>p(null),3e3)}catch(_){const D=((A=(S=_.response)==null?void 0:S.data)==null?void 0:A.error)||"Failed to save activity type";d(D),X.error(D)}},y=async S=>{var A,_;if(confirm(`Delete "${S.title}"? This will deactivate the activity type.`))try{d(null),await UA(S.activityTypeId),X.success("Activity type deleted successfully"),await g()}catch(D){const R=((_=(A=D.response)==null?void 0:A.data)==null?void 0:_.error)||"Failed to delete activity type";d(R),X.error(R)}},w=t.filter(S=>S.isActive!==!1&&S.isActive!==void 0),N=t.filter(S=>S.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(Le,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:m})]}),c&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:c}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>d(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsx(oe,{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(Ie,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Activity Types"}),e.jsx(ve,{className:"text-sm",children:"Manage dealer claim activity types"})]})]}),e.jsxs(E,{onClick:f,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm",children:[e.jsx(bs,{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(Xe,{className:"w-8 h-8 animate-spin text-gray-400"})}):w.length===0?e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{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(Ie,{className:"w-10 h-10 text-slate-400"})}),e.jsx("p",{className:"text-slate-700 font-medium text-lg",children:"No activity types found"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:"Add activity types for dealer claim management"}),e.jsxs(E,{onClick:f,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(bs,{className:"w-4 h-4"}),"Add First Activity Type"]})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{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(me,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Active Activity Types"}),e.jsxs(ve,{className:"text-xs sm:text-sm",children:[w.length," active type",w.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-green-50 rounded-md",children:e.jsx(Le,{className:"w-4 h-4 text-green-600"})})]})}),e.jsx(ee,{className:"space-y-3 pt-4",children:w.map(S=>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:S.title}),e.jsx(se,{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:[S.itemCode&&e.jsxs("span",{className:"font-medium",children:["Item Code: ",e.jsx("span",{className:"text-slate-900",children:S.itemCode})]}),S.taxationType&&e.jsxs("span",{className:"font-medium",children:["Taxation: ",e.jsx("span",{className:"text-slate-900",children:S.taxationType})]}),S.sapRefNo&&e.jsxs("span",{className:"font-medium",children:["SAP Ref: ",e.jsx("span",{className:"text-slate-900",children:S.sapRefNo})]}),S.creditPostingOn&&e.jsxs("span",{className:"font-medium",children:["Credit Posting On: ",e.jsx(se,{variant:"secondary",className:"ml-1 bg-slate-200 text-slate-800",children:S.creditPostingOn})]}),!S.itemCode&&!S.taxationType&&!S.sapRefNo&&!S.creditPostingOn&&e.jsx("span",{className:"text-slate-500 italic",children:"No additional details"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>b(S),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>y(S),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(ln,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},S.activityTypeId))})]}),N.length>0&&e.jsxs(Z,{className:"shadow-lg border-0 rounded-md border-amber-200",children:[e.jsx(oe,{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(me,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Inactive Activity Types"}),e.jsxs(ve,{className:"text-xs sm:text-sm",children:[N.length," inactive type",N.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-amber-50 rounded-md",children:e.jsx(Ze,{className:"w-4 h-4 text-amber-600"})})]})}),e.jsx(ee,{className:"space-y-3 pt-4",children:N.map(S=>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:S.title}),e.jsx(se,{variant:"outline",className:"bg-gradient-to-r from-amber-50 to-orange-50 text-amber-800 border-amber-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Inactive"})]})}),e.jsx("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>b(S),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]})})]},S.activityTypeId))})]})]}),e.jsx(jt,{open:n,onOpenChange:i,children:e.jsxs(xt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(yt,{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(Ie,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ht,{className:"text-xl font-semibold text-slate-900",children:l?"Edit Activity Type":"Add New Activity Type"}),e.jsx(Ut,{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(te,{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(ke,{id:"title",placeholder:"e.g., Riders Mania Claims, Legal Claims Reimbursement",value:x.title,onChange:S=>u({...x,title:S.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(te,{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(ke,{id:"itemCode",placeholder:"e.g., 1, 2, 3",value:x.itemCode,onChange:S=>u({...x,itemCode:S.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(te,{htmlFor:"taxationType",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Taxation Type ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs(Be,{value:x.taxationType,onValueChange:S=>u({...x,taxationType:S}),children:[e.jsx(ze,{id:"taxationType",className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm",children:e.jsx(Ve,{placeholder:"Select Taxation Type"})}),e.jsxs(He,{className:"rounded-lg",children:[e.jsx(Q,{value:"GST",className:"p-3",children:"GST"}),e.jsx(Q,{value:"Non GST",className:"p-3",children:"Non GST"})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select whether the activity is GST or Non-GST"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"sapRefNo",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Claim Document Type (SAP Ref) ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ke,{id:"sapRefNo",placeholder:"e.g., ZCNS, ZRE",value:x.sapRefNo,onChange:S=>u({...x,sapRefNo:S.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Required SAP reference number for CSV generation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"creditPostingOn",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Credit Posting On ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs(Be,{value:x.creditPostingOn,onValueChange:S=>u({...x,creditPostingOn:S}),children:[e.jsx(ze,{id:"creditPostingOn",className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm",children:e.jsx(Ve,{placeholder:"Select Credit Posting Group"})}),e.jsxs(He,{className:"rounded-lg",children:[e.jsx(Q,{value:"Vehicle",className:"p-3",children:"Vehicle"}),e.jsx(Q,{value:"Spares",className:"p-3",children:"Spares"}),e.jsx(Q,{value:"GMA",className:"p-3",children:"GMA"}),e.jsx(Q,{value:"Apparel",className:"p-3",children:"Apparel"})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Categorize for dealer validation (Vehicle, Spares, GMA, or Apparel)"})]})]}),e.jsxs(Et,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(E,{variant:"outline",onClick:()=>i(!1),className:"h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:"Cancel"}),e.jsxs(E,{onClick:j,disabled:!x.title.trim()||!x.taxationType||!x.sapRefNo.trim()||!x.creditPostingOn,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(Ie,{className:"w-4 h-4 mr-2"}),l?"Update Activity Type":"Add Activity Type"]})]})]})})]})}function oa({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:_e("w-full caption-bottom text-sm",t),...s})})}function ca({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:_e("[&_tr]:border-b",t),...s})}function da({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:_e("[&_tr:last-child]:border-0",t),...s})}function ut({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:_e("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function Ee({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:_e("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 Te({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:_e("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function h6(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function Tx({emails:t,onAdd:s,onRemove:a,placeholder:r}){const[n,i]=h.useState(""),l=()=>{const o=n.trim().toLowerCase();if(o){if(!h6(o)){X.error("Please enter a valid email address");return}if(t.includes(o)){X.error("This email is already in the list");return}s(o),i("")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{type:"email",placeholder:r??"e.g., user@royalenfield.com",value:n,onChange:o=>i(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l()),className:"flex-1"}),e.jsxs(E,{type:"button",variant:"outline",size:"sm",onClick:l,className:"shrink-0 gap-1",children:[e.jsx(bs,{className:"w-4 h-4"}),"Add"]})]}),t.length>0?e.jsx("div",{className:"rounded-md border",children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{children:[e.jsx(Ee,{children:"Email"}),e.jsx(Ee,{className:"w-[80px] text-right",children:"Actions"})]})}),e.jsx(da,{children:t.map(o=>e.jsxs(ut,{children:[e.jsx(Te,{className:"font-medium",children:o}),e.jsx(Te,{className:"text-right",children:e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>a(o),className:"text-destructive hover:text-destructive",children:e.jsx(ln,{className:"w-4 h-4"})})})]},o))})]})}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center rounded-md border border-dashed",children:"No viewers added. Add emails above or leave empty to allow all RE users with access."})]})}function kx(t,s){return{enabled:t,template:s}}const Zl=()=>({enabled:!0,templateRe:"26AS data has been added. Please review and use for matching dealer Form 16 submissions.",templateDealers:"New 26AS data has been uploaded. You can now submit your Form 16 for the relevant quarter if you haven’t already."});function p6(){const[t,s]=h.useState(!0),[a,r]=h.useState(!1),[n,i]=h.useState([]),[l,o]=h.useState([]),[c,d]=h.useState(!0),[m,p]=h.useState(7),[x,u]=h.useState(Zl()),[g,f]=h.useState(kx(!0,"Form 16 submitted successfully. Credit note: [CreditNoteRef].")),[b,j]=h.useState(kx(!0,"Form 16 submission was unsuccessful. Issue: [Issue]. Please review.")),[y,w]=h.useState(!0),[N,S]=h.useState(0),[A,_]=h.useState(24),[D,R]=h.useState("09:00"),[v,P]=h.useState("Please submit your Form 16 at your earliest. [Name], due date: [DueDate]."),[C,V]=h.useState(!0),[F,$]=h.useState(0),[I,T]=h.useState(12),[k,z]=h.useState("10:00"),[L,M]=h.useState("Reminder: Form 16 submission is pending. [Name], [Request ID]. Please review.");h.useEffect(()=>{let B=!0;return DA().then(W=>{if(B){if(i(W.submissionViewerEmails??[]),o(W.twentySixAsViewerEmails??[]),d(W.reminderEnabled??!0),p(typeof W.reminderDays=="number"?W.reminderDays:7),W.notification26AsDataAdded){const J=W.notification26AsDataAdded;u({enabled:J.enabled??!0,templateRe:J.templateRe??J.template??Zl().templateRe,templateDealers:J.templateDealers??Zl().templateDealers})}W.notificationForm16SuccessCreditNote&&f(W.notificationForm16SuccessCreditNote),W.notificationForm16Unsuccessful&&j(W.notificationForm16Unsuccessful),w(W.alertSubmitForm16Enabled??!0),S(W.alertSubmitForm16FrequencyDays??0),_(W.alertSubmitForm16FrequencyHours??24),R(W.alertSubmitForm16RunAtTime!==void 0&&W.alertSubmitForm16RunAtTime!==null?W.alertSubmitForm16RunAtTime:"09:00"),P(W.alertSubmitForm16Template??"Please submit your Form 16 at your earliest. [Name], due date: [DueDate]."),V(W.reminderNotificationEnabled??!0),$(W.reminderFrequencyDays??0),T(W.reminderFrequencyHours??12),z(W.reminderRunAtTime!==void 0&&W.reminderRunAtTime!==null?W.reminderRunAtTime:"10:00"),M(W.reminderNotificationTemplate??"Reminder: Form 16 submission is pending. [Name], [Request ID]. Please review.")}}).catch(()=>{B&&X.error("Failed to load Form 16 configuration")}).finally(()=>{B&&s(!1)}),()=>{B=!1}},[]);const U=async()=>{r(!0);try{await FA({submissionViewerEmails:n,twentySixAsViewerEmails:l,reminderEnabled:c,reminderDays:Math.max(1,Math.min(365,m))||7,notification26AsDataAdded:x,notificationForm16SuccessCreditNote:g,notificationForm16Unsuccessful:b,alertSubmitForm16Enabled:y,alertSubmitForm16FrequencyDays:Math.max(0,Math.min(365,N)),alertSubmitForm16FrequencyHours:Math.max(0,Math.min(168,A)),alertSubmitForm16RunAtTime:D??"",alertSubmitForm16Template:v,reminderNotificationEnabled:C,reminderFrequencyDays:Math.max(0,Math.min(365,F)),reminderFrequencyHours:Math.max(0,Math.min(168,I)),reminderRunAtTime:k??"",reminderNotificationTemplate:L}),X.success("Form 16 configuration saved")}catch{X.error("Failed to save Form 16 configuration")}finally{r(!1)}};return t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Xe,{className:"w-8 h-8 animate-spin text-re-green"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Form 16 Administration"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Configure Form 16 access, who can view submission data and 26AS, and notification settings."})]}),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:"Submission data viewers (RE)"}),e.jsx("p",{className:"text-2xl font-semibold",children:n.length}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Who can see Form 16 submissions"})]}),e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"26AS viewers (RE)"}),e.jsx("p",{className:"text-2xl font-semibold",children:l.length}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Who can see 26AS page"})]}),e.jsxs("div",{className:"p-4 bg-green-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Reminders to dealers"}),e.jsx("p",{className:"text-2xl font-semibold text-green-600",children:c?"On":"Off"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Pending Form 16 reminder schedule"})]}),e.jsxs("div",{className:"p-4 bg-purple-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Email / in-app notifications"}),e.jsxs("p",{className:"text-2xl font-semibold text-purple-600",children:[[x==null?void 0:x.enabled,g==null?void 0:g.enabled,b==null?void 0:b.enabled,y,C].filter(Boolean).length," ","/ 5 enabled"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"To dealers and RE as per rules below"})]})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5"}),"Submission data – who can see"]}),e.jsxs(ve,{children:["Users with these email addresses can see Form 16 submission data (and the Form 16 menu in the sidebar). Use the ",e.jsx("strong",{children:"exact login email"})," of each user (the same email they use to sign in). Leave the list empty to allow all RE users with Form 16 access."]})]}),e.jsx(ee,{children:e.jsx(Tx,{emails:n,onAdd:B=>i(W=>[...W,B].sort()),onRemove:B=>i(W=>W.filter(J=>J!==B)),placeholder:"e.g., user@royalenfield.com"})})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(Fb,{className:"w-5 h-5"}),"26AS page and button – who can see"]}),e.jsxs(ve,{children:["Users with these email addresses can see the 26AS page and 26AS menu item. Use the ",e.jsx("strong",{children:"exact login email"})," of each user. Leave empty to allow all RE users."]})]}),e.jsx(ee,{children:e.jsx(Tx,{emails:l,onAdd:B=>o(W=>[...W,B].sort()),onRemove:B=>o(W=>W.filter(J=>J!==B)),placeholder:"e.g., user@royalenfield.com"})})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"w-5 h-5"}),"Reminder schedule (for dealers)"]}),e.jsx(ve,{children:"When reminders are enabled, dealers with pending Form 16 for a quarter are reminded at this interval. Set how often (in days) the system may send them a reminder to submit Form 16."})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{htmlFor:"reminder-enabled",children:"Enable reminders to dealers"}),e.jsx(ms,{id:"reminder-enabled",checked:c,onCheckedChange:d})]}),e.jsxs("div",{className:"space-y-2 max-w-xs",children:[e.jsx(te,{htmlFor:"reminder-days",children:"Remind dealers every (days)"}),e.jsx(ke,{id:"reminder-days",type:"number",min:1,max:365,value:m,onChange:B=>p(parseInt(B.target.value,10)||7)})]})]})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Email and in-app notifications"}),e.jsx(ve,{children:"Configure who receives each notification, what triggers it, and when it is sent. Templates support placeholders such as [Name], [Request ID], [DueDate]."})]}),e.jsx(ee,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Form 16 notifications – recipient and trigger"}),e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0 space-y-3",children:[e.jsx("p",{className:"font-medium",children:"26AS data added"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Sent to:"})," RE users who can view 26AS. ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," As soon as new 26AS data is uploaded."]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Notification messages use a fixed system template and cannot be edited here."})]}),e.jsx(ms,{checked:x.enabled,onCheckedChange:B=>u(W=>({...W,enabled:B}))})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:"Form 16 success – credit note issued"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Sent to:"})," The dealer who submitted the Form 16. ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," Immediately after their submission is matched with 26AS and a credit note is generated."]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Notification message is fixed in the system configuration."})]}),e.jsx(ms,{checked:g.enabled,onCheckedChange:B=>f(W=>({...W,enabled:B}))})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:"Form 16 unsuccessful (mismatch or issue)"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Sent to:"})," The dealer who submitted. ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," When their submission fails (e.g. value mismatch with 26AS, duplicate, or validation error) so they can correct and resubmit."]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Notification message is fixed in the system configuration."})]}),e.jsx(ms,{checked:b.enabled,onCheckedChange:B=>j(W=>({...W,enabled:B}))})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:"Alert – submit Form 16 (to dealers who haven’t submitted)"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Sent to:"})," Dealers who have not yet submitted Form 16 for the current FY. ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," Daily at the time below (server timezone). All settings are API-driven from this config."]}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"alert-run-at",className:"text-sm whitespace-nowrap",children:"Run daily at (optional):"}),e.jsx(ke,{id:"alert-run-at",type:"time",value:D,onChange:B=>R(B.target.value),className:"w-28"}),D?e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>R(""),children:"Clear"}):null]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"24h, server TZ. Leave empty to disable daily run."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"alert-freq-days",className:"text-sm whitespace-nowrap",children:"Frequency (days):"}),e.jsx(ke,{id:"alert-freq-days",type:"number",min:0,max:365,value:N,onChange:B=>S(Math.max(0,parseInt(B.target.value,10)||0)),className:"w-20"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"alert-freq-hours",className:"text-sm whitespace-nowrap",children:"Hours:"}),e.jsx(ke,{id:"alert-freq-hours",type:"number",min:0,max:168,value:A,onChange:B=>_(Math.max(0,parseInt(B.target.value,10)||0)),className:"w-20"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Alert message content is fixed and managed by the system."})]})]}),e.jsx(ms,{checked:y,onCheckedChange:w})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:"Reminder – pending Form 16 (to dealers)"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Sent to:"})," Dealers who have at least one open Form 16 submission without a credit note. ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," Daily at the time below (server timezone). All settings are API-driven from this config."]}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"reminder-run-at",className:"text-sm whitespace-nowrap",children:"Run daily at (optional):"}),e.jsx(ke,{id:"reminder-run-at",type:"time",value:k,onChange:B=>z(B.target.value),className:"w-28"}),k?e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>z(""),children:"Clear"}):null]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"24h, server TZ. Leave empty to disable daily run."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"reminder-freq-days",className:"text-sm whitespace-nowrap",children:"Frequency (days):"}),e.jsx(ke,{id:"reminder-freq-days",type:"number",min:0,max:365,value:F,onChange:B=>$(Math.max(0,parseInt(B.target.value,10)||0)),className:"w-20"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"reminder-freq-hours",className:"text-sm whitespace-nowrap",children:"Hours:"}),e.jsx(ke,{id:"reminder-freq-hours",type:"number",min:0,max:168,value:I,onChange:B=>T(Math.max(0,parseInt(B.target.value,10)||0)),className:"w-20"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Reminder message content is fixed and managed by the system."})]})]}),e.jsx(ms,{checked:C,onCheckedChange:V})]})]})})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(E,{onClick:U,disabled:a,className:"bg-re-green hover:bg-re-green/90 gap-2",children:[a?e.jsx(Xe,{className:"w-4 h-4 animate-spin"}):e.jsx(Ea,{className:"w-4 h-4"}),"Save Form 16 configuration"]})})]})}function g6({open:t,onClose:s,success:a,message:r}){return e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(xt,{className:"sm:max-w-md",children:[e.jsxs(yt,{children:[e.jsxs(ht,{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(Ut,{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(Le,{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(St,{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(Et,{children:e.jsx(E,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const f6=async()=>(await je.get("/user/preferences/notifications")).data.data,b6=async t=>(await je.put("/user/preferences/notifications",t)).data.data;function j6({open:t,onClose:s}){const[a,r]=h.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=h.useState(!0),[l,o]=h.useState(null),[c,d]=h.useState(null),[m,p]=h.useState(null);h.useEffect(()=>{t&&x()},[t]);const x=async()=>{var g,f;try{i(!0),p(null);const b=await f6();r(b)}catch(b){console.error("[NotificationPreferences] Failed to load preferences:",b),p(((f=(g=b.response)==null?void 0:g.data)==null?void 0:f.message)||"Failed to load notification preferences")}finally{i(!1)}},u=async(g,f)=>{var b,j;try{o(g),p(null),d(null);const y={[g]:f},w=await b6(y);r(w),d(`${g==="emailNotificationsEnabled"?"Email":g==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${f?"enabled":"disabled"}`),setTimeout(()=>d(null),3e3)}catch(y){console.error("[NotificationPreferences] Failed to update preference:",y),p(((j=(b=y.response)==null?void 0:b.data)==null?void 0:j.message)||"Failed to update notification preference"),x()}finally{o(null)}};return e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(xt,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(yt,{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(lr,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(ht,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(Ut,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(Qt,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(Xe,{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(Le,{className:"w-4 h-4 text-green-600 shrink-0"}),e.jsx("p",{className:"text-sm text-green-800 font-medium",children:c})]}),m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-md animate-in fade-in slide-in-from-top-2",children:[e.jsx(Ze,{className:"w-4 h-4 text-red-600 shrink-0"}),e.jsx("p",{className:"text-sm text-red-800 font-medium",children:m})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(ba,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(te,{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(Xe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ms,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:g=>u("emailNotificationsEnabled",g),disabled:l==="emailNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(_s,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(te,{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(Xe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ms,{id:"push-notifications-modal",checked:a.pushNotificationsEnabled,onCheckedChange:g=>u("pushNotificationsEnabled",g),disabled:l==="pushNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(zs,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(te,{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(Xe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ms,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>u("inAppNotificationsEnabled",g),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx(Qt,{}),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 y6(){const t=ys(),{user:s}=cs(),a=vr(s),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState(),[d,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[f,b]=h.useState(!0),[j,y]=h.useState(!1),[w,N]=h.useState(!1);h.useEffect(()=>{S()},[]);const S=async()=>{try{b(!0);const _=await by();g(_.length>0)}catch(_){console.error("Failed to check subscription status:",_),g(!1)}finally{b(!1)}},A=async()=>{m(!0),n(!1);try{if(!("Notification"in window)){l(!1),c("Notifications are not supported in this browser. Please use a modern browser like Chrome, Firefox, or Edge."),n(!0),m(!1);return}let _=Notification.permission;if(_==="denied"){l(!1),c(`Notification permission was previously denied. To enable notifications:
|
||
|
||
1. Click the lock icon (🔒) or info icon (ℹ️) in your browser's address bar
|
||
2. Find "Notifications" in the permissions list
|
||
3. Change it from "Block" to "Allow"
|
||
4. Refresh this page and try again
|
||
|
||
Alternatively, you can enable notifications in your browser's site settings.`),n(!0),m(!1);return}if(_==="default"&&(_=await Notification.requestPermission(),_==="denied")){l(!1),c(`Notification permission was denied. To enable notifications:
|
||
|
||
1. Click the lock icon (🔒) or info icon (ℹ️) in your browser's address bar
|
||
2. Find "Notifications" in the permissions list
|
||
3. Change it from "Block" to "Allow"
|
||
4. Refresh this page and try again`),n(!0),m(!1);return}if(_!=="granted"){l(!1),c("Notification permission is required to enable push notifications. Please grant permission and try again."),n(!0),m(!1);return}await o6(),l(!0),c("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),n(!0),await S()}catch(_){console.error("[Settings] Error enabling notifications:",_),l(!1);const D=(_==null?void 0:_.message)||"Unknown error occurred";c(D.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":D.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":D.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${D}`),n(!0)}finally{m(!1)}};return e.jsxs("div",{className:"min-h-screen pb-8",children:[e.jsxs("div",{className:"max-w-7xl mx-auto space-y-6",children:[e.jsxs(Z,{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(ee,{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(lr,{className:"w-7 h-7 sm:w-8 sm:h-8 text-slate-900"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl lg:text-4xl font-bold text-white mb-1 sm:mb-2",children:"Settings"}),e.jsx("p",{className:"text-sm sm:text-base lg:text-lg text-gray-300",children:"Manage your account and preferences"})]})]})})]}),a?e.jsxs(ai,{defaultValue:"user",className:"w-full",children:[e.jsxs(ri,{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(Mt,{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(lr,{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(Mt,{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(ps,{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(Mt,{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(hh,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(Mt,{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(dt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Holidays"}),e.jsx("span",{className:"sm:hidden",children:"Holidays"})]}),e.jsxs(Mt,{value:"templates",className:"flex items-center justify-center gap-2 py-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-md transition-all",children:[e.jsx(Ie,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Templates"}),e.jsx("span",{className:"sm:hidden",children:"Templates"})]})]}),e.jsxs("div",{className:"w-full min-h-[600px]",children:[e.jsx(Lt,{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(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(oe,{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(_s,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-4",children:[f?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):u?e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-md",children:e.jsx("p",{className:"text-xs text-green-800 font-medium",children:"✓ This browser is already registered for push notifications."})}):e.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-md",children:e.jsx("p",{className:"text-xs text-blue-800",children:"Click below to register this browser for receiving push notifications. This needs to be done once per browser/device."})}),e.jsxs(E,{onClick:A,disabled:d||u,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(_s,{className:`w-4 h-4 mr-2 ${d?"animate-pulse":""}`}),d?"Registering...":u?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(oe,{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(rr,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:[e.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"Manage your password, API tokens, and other security preferences."}),e.jsxs(E,{onClick:()=>t("/settings/security"),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(rr,{className:"w-4 h-4 mr-2"}),"Manage Security"]})]})})})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(oe,{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(km,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(ee,{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(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(oe,{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(ps,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(ee,{children:e.jsxs(E,{onClick:()=>x(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(ps,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(Lt,{value:"roles",className:"mt-0",children:e.jsx(u6,{})}),e.jsx(Lt,{value:"system",className:"mt-0",children:e.jsx(c6,{})}),e.jsx(Lt,{value:"holidays",className:"mt-0",children:e.jsx(d6,{})}),e.jsx(Lt,{value:"templates",className:"mt-0",children:w?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsx(oe,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(E,{variant:"ghost",size:"sm",onClick:()=>N(!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-emerald-600 to-emerald-700 rounded-md shadow-md",children:e.jsx(Ie,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Form 16 Administration"}),e.jsx(ve,{className:"text-sm",children:"Configure Form 16 access, who can view submission data and 26AS, and notification settings"})]})]})})})}),e.jsx(p6,{})]}):j?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsx(oe,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(E,{variant:"ghost",size:"sm",onClick:()=>y(!1),className:"gap-2 hover:bg-slate-100",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]}),e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Ie,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Dealer Claim Activity Settings"}),e.jsx(ve,{className:"text-sm",children:"Manage activity types for dealer claim workflows"})]})]})})})}),e.jsx(x6,{})]}):e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{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(Ie,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Template Settings"}),e.jsx(ve,{className:"text-sm",children:"Manage templates and activity types for workflows"})]})]})}),e.jsx(ee,{className:"pt-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Z,{className:"shadow-md hover:shadow-lg transition-all duration-300 border border-slate-200 rounded-lg cursor-pointer group",onClick:()=>y(!0),children:e.jsx(ee,{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(Ie,{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(Z,{className:"shadow-md hover:shadow-lg transition-all duration-300 border border-slate-200 rounded-lg cursor-pointer group",onClick:()=>N(!0),children:e.jsx(ee,{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-emerald-500 to-emerald-600 rounded-lg shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Ie,{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-emerald-600 transition-colors",children:"Form 16"}),e.jsx("p",{className:"text-sm text-slate-600 mt-1",children:"Configure Form 16 access, 26AS viewers, and notification settings"})]})]}),e.jsx("div",{className:"text-slate-400 group-hover:text-emerald-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(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(oe,{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(_s,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-4",children:[f?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):u?e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-md",children:e.jsx("p",{className:"text-xs text-green-800 font-medium",children:"✓ This browser is already registered for push notifications."})}):e.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-md",children:e.jsx("p",{className:"text-xs text-blue-800",children:"Click below to register this browser for receiving push notifications. This needs to be done once per browser/device."})}),e.jsxs(E,{onClick:A,disabled:d||u,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(_s,{className:`w-4 h-4 mr-2 ${d?"animate-pulse":""}`}),d?"Registering...":u?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(oe,{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(rr,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:[e.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"Manage your password, API tokens, and other security preferences."}),e.jsxs(E,{onClick:()=>t("/settings/security"),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(rr,{className:"w-4 h-4 mr-2"}),"Manage Security"]})]})})})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(oe,{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(km,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(ee,{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(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(oe,{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(ps,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(ee,{children:e.jsxs(E,{onClick:()=>x(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(ps,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(g6,{open:r,onClose:()=>n(!1),success:i,message:o}),e.jsx(j6,{open:p,onClose:()=>x(!1)})]})}const v6=Xo("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function N6({className:t,variant:s,...a}){return e.jsx("div",{"data-slot":"alert",role:"alert",className:_e(v6({variant:s}),t),...a})}function w6({className:t,...s}){return e.jsx("div",{"data-slot":"alert-title",className:_e("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",t),...s})}function C6({className:t,...s}){return e.jsx("div",{"data-slot":"alert-description",className:_e("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",t),...s})}function S6(){const[t,s]=h.useState([]),[a,r]=h.useState(!0),[n,i]=h.useState(!1),[l,o]=h.useState(""),[c,d]=h.useState(""),[m,p]=h.useState(null),[x,u]=h.useState(!1),[g,f]=h.useState(!1),[b,j]=h.useState(null);h.useEffect(()=>{y()},[]);const y=async()=>{try{r(!0);const D=await je.get("/api-tokens");s(D.data.data.tokens)}catch(D){console.error("Failed to fetch API tokens:",D),X.error("Failed to load API tokens")}finally{r(!1)}},w=async()=>{if(l.trim())try{u(!0);const D={name:l};c&&(D.expiresInDays=Number(c));const R=await je.post("/api-tokens",D);p(R.data.data.token),X.success("API Token created successfully"),y()}catch(D){console.error("Failed to create token:",D),X.error("Failed to create API token")}finally{u(!1)}},N=D=>{j(D)},S=async()=>{if(b)try{await je.delete(`/api-tokens/${b.id}`),X.success("Token revoked successfully"),s(t.filter(D=>D.id!==b.id)),j(null)}catch(D){console.error("Failed to revoke token:",D),X.error("Failed to revoke token")}},A=()=>{m&&(navigator.clipboard.writeText(m),f(!0),setTimeout(()=>f(!1),2e3),X.success("Token copied to clipboard"))},_=()=>{i(!1),o(""),d(""),p(null)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium text-gray-900",children:"API Tokens"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Manage personal access tokens for external integrations"})]}),e.jsxs(E,{onClick:()=>i(!0),size:"sm",className:"bg-re-green hover:bg-re-green/90 text-white",children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Generate"]})]}),a?e.jsx("div",{className:"text-center py-4 text-gray-500",children:"Loading tokens..."}):t.length===0?e.jsxs("div",{className:"text-center py-8 bg-gray-50 rounded-lg border border-dashed border-gray-300",children:[e.jsx(ph,{className:"w-10 h-10 text-gray-300 mx-auto mb-2"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"No API tokens found"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"Generate a token to access the API programmatically"})]}):e.jsx("div",{className:"rounded-md border",children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{children:[e.jsx(Ee,{children:"Name"}),e.jsx(Ee,{children:"Prefix"}),e.jsx(Ee,{children:"Last Used"}),e.jsx(Ee,{children:"Expires"}),e.jsx(Ee,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:t.map(D=>e.jsxs(ut,{children:[e.jsx(Te,{className:"font-medium",children:D.name}),e.jsxs(Te,{className:"font-mono text-xs bg-slate-100 rounded px-2 py-1 w-fit",children:[D.prefix,"..."]}),e.jsx(Te,{className:"text-gray-500 text-sm",children:D.lastUsedAt?et(new Date(D.lastUsedAt),"MMM d, yyyy"):"Never"}),e.jsx(Te,{className:"text-gray-500 text-sm",children:D.expiresAt?et(new Date(D.expiresAt),"MMM d, yyyy"):"No Expiry"}),e.jsx(Te,{className:"text-right",children:e.jsxs(E,{variant:"ghost",size:"sm",onClick:()=>N(D),className:"text-red-600 hover:text-red-700 hover:bg-red-50",children:[e.jsx(ln,{className:"w-4 h-4"}),e.jsx("span",{className:"sr-only",children:"Revoke"})]})})]},D.id))})]})}),e.jsx(jt,{open:n,onOpenChange:D=>!D&&_(),children:e.jsxs(xt,{className:"sm:max-w-md",children:[e.jsxs(yt,{children:[e.jsx(ht,{children:"Generate API Token"}),e.jsx(Ut,{children:"Create a new token to access the API. Treat this token like a password."})]}),m?e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs(N6,{className:"bg-green-50 border-green-200",children:[e.jsx(za,{className:"h-4 w-4 text-green-600"}),e.jsx(w6,{className:"text-green-800",children:"Token Generated Successfully"}),e.jsx(C6,{className:"text-green-700",children:"Please copy your token now. You won't be able to see it again!"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"p-4 bg-slate-900 rounded-md font-mono text-sm text-green-400 break-all pr-10",children:m}),e.jsx(E,{size:"icon",variant:"ghost",className:"absolute top-1 right-1 text-gray-400 hover:text-white hover:bg-slate-800",onClick:A,children:g?e.jsx(za,{className:"w-4 h-4 text-green-500"}):e.jsx(Ib,{className:"w-4 h-4"})})]})]}):e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"token-name",children:"Token Name"}),e.jsx(ke,{id:"token-name",placeholder:"e.g., CI/CD Pipeline, Prometheus",value:l,onChange:D=>o(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"token-expiry",children:"Expiration (Days)"}),e.jsx(ke,{id:"token-expiry",type:"number",min:"1",placeholder:"Leave empty for no expiry",value:c,onChange:D=>{const R=D.target.value;if(R==="")d("");else{const v=parseInt(R);!isNaN(v)&&v>=1&&d(v)}}})]})]}),e.jsx(Et,{children:m?e.jsx(E,{onClick:_,children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",onClick:_,children:"Cancel"}),e.jsx(E,{onClick:w,disabled:!l.trim()||x,children:x?"Generating...":"Generate Token"})]})})]})}),e.jsx(Fh,{open:!!b,onOpenChange:D=>!D&&j(null),children:e.jsxs(Zo,{children:[e.jsxs(Ph,{children:[e.jsx(_h,{children:"Revoke API Token"}),e.jsxs(Mh,{children:["Are you sure you want to revoke the token ",e.jsx("strong",{children:b==null?void 0:b.name}),"? This action cannot be undone and any applications using this token will lose access immediately."]})]}),e.jsxs(Eh,{children:[e.jsx(Oh,{children:"Cancel"}),e.jsx(Lh,{onClick:S,className:"bg-red-600 hover:bg-red-700 text-white",children:"Revoke Token"})]})]})})]})}function A6(){const t=ys();return e.jsxs("div",{className:"max-w-7xl mx-auto space-y-6 pb-8",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>t("/settings"),children:e.jsx(ws,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Security Settings"}),e.jsx("p",{className:"text-gray-500",children:"Manage your account security and access tokens"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[e.jsxs(Z,{className:"shadow-md",children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-md",children:e.jsx(rr,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(me,{children:"Password"}),e.jsx(ve,{children:"Manage your sign-in password"})]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"p-4 bg-gray-50 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Your password is managed through your organization's Single Sign-On (SSO) provider. Please contact your IT administrator to reset or change your password."})})})]}),e.jsxs(Z,{className:"shadow-md",children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-purple-100 rounded-md",children:e.jsx(ph,{className:"w-5 h-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(me,{children:"API Tokens"}),e.jsx(ve,{children:"Manage personal access tokens for external integrations"})]})]})}),e.jsx(ee,{children:e.jsx(S6,{})})]})]})]})}function T6({onNavigate:t}){const[s,a]=h.useState([]),[r,n]=h.useState(!0),[i,l]=h.useState(1),[o,c]=h.useState(1),[d,m]=h.useState(0),[p,x]=h.useState("all"),[u,g]=h.useState(!1),f=20,b=async(R=i,v=p==="unread")=>{var P,C;try{n(R===1);const V=await nr.list({page:R,limit:f,unreadOnly:v}),F=((P=V.data)==null?void 0:P.notifications)||[],$=((C=V.data)==null?void 0:C.pagination)||{},I=$.total||0,T=$.totalPages||1;a(F),m(I),c(T),l(R)}catch(V){console.error("[Notifications] Failed to fetch:",V)}finally{n(!1),g(!1)}};h.useEffect(()=>{l(1),b(1,p==="unread")},[p]);const j=async R=>{var v;try{if(R.isRead||(await nr.markAsRead(R.notificationId),a(P=>P.map(C=>C.notificationId===R.notificationId?{...C,isRead:!0}:C))),R.actionUrl&&t){const P=(v=R.metadata)==null?void 0:v.requestNumber;if(P){let C=`request/${P}`;(R.notificationType==="mention"||R.notificationType==="comment"||R.notificationType==="worknote")&&(C+="?tab=worknotes"),R.notificationType==="document_added"&&(C+="?tab=documents"),t(C)}}}catch(P){console.error("[Notifications] Error handling notification click:",P)}},y=async()=>{try{g(!0),await nr.markAllAsRead(),await b(i,p==="unread")}catch(R){console.error("[Notifications] Error marking all as read:",R),g(!1)}},w=async R=>{try{await nr.delete(R),a(v=>v.filter(P=>P.notificationId!==R)),m(v=>v-1)}catch(v){console.error("[Notifications] Error deleting notification:",v)}},N=()=>{g(!0),b(i,p==="unread")},S=R=>{R<1||R>o||(l(R),b(R,p==="unread"))},A=R=>{const v="w-6 h-6";switch(R){case"mention":case"comment":return e.jsx(zs,{className:`${v} text-blue-600`});case"worknote":return e.jsx(Ie,{className:`${v} text-purple-600`});case"document_added":return e.jsx(Ie,{className:`${v} text-teal-600`});case"assignment":return e.jsx(Xi,{className:`${v} text-indigo-600`});case"approval":return e.jsx(Le,{className:`${v} text-green-600`});case"rejection":return e.jsx(St,{className:`${v} text-red-600`});case"tat_alert":return e.jsx(st,{className:`${v} text-orange-600`});case"tat_breach":return e.jsx(Ze,{className:`${v} text-red-600`});case"tat_breach_initiator":return e.jsx(ts,{className:`${v} text-amber-600`});default:return e.jsx(_s,{className:`${v} text-gray-600`})}},_=R=>{switch(R==null?void 0:R.toUpperCase()){case"URGENT":return"bg-red-100 text-red-800 border-red-200";case"HIGH":return"bg-orange-100 text-orange-800 border-orange-200";case"MEDIUM":return"bg-blue-100 text-blue-800 border-blue-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},D=s.filter(R=>!R.isRead).length;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-3xl font-bold text-gray-900 flex items-center gap-3",children:[e.jsx(_s,{className:"w-8 h-8 text-blue-600"}),"Notifications"]}),e.jsxs("p",{className:"text-gray-600 mt-1",children:[d," total notification",d!==1?"s":"",D>0&&` • ${D} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:N,disabled:u,className:"gap-2",children:[e.jsx($t,{className:`w-4 h-4 ${u?"animate-spin":""}`}),"Refresh"]}),D>0&&e.jsxs(E,{variant:"outline",size:"sm",onClick:y,disabled:u,className:"gap-2",children:[e.jsx(Pb,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{variant:p==="all"?"default":"outline",size:"sm",onClick:()=>{x("all"),l(1)},children:"All Notifications"}),e.jsxs(E,{variant:p==="unread"?"default":"outline",size:"sm",onClick:()=>{x("unread"),l(1)},children:["Unread",D>0&&e.jsx(se,{className:"ml-2 bg-red-500 text-white",children:D})]})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Recent Activity"}),e.jsx(ve,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(ee,{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(_s,{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:p==="unread"?"You're all caught up! No unread notifications.":"You don't have any notifications yet."})]}):e.jsx("div",{className:"space-y-2",children:s.map(R=>{var v;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${R.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>j(R),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:A(R.notificationType)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("h4",{className:`text-sm ${R.isRead?"font-semibold":"font-bold"} text-gray-900`,children:R.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[R.priority&&R.priority!=="LOW"&&e.jsx(se,{variant:"outline",className:`text-xs ${_(R.priority)}`,children:R.priority}),!R.isRead&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-600"})]})]}),e.jsx("p",{className:"text-sm text-gray-700 mb-2 line-clamp-2",children:R.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[Xx(new Date(R.createdAt),{addSuffix:!0}),((v=R.metadata)==null?void 0:v.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",R.metadata.requestNumber]})]}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:P=>{P.stopPropagation(),w(R.notificationId)},children:e.jsx(ln,{className:"w-3.5 h-3.5"})})]})]})]})},R.notificationId)})})})]}),!r&&o>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing ",(i-1)*f+1," to ",Math.min(i*f,d)," of ",d," notifications"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>S(i-1),disabled:i===1,children:[e.jsx(Uo,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,o)},(R,v)=>{let P;return o<=5||i<=3?P=v+1:i>=o-2?P=o-4+v:P=i-2+v,e.jsx(E,{variant:i===P?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>S(P),children:P},P)})}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>S(i+1),disabled:i===o,children:["Next",e.jsx(nn,{className:"w-4 h-4"})]})]})]})]})}function k6({onBack:t}){return e.jsx("div",{className:"flex items-center justify-between","data-testid":"detailed-reports-header",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(E,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(ws,{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(Ie,{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 Gc({dateRange:t,customStartDate:s,customEndDate:a,showCustomDatePicker:r,tempCustomStartDate:n,tempCustomEndDate:i,onDateRangeChange:l,onShowCustomDatePickerChange:o,onStartDateChange:c,onEndDateChange:d,onApply:m,onCancel:p,testIdPrefix:x="date-filter"}){const u=s&&a?`${et(s,"d MMM yyyy")} - ${et(a,"d MMM yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${x}-container`,children:[e.jsx(dt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:t,onValueChange:l,"data-testid":`${x}-select`,children:[e.jsx(ze,{className:"w-[160px]",children:e.jsx(Ve,{placeholder:"Date Range"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"today",children:"Today"}),e.jsx(Q,{value:"week",children:"This Week"}),e.jsx(Q,{value:"month",children:"This Month"}),e.jsx(Q,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(ra,{open:r,onOpenChange:o,children:[e.jsx(na,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${x}-custom-trigger`,children:[e.jsx(dt,{className:"w-4 h-4"}),u]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:`${x}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(Xs,{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:`${x}-start-date`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:`${x}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(Xs,{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:`${x}-end-date`})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{size:"sm",onClick:m,disabled:!n||!i,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":`${x}-apply-button`,children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:p,"data-testid":`${x}-cancel-button`,children:"Cancel"})]})]})})]})]})}function R6(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 I0(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 P0(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 D6(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function F6({lifecycleRequests:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,exporting:p,onDateRangeChange:x,onShowCustomDatePickerChange:u,onStartDateChange:g,onEndDateChange:f,onApplyCustomDate:b,onCancelCustomDate:j,onPageChange:y,onExport:w,onViewRequest:N}){return e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(oe,{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(Ot,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(ve,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",onClick:w,disabled:p,"data-testid":"export-lifecycle-button",children:[e.jsx(kt,{className:"w-4 h-4"}),p?"Exporting...":"Download CSV"]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(Gc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:x,onShowCustomDatePickerChange:u,onStartDateChange:g,onEndDateChange:f,onApply:b,onCancel:j,testIdPrefix:"lifecycle"})})]}),e.jsxs(ee,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(Xe,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading lifecycle data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"lifecycle-error",children:[e.jsx(Ze,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"lifecycle-empty",children:e.jsx("p",{className:"text-sm",children:"No lifecycle data available"})}):e.jsx("div",{className:"space-y-4",children:t.map(S=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${S.id}`,children:e.jsx("div",{className:"p-4 bg-gradient-to-r from-gray-50 to-white hover:bg-gray-100 cursor-pointer transition-all",onClick:()=>N(S.requestId||S.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:A=>{A.stopPropagation(),N(S.requestId||S.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${S.id}`,children:S.id}),e.jsx(se,{className:I0(S.priority),"data-testid":`lifecycle-priority-${S.id}`,children:S.priority}),e.jsx(se,{className:P0(S.status),"data-testid":`lifecycle-status-${S.id}`,children:S.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:S.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:S.initiator})," on ",S.initDate]}),S.currentStage&&!S.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",S.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:S.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",S.currentLevel,"/",S.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:S.overallTAT}),S.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[S.breachCount," breach",S.breachCount>1?"es":""]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>N(S.requestId||S.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${S.id}`,children:e.jsx(nn,{className:"w-4 h-4"})})]})]})})},S.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(Xe,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>y(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>y(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function I6({activityLog:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,filterCategory:p,filterSeverity:x,exporting:u,onDateRangeChange:g,onShowCustomDatePickerChange:f,onStartDateChange:b,onEndDateChange:j,onApplyCustomDate:y,onCancelCustomDate:w,onCategoryChange:N,onSeverityChange:S,onClearFilters:A,onPageChange:_,onExport:D,onViewRequest:R}){const v=p!=="all"||x!=="all"||i!=="month"||l||o;return e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(oe,{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(xh,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(ve,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",onClick:D,disabled:u,"data-testid":"export-activity-button",children:[e.jsx(kt,{className:"w-4 h-4"}),u?"Exporting...":"Download CSV"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(Gc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:g,onShowCustomDatePickerChange:f,onStartDateChange:b,onEndDateChange:j,onApply:y,onCancel:w,testIdPrefix:"activity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Category:"}),e.jsxs(Be,{value:p,onValueChange:N,"data-testid":"activity-category-filter",children:[e.jsx(ze,{className:"w-40",children:e.jsx(Ve,{placeholder:"All Categories"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Categories"}),e.jsx(Q,{value:"WORKFLOW",children:"Workflow"}),e.jsx(Q,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(Q,{value:"DOCUMENT",children:"Document"}),e.jsx(Q,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(Q,{value:"SYSTEM",children:"System"}),e.jsx(Q,{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(Be,{value:x,onValueChange:S,"data-testid":"activity-severity-filter",children:[e.jsx(ze,{className:"w-40",children:e.jsx(Ve,{placeholder:"All Severities"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Severities"}),e.jsx(Q,{value:"INFO",children:"Info"}),e.jsx(Q,{value:"WARNING",children:"Warning"}),e.jsx(Q,{value:"ERROR",children:"Error"}),e.jsx(Q,{value:"CRITICAL",children:"Critical"})]})]})]}),v&&e.jsx(E,{variant:"ghost",size:"sm",onClick:A,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(ee,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(Xe,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading activity data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"activity-error",children:[e.jsx(Ze,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"activity-empty",children:e.jsx("p",{className:"text-sm",children:"No activity data available"})}):e.jsxs("div",{className:"rounded-lg border",children:[e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{className:"bg-gray-50",children:[e.jsx(Ee,{className:"font-semibold",children:"Timestamp"}),e.jsx(Ee,{className:"font-semibold",children:"User"}),e.jsx(Ee,{className:"font-semibold",children:"Action"}),e.jsx(Ee,{className:"font-semibold",children:"Details"}),e.jsx(Ee,{className:"font-semibold",children:"IP Address"}),e.jsx(Ee,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(da,{children:t.map((P,C)=>e.jsxs(ut,{className:"hover:bg-gray-50","data-testid":`activity-row-${C}`,children:[e.jsx(Te,{className:"text-xs font-medium",children:P.timestamp}),e.jsx(Te,{className:"text-sm",children:P.user}),e.jsx(Te,{children:e.jsx(se,{className:R6(P.action),"data-testid":`activity-action-${C}`,children:P.action})}),e.jsx(Te,{className:"text-sm text-gray-600",children:P.details}),e.jsx(Te,{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(Te,{children:P.requestId!=="-"&&P.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const V=P.requestId;V&&R(V)},className:"hover:underline","data-testid":`activity-request-link-${C}`,children:e.jsx(se,{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:"-"})})]},C))})]}),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(Xe,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>_(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>_(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function P6({agingWorkflows:t,loading:s,loadingPage:a,error:r,pagination:n,threshold:i,thresholdError:l,dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:p,tempCustomEndDate:x,searchQuery:u,exporting:g,onThresholdChange:f,onThresholdBlur:b,onDateRangeChange:j,onShowCustomDatePickerChange:y,onStartDateChange:w,onEndDateChange:N,onApplyCustomDate:S,onCancelCustomDate:A,onSearchChange:_,onPageChange:D,onExport:R,onViewRequest:v}){return e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(oe,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-amber-100 rounded-lg",children:e.jsx(Wo,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(ve,{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(ke,{type:"number",min:"1",value:i,onChange:P=>f(P.target.value),onBlur:b,className:`w-24 ${l?"border-red-500 focus:border-red-500 focus:ring-red-500":""}`,placeholder:"Days","data-testid":"aging-threshold-input"}),e.jsx("span",{className:"text-sm text-gray-600 whitespace-nowrap",children:"days"})]}),l&&e.jsx("span",{className:"text-xs text-red-600",children:l})]})]}),e.jsxs(se,{variant:"outline",className:"font-semibold","data-testid":"aging-total-badge",children:[n.totalRecords," workflows"]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",onClick:R,disabled:g,"data-testid":"export-aging-button",children:[e.jsx(kt,{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(Gc,{dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:p,tempCustomEndDate:x,onDateRangeChange:j,onShowCustomDatePickerChange:y,onStartDateChange:w,onEndDateChange:N,onApply:S,onCancel:A,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(ke,{placeholder:"Search by Request ID, Title, or Initiator...",value:u,onChange:P=>_(P.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(ee,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(Xe,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading aging data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"aging-error",children:[e.jsx(Ze,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"aging-empty",children:e.jsxs("p",{className:"text-sm",children:["No workflows found exceeding ",i," days threshold"]})}):e.jsxs("div",{className:"rounded-lg border",children:[e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{className:"bg-gray-50",children:[e.jsx(Ee,{className:"font-semibold",children:"Request ID"}),e.jsx(Ee,{className:"font-semibold",children:"Title"}),e.jsx(Ee,{className:"font-semibold",children:"Initiator"}),e.jsx(Ee,{className:"font-semibold",children:"Start Date"}),e.jsx(Ee,{className:"font-semibold",children:"Days Open"}),e.jsx(Ee,{className:"font-semibold",children:"Current Stage"}),e.jsx(Ee,{className:"font-semibold",children:"Assigned To"}),e.jsx(Ee,{className:"font-semibold",children:"Priority"}),e.jsx(Ee,{className:"font-semibold",children:"Status"})]})}),e.jsx(da,{children:t.map(P=>e.jsxs(ut,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${P.id}`,children:[e.jsx(Te,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>v(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(Te,{className:"text-sm",children:P.title}),e.jsx(Te,{className:"text-sm",children:P.initiator}),e.jsx(Te,{className:"text-sm text-gray-600",children:P.startDate}),e.jsx(Te,{children:e.jsxs(se,{className:`${D6(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(Te,{className:"text-sm",children:P.currentStage}),e.jsx(Te,{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(Te,{children:e.jsx(se,{className:I0(P.priority),"data-testid":`aging-priority-${P.id}`,children:P.priority})}),e.jsx(Te,{children:e.jsx(se,{className:P0(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(Xe,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>D(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>D(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function ql(t="month"){const[s,a]=h.useState(t),[r,n]=h.useState(void 0),[i,l]=h.useState(void 0),[o,c]=h.useState(!1),[d,m]=h.useState(void 0),[p,x]=h.useState(void 0),u=h.useCallback(N=>{const S=N;a(S),S!=="custom"?(n(void 0),l(void 0),m(void 0),x(void 0),c(!1)):(m(r),x(i),c(!0))},[r,i]),g=h.useCallback(()=>{if(d&&p){if(d>p){const N=d;n(p),l(N),m(p),x(N)}else n(d),l(p);c(!1)}},[d,p]),f=h.useCallback(()=>{c(!1),m(r),x(i),(!r||!i)&&(n(void 0),l(void 0),a("month"))},[r,i]),b=h.useCallback(N=>{N?(m(N),p&&N>p&&x(N)):m(void 0)},[p]),j=h.useCallback(N=>{N?(x(N),d&&N<d&&m(N)):x(void 0)},[d]),y=h.useCallback(()=>r&&i?`${et(r,"MMM d, yyyy")} - ${et(i,"MMM d, yyyy")}`:"Select dates",[r,i]),w=h.useCallback(()=>{a("month"),n(void 0),l(void 0),c(!1),m(void 0),x(void 0)},[]);return{dateRange:s,customStartDate:r,customEndDate:i,showCustomDatePicker:o,tempCustomStartDate:d,tempCustomEndDate:p,setShowCustomDatePicker:c,handleDateRangeChange:u,handleApplyCustomDate:g,handleCancelCustomDate:f,handleStartDateChange:b,handleEndDateChange:j,getDisplayDateRange:y,reset:w}}function E6(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return Kt(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${Kt(r)}`:`${a}d`}function E0(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 Sr(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 _0(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 _6=10;function M6({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=h.useState([]),[i,l]=h.useState(!0),[o,c]=h.useState(!1),[d,m]=h.useState(null),[p,x]=h.useState({page:1,totalPages:1,totalRecords:0}),u=h.useRef(!0),g=h.useCallback(async(f=1)=>{const b=f===1&&u.current;try{b?l(!0):c(!0),m(null);const j=await _t.getLifecycleReport(f,_6,t,s,a),y=j.lifecycleData.map(w=>{const N=E6(w.overallTATHours);return{id:w.requestNumber,requestId:w.requestId,title:w.title,priority:w.priority||"medium",status:w.status,initiator:w.initiatorName||"Unknown",initDate:E0(w.submissionDate),currentStage:w.currentStageName||`Level ${w.currentLevel}`,overallTAT:N,currentLevel:w.currentLevel,totalLevels:w.totalLevels,breachCount:w.breachCount||0}});n(y),x({page:j.pagination.currentPage,totalPages:j.pagination.totalPages,totalRecords:j.pagination.totalRecords})}catch(j){console.error("Failed to fetch lifecycle data:",j),m((j==null?void 0:j.message)||"Failed to load lifecycle data")}finally{b?l(!1):c(!1)}b&&(u.current=!1)},[t,s,a]);return h.useEffect(()=>{t==="custom"&&(!s||!a)||g(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:o,error:d,pagination:p,fetchData:g}}const L6=20;function O6({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,l]=h.useState([]),[o,c]=h.useState(!0),[d,m]=h.useState(!1),[p,x]=h.useState(null),[u,g]=h.useState({page:1,totalPages:1,totalRecords:0}),f=h.useRef(!0),b=h.useCallback(async(j=1)=>{const y=j===1&&f.current;try{y?c(!0):m(!0),x(null);const w=await _t.getActivityLogReport(j,L6,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),N=w.activities.map(S=>{const A=_0(S.type||"",S.details),_=(S.type||"").toLowerCase()==="login"||S.requestId==="00000000-0000-0000-0000-000000000001"||S.requestId==="SYSTEM_LOGIN",D=_?S.details||"User login":S.requestTitle||S.requestNumber||S.details||"N/A";return{timestamp:S.timestamp?E0(S.timestamp):"N/A",user:S.userName||"Unknown",action:A,details:D,ip:S.ipAddress||"N/A",userAgent:S.userAgent||null,requestId:_?"System Login":S.requestNumber||S.requestId||"-",userId:S.userId}});l(N),g({page:w.pagination.currentPage,totalPages:w.pagination.totalPages,totalRecords:w.pagination.totalRecords})}catch(w){console.error("Failed to fetch activity data:",w),x((w==null?void 0:w.message)||"Failed to load activity data")}finally{y?c(!1):m(!1)}y&&(f.current=!1)},[r,n,t,s,a]);return h.useEffect(()=>{t==="custom"&&(!s||!a)||b(1)},[r,n,t,s,a]),{activityLog:i,loading:o,loadingPage:d,error:p,pagination:u,fetchData:b}}const $6=20;function U6({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,l]=h.useState([]),[o,c]=h.useState(!0),[d,m]=h.useState(!1),[p,x]=h.useState(null),[u,g]=h.useState({page:1,totalPages:1,totalRecords:0}),f=h.useRef(!0),b=h.useCallback(async(y=1)=>{const w=y===1&&f.current;try{w?c(!0):m(!0),x(null);const N=parseInt(t,10);if(isNaN(N)||N<1){x("Please enter a valid threshold (minimum 1 day)");return}const S=await _t.getWorkflowAgingReport(N,y,$6,s,a,r),A=S.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(A),g({page:S.pagination.currentPage,totalPages:S.pagination.totalPages,totalRecords:S.pagination.totalRecords})}catch(N){console.error("Failed to fetch aging data:",N),x((N==null?void 0:N.message)||"Failed to load aging data")}finally{w?c(!1):m(!1)}w&&(f.current=!1)},[t,s,a,r]),j=h.useMemo(()=>i.filter(y=>{var N,S,A;if(!n)return!0;const w=n.toLowerCase();return((N=y.id)==null?void 0:N.toLowerCase().includes(w))||((S=y.title)==null?void 0:S.toLowerCase().includes(w))||((A=y.initiator)==null?void 0:A.toLowerCase().includes(w))}),[i,n]);return h.useEffect(()=>{s==="custom"&&(!a||!r)||b(1)},[t,s,a,r]),{agingWorkflows:j,loading:o,loadingPage:d,error:p,pagination:u,fetchData:b}}function B6(t="7"){const[s,a]=h.useState(t),[r,n]=h.useState(null),i=h.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=h.useCallback(()=>{(s===""||isNaN(parseInt(s,10))||parseInt(s,10)<1)&&(a("1"),n(null))},[s]);return{threshold:s,thresholdError:r,setThreshold:a,handleThresholdChange:i,handleThresholdBlur:l}}async function V6(t,s,a){const r=await _t.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 Ps(i.requestId||i.requestNumber),o=i.submissionDate?Sr(i.submissionDate):"N/A",c=i.closureDate?Sr(i.closureDate):"N/A",d=i.overallTATHours||0,m=d>0?(d/8).toFixed(2):"0",p=i.totalLevels||1,x=Math.min(Math.max(1,i.currentLevel||1),p),u=(l==null?void 0:l.approvals)||[];if(u.length===0){const g=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,c,p.toString(),x.toString(),d.toString(),m,(i.breachCount||0).toString(),"N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(g.join(","))}else u.forEach(g=>{const f=g.levelStartTime?Sr(g.levelStartTime):"N/A",b=g.levelEndTime||g.completedAt?Sr(g.levelEndTime||g.completedAt):"N/A",j=g.tatHours||0,y=g.tatDays||(j>0?(j/8).toFixed(2):"0");let w="N/A",N="N/A",S="N/A",A="N/A";if(g.levelStartTime){const D=new Date(g.levelStartTime);if(N=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-D.getTime())/(1e3*60*60)).toFixed(2),j>0){const P=parseFloat(N);S=Math.max(0,j-P).toFixed(2),A=(P/j*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?w=P<=j?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?w=P<=j?"On Track":"At Risk":w="N/A"}}const _=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,c,(i.totalLevels||0).toString(),(i.currentLevel||0).toString(),d.toString(),m,(i.breachCount||0).toString(),(g.levelNumber||"").toString(),`"${(g.levelName||`Level ${g.levelNumber}`).replace(/"/g,'""')}"`,`"${(g.approverName||"N/A").replace(/"/g,'""')}"`,`"${(g.approverEmail||"N/A").replace(/"/g,'""')}"`,g.status||"PENDING",f,b,j.toString(),y.toString(),w,N,S,A];n.push(_.join(","))})}catch(l){console.error(`Failed to fetch details for request ${i.requestNumber}:`,l);const o=i.submissionDate?Sr(i.submissionDate):"N/A",c=i.overallTATHours||0,d=c>0?(c/8).toFixed(2):"0",m=i.totalLevels||1,p=Math.min(Math.max(1,i.currentLevel||1),m),x=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,"N/A",m.toString(),p.toString(),c.toString(),d,(i.breachCount||0).toString(),"Error","Error fetching details","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(x.join(","))}Yc(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function z6(t,s,a,r,n){const i=await _t.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=_0(o.type||"",o.details),m=[o.timestamp?Sr(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(","))}),Yc(l,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function H6(t,s,a,r){const n=await _t.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?Sr(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(","))}),Yc(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function Yc(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 W6(){const[t,s]=h.useState(!1),[a,r]=h.useState(!1),[n,i]=h.useState(!1),l=h.useCallback(async(d,m,p)=>{try{s(!0),await V6(d,m,p)}catch(x){console.error("Failed to export lifecycle data:",x),alert("Failed to export lifecycle data. Please try again.")}finally{s(!1)}},[]),o=h.useCallback(async(d,m,p,x,u)=>{try{r(!0),await z6(d,m,p,x,u)}catch(g){console.error("Failed to export activity data:",g),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),c=h.useCallback(async(d,m,p,x)=>{try{i(!0),await H6(d,m,p,x)}catch(u){console.error("Failed to export aging data:",u),alert("Failed to export aging data. Please try again.")}finally{i(!1)}},[]);return{exportingLifecycle:t,exportingActivity:a,exportingAging:n,handleExportLifecycle:l,handleExportActivity:o,handleExportAging:c}}function G6({onBack:t}){const s=ys(),[a,r]=h.useState(""),[n,i]=h.useState("all"),[l,o]=h.useState("all"),c=ql("month"),d=ql("month"),m=ql("month"),p=B6("7"),x=M6({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),u=O6({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:l}),g=U6({threshold:p.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),f=W6(),b=h.useCallback(()=>{t?t():s("/dashboard")},[t,s]),j=h.useCallback(A=>{Vi({requestId:A,navigate:s})},[s]),y=h.useCallback(()=>{f.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[f,c]),w=h.useCallback(()=>{f.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,l)},[f,d,n,l]),N=h.useCallback(()=>{const A=parseInt(p.threshold,10);!isNaN(A)&&A>=1&&f.handleExportAging(A,m.dateRange,m.customStartDate,m.customEndDate)},[f,p.threshold,m]),S=h.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(k6,{onBack:b}),e.jsx(F6,{lifecycleRequests:x.lifecycleRequests,loading:x.loading,loadingPage:x.loadingPage,error:x.error,pagination:x.pagination,dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate,showCustomDatePicker:c.showCustomDatePicker,tempCustomStartDate:c.tempCustomStartDate,tempCustomEndDate:c.tempCustomEndDate,exporting:f.exportingLifecycle,onDateRangeChange:c.handleDateRangeChange,onShowCustomDatePickerChange:c.setShowCustomDatePicker,onStartDateChange:c.handleStartDateChange,onEndDateChange:c.handleEndDateChange,onApplyCustomDate:c.handleApplyCustomDate,onCancelCustomDate:c.handleCancelCustomDate,onPageChange:x.fetchData,onExport:y,onViewRequest:j}),e.jsx(I6,{activityLog:u.activityLog,loading:u.loading,loadingPage:u.loadingPage,error:u.error,pagination:u.pagination,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,showCustomDatePicker:d.showCustomDatePicker,tempCustomStartDate:d.tempCustomStartDate,tempCustomEndDate:d.tempCustomEndDate,filterCategory:n,filterSeverity:l,exporting: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:S,onPageChange:u.fetchData,onExport:w,onViewRequest:j}),e.jsx(P6,{agingWorkflows:g.agingWorkflows,loading:g.loading,loadingPage:g.loadingPage,error:g.error,pagination:g.pagination,threshold:p.threshold,thresholdError:p.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:p.handleThresholdChange,onThresholdBlur:p.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:N,onViewRequest:j})]})})}function xi({className:t,...s}){return e.jsx("div",{"data-slot":"skeleton",className:_e("bg-accent animate-pulse rounded-md",t),...s})}function Y6(){const t=ys(),[s,a]=h.useState(()=>gx()||[]),[r,n]=h.useState(()=>!gx()),[i,l]=h.useState(""),o=async()=>{try{s.length===0&&n(!0);const m=await xl();a(m||[])}catch(m){console.error("Failed to fetch templates:",m),X.error("Failed to load templates")}finally{n(!1)}};h.useEffect(()=>{o()},[]);const c=s.filter(m=>m.name.toLowerCase().includes(i.toLowerCase())||m.category.toLowerCase().includes(i.toLowerCase())),d=m=>{switch(m.toLowerCase()){case"high":return"bg-red-100 text-red-700 border-red-200";case"medium":return"bg-orange-100 text-orange-700 border-orange-200";case"low":return"bg-green-100 text-green-700 border-green-200";default:return"bg-gray-100 text-gray-700 border-gray-200"}};return e.jsxs("div",{className:"max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:"Admin Templates"}),e.jsx("p",{className:"text-gray-500",children:"Manage workflow templates for your organization"})]}),e.jsxs(E,{onClick:()=>t("/admin/create-template"),className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(bs,{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(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(ke,{placeholder:"Search templates...",className:"pl-10 border-gray-200",value:i,onChange:m=>l(m.target.value)})]})}),r?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(m=>e.jsxs(Z,{className:"h-48",children:[e.jsxs(oe,{children:[e.jsx(xi,{className:"h-6 w-3/4 mb-2"}),e.jsx(xi,{className:"h-4 w-1/2"})]}),e.jsxs(ee,{children:[e.jsx(xi,{className:"h-4 w-full mb-2"}),e.jsx(xi,{className:"h-4 w-2/3"})]})]},m))}):c.length===0?e.jsxs("div",{className:"text-center py-16 bg-white rounded-lg border border-dashed border-gray-300",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Ie,{className:"w-8 h-8 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No templates found"}),e.jsx("p",{className:"text-gray-500 max-w-sm mx-auto mb-6",children:i?"Try adjusting your search terms":"Get started by creating your first workflow template"}),!i&&e.jsx(E,{onClick:()=>t("/admin/create-template"),variant:"outline",children:"Create Template"})]}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:c.map(m=>{var p;return e.jsxs(Z,{className:"hover:shadow-md transition-shadow duration-200 group",children:[e.jsxs(oe,{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(Ie,{className:"w-5 h-5"})}),e.jsx(se,{variant:"outline",className:d(m.priority),children:m.priority})]}),e.jsx(me,{className:"line-clamp-1 text-lg",children:m.name}),e.jsx(ve,{className:"line-clamp-3 min-h-[4.5rem]",children:m.description})]}),e.jsxs(ee,{children:[e.jsxs("div",{className:"text-sm text-gray-500 mb-4 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Category:"}),e.jsx("span",{className:"font-medium text-gray-900",children:m.category})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"SLA:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[m.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Approvers:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[((p=m.approvers)==null?void 0:p.length)||0," levels"]})]})]}),e.jsx("div",{className:"flex gap-2 pt-2 border-t mt-2",children:e.jsxs(E,{variant:"outline",className:"flex-1 text-blue-600 hover:text-blue-700 hover:bg-blue-50 border-blue-100",onClick:()=>t(`/admin/edit-template/${m.id}`),children:[e.jsx(Eb,{className:"w-4 h-4 mr-2"}),"Edit"]})})]})]},m.id)})})]})}function Rx(){const t=ys(),{templateId:s}=_a(),a=!!s,[r,n]=h.useState(!1),[i,l]=h.useState(!1),{searchResults:o,searchLoading:c,searchUsersDebounced:d,clearSearch:m}=Kg(),[p,x]=h.useState(""),[u,g]=h.useState({name:"",description:"",category:"General",priority:"medium",estimatedTime:"2 days",suggestedSLA:24,approvers:[]});h.useEffect(()=>{a&&s&&(async()=>{try{l(!0);const D=(await xl()).find(R=>R.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||[]}):(X.error("Template not found"),t("/admin/templates"))}catch(_){console.error("Failed to load template:",_),X.error("Failed to load template details")}finally{l(!1)}})()},[a,s,t]);const f=A=>{const{name:_,value:D}=A.target;g(R=>({...R,[_]:D}))},b=(A,_)=>{g(D=>({...D,[A]:_}))},j=A=>{if(x(A),A.startsWith("@")&&A.slice(1).length>=1){d(A,5);return}m()},y=A=>{if(u.approvers.some(_=>_.userId===A.userId)){X.error("Approver already added");return}g(_=>({..._,approvers:[..._.approvers,{userId:A.userId,name:A.displayName||A.email,email:A.email,level:_.approvers.length+1,tat:24,tatType:"hours"}]})),x(""),m()},w=A=>{const _=[...u.approvers];_.splice(A,1),_.forEach((D,R)=>D.level=R+1),g(D=>({...D,approvers:_}))},N=async A=>{if(A.preventDefault(),!u.name||!u.description){X.error("Please fill in required fields");return}if(u.approvers.length===0){X.error("Please add at least one approver");return}const _={...u,approvers:u.approvers.map(D=>({...D,tat:D.tatType==="days"?parseInt(D.tat)*24:parseInt(D.tat)}))};try{n(!0),a&&s?(await iT(s,_),X.success("Template updated successfully")):(await nT(_),X.success("Template created successfully")),t("/admin/templates")}catch(D){X.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(Xe,{className:"h-8 w-8 animate-spin text-gray-400"})});const S=u.name&&u.description&&u.approvers.length>0&&u.approvers.every(A=>{const _=parseInt(String(A.tat))||0,D=A.tatType==="days"?7:24;return _>=1&&_<=D});return e.jsxs("div",{className:"max-w-4xl mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>t("/admin/templates"),children:e.jsx(ws,{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:N,className:"space-y-6",children:[e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Basic Information"}),e.jsx(ve,{children:"General details about the template"})]}),e.jsxs(ee,{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(te,{htmlFor:"name",children:"Template Name *"}),e.jsx(ke,{id:"name",name:"name",placeholder:"e.g., Office Stationery Request",value:u.name,onChange:f,className:"border-gray-200",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"category",children:"Category"}),e.jsx("div",{className:"relative",children:e.jsx(ke,{id:"category",name:"category",placeholder:"e.g., Admin, HR, Finance",value:u.category,onChange:f,className:"border-gray-200"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"description",children:"Description *"}),e.jsx(Os,{id:"description",name:"description",placeholder:"Describe what this request is for...",value:u.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(te,{htmlFor:"priority",children:"Default Priority"}),e.jsxs(Be,{name:"priority",value:u.priority,onValueChange:A=>b("priority",A),children:[e.jsx(ze,{children:e.jsx(Ve,{placeholder:"Select priority"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"low",children:"Low"}),e.jsx(Q,{value:"medium",children:"Medium"}),e.jsx(Q,{value:"high",children:"High"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"estimatedTime",children:"Estimated Time"}),e.jsx(ke,{id:"estimatedTime",name:"estimatedTime",placeholder:"e.g., 2 days",value:u.estimatedTime,onChange:f,className:"border-gray-200"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"suggestedSLA",children:"SLA (Hours)"}),e.jsx(ke,{id:"suggestedSLA",name:"suggestedSLA",type:"number",placeholder:"24",value:u.suggestedSLA,onChange:f,className:"border-gray-200"})]})]})]})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Approver Workflow"}),e.jsx(ve,{children:"Define static approvers for this template"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[u.approvers.map((A,_)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsxs(se,{variant:"outline",className:"bg-white",children:["Level ",A.level]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:A.name}),e.jsx("div",{className:"text-sm text-gray-500",children:A.email})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(te,{htmlFor:`tat-${_}`,className:"text-xs whitespace-nowrap",children:"TAT"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ke,{id:`tat-${_}`,type:"number",className:"h-8 w-16 border-gray-200",value:A.tat||"",min:1,max:A.tatType==="days"?7:24,placeholder:A.tatType==="days"?"1":"24",onChange:D=>{if((parseInt(D.target.value)||0)<0)return;const v=[...u.approvers];v[_].tat=D.target.value,g(P=>({...P,approvers:v}))}}),e.jsxs(Be,{value:A.tatType||"hours",onValueChange:D=>{const R=[...u.approvers];R[_].tatType=D,R[_].tat=1,g(v=>({...v,approvers:R}))},children:[e.jsx(ze,{className:"h-8 w-20 text-xs px-2",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Q,{value:"hours",children:"Hours"}),e.jsx(Q,{value:"days",children:"Days"})]})]})]})]})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>w(_),children:e.jsx(bt,{className:"w-4 h-4 text-gray-500 hover:text-red-600"})})]},_)),u.approvers.length===0&&e.jsx("div",{className:"text-center p-8 border-2 border-dashed rounded-lg text-gray-500 text-sm",children:"No approvers defined. Requests will be auto-approved or require manual assignment."})]}),e.jsxs("div",{className:"space-y-2 relative",children:[e.jsx(te,{children:"Add Approver"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ke,{placeholder:"Type '@' to search user by name or email...",value:p,onChange:A=>j(A.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(A=>e.jsxs("div",{className:"p-2 hover:bg-gray-50 cursor-pointer flex items-center gap-3",onClick:()=>y(A),children:[e.jsx(ls,{className:"h-8 w-8",children:e.jsx(os,{children:(A.displayName||"U").substring(0,2)})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:A.displayName}),e.jsx("div",{className:"text-xs text-gray-500",children:A.email})]})]},A.userId))]})]}),u.approvers.length>0&&e.jsx("div",{className:"mt-6 p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(st,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{const A=u.approvers.reduce((D,R)=>{const v=Number(R.tat||0);return(R.tatType||"hours")==="days"?D+v:D+v/24},0)||0,_=Math.ceil(A);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[_," ",_===1?"Day":"Days"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Duration"})]})})()})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:u.approvers.map((A,_)=>{const D=Number(A.tat||0),v=(A.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:[v," ",v===1?"hour":"hours"]})]})},_):null})}),(()=>{const A=u.approvers.reduce((D,R)=>{const v=Number(R.tat||0);return(R.tatType||"hours")==="days"?D+v*24:D+v},0)||0,_=Math.ceil(A/8);return A===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:[A,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children:_}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Working Days*"})]})]}),e.jsx("p",{className:"text-xs text-emerald-600 mt-2 text-center",children:"*Based on 8-hour working days"})]})})()]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[e.jsx(E,{type:"button",variant:"outline",onClick:()=>t("/admin/templates"),children:"Cancel"}),e.jsx(E,{type:"submit",disabled:r||!S,className:"bg-re-green hover:bg-re-green/90",children:r?"Saving...":e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"w-4 h-4 mr-2"}),a?"Update Template":"Create Template"]})})]})]})]})}function K6({template:t,formData:s,setFormData:a,documents:r,setDocuments:n}){const i=h.useRef(null),[l,o]=h.useState(null),c=u=>{u.target.files&&u.target.files.length>0&&n([...r,...Array.from(u.target.files)])},d=u=>{const g=[...r];g.splice(u,1),n(g)},m=u=>{const g=URL.createObjectURL(u);o({file:u,url:g})},p=()=>{l!=null&&l.url&&URL.revokeObjectURL(l.url),o(null)},x=u=>u.type.includes("image")||u.type.includes("pdf");return e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(Z,{className:"shadow-sm",children:e.jsxs(ee,{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(Z,{children:e.jsxs(ee,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"requestTitle",children:"Request Title *"}),e.jsx(ke,{id:"requestTitle",value:s.title,onChange:u=>a({...s,title:u.target.value}),placeholder:`Request for ${t.name}`,className:"border-gray-200"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(Jn,{value:s.description||"",onChange:u=>a({...s,description:u}),placeholder:"Provide comprehensive details about your request...",className:"min-h-[120px] text-base border-gray-200 bg-white shadow-sm",minHeight:"120px"})]})]})}),e.jsx(Z,{children:e.jsxs(ee,{className:"pt-6 space-y-4",children:[e.jsx(te,{children:"Supporting Documents"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>{var u;return(u=i.current)==null?void 0:u.click()},children:[e.jsx(js,{className:"w-10 h-10 text-gray-400 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium text-gray-700",children:"Click to upload files"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"PDF, Excel, Images (Max 10MB)"}),e.jsx("input",{ref:i,type:"file",multiple:!0,className:"hidden",onChange:c})]}),r.length>0&&e.jsx("div",{className:"grid grid-cols-1 gap-2 mt-4",children:r.map((u,g)=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-white border rounded-lg shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center",children:e.jsx(Ie,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-800 truncate max-w-[200px]",children:u.name}),e.jsxs("p",{className:"text-xs text-gray-500",children:[(u.size/1024/1024).toFixed(2)," MB"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[x(u)&&e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>m(u),children:e.jsx(Ct,{className:"w-4 h-4 text-gray-500 hover:text-blue-600"})}),e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>d(g),children:e.jsx(bt,{className:"w-4 h-4 text-gray-500 hover:text-red-500"})})]})]},g))})]})}),l&&e.jsx(Mr,{fileName:l.file.name,fileType:l.file.type,fileUrl:l.url,fileSize:l.file.size,open:!!l,onClose:p})]})}function Q6({template:t,formData:s,documents:a}){const r=t.workflowApprovers||[];return e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Ze,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900",children:"Ready to Submit?"}),e.jsx("p",{className:"text-sm text-blue-700 mt-1",children:"Please review the details below. This request will follow the standardized approval workflow defined by the administrator."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsxs(Z,{children:[e.jsx(oe,{className:"pb-3",children:e.jsx(me,{className:"text-lg",children:"Request Overview"})}),e.jsx(ee,{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:Ra(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(se,{variant:"secondary",className:"pl-1 pr-2 py-1 flex items-center gap-1.5 h-auto",children:[e.jsx(Ie,{className:"w-3 h-3 text-gray-500"}),e.jsx("span",{className:"truncate max-w-[150px]",children:n.name})]},i))})]})]})})]}),e.jsxs(Z,{children:[e.jsx(oe,{className:"pb-3",children:e.jsx(me,{className:"text-lg",children:"Approval Workflow"})}),e.jsx(ee,{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(se,{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(Z,{children:[e.jsx(oe,{className:"pb-3",children:e.jsx(me,{className:"text-sm uppercase text-gray-500",children:"Properties"})}),e.jsxs(ee,{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(Qt,{}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Priority"}),e.jsx(se,{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(Qt,{}),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 X6(){const{templateId:t}=_a(),s=ys(),{user:a}=cs(),[r,n]=h.useState(!0),[i,l]=h.useState(!1),[o,c]=h.useState(null),[d,m]=h.useState(1),[p,x]=h.useState([]),[u,g]=h.useState({title:"",description:""}),f=["Request Details","Review & Submit"];h.useEffect(()=>{t&&(async()=>{try{n(!0);const w=(await xl()).find(N=>N.id===t);if(w){const N={id:w.id,name:w.name,description:w.description,category:w.category,icon:Ie,estimatedTime:w.estimatedTime,commonApprovers:w.approvers.map(S=>S.name),workflowApprovers:w.approvers,suggestedSLA:w.suggestedSLA,priority:w.priority,fields:w.fields||{}};c(N),g({title:N.name,description:N.description})}else X.error("Template not found")}catch(y){console.error("Error loading template:",y),X.error("Failed to load template details")}finally{n(!1)}})()},[t,s]);const b=async()=>{var j;if(o)try{l(!0);const y={templateId:o.id,templateType:"TEMPLATE",title:u.title,description:u.description,priorityUi:o.priority==="high"?"express":"standard",approverCount:((j=o.workflowApprovers)==null?void 0:j.length)||0,approvers:(o.workflowApprovers||[]).map(N=>({email:N.email,name:N.name,tat:N.tat,tatType:"hours"})),spectators:[],ccList:[]},w=await ic(y,p);w&&w.id&&await cp(w.id),X.success("Request Submitted Successfully",{description:`Your request "${u.title}" has been created.`}),s("/my-requests")}catch(y){console.error("Submission failed:",y),X.error("Failed to submit request")}finally{l(!1)}};return r?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):o?e.jsxs("div",{className:"h-screen flex flex-col bg-gray-50 overflow-hidden",children:[e.jsxs("header",{className:"bg-white border-b flex-shrink-0 z-10",children:[e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>s("/new-request"),children:e.jsx(ws,{className:"w-5 h-5 text-gray-500"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold text-gray-900",children:"New Request"}),e.jsx("p",{className:"text-sm text-gray-500",children:o.name})]})]}),e.jsx(E,{variant:"outline",onClick:()=>s("/dashboard"),children:"Cancel Request"})]}),e.jsx(Yg,{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(K6,{template:o,formData:u,setFormData:g,documents:p,setDocuments:x}):e.jsx(Q6,{template:o,formData:u,documents:p})})}),e.jsx("footer",{className:"bg-white border-t px-6 py-4 flex-shrink-0 z-10",children:e.jsxs("div",{className:"max-w-4xl mx-auto flex items-center justify-between",children:[e.jsx(E,{variant:"outline",onClick:()=>d===1?s("/new-request"):m(1),disabled:i,children:d===1?"Cancel":"Back to Details"}),e.jsx(E,{onClick:()=>d===1?m(2):b(),disabled:i,className:"bg-re-green hover:bg-re-green/90",children:d===1?e.jsxs(e.Fragment,{children:["Review Request ",e.jsx(nn,{className:"w-4 h-4 ml-1"})]}):e.jsxs(e.Fragment,{children:[i?"Submitting...":"Submit Request"," ",e.jsx(za,{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(Ie,{className:"w-8 h-8 text-red-600"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Template Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The requested template could not be loaded. It may have been deleted or you do not have permission to view it."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsx(E,{variant:"outline",onClick:()=>s("/dashboard"),children:"Go to Dashboard"}),e.jsx(E,{onClick:()=>s("/new-request"),children:"Browse Templates"})]})]})})}function J6({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(te,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(Be,{value:t,onValueChange:a,children:[e.jsx(ze,{id:"default-period",children:e.jsx(Ve,{})}),e.jsx(He,{children:n.map(i=>e.jsx(Q,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(ke,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function Z6({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(ms,{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(ms,{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(ms,{checked:a,onCheckedChange:i})]})]})}const q6=["CSV","Excel","PDF","JSON"];function eR({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(te,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:q6.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Wc,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(te,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function tR({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(ke,{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 sR(){const[t,s]=h.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{X.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Analytics & Reporting Configuration"}),e.jsx(ve,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(J6,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(Qt,{}),e.jsx(Z6,{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(Qt,{}),e.jsx(eR,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(tR,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(E,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Ea,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const aR=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"}},rR=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function nR({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{children:[e.jsx(Ee,{children:"User"}),e.jsx(Ee,{children:"Role"}),e.jsx(Ee,{children:"Department"}),e.jsx(Ee,{children:"Status"}),e.jsx(Ee,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:t.length===0?e.jsx(ut,{children:e.jsx(Te,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(ut,{className:"hover:bg-muted/50",children:[e.jsx(Te,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ls,{className:"size-10",children:e.jsx(os,{className:"bg-re-green text-white",children:rR(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(Te,{children:e.jsx(se,{className:aR(n.role),children:n.role})}),e.jsx(Te,{children:n.department}),e.jsx(Te,{children:e.jsxs(se,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(us,{className:"w-3 h-3 mr-1"}),n.status]})}),e.jsx(Te,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx(tl,{className:"w-4 h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(_b,{className:"w-4 h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(ln,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function iR({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 lR(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function oR(){const[t,s]=h.useState(""),[a,r]=h.useState([]),[n,i]=h.useState(!1),[l,o]=h.useState(null),[c,d]=h.useState("USER"),[m,p]=h.useState(!1),[x,u]=h.useState(!1),[g,f]=h.useState(null),[b,j]=h.useState([]),[y,w]=h.useState(!1),[N,S]=h.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[A,_]=h.useState("ELEVATED"),[D,R]=h.useState(1),[v,P]=h.useState(1),[C,V]=h.useState(0),F=10,$=h.useRef(null),I=h.useCallback(lR(async re=>{var K,ae,Ne;if(!re||!re.startsWith("@")||re.length<2){r([]),i(!1);return}i(!0);try{const Se=re.slice(1),Je=((K=(await sa.searchUsers(Se,20)).data)==null?void 0:K.data)||[];r(Je)}catch(Se){console.error("Search failed:",Se),f({type:"error",text:((Ne=(ae=Se.response)==null?void 0:ae.data)==null?void 0:Ne.message)||"Failed to search users"})}finally{i(!1)}},300),[]),T=re=>{const K=re.target.value;s(K),I(K)},k=async re=>{var K,ae;try{const Ne=b.find(Pe=>Pe.email.toLowerCase()===re.toLowerCase());if(Ne)return Ne.role;const Je=(((ae=(K=(await sa.getUsersByRole("ALL",1,1e3)).data)==null?void 0:K.data)==null?void 0:ae.users)||[]).find(Pe=>{var Oe;return((Oe=Pe.email)==null?void 0:Oe.toLowerCase())===re.toLowerCase()});return Je&&Je.role?Je.role:null}catch(Ne){return console.error("Failed to fetch user role:",Ne),null}},z=async re=>{o(re),s(re.email),r([]),u(!0);try{const K=await k(re.email);d(K||"USER")}catch(K){console.error("Failed to fetch user role:",K),d("USER")}finally{u(!1)}},L=async()=>{var re,K;if(!l||!c){f({type:"error",text:"Please select a user and role"});return}p(!0),f(null);try{await sa.assignRole(l.email,c),f({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await M(),await U(),X.success("Role assigned successfully")}catch(ae){console.error("Role assignment failed:",ae);const Ne=((K=(re=ae.response)==null?void 0:re.data)==null?void 0:K.error)||"Failed to assign role";f({type:"error",text:Ne}),X.error(Ne)}finally{p(!1)}},M=async(re=D)=>{var K,ae,Ne,Se,Ge,Je;w(!0);try{const Pe=await sa.getUsersByRole(A,re,F),Oe=((ae=(K=Pe.data)==null?void 0:K.data)==null?void 0:ae.users)||[],ie=(Se=(Ne=Pe.data)==null?void 0:Ne.data)==null?void 0:Se.pagination,pe=(Je=(Ge=Pe.data)==null?void 0:Ge.data)==null?void 0:Je.summary;j(Oe.map(we=>({userId:we.userId,email:we.email,displayName:we.displayName||we.email,role:we.role||"USER",department:we.department,designation:we.designation,isActive:we.isActive!==!1}))),ie&&(R(ie.currentPage),P(ie.totalPages),V(ie.totalUsers)),pe&&S(we=>({...we,admins:pe.ADMIN||0,management:pe.MANAGEMENT||0,users:pe.USER||0,total:(pe.ADMIN||0)+(pe.MANAGEMENT||0)+(pe.USER||0)}))}catch(Pe){console.error("Failed to fetch users:",Pe),X.error("Failed to load users")}finally{w(!1)}},U=async()=>{var re,K,ae,Ne,Se,Ge;try{const Je=await sa.getRoleStatistics(),Pe=((K=(re=Je.data)==null?void 0:re.data)==null?void 0:K.statistics)||((ae=Je.data)==null?void 0:ae.statistics)||[],Oe={admins:parseInt(((Ne=Pe.find(ie=>ie.role==="ADMIN"))==null?void 0:Ne.count)||"0"),management:parseInt(((Se=Pe.find(ie=>ie.role==="MANAGEMENT"))==null?void 0:Se.count)||"0"),users:parseInt(((Ge=Pe.find(ie=>ie.role==="USER"))==null?void 0:Ge.count)||"0")};S(ie=>({...ie,...Oe,total:Oe.admins+Oe.management+Oe.users,active:ie.active||Oe.admins+Oe.management+Oe.users,inactive:ie.inactive||0}))}catch(Je){console.error("Failed to fetch statistics:",Je)}};h.useEffect(()=>{M(1),U()},[A]);const B=re=>{_(re),R(1)},W=re=>{M(re)},J=async(re,K)=>{var ae,Ne;try{await sa.updateUserRole(re,K),X.success("User role updated successfully"),await M(),await U()}catch(Se){console.error("Failed to update user role:",Se),X.error(((Ne=(ae=Se.response)==null?void 0:ae.data)==null?void 0:Ne.error)||"Failed to update user role")}},O=async re=>{b.find(ae=>ae.userId===re)&&X.info("User status toggle functionality coming soon")},H=async re=>{const K=b.find(ae=>ae.userId===re);if(K){if(K.role==="ADMIN"){X.error("Cannot delete admin user");return}X.info("User deletion functionality coming soon")}};h.useEffect(()=>{const re=K=>{$.current&&!$.current.contains(K.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",re),()=>{document.removeEventListener("mousedown",re)}},[a]);const Y={total:N.total,active:N.active,inactive:N.inactive,admins:N.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(iR,{stats:Y}),e.jsxs(Z,{children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(me,{children:"Assign User Role"}),e.jsx(ve,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(E,{onClick:L,disabled:!l||m,className:"bg-re-green hover:bg-re-green/90",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",ref:$,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(ke,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:T,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx(Xe,{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(re=>e.jsxs("button",{onClick:()=>z(re),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:re.displayName||re.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:re.email}),re.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[re.department,re.designation?` • ${re.designation}`:""]})]},re.userId))})]})]}),l&&e.jsx("div",{className:"border-2 border-re-green/20 bg-re-green/5 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-re-green flex items-center justify-center text-white font-bold shadow-md",children:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-gray-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[l.department,l.designation?` • ${l.designation}`:""]}),x&&e.jsxs("p",{className:"text-xs text-re-green mt-1 flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3 animate-spin"}),"Checking current role..."]})]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>{o(null),s(""),d("USER"),u(!1)},children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Select Role"}),e.jsxs(Be,{value:c,onValueChange:re=>d(re),disabled:x,children:[e.jsx(ze,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ve,{placeholder:x?"Loading current role...":"Select role"})}),e.jsxs(He,{className:"rounded-lg",children:[e.jsx(Q,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(Q,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(Q,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vr,{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(Le,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Ze,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${g.type==="success"?"text-green-800":"text-red-800"}`,children:g.text})]})})]})]}),e.jsxs(Z,{children:[e.jsx(oe,{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(me,{className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(ve,{children:["View and manage user accounts and roles (",C," ",A!=="ALL"&&A!=="ELEVATED"?A.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Be,{value:A,onValueChange:B,children:[e.jsx(ze,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ve,{placeholder:"Filter by role"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",N.admins+N.management,")"]})]})}),e.jsx(Q,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",N.admins,")"]})]})}),e.jsx(Q,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",N.management,")"]})]})}),e.jsx(Q,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",N.users,")"]})]})}),e.jsx(Q,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",N.admins+N.management+N.users,")"]})]})})]})]})})]})}),e.jsx(ee,{className:"pt-6",children:y?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Xe,{className:"w-6 h-6 animate-spin text-re-green mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading users..."})]}):b.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(Zt,{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:A==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(nR,{users:b.map(re=>({id:re.userId,name:re.displayName,email:re.email,role:re.role,department:re.department||"N/A",status:re.isActive?"active":"inactive"})),onEdit:re=>{const K=b.find(ae=>ae.userId===re);if(K){const ae=K.role==="USER"?"MANAGEMENT":K.role==="MANAGEMENT"?"ADMIN":"USER";J(re,ae)}},onToggleStatus:O,onDelete:H}),v>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,C)," of ",C," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>W(D-1),disabled:D===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,v)},(re,K)=>{let ae;return v<=5||D<=3?ae=K+1:D>=v-2?ae=v-4+K:ae=D-2+K,e.jsx(E,{variant:D===ae?"default":"outline",size:"sm",onClick:()=>W(ae),className:`w-9 h-9 p-0 ${D===ae?"bg-re-green hover:bg-re-green/90":""}`,children:ae},ae)})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>W(D+1),disabled:D===v,children:"Next"})]})]})]})})]})]})}function cR({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yi,{className:"w-5 h-5 text-re-green"}),e.jsx(me,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(ve,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(ee,{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(te,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(ke,{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(st,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(ke,{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(st,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function dR({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"w-5 h-5 text-re-green"}),e.jsx(me,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(ve,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(ee,{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(te,{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(Po,{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(_s,{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(te,{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(Po,{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(ts,{className:"w-3 h-3"}),"Send escalation warning when ",s,"% of TAT elapsed"]})]})]})})]})}const wn=[{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 mR({workStartHour:t,workEndHour:s,workStartDay:a,workEndDay:r,onWorkStartHourChange:n,onWorkEndHourChange:i,onWorkStartDayChange:l,onWorkEndDayChange:o}){var c,d,m;return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"w-5 h-5 text-re-green"}),e.jsx(me,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(ve,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(ee,{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(te,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(ke,{id:"work-start-hour",type:"number",min:"0",max:"23",value:t,onChange:p=>n(parseInt(p.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(st,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(ke,{id:"work-end-hour",type:"number",min:"0",max:"23",value:s,onChange:p=>i(parseInt(p.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(st,{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(te,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(Be,{value:a.toString(),onValueChange:p=>l(parseInt(p)),children:[e.jsx(ze,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ve,{placeholder:"Select start day"})}),e.jsx(He,{children:wn.map(p=>e.jsx(Q,{value:p.value.toString(),children:p.label},p.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(te,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(Be,{value:r.toString(),onValueChange:p=>o(parseInt(p)),children:[e.jsx(ze,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ve,{placeholder:"Select end day"})}),e.jsx(He,{children:wn.map(p=>e.jsx(Q,{value:p.value.toString(),children:p.label},p.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=wn.find(p=>p.value===a))==null?void 0:c.label} only`:` ${(d=wn.find(p=>p.value===a))==null?void 0:d.label} to ${(m=wn.find(p=>p.value===r))==null?void 0:m.label}`]})})]})]})}function uR(){const[t,s]=h.useState(!0),[a,r]=h.useState(!1),[n,i]=h.useState({expressHours:24,standardHours:72,reminderThreshold1:50,reminderThreshold2:75,workStartHour:9,workEndHour:18,workStartDay:1,workEndDay:5});h.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await ul("TAT_SETTINGS"),m={};d.forEach(p=>{m[p.configKey]=p.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),X.error("Failed to load TAT configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([Bs("DEFAULT_TAT_EXPRESS_HOURS",n.expressHours.toString()),Bs("DEFAULT_TAT_STANDARD_HOURS",n.standardHours.toString()),Bs("TAT_REMINDER_THRESHOLD_1",n.reminderThreshold1.toString()),Bs("TAT_REMINDER_THRESHOLD_2",n.reminderThreshold2.toString()),Bs("WORK_START_HOUR",n.workStartHour.toString()),Bs("WORK_END_HOUR",n.workEndHour.toString()),Bs("WORK_START_DAY",n.workStartDay.toString()),Bs("WORK_END_DAY",n.workEndDay.toString())]),X.success("TAT configuration saved successfully"),await l()}catch(p){console.error("Failed to save TAT configuration:",p),X.error(((m=(d=p.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(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(Xe,{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(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{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(st,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(cR,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx(Qt,{}),e.jsx(mR,{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(Qt,{}),e.jsx(dR,{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(E,{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(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function xR({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(ms,{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(ms,{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(ms,{checked:a,onCheckedChange:i})]})]})}function hR({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(te,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(Be,{value:t,onValueChange:a,children:[e.jsx(ze,{id:"notification-frequency",children:e.jsx(Ve,{placeholder:"Select frequency"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"Immediate",children:"Immediate"}),e.jsx(Q,{value:"Hourly",children:"Hourly"}),e.jsx(Q,{value:"Daily",children:"Daily"}),e.jsx(Q,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(ke,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function pR({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(Os,{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 gR(){const[t,s]=h.useState({emailNotifications:!0,inAppNotifications:!0,autoReminders:!0,notificationFrequency:"Immediate",reminderFrequency:12,emailTemplate:"Dear [Name], You have a pending approval request [Request ID] that requires your attention. TAT remaining: [TAT]. Please review at your earliest convenience."}),a=()=>{X.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Notification Configuration"}),e.jsx(ve,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(xR,{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(Qt,{}),e.jsx(hR,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(pR,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(E,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Ea,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function fR({maxFileSizeMB:t,retentionDays:s,onMaxFileSizeChange:a,onRetentionDaysChange:r}){const n=Math.round(s/365*10)/10;return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-5 h-5 text-re-green"}),e.jsx(me,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(ve,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(ee,{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(te,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(ke,{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(js,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(ke,{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(sl,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const bR=[{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 jR({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(Z,{className:"border-0 shadow-sm",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ho,{className:"w-5 h-5 text-re-green"}),e.jsx(me,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(ve,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:bR.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(te,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(ke,{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 yR(){const[t,s]=h.useState(!0),[a,r]=h.useState(!1),[n,i]=h.useState({maxFileSizeMB:10,retentionDays:365,allowedFileTypes:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"});h.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await ul("DOCUMENT_POLICY"),m={};d.forEach(p=>{m[p.configKey]=p.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),X.error("Failed to load document configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([Bs("MAX_FILE_SIZE_MB",n.maxFileSizeMB.toString()),Bs("DOCUMENT_RETENTION_DAYS",n.retentionDays.toString()),Bs("ALLOWED_FILE_TYPES",n.allowedFileTypes)]),X.success("Document policy saved successfully"),await l()}catch(p){console.error("Failed to save document configuration:",p),X.error(((m=(d=p.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(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(Xe,{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(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{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(Ie,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(fR,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx(Qt,{}),e.jsx(jR,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:d=>c({allowedFileTypes:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(E,{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(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function vR(){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 NR=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],wR=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 CR({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(se,{className:wR(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:NR.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Wc,{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 SR(){const[t,s]=h.useState({Initiator:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0},Approver:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0},Spectator:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0}}),a=()=>{X.success("Dashboard layout saved successfully")},r=(i,l,o)=>{s(c=>({...c,[i]:{...c[i],[l]:o}}))},n=["Initiator","Approver","Spectator"];return e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Dashboard Layout Configuration"}),e.jsx(ve,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsx(vR,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(CR,{role:i,kpis:t[i]||{},onKPIToggle:(l,o)=>r(i,l,o)},i))}),e.jsxs(E,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Ea,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}function AR({aiEnabled:t,onAiEnabledChange:s}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gh,{className:"w-5 h-5 text-re-green"}),e.jsx(me,{className:"text-base font-semibold",children:"Vertex AI Gemini Configuration"})]}),e.jsx(ve,{className:"text-sm",children:"Configure AI features. Model and region are configured via environment variables."})]}),e.jsx(ee,{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(ms,{checked:t,onCheckedChange:s})]})})]})}function TR({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ki,{className:"w-5 h-5 text-re-green"}),e.jsx(me,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(ve,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(ee,{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(ms,{checked:t,onCheckedChange:s})]})})})]})}function kR({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hh,{className:"w-5 h-5 text-re-green"}),e.jsx(me,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(ve,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Length"}),e.jsx(ke,{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 RR(){const[t,s]=h.useState(!0),[a,r]=h.useState(!1),[n,i]=h.useState({aiEnabled:!0,aiRemarkGeneration:!0,maxRemarkChars:2e3});h.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await ul("AI_CONFIGURATION"),m={};d.forEach(p=>{m[p.configKey]=p.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),X.error("Failed to load AI configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([Bs("AI_ENABLED",n.aiEnabled.toString()),Bs("AI_REMARK_GENERATION_ENABLED",n.aiRemarkGeneration.toString()),Bs("AI_MAX_REMARK_LENGTH",n.maxRemarkChars.toString())]),X.success("AI configuration saved successfully"),await l()}catch(p){console.error("Failed to save AI configuration:",p),X.error(((m=(d=p.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(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(Xe,{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(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{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(Ki,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(me,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(ve,{className:"text-sm text-gray-600",children:"Configure Vertex AI Gemini settings and enable/disable AI-powered features"})]})]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(AR,{aiEnabled:n.aiEnabled,onAiEnabledChange:d=>c({aiEnabled:d})}),e.jsx(Qt,{}),e.jsx(TR,{aiRemarkGeneration:n.aiRemarkGeneration,onRemarkGenerationChange:d=>c({aiRemarkGeneration:d})}),e.jsx(Qt,{}),e.jsx(kR,{maxRemarkChars:n.maxRemarkChars,onMaxRemarkCharsChange:d=>c({maxRemarkChars:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(E,{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(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const Dx=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function DR({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(te,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(Be,{value:t,onValueChange:a,children:[e.jsx(ze,{id:"spectator-permission",children:e.jsx(Ve,{placeholder:"Select permission"})}),e.jsx(He,{children:Dx.map(n=>e.jsx(Q,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(Be,{value:s,onValueChange:r,children:[e.jsx(ze,{id:"link-sharing-permission",children:e.jsx(Ve,{placeholder:"Select permission"})}),e.jsx(He,{children:Dx.map(n=>e.jsx(Q,{value:n,children:n},n))})]})]})]})}function FR({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(ms,{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(ms,{checked:s,onCheckedChange:r})]})]})}function IR(){const[t,s]=h.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{X.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Workflow Sharing Policy"}),e.jsx(ve,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(DR,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(Qt,{}),e.jsx(FR,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(E,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Ea,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function PR(){const{user:t}=cs(),[s,a]=h.useState(""),[r,n]=h.useState("sharing"),i=[{name:"Request Volume & Status",count:4,kpis:[{id:"total-requests",title:"Total Requests Created",description:"Count of all workflow requests created in a selected period.",value:5,change:12,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"open-requests",title:"Open Requests",description:"Number of workflows currently in progress with age.",value:3,change:-5,changeType:"down",period:"Today",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"approved-requests",title:"Approved Requests",description:"Requests fully approved and closed.",value:1,change:8,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"rejected-requests",title:"Rejected Requests",description:"Requests rejected at any approval stage.",value:1,period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"}]},{name:"TAT Efficiency",count:3,kpis:[{id:"avg-tat-compliance",title:"Average TAT Compliance %",description:"% of workflows completed within defined TAT vs breached ones at every level.",value:100,unit:"%",change:3,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200"},{id:"avg-approval-cycle",title:"Avg Approval Cycle Time (Days)",description:"Average total time from creation to closure.",value:5.2,unit:" days",change:-15,changeType:"down",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200",thresholdBreached:!0},{id:"delayed-workflows",title:"Delayed Workflows",description:"Requests currently breaching their TAT.",value:0,change:-2,changeType:"down",period:"Today",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200"}]},{name:"Approver Load",count:2,kpis:[{id:"pending-actions",title:"Pending Actions (My Queue)",description:"Requests currently awaiting user's approval with age.",value:3,period:"Today",visibleTo:["Management","Admin"],category:"Approver Load",bgColor:"bg-orange-50",borderColor:"border-orange-200"},{id:"approvals-completed",title:"Approvals Completed (Today/Week)",description:"Count of actions taken within a time frame.",value:0,change:22,changeType:"up",period:"Week",visibleTo:["Management","Admin"],category:"Approver Load",bgColor:"bg-orange-50",borderColor:"border-orange-200"}]},{name:"Engagement & Quality",count:2,kpis:[{id:"comments-worknotes",title:"Comments / Work Notes Added",description:"Measures collaboration activity.",value:8,change:18,changeType:"up",period:"Week",visibleTo:["Management","Admin"],category:"Engagement & Quality",bgColor:"bg-purple-50",borderColor:"border-purple-200"},{id:"attachments-uploaded",title:"Attachments Uploaded",description:"Number of documents added to workflows.",value:16,change:10,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Engagement & Quality",bgColor:"bg-purple-50",borderColor:"border-purple-200"}]},{name:"AI & Closure Insights",count:2,kpis:[{id:"avg-conclusion-length",title:"Avg Conclusion Remark Length",description:"Indicates depth of closure remarks (optional).",value:85,unit:" chars",change:5,changeType:"up",period:"Month",visibleTo:["Management","Admin"],category:"AI & Closure Insights",bgColor:"bg-pink-50",borderColor:"border-pink-200"},{id:"ai-summary-adoption",title:"AI Summary Adoption %",description:"How many closures used AI-generated text vs manual edits.",value:0,unit:"%",change:25,changeType:"up",period:"Month",visibleTo:["Management","Admin"],category:"AI & Closure Insights",bgColor:"bg-pink-50",borderColor:"border-pink-200"}]}],l=i.map(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 flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-re-black flex items-center gap-2",children:[e.jsx(ps,{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("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>X.info("COB&NDC – Coming soon"),children:"COB&NDC"}),e.jsxs(se,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(ps,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]})]}),e.jsx(Qt,{}),e.jsxs(ai,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(ri,{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(Mt,{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(Mt,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(Mt,{value:"users",className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Mt,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(st,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(Mt,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(_s,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(Mt,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(Mt,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(Mb,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(Mt,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(gh,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(Mt,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(an,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(Lt,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(Z,{children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(me,{children:"KPI Configuration"}),e.jsx(ve,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(se,{className:"bg-blue-50 text-blue-700",children:[o," / ",o," KPIs Active"]})]})}),e.jsxs(ee,{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(Cs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(ke,{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(Ot,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:d.name}),e.jsxs(se,{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(se,{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(Lb,{className:"w-3 h-3"}):e.jsx(Ob,{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(p=>e.jsx(se,{className:`${c(p)} text-xs px-1.5 py-0`,children:p},p))]}),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(Ze,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},m.id))})]},d.name))]})]})}),e.jsx(Lt,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(sR,{})}),e.jsx(Lt,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(oR,{})}),e.jsx(Lt,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(uR,{})}),e.jsx(Lt,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(gR,{})}),e.jsx(Lt,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(yR,{})}),e.jsx(Lt,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(SR,{})}),e.jsx(Lt,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(RR,{})}),e.jsx(Lt,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(IR,{})})]})]})}function ER(t){if(!t)return"–";try{const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}catch{return t}}function Fx(t){return t==null?"–":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}const eo={totalCreditNotes:0,totalAmount:0,activeDealersCount:0};function _R(){const t=ys(),[s,a]=h.useState([]),[r,n]=h.useState(eo),[i,l]=h.useState(!0),[o,c]=h.useState(""),d=h.useCallback(async p=>{try{l(!0);const x=await jy(p);a(x.creditNotes),n(x.summary??eo)}catch(x){console.error("[Form16CreditNotes] Failed to fetch:",x),X.error(x instanceof Error?x.message:"Failed to load credit notes"),a([]),n(eo)}finally{l(!1)}},[]);h.useEffect(()=>{d()},[d]);const m=h.useMemo(()=>{if(!o.trim())return s;const p=o.trim().toLowerCase();return s.filter(x=>{var u;return x.creditNoteNumber&&x.creditNoteNumber.toLowerCase().includes(p)||x.dealerName&&x.dealerName.toLowerCase().includes(p)||x.dealerCode&&x.dealerCode.toLowerCase().includes(p)||((u=x.submission)==null?void 0:u.form16aNumber)&&x.submission.form16aNumber.toLowerCase().includes(p)})},[s,o]);return e.jsx("div",{className:"space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full",children:e.jsxs("div",{className:"w-full min-w-0",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-2",children:"Credit Notes"}),e.jsx("p",{className:"text-sm text-gray-600",children:"View and manage all issued credit notes"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-6",children:[e.jsx(Z,{children:e.jsxs(oe,{className:"pb-3",children:[e.jsx(ve,{children:"Total Credit Notes Issued"}),e.jsx(me,{className:"text-3xl",children:i?"...":r.totalCreditNotes})]})}),e.jsx(Z,{children:e.jsxs(oe,{className:"pb-3",children:[e.jsx(ve,{children:"Total Credit Amount"}),e.jsx(me,{className:"text-3xl text-green-600",children:i?"...":Fx(r.totalAmount)})]})}),e.jsx(Z,{children:e.jsxs(oe,{className:"pb-3",children:[e.jsx(ve,{children:"Active Dealers"}),e.jsx(me,{className:"text-3xl",children:i?"...":r.activeDealersCount})]})})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"All Credit Notes"}),e.jsxs(ve,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"Search by credit note number, dealer name, or Form 16A number"}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Cs,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(ke,{type:"search",placeholder:"Search credit notes...",value:o,onChange:p=>c(p.target.value),className:"pl-9"})]})]})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{children:[e.jsx(Ee,{children:"Credit Note No."}),e.jsx(Ee,{children:"Dealer Name"}),e.jsx(Ee,{children:"Form 16A No."}),e.jsx(Ee,{children:"Amount"}),e.jsx(Ee,{children:"Issue Date"}),e.jsx(Ee,{children:"Status"}),e.jsx(Ee,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:i?e.jsx(ut,{children:e.jsxs(Te,{colSpan:7,className:"text-center py-12",children:[e.jsx(Xe,{className:"w-6 h-6 animate-spin mx-auto mb-2 text-teal-600"}),e.jsx("p",{className:"text-gray-500",children:"Loading credit notes..."})]})}):m.length===0?e.jsx(ut,{children:e.jsxs(Te,{colSpan:7,className:"text-center py-12 text-gray-500",children:[e.jsx(Pt,{className:"w-12 h-12 mx-auto mb-3 text-gray-400"}),e.jsx("p",{children:"No credit notes found"}),e.jsx("p",{className:"text-sm mt-1",children:o.trim()?"Try a different search.":"Credit notes will appear here once issued."})]})}):m.map(p=>{var x,u,g;return e.jsxs(ut,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(Te,{className:"font-medium",children:p.creditNoteNumber?p.creditNoteNumber.startsWith("CN")?p.creditNoteNumber:`CN #${p.creditNoteNumber}`:"–"}),e.jsx(Te,{children:p.dealerName??p.dealerCode??"–"}),e.jsx(Te,{children:((x=p.submission)==null?void 0:x.form16aNumber)??"–"}),e.jsx(Te,{children:Fx(p.amount)}),e.jsx(Te,{children:ER(p.issueDate)}),e.jsx(Te,{children:e.jsx(se,{className:((u=p.status)==null?void 0:u.toLowerCase())==="issued"||((g=p.status)==null?void 0:g.toLowerCase())==="completed"?"bg-green-100 text-green-800 border-green-200":"bg-gray-100 text-gray-700 border-gray-200",children:p.status??"–"})}),e.jsx(Te,{className:"text-right",children:e.jsx(E,{variant:"outline",size:"sm",onClick:()=>t(`/form16/credit-notes/${p.id}`),children:"View Details"})})]},p.id)})})]})})})]})]})})}function to(t){if(!t)return"–";try{const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}catch{return t}}function Ix(t){return t==null?"–":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function MR(){var g;const t=ys(),{id:s}=_a(),[a,r]=h.useState(null),[n,i]=h.useState(!0);h.useEffect(()=>{const f=s?parseInt(s,10):NaN;if(Number.isNaN(f)){i(!1);return}let b=!1;return Ny(f).then(j=>{b||r(j)}).catch(j=>{b||(X.error(j instanceof Error?j.message:"Failed to load credit note"),t("/form16/credit-notes"))}).finally(()=>{b||i(!1)}),()=>{b=!0}},[s,t]);const l=()=>{X.info("Resend to dealer – integration pending")},o=()=>{X.info("Download credit note – integration pending")};if(n)return e.jsx("div",{className:"min-h-screen bg-gray-50 p-4 md:p-6 flex items-center justify-center",children:e.jsx(Xe,{className:"w-8 h-8 animate-spin text-teal-600"})});if(!a)return null;const{creditNote:c,dealerName:d,dealerEmail:m,dealerContact:p,dealerCreditNotes:x}=a,u=c.creditNoteNumber?c.creditNoteNumber.startsWith("CN")?c.creditNoteNumber:`CN #${c.creditNoteNumber}`:"–";return e.jsx("div",{className:"space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full",children:e.jsxs("div",{className:"w-full min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[e.jsxs(E,{variant:"ghost",size:"sm",onClick:()=>t("/form16/credit-notes"),className:"text-gray-600 hover:text-gray-900",children:[e.jsx(ws,{className:"w-4 h-4 mr-2"}),"Back to Credit Notes"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:l,children:[e.jsx(ba,{className:"w-4 h-4 mr-2"}),"Resend to Dealer"]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:o,children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Download Credit Note"]})]})]}),e.jsx(Z,{className:"mb-6",children:e.jsxs(ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-1",children:[e.jsx("span",{className:"text-xl font-semibold text-gray-900",children:u}),e.jsx(se,{className:"bg-green-100 text-green-800 border-green-200",children:c.status??"Issued"})]}),e.jsxs("p",{className:"text-sm text-gray-500",children:["Issued on ",to(c.issueDate)]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Credit Amount"}),e.jsx("p",{className:"text-2xl font-semibold text-green-600",children:Ix(c.amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mt-6 pt-6 border-t border-gray-100",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide",children:"Dealer Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:d||"–"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide",children:"Form 16A Number"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:((g=c.submission)==null?void 0:g.form16aNumber)??"–"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide",children:"Email"}),e.jsx("p",{className:"text-sm text-gray-700",children:m||"–"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide",children:"Contact"}),e.jsx("p",{className:"text-sm text-gray-700",children:p||"–"})]})]})]})}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Dealer Transaction History"}),e.jsxs(ve,{children:["All credit notes issued to ",d||"this dealer"]})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{children:[e.jsx(Ee,{children:"Submission Date"}),e.jsx(Ee,{children:"Form 16A No."}),e.jsx(Ee,{children:"Amount"}),e.jsx(Ee,{children:"Credit Note Issued"}),e.jsx(Ee,{children:"Credit Note No."}),e.jsx(Ee,{children:"CN Issue Date"}),e.jsx(Ee,{children:"Status"})]})}),e.jsx(da,{children:x.length===0?e.jsx(ut,{children:e.jsx(Te,{colSpan:7,className:"text-center py-8 text-gray-500",children:"No other credit notes for this dealer"})}):x.map(f=>{var b,j;return e.jsxs(ut,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(Te,{children:to(f.submittedDate)}),e.jsx(Te,{children:f.form16aNumber??"–"}),e.jsx(Te,{children:Ix(f.amount)}),e.jsx(Te,{children:e.jsx(se,{className:"bg-green-100 text-green-800 border-green-200",children:"Yes"})}),e.jsx(Te,{children:f.creditNoteNumber?f.creditNoteNumber.startsWith("CN")?f.creditNoteNumber:`CN #${f.creditNoteNumber}`:"–"}),e.jsx(Te,{children:to(f.issueDate)}),e.jsx(Te,{children:e.jsx(se,{className:((b=f.status)==null?void 0:b.toLowerCase())==="withdrawn"?"bg-red-50 text-red-700 border-red-200":"bg-green-100 text-green-800 border-green-200",children:((j=f.status)==null?void 0:j.toLowerCase())==="withdrawn"?"Withdrawn":"Completed"})})]},f.id)})})]})})})]})]})})}function LR({state:t="idle",onFileSelect:s,errorMessage:a,className:r="",disabled:n=!1}){const[i,l]=h.useState(!1),o=i&&!n?"dragging":t,c=f=>{f.preventDefault(),!n&&l(!0)},d=()=>{l(!1)},m=f=>{if(f.preventDefault(),l(!1),n)return;const j=f.dataTransfer.files[0];j&&s(j)},p=f=>{const b=f.target.files,j=b==null?void 0:b[0];j&&s(j)},x={idle:{icon:js,text:"Drop PDF here or click to browse",subtext:"Only .pdf | Form 16A certificate",bgColor:"bg-white hover:bg-gray-50",borderColor:"border-gray-300 border-dashed",iconColor:"text-gray-400"},dragging:{icon:js,text:"Release to upload",subtext:"Drop your Form 16A PDF here",bgColor:"bg-blue-50",borderColor:"border-blue-400 border-dashed",iconColor:"text-blue-500"},validating:{icon:Xe,text:"Validating Form 16A...",subtext:"Please wait",bgColor:"bg-blue-50",borderColor:"border-blue-300",iconColor:"text-blue-600 animate-spin"},extracting:{icon:Xe,text:"Extracting data from Form 16A...",subtext:"Using Google Gemini (regex fallback if needed)",bgColor:"bg-blue-50",borderColor:"border-blue-300",iconColor:"text-blue-600 animate-spin"},success:{icon:us,text:"Form 16A uploaded successfully",subtext:"Document ready for submission",bgColor:"bg-green-50",borderColor:"border-green-300",iconColor:"text-green-600"},error:{icon:Ze,text:"Upload failed",subtext:a||"Please try again",bgColor:"bg-red-50",borderColor:"border-red-300",iconColor:"text-red-600"}},u=x[o]??x.idle,g=u.icon;return e.jsx("div",{className:r,children:e.jsxs("label",{className:`flex flex-col items-center justify-center w-full min-h-[200px] border-2 rounded-lg transition-all ${(u==null?void 0:u.bgColor)??""} ${(u==null?void 0:u.borderColor)??""} ${!n&&t==="idle"?"cursor-pointer":"cursor-default"}`,onDragOver:c,onDragLeave:d,onDrop:m,children:[e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 px-4",children:[e.jsx(g,{className:`w-12 h-12 mb-4 ${(u==null?void 0:u.iconColor)??""}`}),e.jsx("p",{className:"mb-2 text-gray-700 font-medium",children:(u==null?void 0:u.text)??""}),e.jsx("p",{className:"text-sm text-gray-500",children:(u==null?void 0:u.subtext)??""})]}),o==="idle"&&!n&&e.jsx("input",{type:"file",className:"hidden",accept:".pdf,application/pdf",onChange:p})]})})}function OR(t){if(!t)return"—";try{return new Date(t).toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}catch{return String(t)}}function Ks(t){return t==null||t===""?e.jsx("span",{className:"text-gray-500 italic",children:"N/A"}):typeof t=="number"?t.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2}):String(t)}function $R(t){if(!t)return e.jsx("span",{className:"text-gray-500 italic",children:"N/A"});const s=t.deductorName??t.nameAndAddressOfDeductor??null,a=t.deductorAddress??null,r=t.deductorPhone??null,n=t.deductorEmail??null,i=e.jsx("span",{className:"text-gray-500 italic",children:"N/A"});return e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-gray-500",children:"Name: "}),s??i]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-gray-500",children:"Address: "}),a??i]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-gray-500",children:"Number: "}),r??i]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-gray-500",children:"Email: "}),n??i]})]})}function UR(){const t=ys(),[s,a]=h.useState([]),[r,n]=h.useState(!0),[i,l]=h.useState(""),[o,c]=h.useState(""),[d,m]=h.useState(null),[p,x]=h.useState("idle"),[u,g]=h.useState(null),[f,b]=h.useState(null),[j,y]=h.useState(!1),[w,N]=h.useState(""),[S,A]=h.useState(""),[_,D]=h.useState(null),[R,v]=h.useState(!1);h.useEffect(()=>{let I=!1;return zh().then(T=>{I||a(Array.isArray(T)?T:[])}).catch(()=>{I||a([])}).finally(()=>{I||n(!1)}),()=>{I=!0}},[]);const P=h.useCallback(()=>{if(!d)return;const I=URL.createObjectURL(d);D(I),v(!0)},[d]),C=h.useCallback(()=>{v(!1),_&&(URL.revokeObjectURL(_),D(null))},[_]),V=h.useCallback(async I=>{if(!I.name.toLowerCase().endsWith(".pdf")){X.error("Please upload a PDF file");return}m(I),g(null),b(null),x("extracting");try{X.loading("Extracting data with Google Gemini...",{id:"form16-ocr"});const T=await wy(I);g(T.extractedData),b(T.ocrProvider||null),N(T.extractedData.tanNumber??T.extractedData.tanOfDeductor??""),A(T.extractedData.deductorName??T.extractedData.nameAndAddressOfDeductor??""),l(T.extractedData.financialYear??""),c(T.extractedData.quarter??""),x("success"),X.success(T.ocrProvider?`Data extracted via ${T.ocrProvider}`:"Data extracted",{id:"form16-ocr"})}catch(T){x("error");const k=T instanceof Error?T.message:"Failed to extract data from PDF";X.error(k,{id:"form16-ocr"})}},[]),F=async()=>{var M;if(!i||!o){X.error("Financial year and quarter could not be extracted from the PDF. Please ensure you upload a valid Form 16A certificate.");return}if(!d){X.error("Please upload Form 16A PDF");return}const I=((u==null?void 0:u.form16aNumber)??"").trim()||`F16-${i}-${o}-${Date.now()}`,T=(u==null?void 0:u.tdsAmount)??(u==null?void 0:u.totalTaxDeducted)??0,k=(u==null?void 0:u.totalAmount)??(u==null?void 0:u.totalAmountPaid)??0,z=(w||((u==null?void 0:u.tanNumber)??(u==null?void 0:u.tanOfDeductor)??"")).trim(),L=(S||((u==null?void 0:u.deductorName)??(u==null?void 0:u.nameAndAddressOfDeductor)??"")).trim();if(!z||!L){X.error("TAN and Deductor name are required. Please enter or correct them below.");return}y(!0);try{const U=await Cy({financialYear:i,quarter:o,form16aNumber:I,tdsAmount:Number(T)||0,totalAmount:Number(k)||0,tanNumber:z,deductorName:L,file:d,extractedData:u??void 0}),B=U.validationStatus,W=B==="success"?"success":B==="duplicate"?"duplicate":B==="failed"?"mismatch":"error",J=W==="duplicate"?"A credit note has already been issued for this financial year and quarter. This submission is recorded as a new version.":void 0;X.success(W==="success"?"Form 16A matched with 26AS. Credit note generated.":"Form 16A submitted successfully"),t("/form16/submit/result",{state:{status:W,requestId:U.requestId,requestNumber:U.requestNumber,creditNoteNumber:U.creditNoteNumber??void 0,message:J}})}catch(U){const B=U&&typeof U=="object"&&"response"in U?U.response:void 0,W=((M=B==null?void 0:B.data)==null?void 0:M.message)??(U instanceof Error?U.message:"Failed to submit");(B==null?void 0:B.status)===400&&typeof W=="string"&&(W.toLowerCase().includes("duplicate")||W.toLowerCase().includes("already exist"))?t("/form16/submit/result",{state:{status:"duplicate",requestId:"",message:W}}):X.error(String(W))}finally{y(!1)}},$=!!d;return e.jsx("div",{className:"min-h-[80vh] w-full bg-gray-50 p-4 md:p-6",children:e.jsxs("div",{className:"w-full max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{type:"button",variant:"ghost",size:"icon",onClick:()=>t(-1),"aria-label":"Go back",children:e.jsx(ws,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Submit Form 16A"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Upload your TDS certificate for credit reconciliation"})]})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Quarters Pending Submission"}),e.jsx(ve,{children:"These quarters don't have completed Form 16A submissions. Please submit Form 16A for these quarters."})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{className:"bg-gray-50",children:[e.jsx(Ee,{children:"Dealer Name"}),e.jsx(Ee,{children:"Financial Year"}),e.jsx(Ee,{children:"Quarter"}),e.jsx(Ee,{children:"Version"}),e.jsx(Ee,{children:"Status"}),e.jsx(Ee,{children:"26AS start date"}),e.jsx(Ee,{children:"Days Status"}),e.jsx(Ee,{className:"text-right",children:"Action"})]})}),e.jsx(da,{children:r?e.jsx(ut,{children:e.jsxs(Te,{colSpan:8,className:"text-center py-12 text-gray-500",children:[e.jsx(Xe,{className:"w-8 h-8 animate-spin mx-auto mb-2"}),e.jsx("p",{children:"Loading..."})]})}):s.length===0?e.jsx(ut,{children:e.jsx(Te,{colSpan:8,className:"text-center py-12 text-gray-500",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Ie,{className:"w-12 h-12 text-gray-300"}),e.jsx("p",{children:"No pending submissions. All quarters are complete."})]})})}):s.map(I=>e.jsxs(ut,{className:"hover:bg-gray-50",children:[e.jsx(Te,{className:"text-sm text-gray-900",children:I.dealer_name??"Your submission"}),e.jsx(Te,{children:e.jsxs("span",{className:"text-sm text-gray-900",children:["FY ",I.financial_year]})}),e.jsx(Te,{children:e.jsx(se,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:I.quarter})}),e.jsx(Te,{children:e.jsx(se,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:I.has_submission?"V1":"—"})}),e.jsx(Te,{children:e.jsx(se,{variant:"outline",className:I.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":I.has_submission?"bg-slate-50 text-slate-600 border-slate-200":"bg-gray-100 text-gray-600 border-gray-200",children:I.latest_submission_status==="failed"?"Failed":I.has_submission?"Under review":"Not Submitted"})}),e.jsx(Te,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-700",children:OR(I.twenty_six_as_start_date??I.audit_start_date)})]})}),e.jsx(Te,{children:I.days_since_26as_uploaded!=null&&I.days_since_26as_uploaded>=0?e.jsxs("span",{className:"text-sm font-medium text-gray-700",children:["due from ",I.days_since_26as_uploaded," days"]}):e.jsx("span",{className:"text-sm text-gray-500",children:"—"})}),e.jsx(Te,{className:"text-right",children:e.jsx(E,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>t("/form16/submit"),children:"Submit Now"})})]},`${I.financial_year}|${I.quarter}`))})]})})})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Upload Form 16A Certificate"}),e.jsx(ve,{children:"PDF only. Financial year and quarter are taken from the certificate via OCR; no need to enter them manually."})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsx(LR,{state:p==="extracting"?"extracting":p==="error"?"error":p==="success"?"success":"idle",onFileSelect:V,disabled:p==="extracting"}),d&&e.jsxs("div",{className:`flex items-center justify-between p-3 rounded-lg border ${p==="extracting"?"bg-blue-50 border-blue-200":p==="error"?"bg-red-50 border-red-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[p==="extracting"?e.jsx(Xe,{className:"w-5 h-5 text-blue-600 shrink-0 animate-spin"}):p==="error"?e.jsx(Ze,{className:"w-5 h-5 text-red-600 shrink-0"}):e.jsx(us,{className:"w-5 h-5 text-green-600 shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:d.name}),e.jsxs("span",{className:"text-xs text-gray-500",children:[(d.size/1024).toFixed(1)," KB",p==="extracting"&&" • Extracting...",p==="error"&&" • Extraction failed",p==="success"&&u&&" • Data extracted"]})]}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>{m(null),g(null),b(null),N(""),A(""),l(""),c(""),x("idle"),C()},disabled:p==="extracting",children:"Remove"})]}),d&&e.jsxs(E,{type:"button",variant:"outline",className:"w-full",onClick:P,disabled:p==="extracting",children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),"View Uploaded Form 16A"]})]})]}),e.jsxs(Z,{className:"border-blue-200 bg-blue-50",children:[e.jsx(oe,{children:e.jsxs(me,{className:"text-blue-900 flex items-center gap-2",children:[e.jsx(Er,{className:"w-5 h-5"}),"Important Notes"]})}),e.jsx(ee,{className:"space-y-2 text-sm text-blue-800",children:e.jsxs("ul",{className:"list-disc list-inside space-y-1 ml-2",children:[e.jsx("li",{children:"Ensure the Form 16A certificate is issued by the correct deductor (TAN and name must match)"}),e.jsx("li",{children:"The certificate should match your Form 26AS data from the Income Tax portal"}),e.jsx("li",{children:"If you submit multiple versions for the same quarter, only the latest approved version will be processed"}),e.jsx("li",{children:"You can track all submissions in the Requests section (filter by Form 16)"}),e.jsx("li",{children:"Processing typically takes 2–3 business days after validation"})]})})]}),$&&e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5 text-blue-600"}),e.jsx(me,{children:"Form 16A Extracted Details"})]}),e.jsx(ve,{children:p==="extracting"?"Extracting with Google Gemini (or regex fallback)...":u?f?`Extracted via ${f}. Unmapped fields show N/A.`:"Certificate details extracted from uploaded document.":p==="error"?"Extraction failed. You can remove the file and try again.":"Waiting for extraction..."})]}),e.jsx(ee,{className:"space-y-6",children:p==="extracting"?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(Xe,{className:"w-8 h-8 text-blue-600 animate-spin mr-3"}),e.jsx("p",{className:"text-gray-600",children:"Extracting data..."})]}):p==="error"?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(Ze,{className:"w-8 h-8 text-amber-600 mr-3 shrink-0"}),e.jsx("p",{className:"text-gray-600",children:"Data extraction failed. Please remove the file and try uploading again."})]}):u?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Deductor details"}),e.jsx("div",{className:"text-sm mt-1 font-medium space-y-0.5",children:$R(u)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"TAN of the deductor"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:Ks(u.tanOfDeductor??u.tanNumber)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Total (Rs)"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:(u.totalAmountPaid??u.totalAmount)!=null?`₹ ${Ks(u.totalAmountPaid??u.totalAmount)}`:Ks(null)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Total tax deducted"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:(u.totalTaxDeducted??u.tdsAmount)!=null?`₹ ${Ks(u.totalTaxDeducted??u.tdsAmount)}`:Ks(null)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Total TDS deposited"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:(u.totalTdsDeposited??u.tdsAmount)!=null?`₹ ${Ks(u.totalTdsDeposited??u.tdsAmount)}`:Ks(null)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Nature of payment"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:Ks(u.natureOfPayment)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Transaction date"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:Ks(u.transactionDate)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Status of matching with OLTAS"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:Ks(u.statusOfMatchingOltas)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Date of booking"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:Ks(u.dateOfBooking)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Form 16 Assessment Year"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:Ks(u.assessmentYear)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Quarter"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:Ks(u.quarter)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Certificate No / Form 16A No"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:Ks(u.form16aNumber)})]})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsx("p",{className:"text-sm font-medium text-gray-700",children:"Correct if needed (required for submit)"}),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(te,{htmlFor:"form16-tan",children:"TAN of deductor *"}),e.jsx(ke,{id:"form16-tan",value:w,onChange:I=>N(I.target.value),placeholder:"e.g. BLRH07660C",maxLength:10})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(te,{htmlFor:"form16-deductor",children:"Deductor name *"}),e.jsx(ke,{id:"form16-deductor",value:S,onChange:I=>A(I.target.value),placeholder:"Name and address of deductor"})]})]})]}),e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-green-50 border border-green-200 rounded-lg",children:[e.jsx(us,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-green-800",children:[e.jsx("p",{className:"font-medium",children:"Data extracted"}),e.jsx("p",{className:"mt-1",children:"These values will be validated on submit. You can correct TAN and Deductor name above if needed."})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(E,{type:"button",variant:"outline",onClick:()=>t(-1),disabled:j,children:"Cancel"}),e.jsxs(E,{type:"button",className:"bg-re-green hover:bg-re-green/90",onClick:F,disabled:!i||!o||j,children:[j?e.jsx(Xe,{className:"w-4 h-4 animate-spin mr-2"}):null,"Submit Form 16A"]})]})]}):null})]}),e.jsx(jt,{open:R,onOpenChange:I=>!I&&C(),children:e.jsxs(xt,{className:"max-w-4xl max-h-[90vh] flex flex-col","aria-describedby":"form16-pdf-description",children:[e.jsxs(yt,{children:[e.jsx(ht,{children:"Form 16A Certificate"}),e.jsx(Ut,{id:"form16-pdf-description",className:"sr-only",children:"Preview of the uploaded Form 16A PDF certificate"})]}),e.jsx("div",{className:"flex-1 min-h-0 rounded border bg-gray-100",children:_&&e.jsx("iframe",{title:"Form 16A PDF",src:_,className:"w-full h-[70vh] rounded"})})]})})]})})}const BR={success:"bg-teal-100 text-teal-800 border-teal-200",failed:"bg-red-100 text-red-800 border-red-200",pending:"bg-gray-100 text-gray-700 border-gray-200"};function VR({variant:t,label:s,showIcon:a=!0}){const r=t==="success"?us:t==="failed"?St:st;return e.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm font-medium ${BR[t]}`,children:[a&&e.jsx(r,{className:"h-4 w-4 shrink-0"}),s]})}function zR({step:t,label:s,state:a,isLast:r}){const n=a==="completed"?us:a==="failed"?St:Bo,i=a==="completed"?"text-teal-600 bg-teal-100":a==="failed"?"text-red-600 bg-red-100":"text-gray-400 bg-gray-100";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col items-center flex-1 min-w-0",children:[e.jsx("div",{className:`flex items-center justify-center w-8 h-8 rounded-full shrink-0 ${i}`,children:a==="pending"?e.jsx("span",{className:"text-xs font-medium text-gray-500",children:t}):e.jsx(n,{className:"w-4 h-4"})}),e.jsx("p",{className:"text-xs font-medium text-gray-600 mt-2 text-center max-w-[80px] truncate",title:s,children:s})]}),!r&&e.jsx("div",{className:"w-8 sm:w-12 h-0.5 bg-gray-200 self-start mt-4 shrink-0","aria-hidden":!0})]})}function HR({status:t,requestId:s,creditNoteNumber:a,message:r,onComplete:n,onResubmit:i,onViewRequest:l}){const o=t==="success",c=t==="mismatch",d=t==="duplicate",m=t==="error";h.useEffect(()=>{if(!o)return;const x=setTimeout(n,5e3);return()=>clearTimeout(x)},[o,n]);const p=[{label:"Form 16A Uploaded",state:d?"failed":"completed"},{label:"Validation",state:d?"failed":m?"pending":"completed"},{label:"26AS Matching",state:o?"completed":c||d?"failed":"pending"},{label:"Credit Note",state:o?"completed":"pending"}];return e.jsx("div",{className:"min-h-[calc(100vh-10rem)] flex items-center justify-center",children:e.jsx(Ht.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{duration:.4},className:"w-full max-w-2xl",children:e.jsx(Z,{className:o?"border-teal-200 shadow-xl":d?"border-red-300 shadow-xl bg-red-50/50":c?"border-amber-200 shadow-xl bg-amber-50/30":"border-gray-200 shadow-xl bg-gray-50/30",children:e.jsxs(ee,{className:"pt-12 pb-10",children:[e.jsx(Ht.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{delay:.15},className:"flex justify-center mb-6",children:e.jsx(VR,{variant:o?"success":d?"failed":m?"pending":"failed",label:o?"Matched & Credit Note Generated":d?"Duplicate Submission":c?"Value Mismatch":"Request Received",showIcon:!0})}),e.jsx(Ht.div,{initial:{scale:0},animate:{scale:1},transition:{delay:.2,type:"spring",stiffness:200},className:"flex justify-center mb-6",children:e.jsx("div",{className:`w-20 h-20 rounded-full flex items-center justify-center ${o?"bg-teal-100":d?"bg-red-100":m?"bg-gray-100":"bg-amber-100"}`,children:o?e.jsx(us,{className:"w-12 h-12 text-teal-600"}):d?e.jsx($b,{className:"w-12 h-12 text-red-600"}):m?e.jsx(Ze,{className:"w-12 h-12 text-gray-500"}):e.jsx(Ze,{className:"w-12 h-12 text-amber-600"})})}),e.jsx(Ht.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.3},className:"text-center mb-6",children:o?e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-gray-900 mb-2",children:"Request Submitted Successfully"}),e.jsx("p",{className:"text-gray-700 font-medium text-teal-800",children:"Details have matched and credit note is generated."}),e.jsx("p",{className:"text-gray-600 text-sm mt-1",children:"Your Form 16A data matched with 26AS records. Credit note has been generated."})]}):d?e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-gray-900 mb-2 text-red-700 font-semibold",children:"Duplicate Submission"}),e.jsx("p",{className:"text-gray-900 font-medium",children:"This Form 16A has already been submitted for the same quarter and financial year."}),e.jsx("p",{className:"text-gray-700 text-sm mt-1",children:"A credit note may already have been issued. Please check your Closed Requests or Credit Notes."}),r&&e.jsxs("div",{className:"mt-3 p-3 bg-red-50 border-2 border-red-200 rounded-md",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 mb-1",children:"Duplicate submission — not allowed"}),e.jsx("p",{className:"text-sm text-gray-900 whitespace-pre-wrap",children:r})]})]}):c?e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-gray-900 mb-2",children:"Value Mismatch"}),e.jsx("p",{className:"text-gray-700 font-medium text-amber-800",children:"Resubmit the form carefully."}),e.jsx("p",{className:"text-gray-600 text-sm mt-1",children:"Form 16A details did not match with 26AS data. Please verify the certificate and resubmit with correct details."}),r&&e.jsxs("div",{className:"mt-3 p-3 bg-amber-50 border border-amber-200 rounded-md",children:[e.jsx("p",{className:"text-sm font-semibold text-amber-900 mb-1",children:"Validation Error:"}),e.jsx("p",{className:"text-sm text-amber-800 whitespace-pre-wrap",children:r})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-gray-900 mb-2",children:"Request Submitted"}),e.jsx("p",{className:"text-gray-700 font-medium text-gray-800",children:"Your request has been received and is being processed."}),e.jsx("p",{className:"text-gray-600 text-sm mt-1",children:"If there was an issue, you can try again or contact support."}),r&&e.jsx("p",{className:"text-sm text-gray-600 mt-2 italic",children:r})]})}),e.jsxs(Ht.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.4},className:`rounded-lg p-4 mb-6 text-center ${o?"bg-teal-50 border border-teal-200":d?"bg-red-50 border-2 border-red-200":"bg-white border border-amber-200"}`,children:[e.jsx("p",{className:`text-sm mb-1 ${d?"text-red-700":"text-gray-600"}`,children:"Request ID"}),e.jsx("p",{className:`font-mono tracking-wide ${d?"text-red-800 font-semibold":"text-gray-900"}`,children:s||"—"}),o&&a&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-gray-600 mt-3 mb-1",children:"Credit Note Number"}),e.jsx("p",{className:"text-gray-900 font-mono font-medium text-teal-700",children:a})]})]}),e.jsxs(Ht.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.5},className:"mb-8",children:[e.jsx("p",{className:"text-sm text-gray-600 mb-4 text-center",children:"Process flow"}),e.jsx("div",{className:"flex items-center justify-center gap-0",children:p.map((x,u)=>e.jsx(zR,{step:u+1,label:x.label,state:x.state,isLast:u===p.length-1},u))})]}),e.jsx(Ht.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.6},className:"flex flex-col sm:flex-row items-center justify-center gap-3",children:o?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-gray-500 mb-2 sm:mb-0 sm:mr-2",children:"Redirecting to My Requests in a moment..."}),e.jsx(E,{onClick:n,variant:"outline",className:"border-teal-300 text-teal-700",children:"Back to My Requests"})]}):e.jsxs(e.Fragment,{children:[m&&l&&e.jsx(E,{onClick:l,className:"bg-teal-600 hover:bg-teal-700",children:"View Request"}),i&&(c||d||m)&&e.jsx(E,{onClick:i,className:d?"bg-red-600 hover:bg-red-700":c?"bg-amber-600 hover:bg-amber-700":"bg-gray-600 hover:bg-gray-700",children:d?"Back to New Submission":c?"Resubmit Form 16A":"Try Again"}),e.jsx(E,{onClick:n,variant:"outline",children:"Back to My Requests"})]})})]})})})})}const Cn="form16_submission_result";function WR(){const t=ys(),a=zb().state,r=(()=>{try{const d=sessionStorage.getItem(Cn);return d?JSON.parse(d):null}catch{return null}})(),n=a!=null&&a.status||a!=null&&a.requestId?a:r,i=!!(n!=null&&n.status);h.useEffect(()=>{i&&sessionStorage.setItem(Cn,JSON.stringify(n))},[i,n]);const l=h.useCallback(()=>{sessionStorage.removeItem(Cn),t("/my-requests",{replace:!0})},[t]),o=h.useCallback(()=>{sessionStorage.removeItem(Cn),t("/form16/submit",{replace:!0})},[t]),c=h.useCallback(()=>{n!=null&&n.requestNumber&&(sessionStorage.removeItem(Cn),t(`/request/${n.requestNumber}`,{replace:!0}))},[t,n==null?void 0:n.requestNumber]);return i?e.jsx(HR,{status:n.status,requestId:n.requestNumber??n.requestId,creditNoteNumber:n.creditNoteNumber,message:n.message,onComplete:l,onResubmit:o,onViewRequest:n.requestNumber?c:void 0}):(t("/form16/submit",{replace:!0}),null)}const Sn=50,GR=["Q1","Q2","Q3","Q4"],YR=[{value:"194A",label:"194A - Interest"},{value:"194C",label:"194C - Contractor"},{value:"194J",label:"194J - Professional"},{value:"194H",label:"194H - Commission"},{value:"194Q",label:"194Q"},{value:"206CH",label:"206CH"}];function Px(t){if(!t)return"–";try{const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"})}catch{return t}}function hi(t){return t==null?"–":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function KR(){const t=new Date().getFullYear(),s=[];for(let a=0;a<6;a++){const r=t-a,n=(r+1).toString().slice(-2);s.push(`${r}-${n}`)}return s}function QR(t){switch((t||"").trim().toUpperCase().slice(0,1)){case"F":return e.jsx(se,{className:"bg-green-100 text-green-700 border-green-300",children:"F"});case"O":return e.jsx(se,{className:"bg-orange-100 text-orange-700 border-orange-300",children:"O"});case"M":return e.jsx(se,{className:"bg-blue-100 text-blue-700 border-blue-300",children:"M"});case"U":return e.jsx(se,{className:"bg-red-100 text-red-700 border-red-300",children:"U"});case"P":return e.jsx(se,{className:"bg-amber-100 text-amber-700 border-amber-300",children:"P"});default:return t?e.jsx(se,{variant:"secondary",children:t}):null}}function XR(){const[t,s]=h.useState(!1),[a,r]=h.useState({assessmentYear:"all",quarter:"all",section:"all",deductor:"",status:"all"}),[n,i]=h.useState(""),l=h.useRef(null),[o,c]=h.useState(!1),[d,m]=h.useState(!1),[p,x]=h.useState(0),[u,g]=h.useState(0),[f,b]=h.useState(null),j=h.useRef(null),y=h.useRef(null),[w,N]=h.useState([]),[S,A]=h.useState(0),[_,D]=h.useState({totalRecords:0,booked:0,notBooked:0,pending:0,totalTaxDeducted:0}),[R,v]=h.useState(!0),[P,C]=h.useState(0),[V,F]=h.useState([]),[$,I]=h.useState(!1),T=KR(),k=h.useCallback(async()=>{try{I(!0);const K=await Ay(50);F(K)}catch(K){console.error("[Form16_26AS] upload history",K),F([])}finally{I(!1)}},[]),z=h.useCallback(async(K=0)=>{try{v(!0);const ae={limit:Sn,offset:K*Sn};a.assessmentYear!=="all"&&(ae.financialYear=a.assessmentYear),a.quarter!=="all"&&(ae.quarter=a.quarter),a.section!=="all"&&(ae.sectionCode=a.section),a.deductor.trim()&&(ae.search=a.deductor.trim()),a.status!=="all"&&(ae.status=a.status);const Ne=await Sy(ae);N(Ne.entries),A(Ne.total),D(Ne.summary),C(K)}catch(ae){console.error("[Form16_26AS]",ae),X.error(ae instanceof Error?ae.message:"Failed to load 26AS entries"),N([]),A(0),D({totalRecords:0,booked:0,notBooked:0,pending:0,totalTaxDeducted:0})}finally{v(!1)}},[a.assessmentYear,a.quarter,a.section,a.deductor,a.status]);h.useEffect(()=>{z(0)},[z]),h.useEffect(()=>{k()},[k]),h.useEffect(()=>(l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{r(K=>({...K,deductor:n.trim()}))},300),()=>{l.current&&clearTimeout(l.current)}),[n]),h.useEffect(()=>()=>{y.current&&(clearInterval(y.current),y.current=null)},[]);const L=K=>{var Ne;const ae=(Ne=K.target.files)==null?void 0:Ne[0];if(ae){if(ae.size>50*1024*1024){X.error("File size must be less than 50MB");return}if(!ae.name.toLowerCase().endsWith(".txt")){X.error("Only .txt files are supported");return}b(ae)}},M=async()=>{var K,ae;if(!f){X.error("Please select a file");return}m(!0),x(0),g(0),y.current&&(clearInterval(y.current),y.current=null);try{const Ne=await ky(f,Se=>{if(x(Se),Se>=100&&!y.current){g(0);let Ge=0;y.current=setInterval(()=>{Ge+=1,g(Je=>Math.min(99,Je+4+Math.floor(Ge/3)))},300)}});y.current&&(clearInterval(y.current),y.current=null),g(100),Ne.imported>0?(X.success(`Successfully imported ${Ne.imported} entries.${(K=Ne.errors)!=null&&K.length?` ${Ne.errors.length} warnings.`:""}`),c(!1),b(null),j.current&&(j.current.value=""),z(0),k()):(ae=Ne.errors)!=null&&ae.length&&X.error(Ne.errors[0]||"Upload failed")}catch(Ne){y.current&&(clearInterval(y.current),y.current=null),X.error(Ne instanceof Error?Ne.message:"Upload failed")}finally{m(!1),x(0),g(0)}},U=()=>{r({assessmentYear:"all",quarter:"all",section:"all",deductor:"",status:"all"}),i("")},B=a.assessmentYear!=="all"||a.quarter!=="all"||a.section!=="all"||a.deductor!==""||a.status!=="all",W=Math.max(1,Math.ceil(S/Sn)),J=P>0,O=P<W-1,H=Math.max(0,Math.min(P-4,W-9)),Y=Math.min(W-1,H+8),re=Array.from({length:Y-H+1},(K,ae)=>H+ae);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:"w-full max-w-[98vw] xl:max-w-[1920px] mx-auto space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-1",children:"Form 26AS - TDS Data"}),e.jsx("p",{className:"text-gray-600 text-sm",children:"View and manage TDS deduction records from Form 26AS"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[180px] max-w-[280px]",children:[e.jsx(Cs,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(ke,{placeholder:"Search...",value:n,onChange:K=>i(K.target.value),className:"pl-9 h-9"})]}),e.jsxs(E,{onClick:()=>c(!0),className:"gap-2 bg-teal-600 hover:bg-teal-700 text-white",children:[e.jsx(js,{className:"w-4 h-4"}),"Upload 26AS File"]}),e.jsxs(E,{variant:"outline",onClick:()=>s(!t),className:"gap-2",children:[e.jsx(Pa,{className:"w-4 h-4"}),"Filters",B&&e.jsx(se,{className:"ml-1 bg-teal-600 hover:bg-teal-700 text-white",children:[a.assessmentYear,a.quarter,a.section,a.deductor,a.status].filter(K=>K!==""&&K!=="all").length}),t?e.jsx(Wi,{className:"w-4 h-4"}):e.jsx(rn,{className:"w-4 h-4"})]})]})]}),e.jsx(jt,{open:o,onOpenChange:c,children:e.jsxs(xt,{className:"max-w-md",children:[e.jsxs(yt,{children:[e.jsxs(ht,{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-5 h-5"}),"Upload 26AS Data File"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a 26AS text file (.txt) to import TDS data. Large files will be processed in batches."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"file-upload",children:"Select 26AS File"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("input",{ref:j,id:"file-upload",type:"file",accept:".txt",onChange:L,disabled:d,className:"hidden"}),e.jsxs(E,{variant:"outline",onClick:()=>{var K;return(K=j.current)==null?void 0:K.click()},disabled:d,className:"gap-2",children:[e.jsx(Ie,{className:"w-4 h-4"}),"Choose File"]}),f&&e.jsxs("span",{className:"text-sm text-gray-700 truncate",children:[f.name," (",(f.size/1024/1024).toFixed(2)," MB)"]})]})]}),d&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"1. Uploading file to server"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsx("span",{children:"Sending your file to the server"}),e.jsxs("span",{children:[Math.round(p),"%"]})]}),e.jsx(Zs,{value:p,className:"h-2"})]}),p>=100&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"2. Processing & saving to database"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsx("span",{children:"Parsing 26AS data and saving TDS records"}),e.jsxs("span",{children:[Math.round(u),"%"]})]}),e.jsx(Zs,{value:u,className:"h-2",indicatorClassName:"bg-teal-600"})]})]})]}),e.jsxs(Et,{children:[e.jsx(E,{variant:"outline",onClick:()=>{c(!1),b(null),j.current&&(j.current.value="")},disabled:d,children:"Cancel"}),e.jsx(E,{onClick:M,disabled:!f||d,className:"bg-teal-600 hover:bg-teal-700 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-4 h-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(js,{className:"w-4 h-4"}),"Upload"]})})]})]})}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Management"}),e.jsx(ve,{children:"History of 26AS file uploads: when and which user added or uploaded 26AS data"})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{children:[e.jsx(Ee,{children:"Date & Time"}),e.jsx(Ee,{children:"User"}),e.jsx(Ee,{children:"File Name"}),e.jsx(Ee,{className:"text-right",children:"Records Imported"}),e.jsx(Ee,{className:"text-right",children:"Errors"})]})}),e.jsx(da,{children:$?e.jsx(ut,{children:e.jsxs(Te,{colSpan:5,className:"text-center py-8",children:[e.jsx(Xe,{className:"w-6 h-6 animate-spin mx-auto text-teal-600"}),e.jsx("p",{className:"text-sm text-gray-500 mt-2",children:"Loading upload history..."})]})}):V.length===0?e.jsx(ut,{children:e.jsx(Te,{colSpan:5,className:"text-center py-8 text-gray-500",children:"No upload history yet. Uploads will appear here after you add a 26AS file."})}):V.map(K=>e.jsxs(ut,{className:"hover:bg-gray-50",children:[e.jsx(Te,{className:"text-sm whitespace-nowrap",children:K.uploadedAt?new Date(K.uploadedAt).toLocaleString("en-IN",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"–"}),e.jsx(Te,{className:"text-sm",children:K.uploadedByDisplayName||K.uploadedByEmail||K.uploadedBy||"–"}),e.jsx(Te,{className:"text-sm text-gray-600 max-w-[200px] truncate",title:K.fileName||void 0,children:K.fileName||"–"}),e.jsx(Te,{className:"text-right font-medium",children:K.recordsImported}),e.jsx(Te,{className:"text-right",children:K.errorsCount>0?K.errorsCount:"–"})]},K.id))})]})})})]}),t&&e.jsxs(Z,{children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{children:"Filter TDS Records"}),B&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:U,className:"gap-2 text-gray-600",children:[e.jsx(bt,{className:"w-4 h-4"}),"Clear All"]})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Assessment Year"}),e.jsxs(Be,{value:a.assessmentYear,onValueChange:K=>r(ae=>({...ae,assessmentYear:K})),children:[e.jsx(ze,{children:e.jsx(Ve,{placeholder:"Select year"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Years"}),T.map(K=>e.jsx(Q,{value:K,children:K},K))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Quarter"}),e.jsxs(Be,{value:a.quarter,onValueChange:K=>r(ae=>({...ae,quarter:K})),children:[e.jsx(ze,{children:e.jsx(Ve,{placeholder:"Select quarter"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Quarters"}),GR.map(K=>e.jsx(Q,{value:K,children:K},K))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Section"}),e.jsxs(Be,{value:a.section,onValueChange:K=>r(ae=>({...ae,section:K})),children:[e.jsx(ze,{children:e.jsx(Ve,{placeholder:"Select section"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Sections"}),YR.map(K=>e.jsx(Q,{value:K.value,children:K.label},K.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Deductor"}),e.jsx(ke,{placeholder:"Search deductor...",value:a.deductor,onChange:K=>r(ae=>({...ae,deductor:K.target.value})),className:"h-9"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Status"}),e.jsxs(Be,{value:a.status,onValueChange:K=>r(ae=>({...ae,status:K})),children:[e.jsx(ze,{children:e.jsx(Ve,{placeholder:"Select status"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Status"}),e.jsx(Q,{value:"F",children:"F – Final (Booked)"}),e.jsx(Q,{value:"O",children:"O – Overbooked"}),e.jsx(Q,{value:"P",children:"P – Pending"})]})]})]})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4",children:[e.jsx(Z,{children:e.jsxs(oe,{className:"pb-3",children:[e.jsx(ve,{children:"Total Records"}),e.jsx(me,{className:"text-2xl",children:_.totalRecords})]})}),e.jsx(Z,{children:e.jsxs(oe,{className:"pb-3",children:[e.jsx(ve,{children:"Booked"}),e.jsx(me,{className:"text-2xl text-green-600",children:_.booked})]})}),e.jsx(Z,{children:e.jsxs(oe,{className:"pb-3",children:[e.jsx(ve,{children:"Not Booked"}),e.jsx(me,{className:"text-2xl text-red-600",children:_.notBooked})]})}),e.jsx(Z,{children:e.jsxs(oe,{className:"pb-3",children:[e.jsx(ve,{children:"Pending"}),e.jsx(me,{className:"text-2xl text-amber-600",children:_.pending})]})}),e.jsx(Z,{className:"lg:col-span-1",children:e.jsxs(oe,{className:"pb-3",children:[e.jsx(ve,{children:"Total Tax Deducted"}),e.jsx(me,{className:"text-xl",children:hi(_.totalTaxDeducted)})]})})]}),e.jsxs(Z,{children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx(me,{children:"TDS Records from Form 26AS"}),e.jsx(ve,{children:B?`Showing ${w.length} of ${S} records`:`Complete list of TDS deduction records (${S} total)`})]}),e.jsxs(E,{variant:"outline",size:"sm",disabled:!0,children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Export"]})]})}),e.jsxs(ee,{className:"p-0",children:[e.jsx("div",{className:"overflow-auto min-h-[320px]",style:{maxHeight:"calc(100vh - 380px)"},children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{className:"bg-gray-50",children:[e.jsx(Ee,{className:"w-14",children:"Sr No"}),e.jsx(Ee,{className:"min-w-[180px]",children:"Name of Deductor"}),e.jsx(Ee,{className:"text-right min-w-[110px]",children:"Total Amount Paid"}),e.jsx(Ee,{className:"text-right min-w-[110px]",children:"Total Tax Deducted"}),e.jsx(Ee,{className:"text-right min-w-[110px]",children:"Total TDS Deposited"}),e.jsx(Ee,{className:"min-w-[100px]",children:"TAN of Deductor"}),e.jsx(Ee,{className:"min-w-[72px]",children:"Section"}),e.jsx(Ee,{className:"min-w-[64px]",children:"Quarter"}),e.jsx(Ee,{className:"min-w-[90px]",children:"Assessment Year"}),e.jsx(Ee,{className:"min-w-[90px]",children:"Financial Year"}),e.jsx(Ee,{className:"min-w-[100px]",children:"Transaction Date"}),e.jsx(Ee,{className:"min-w-[64px]",children:"Status"}),e.jsx(Ee,{className:"min-w-[100px]",children:"Date of Booking"})]})}),e.jsx(da,{children:R?e.jsx(ut,{children:e.jsx(Te,{colSpan:13,className:"text-center py-12",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Xe,{className:"w-6 h-6 animate-spin text-teal-600"}),e.jsx("p",{className:"text-gray-500",children:"Loading 26AS data..."})]})})}):w.length===0?e.jsx(ut,{children:e.jsxs(Te,{colSpan:13,className:"text-center py-12 text-gray-500",children:[B?"No records match your filters":"No TDS records found. Upload a 26AS file to get started.",B&&e.jsx(E,{variant:"outline",size:"sm",onClick:U,className:"mt-2",children:"Clear Filters"})]})}):w.map((K,ae)=>e.jsxs(ut,{className:"hover:bg-gray-50",children:[e.jsx(Te,{className:"text-center text-sm text-gray-900",children:P*Sn+ae+1}),e.jsx(Te,{className:"text-sm text-gray-900",children:K.deductorName||"–"}),e.jsx(Te,{className:"text-right text-sm text-gray-900",children:hi(K.amountPaid??0)}),e.jsx(Te,{className:"text-right text-sm text-gray-900",children:hi(K.taxDeducted)}),e.jsx(Te,{className:"text-right text-sm text-gray-900",children:hi(K.totalTdsDeposited??0)}),e.jsx(Te,{className:"text-sm text-gray-700 font-mono",children:K.tanNumber}),e.jsx(Te,{children:e.jsx(se,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:K.sectionCode||"–"})}),e.jsx(Te,{children:e.jsx(se,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:K.quarter})}),e.jsx(Te,{className:"text-sm text-gray-700 font-medium",children:K.assessmentYear||"–"}),e.jsx(Te,{className:"text-sm text-gray-700 font-medium",children:K.financialYear||"–"}),e.jsx(Te,{className:"text-sm text-gray-700",children:Px(K.transactionDate)}),e.jsx(Te,{children:QR(K.statusOltas)}),e.jsx(Te,{className:"text-sm text-gray-700",children:Px(K.dateOfBooking)})]},K.id))})]})}),!R&&S>Sn&&e.jsxs("div",{className:"flex items-center justify-between mt-4 px-6 pb-6",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Page ",P+1," of ",W," (",S," records)"]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-wrap justify-center",children:[e.jsxs(E,{variant:"outline",size:"sm",disabled:!J,onClick:()=>z(P-1),children:[e.jsx(Uo,{className:"w-4 h-4"}),"Previous"]}),re.map(K=>e.jsx(E,{variant:K===P?"default":"outline",size:"sm",className:K===P?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>z(K),children:K+1},K)),e.jsxs(E,{variant:"outline",size:"sm",disabled:!O,onClick:()=>z(P+1),children:["Next",e.jsx(nn,{className:"w-4 h-4"})]})]})]})]})]})]})})}function Ex(t){if(!t)return"—";try{const s=new Date(t+"Z"),a=s.getUTCDate(),n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][s.getUTCMonth()],i=s.getUTCFullYear();return`${a}-${n}-${i}`}catch{return t}}const JR=[{value:"2024-25",label:"2024-25"},{value:"2023-24",label:"2023-24"},{value:"2022-23",label:"2022-23"},{value:"",label:"All Years"}];function ZR(){const[t,s]=h.useState(null),[a,r]=h.useState([]),[n,i]=h.useState({totalDealers:0,nonSubmittedCount:0,neverSubmittedCount:0,overdue90Count:0}),[l,o]=h.useState(!0),[c,d]=h.useState("2024-25");h.useEffect(()=>{m()},[c]);const m=async()=>{try{o(!0);const x=await Ry(c||void 0);r(x.dealers),i(x.summary)}catch(x){console.error("Error fetching non-submitted dealers:",x),X.error("Failed to load non-submitted dealers"),r([]),i({totalDealers:0,nonSubmittedCount:0,neverSubmittedCount:0,overdue90Count:0})}finally{o(!1)}},p=async x=>{s(x.id);try{await Dy(x.dealerCode,c||void 0),X.success(`Notification sent to ${x.dealerName}`,{description:`Reminder sent for missing quarters: ${x.missingQuarters.join(", ")}. Last notified column updated.`}),await m()}catch(u){console.error("Notify dealer error:",u),X.error("Failed to send notification")}finally{s(null)}};return e.jsx("div",{className:"space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full",children:e.jsxs("div",{className:"w-full min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-2",children:"Non-Submitted Dealers"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Dealers who have not submitted Form 16A for one or more quarters"})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("select",{value:c,onChange:x=>d(x.target.value),className:"px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 bg-white",children:JR.map(x=>e.jsx("option",{value:x.value,children:x.value?`FY ${x.label}`:x.label},x.value||"all"))})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(Z,{children:e.jsxs(oe,{className:"pb-3",children:[e.jsx(ve,{children:"Non-Submitted / Total Dealers"}),e.jsx(me,{className:"text-3xl text-red-600",children:l?"...":`${n.nonSubmittedCount}/${n.totalDealers}`})]})}),e.jsx(Z,{children:e.jsxs(oe,{className:"pb-3",children:[e.jsx(ve,{children:"Never Submitted"}),e.jsx(me,{className:"text-3xl text-amber-600",children:l?"...":n.neverSubmittedCount})]})}),e.jsx(Z,{children:e.jsxs(oe,{className:"pb-3",children:[e.jsx(ve,{children:"Overdue (90+ days)"}),e.jsx(me,{className:"text-3xl text-orange-600",children:l?"...":n.overdue90Count})]})})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Dealer List"}),e.jsx(ve,{children:"Dealers with missing Form 16A submissions"})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{children:[e.jsx(Ee,{children:"Dealer Details"}),e.jsx(Ee,{children:"Contact Information"}),e.jsx(Ee,{children:"Location"}),e.jsx(Ee,{children:"Missing Quarters"}),e.jsx(Ee,{children:"Last Submission"}),e.jsx(Ee,{children:"Last Notified"}),e.jsx(Ee,{className:"text-right",children:"Action"})]})}),e.jsx(da,{children:l?e.jsx(ut,{children:e.jsxs(Te,{colSpan:7,className:"text-center py-12",children:[e.jsx(Xe,{className:"w-6 h-6 animate-spin mx-auto mb-2 text-teal-600"}),e.jsx("p",{className:"text-gray-500",children:"Loading dealers..."})]})}):a.length===0?e.jsx(ut,{children:e.jsxs(Te,{colSpan:7,className:"text-center py-12 text-gray-500",children:[e.jsx("p",{children:"No dealers with missing quarters found"}),e.jsx("p",{className:"text-sm mt-1",children:"All dealers have submitted Form 16A for the selected period"})]})}):a.map(x=>{var u;return e.jsxs(ut,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(Te,{children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:x.dealerName}),e.jsx("p",{className:"text-xs text-gray-500",children:x.dealerCode})]})}),e.jsx(Te,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-600",children:[e.jsx(ba,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:x.email||"—"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-600",children:[e.jsx(Wn,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:x.phone||"—"})]})]})}),e.jsx(Te,{className:"text-sm",children:x.location||"—"}),e.jsx(Te,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:x.missingQuarters.map((g,f)=>e.jsx(se,{variant:"destructive",className:"text-xs",children:g},f))})}),e.jsx(Te,{children:x.lastSubmissionDate?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:Ex(x.lastSubmissionDate)}),e.jsxs("p",{className:`text-xs ${x.daysSinceLastSubmission!=null&&x.daysSinceLastSubmission>90?"text-red-600":"text-gray-500"}`,children:[x.daysSinceLastSubmission," days ago"]})]}):e.jsx(se,{variant:"outline",className:"text-xs bg-red-50 text-red-700 border-red-200",children:"Never Submitted"})}),e.jsx(Te,{children:x.lastNotifiedDate?e.jsx(Dn,{children:e.jsxs(bi,{children:[e.jsx(ji,{asChild:!0,children:e.jsxs("div",{className:"space-y-1 cursor-help",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-600",children:[e.jsx(dt,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:Ex(x.lastNotifiedDate)})]}),x.notificationCount>1&&e.jsxs(se,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[x.notificationCount,"x"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-600",children:[e.jsx(Vt,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:x.lastNotifiedBy})]})]})}),e.jsx(yi,{side:"left",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium",children:["Notification History (",x.notificationCount,")"]}),e.jsx("div",{className:"space-y-1.5",children:(u=x.notificationHistory)==null?void 0:u.map((g,f)=>e.jsxs("div",{className:"text-xs border-l-2 border-blue-400 pl-2 py-0.5",children:[e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{className:"text-gray-600",children:g.date}),e.jsx(se,{variant:"outline",className:"text-xs h-4 px-1",children:g.method})]}),e.jsxs("p",{className:"text-gray-500 text-xs",children:["by ",g.notifiedBy]})]},f))})]})})]})}):e.jsx(se,{variant:"outline",className:"text-xs bg-gray-50 text-gray-600 border-gray-200",children:"Never Notified"})}),e.jsx(Te,{className:"text-right",children:e.jsxs(E,{size:"sm",onClick:()=>p(x),disabled:t===x.id,className:"bg-teal-600 hover:bg-teal-700 text-white",children:[e.jsx(_s,{className:"w-4 h-4 mr-1"}),t===x.id?"Sending...":"Notify"]})})]},x.id)})})]})})})]})]})})}function qR(){const t=ys(),[s,a]=h.useState([]),[r,n]=h.useState([]),[i,l]=h.useState(!0),[o,c]=h.useState(!1),[d,m]=h.useState({financialYear:"all",quarter:"all"});h.useEffect(()=>{let A=!1;return(async()=>{l(!0);try{const[_,D]=await Promise.all([zh(),Fy({status:"pending,failed,completed"})]);A||(a(Array.isArray(_)?_:[]),n(Array.isArray(D)?D:[]))}catch{A||(X.error("Failed to load pending submissions"),a([]),n([]))}finally{A||l(!1)}})(),()=>{A=!0}},[]);const p=s.filter(A=>!(d.financialYear!=="all"&&A.financial_year!==d.financialYear||d.quarter!=="all"&&A.quarter!==d.quarter)),x=p.length,u=p.filter(A=>(A.days_overdue??0)>0).length,g=p.filter(A=>(A.days_remaining??0)>0).length,f=()=>m({financialYear:"all",quarter:"all"}),b=d.financialYear!=="all"||d.quarter!=="all",j=A=>{if(!A)return"—";try{return new Date(A).toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}catch{return A}},y=A=>A==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(A),w=A=>{const _=(A||"").toLowerCase();return _==="completed"?"bg-emerald-50 text-emerald-700 border-emerald-200":_==="balance mismatch"||_==="failed"?"bg-red-50 text-red-700 border-red-200":_==="resubmission needed"||_==="duplicate"||_==="duplicate submission"?"bg-amber-50 text-amber-700 border-amber-200":"bg-slate-50 text-slate-600 border-slate-200"},N=A=>{t("/form16/submit")},S=[...new Set(s.map(A=>A.financial_year))].sort();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Pending Submissions"}),e.jsx("p",{className:"text-gray-600 mt-1",children:"Quarters for which Form 16A has not been submitted."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{className:"bg-teal-600 hover:bg-teal-700",onClick:()=>t("/form16/submit"),children:"New Submission"}),e.jsxs(E,{variant:"outline",onClick:()=>c(!o),className:"gap-2",children:[e.jsx(Pa,{className:"w-4 h-4"}),"Filters",b&&e.jsx(se,{variant:"default",className:"ml-1 bg-teal-600 hover:bg-teal-700",children:[d.financialYear,d.quarter].filter(A=>A!=="all").length}),o?e.jsx(Wi,{className:"w-4 h-4"}):e.jsx(rn,{className:"w-4 h-4"})]})]})]}),o&&e.jsxs(Z,{children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{className:"text-base",children:"Filter"}),b&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:f,className:"gap-2 text-gray-600 hover:text-gray-900",children:[e.jsx(bt,{className:"w-4 h-4"}),"Clear All"]})]})}),e.jsx(ee,{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(te,{children:"Financial Year"}),e.jsxs(Be,{value:d.financialYear,onValueChange:A=>m(_=>({..._,financialYear:A})),children:[e.jsx(ze,{children:e.jsx(Ve,{placeholder:"All years"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Years"}),S.map(A=>e.jsx(Q,{value:A,children:A},A))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Quarter"}),e.jsxs(Be,{value:d.quarter,onValueChange:A=>m(_=>({..._,quarter:A})),children:[e.jsx(ze,{children:e.jsx(Ve,{placeholder:"All quarters"})}),e.jsxs(He,{children:[e.jsx(Q,{value:"all",children:"All Quarters"}),e.jsx(Q,{value:"Q1",children:"Q1"}),e.jsx(Q,{value:"Q2",children:"Q2"}),e.jsx(Q,{value:"Q3",children:"Q3"}),e.jsx(Q,{value:"Q4",children:"Q4"})]})]})]})]})})]}),u>0&&e.jsx(Z,{className:"border-red-200 bg-red-50",children:e.jsx(ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ts,{className:"w-5 h-5 text-red-600 flex-shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-sm text-red-800",children:[e.jsxs("span",{className:"font-semibold",children:[u," overdue submission",u>1?"s":""," detected."]}),"Please submit Form 16A immediately to avoid penalties."]})]})})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(Z,{children:e.jsx(ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500 mb-1",children:"Total Pending"}),e.jsx("p",{className:"text-2xl font-semibold text-gray-900",children:x})]}),e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center",children:e.jsx(Ie,{className:"w-6 h-6 text-gray-600"})})]})})}),e.jsx(Z,{children:e.jsx(ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500 mb-1",children:"Overdue"}),e.jsx("p",{className:"text-2xl font-semibold text-red-600",children:u})]}),e.jsx("div",{className:"w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center",children:e.jsx(ts,{className:"w-6 h-6 text-red-600"})})]})})}),e.jsx(Z,{children:e.jsx(ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500 mb-1",children:"Upcoming"}),e.jsx("p",{className:"text-2xl font-semibold text-amber-600",children:g})]}),e.jsx("div",{className:"w-12 h-12 bg-amber-100 rounded-lg flex items-center justify-center",children:e.jsx(dt,{className:"w-6 h-6 text-amber-600"})})]})})})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Pending Form 16A Submissions"}),e.jsx(ve,{children:"Complete list of quarters awaiting submission."})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{className:"bg-gray-50",children:[e.jsx(Ee,{children:"Dealer Name"}),e.jsx(Ee,{children:"Financial Year"}),e.jsx(Ee,{children:"Quarter"}),e.jsx(Ee,{children:"Version"}),e.jsx(Ee,{children:"Status"}),e.jsx(Ee,{children:"26AS start date"}),e.jsx(Ee,{children:"Days Status"}),e.jsx(Ee,{className:"text-right",children:"Action"})]})}),e.jsx(da,{children:i?e.jsx(ut,{children:e.jsxs(Te,{colSpan:8,className:"text-center py-12 text-gray-500",children:[e.jsx(Xe,{className:"w-8 h-8 animate-spin mx-auto mb-2"}),e.jsx("p",{children:"Loading..."})]})}):p.length===0?e.jsx(ut,{children:e.jsx(Te,{colSpan:8,className:"text-center py-12 text-gray-500",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Ie,{className:"w-12 h-12 text-gray-300"}),e.jsx("p",{children:b?"No quarters match your filters":"No pending submissions"}),b&&e.jsx(E,{variant:"outline",size:"sm",onClick:f,className:"mt-2",children:"Clear Filters"}),!b&&e.jsx(E,{size:"sm",className:"bg-teal-600 hover:bg-teal-700 mt-2",onClick:()=>t("/form16/submit"),children:"New Submission"})]})})}):p.map(A=>e.jsxs(ut,{className:"hover:bg-gray-50",children:[e.jsx(Te,{className:"text-sm text-gray-900",children:A.dealer_name??"Your submission"}),e.jsx(Te,{children:e.jsxs("span",{className:"text-sm text-gray-900",children:["FY ",A.financial_year]})}),e.jsx(Te,{children:e.jsx(se,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:A.quarter})}),e.jsx(Te,{children:e.jsx(se,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:A.has_submission?"V1":"—"})}),e.jsx(Te,{children:e.jsx(se,{variant:"outline",className:A.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":A.has_submission?"bg-slate-50 text-slate-600 border-slate-200":"bg-gray-100 text-gray-600 border-gray-200",children:A.latest_submission_status==="failed"?"Failed":A.has_submission?"Under review":"Not Submitted"})}),e.jsx(Te,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-700",children:j(A.twenty_six_as_start_date??A.audit_start_date)})]})}),e.jsx(Te,{children:A.days_since_26as_uploaded!=null&&A.days_since_26as_uploaded>=0?e.jsxs("span",{className:"text-sm font-medium text-gray-700",children:["due from ",A.days_since_26as_uploaded," days"]}):e.jsx("span",{className:"text-sm text-gray-500",children:"—"})}),e.jsx(Te,{className:"text-right",children:e.jsx(E,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>N(),children:"Submit Now"})})]},`${A.financial_year}|${A.quarter}`))})]})})})]}),e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsx(me,{children:"Your Form 16 Submissions"}),e.jsx(ve,{children:"Requests you have submitted. Total amount and credit note (when issued) are shown. Status is never shown as Pending."})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(ut,{className:"bg-gray-50",children:[e.jsx(Ee,{children:"Request ID"}),e.jsx(Ee,{children:"Financial Year"}),e.jsx(Ee,{children:"Quarter"}),e.jsx(Ee,{className:"text-right",children:"Total Amount"}),e.jsx(Ee,{children:"Credit Note No."}),e.jsx(Ee,{children:"Status"}),e.jsx(Ee,{children:"Submitted"}),e.jsx(Ee,{className:"text-right",children:"Action"})]})}),e.jsx(da,{children:i?e.jsx(ut,{children:e.jsx(Te,{colSpan:8,className:"text-center py-8 text-gray-500",children:e.jsx(Xe,{className:"w-6 h-6 animate-spin mx-auto"})})}):r.length===0?e.jsx(ut,{children:e.jsx(Te,{colSpan:8,className:"text-center py-8 text-gray-500",children:'No Form 16 submissions yet. Use "New Submission" to submit.'})}):r.map(A=>e.jsxs(ut,{className:"hover:bg-gray-50",children:[e.jsx(Te,{className:"font-mono text-sm",children:A.requestId?String(A.requestId).slice(0,8)+"…":"—"}),e.jsxs(Te,{children:["FY ",A.financial_year]}),e.jsx(Te,{children:e.jsx(se,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:A.quarter})}),e.jsx(Te,{className:"text-right font-medium",children:y(A.total_amount)}),e.jsx(Te,{children:A.credit_note_number??"—"}),e.jsx(Te,{children:e.jsx(se,{variant:"outline",className:w(A.display_status),children:A.display_status??(A.status==="completed"?"Completed":A.status==="failed"?"Failed":"Under review")})}),e.jsx(Te,{className:"text-sm text-gray-600",children:j(A.submitted_date)}),e.jsx(Te,{className:"text-right",children:e.jsx(E,{variant:"outline",size:"sm",onClick:()=>t(`/request/${A.requestId}`),children:"View Request"})})]},A.id))})]})})})]}),s.length>0&&e.jsxs(Z,{className:"border-amber-200 bg-amber-50/50",children:[e.jsxs(oe,{children:[e.jsx(me,{className:"text-amber-900",children:"Quarters Pending Submission"}),e.jsx(ve,{className:"text-amber-700",children:"These quarters don't have completed Form 16A submissions. Please submit Form 16A for these quarters."})]}),e.jsx(ee,{children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:s.slice(0,8).map(A=>e.jsx("div",{className:"p-3 bg-white rounded-lg border border-amber-200",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-gray-900",children:A.quarter}),e.jsx("p",{className:"text-sm text-gray-600",children:A.financial_year}),A.has_submission&&A.latest_submission_status&&e.jsx(se,{variant:"outline",className:`mt-1 text-xs ${A.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":"bg-slate-50 text-slate-600 border-slate-200"}`,children:A.latest_submission_status==="failed"?"Failed":"Under review"})]}),e.jsx(E,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>t("/form16/submit"),children:"Submit"})]})},`${A.financial_year}|${A.quarter}`))})})]})]})}function eD({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[l,o]=h.useState(""),[c,d]=h.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)}}},p=()=>{o(""),s()},u=a==="approve"?{title:"Approve Request",description:"Please provide your approval comments and remarks",icon:Le,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:St,iconColor:"text-red-600",buttonColor:"bg-red-600 hover:bg-red-700",badgeColor:"bg-red-100 text-red-800 border-red-200",placeholder:"Enter detailed reasons for rejection and any suggestions for improvement..."},g=u.icon;return e.jsx(jt,{open:t,onOpenChange:p,children:e.jsxs(xt,{className:"max-w-2xl bg-white",children:[e.jsxs(yt,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:`p-2 rounded-lg ${a==="approve"?"bg-green-100":"bg-red-100"}`,children:e.jsx(g,{className:`w-6 h-6 ${u.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ht,{className:"text-xl",children:u.title}),e.jsx(Ut,{className:"mt-1",children:u.description})]})]}),e.jsxs("div",{className:"space-y-3 p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Request ID:"}),e.jsx(se,{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(se,{className:u.badgeColor,variant:"outline",children:[e.jsx(g,{className:"w-3 h-3 mr-1"}),a==="approve"?"APPROVE":"REJECT"]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(Os,{id:"comment",placeholder:u.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(ts,{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(ts,{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(Le,{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(Et,{className:"gap-2",children:[e.jsx(E,{variant:"outline",onClick:p,disabled:c,children:"Cancel"}),e.jsx(E,{onClick:m,disabled:!l.trim()||c||l.length>500,className:u.buttonColor,children:c?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(g,{className:"w-4 h-4 mr-2"}),a==="approve"?"Approve Request":"Reject Request"]})})]})]})})}var tD=(t,s,a,r,n,i,l,o)=>{let c=document.documentElement,d=["light","dark"];function m(u){(Array.isArray(t)?t:[t]).forEach(g=>{let f=g==="class",b=f&&i?n.map(j=>i[j]||j):n;f?(c.classList.remove(...b),c.classList.add(i&&i[u]?i[u]:u)):c.setAttribute(g,u)}),p(u)}function p(u){o&&d.includes(u)&&(c.style.colorScheme=u)}function x(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let u=localStorage.getItem(s)||a,g=l&&u==="system"?x():u;m(g)}catch{}},sD=h.createContext(void 0),aD={setTheme:t=>{},themes:[]},rD=()=>{var t;return(t=h.useContext(sD))!=null?t:aD};h.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 h.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${tD.toString()})(${m})`}})});const nD=({...t})=>{const{theme:s="system"}=rD();return e.jsx(Ub,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function iD({open:t,onClose:s,onSelect:a,managers:r=[],errorType:n,message:i,isLoading:l=!1}){const o=c=>{a(c)};return e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(xt,{className:"sm:max-w-[600px]",children:[e.jsxs(yt,{children:[e.jsx(ht,{className:"flex items-center gap-2",children:n==="NO_MANAGER_FOUND"?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-amber-500"}),"Manager Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"w-5 h-5 text-blue-500"}),"Select Your Manager"]})}),e.jsx(Ut,{children:n==="NO_MANAGER_FOUND"?e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-sm text-gray-600",children:i||"No reporting manager found in the system. Please ensure your manager is correctly configured in your profile."}),e.jsx("p",{className:"text-sm text-gray-500 mt-2",children:"Please contact your administrator to update your manager information, or try again later."})]}):e.jsx("div",{className:"mt-2",children:e.jsx("p",{className:"text-sm text-gray-600",children:i||"Multiple managers were found with the same name. Please select the correct manager from the list below."})})})]}),e.jsx("div",{className:"mt-4",children:n==="NO_MANAGER_FOUND"?e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ze,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-amber-900",children:"Unable to Proceed"}),e.jsx("p",{className:"text-sm text-amber-700 mt-1",children:"We couldn't find your reporting manager in the system. The claim request cannot be created without a valid manager assigned."})]})]})}):e.jsx("div",{className:"space-y-3 max-h-[400px] overflow-y-auto",children:r.map(c=>e.jsx("div",{className:"border rounded-lg p-4 hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>!l&&o(c.email),children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-1",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Vt,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsx("p",{className:"font-medium text-gray-900",children:c.displayName||`${c.firstName||""} ${c.lastName||""}`.trim()||"Unknown"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(ba,{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($o,{className:"w-4 h-4"}),e.jsx("span",{children:c.department})]})]})]})]}),e.jsx(E,{onClick:d=>{d.stopPropagation(),o(c.email)},disabled:l,className:"flex-shrink-0",size:"sm",children:"Select"})]})},c.userId))})}),e.jsx("div",{className:"flex justify-end gap-3 mt-6",children:n==="NO_MANAGER_FOUND"?e.jsx(E,{onClick:s,variant:"outline",children:"Close"}):e.jsx(e.Fragment,{children:e.jsx(E,{onClick:s,variant:"outline",disabled:l,children:"Cancel"})})})]})})}function lD({onViewRequest:t}){const{user:s}=cs();return al(s)?e.jsx(U4,{onViewRequest:t}):e.jsx(z4,{onViewRequest:t})}function _x({onNavigate:t,onNewRequest:s}){const[a,r]=h.useState(!1),[n,i]=h.useState(!0);return h.useEffect(()=>{try{const l=at.getUserData();r((l==null?void 0:l.jobTitle)==="Dealer")}catch(l){console.error("[App] Error checking dealer status:",l),r(!1)}finally{i(!1)}},[]),n?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"w-8 h-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})}):a?e.jsx(nk,{onNavigate:t,onNewRequest:s}):e.jsx(nw,{onNavigate:t,onNewRequest:s})}function oD({onLogout:t}){const s=ys(),[a,r]=h.useState(null),[n,i]=h.useState([]),[l,o]=h.useState(""),[c,d]=h.useState(""),[m,p]=h.useState(!1),[x,u]=h.useState(null);h.useEffect(()=>{const A=localStorage.getItem("dynamicRequests");if(A)try{const _=JSON.parse(A);i(_)}catch(_){console.error("Error parsing dynamic requests:",_)}},[]),h.useEffect(()=>{n.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(n))},[n]);const g=A=>{if(A==="profile"){s("/profile");return}if(A==="settings"){s("/settings");return}A.startsWith("/")?s(A):s(`/${A}`)},f=(A,_,D,R)=>{o(A),d(_||"Unknown Request"),Vi({requestId:A,status:D,request:R,navigate:s})},b=()=>{s(-1)},j=()=>{s("/new-request")},y=A=>{var R,v,P,C,V,F,$,I,T,k,z;if(A.templateType){A.templateType==="claim-management"&&s("/claim-management");return}if(A.backendId){s("/my-requests");return}const D={id:`RE-REQ-2024-${String(n.length+1).padStart(3,"0")}`,title:A.title,description:A.description||"",category:A.category||"General",subcategory:A.subcategory||"",status:"pending",priority:A.priority||"standard",amount:A.budget||"N/A",slaProgress:0,slaRemaining:"5 days",slaEndDate:new Date(Date.now()+5*24*60*60*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),currentStep:1,totalSteps:((R=A.approvers)==null?void 0:R.length)||1,currentApprover:((P=(v=A.approvers)==null?void 0:v[0])==null?void 0:P.name)||((F=(V=(C=A.approvers)==null?void 0:C[0])==null?void 0:V.email)==null?void 0:F.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${(($=A.approvers)==null?void 0:$.length)||1}`,template:"custom",initiator:{name:"Current User",role:A.initiatorRole||"Employee",department:A.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:A.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:(A.approvers||[]).filter(L=>L).map((L,M)=>{var W;const U=(L==null?void 0:L.name)||((W=L==null?void 0:L.email)==null?void 0:W.split("@")[0])||`Approver ${M+1}`,B=(L==null?void 0:L.email)||"";return{step:M+1,approver:`${U}${B?` (${B})`:""}`,role:(L==null?void 0:L.role)||`Level ${(L==null?void 0:L.level)||M+1} Approver`,status:M===0?"pending":"waiting",tatHours:L!=null&&L.tat?typeof L.tat=="string"?parseInt(L.tat):L.tat:48,elapsedHours:0,assignedAt:M===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(A.spectators||[]).filter(L=>L&&(L.name||L.email)).map(L=>{var U;const M=(L==null?void 0:L.name)||((U=L==null?void 0:L.email)==null?void 0:U.split("@")[0])||"Observer";return{name:M,role:(L==null?void 0:L.role)||(L==null?void 0:L.department)||"Observer",avatar:M.split(" ").map(B=>B[0]).join("").toUpperCase().slice(0,2)||"OB"}}),auditTrail:[{type:"created",action:"Request Created",details:`Custom request "${A.title}" created`,user:"Current User",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})},{type:"assignment",action:"Assigned to Approver",details:`Request assigned to ${((T=(I=A.approvers)==null?void 0:I[0])==null?void 0:T.name)||((z=(k=A.approvers)==null?void 0:k[0])==null?void 0:z.email)||"first approver"}`,user:"System",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}],tags:A.tags||["custom-request"]};i([...n,D]),s("/my-requests")},w=(A,_)=>new Promise(D=>{setTimeout(()=>{A==="approve"?X.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):X.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),r(null),D(!0)},1e3)}),N=()=>{r(null)},S=async(A,_)=>{var D,R,v,P,C,V,F;try{const $={activityName:A.activityName,activityType:A.activityType,dealerCode:A.dealerCode,dealerName:A.dealerName,dealerEmail:A.dealerEmail||void 0,dealerPhone:A.dealerPhone||void 0,dealerAddress:A.dealerAddress||void 0,activityDate:A.activityDate?new Date(A.activityDate).toISOString():void 0,location:A.location,requestDescription:A.requestDescription,periodStartDate:A.periodStartDate?new Date(A.periodStartDate).toISOString():void 0,periodEndDate:A.periodEndDate?new Date(A.periodEndDate).toISOString():void 0,estimatedBudget:A.estimatedBudget||void 0,approvers:A.approvers||[]},I=await D5($);if(!I||!I.request)throw new Error("Invalid response from server: Request object not found");const T=I.request;if(!T.requestNumber&&!T.requestId)throw new Error("Invalid response from server: Request identifier not found");p(!1),u(null),X.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),T.requestNumber?s(`/request/${T.requestNumber}`):T.requestId?s(`/request/${T.requestId}`):s("/my-requests")}catch($){console.error("[App] Error creating claim request:",$);const I=(D=$==null?void 0:$.response)==null?void 0:D.data,T=(I==null?void 0:I.code)||((R=I==null?void 0:I.error)==null?void 0:R.code);if(T==="NO_MANAGER_FOUND"){u({errorType:"NO_MANAGER_FOUND",message:(I==null?void 0:I.message)||((v=I==null?void 0:I.error)==null?void 0:v.message)||"No reporting manager found. Please ensure your manager is correctly configured in the system.",pendingClaimData:A}),p(!0);return}if(T==="MULTIPLE_MANAGERS_FOUND"){const z=(I==null?void 0:I.managers)||((P=I==null?void 0:I.error)==null?void 0:P.managers)||[];u({errorType:"MULTIPLE_MANAGERS_FOUND",managers:z,message:(I==null?void 0:I.message)||((C=I==null?void 0:I.error)==null?void 0:C.message)||"Multiple managers found. Please select one.",pendingClaimData:A}),p(!0);return}const k=((F=(V=$==null?void 0:$.response)==null?void 0:V.data)==null?void 0:F.message)||($==null?void 0:$.message)||"Failed to create claim request";X.error("Failed to Submit Claim Request",{description:k})}};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(Wb,{children:[e.jsx(Dt,{path:"/login/callback",element:e.jsx(Dh,{})}),e.jsx(Dt,{path:"/",element:e.jsx(Jt,{currentPage:"dashboard",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(_x,{onNavigate:g,onNewRequest:j})})}),e.jsx(Dt,{path:"/dashboard",element:e.jsx(Jt,{currentPage:"dashboard",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(_x,{onNavigate:g,onNewRequest:j})})}),e.jsxs(Dt,{element:e.jsx(Jt,{currentPage:"admin",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(Gb,{})}),children:[e.jsx(Dt,{path:"/admin",element:e.jsx(PR,{})}),e.jsx(Dt,{path:"/admin/create-template",element:e.jsx(Rx,{})}),e.jsx(Dt,{path:"/admin/edit-template/:templateId",element:e.jsx(Rx,{})}),e.jsx(Dt,{path:"/admin/templates",element:e.jsx(Y6,{})})]}),e.jsx(Dt,{path:"/create-admin-request/:templateId",element:e.jsx(X6,{})}),e.jsx(Dt,{path:"/open-requests",element:e.jsx(Jt,{currentPage:"open-requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(pk,{onViewRequest:f})})}),e.jsx(Dt,{path:"/closed-requests",element:e.jsx(Jt,{currentPage:"closed-requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx($k,{onViewRequest:f})})}),e.jsx(Dt,{path:"/shared-summaries",element:e.jsx(Jt,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(Gk,{})})}),e.jsx(Dt,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(Jt,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(Yk,{})})}),e.jsx(Dt,{path:"/form16/credit-notes",element:e.jsx(Jt,{currentPage:"form16-credit-notes",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(_R,{})})}),e.jsx(Dt,{path:"/form16/credit-notes/:id",element:e.jsx(Jt,{currentPage:"form16-credit-notes",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(MR,{})})}),e.jsx(Dt,{path:"/form16/submit",element:e.jsx(Jt,{currentPage:"form16-submit",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(UR,{})})}),e.jsx(Dt,{path:"/form16/submit/result",element:e.jsx(Jt,{currentPage:"form16-submit",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(WR,{})})}),e.jsx(Dt,{path:"/form16/26as",element:e.jsx(Jt,{currentPage:"form16-26as",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(XR,{})})}),e.jsx(Dt,{path:"/form16/pending-submissions",element:e.jsx(Jt,{currentPage:"form16-pending-submissions",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(qR,{})})}),e.jsx(Dt,{path:"/form16/non-submitted-dealers",element:e.jsx(Jt,{currentPage:"form16-non-submitted-dealers",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(ZR,{})})}),e.jsx(Dt,{path:"/my-requests",element:e.jsx(Jt,{currentPage:"my-requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(u4,{onViewRequest:f,dynamicRequests:n})})}),e.jsx(Dt,{path:"/requests",element:e.jsx(Jt,{currentPage:"requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(lD,{onViewRequest:f})})}),e.jsx(Dt,{path:"/approver-performance",element:e.jsx(Jt,{currentPage:"approver-performance",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(a6,{})})}),e.jsx(Dt,{path:"/request/:requestId",element:e.jsx(Jt,{currentPage:"request-detail",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(Wk,{requestId:"",onBack:b,dynamicRequests:n})})}),e.jsx(Dt,{path:"/work-notes/:requestId",element:e.jsx(Kk,{})}),e.jsx(Dt,{path:"/new-request",element:e.jsx(jx,{onBack:b,onSubmit:y})}),e.jsx(Dt,{path:"/edit-request/:requestId",element:e.jsx(jx,{onBack:b,onSubmit:y,requestId:void 0,isEditMode:!0})}),e.jsx(Dt,{path:"/claim-management",element:e.jsx(K5,{onBack:b,onSubmit:S})}),e.jsx(Dt,{path:"/profile",element:e.jsx(Jt,{currentPage:"profile",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(r6,{})})}),e.jsx(Dt,{path:"/settings",element:e.jsx(Jt,{currentPage:"settings",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(y6,{})})}),e.jsx(Dt,{path:"/settings/security",element:e.jsx(Jt,{currentPage:"settings",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(A6,{})})}),e.jsx(Dt,{path:"/notifications",element:e.jsx(Jt,{currentPage:"notifications",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(T6,{onNavigate:g})})}),e.jsx(Dt,{path:"/detailed-reports",element:e.jsx(Jt,{currentPage:"detailed-reports",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(G6,{})})})]}),e.jsx(nD,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),e.jsx(iD,{open:m,onClose:()=>{p(!1),u(null)},onSelect:async A=>{x!=null&&x.pendingClaimData&&await S(x.pendingClaimData)},managers:x==null?void 0:x.managers,errorType:(x==null?void 0:x.errorType)||"NO_MANAGER_FOUND",message:x==null?void 0:x.message,isLoading:!1}),a&&e.jsx(eD,{isOpen:!!a,onClose:N,action:a,requestId:l,requestTitle:c,onSubmit:w})]})}function cD(t){const{onLogout:s}=t||{};return e.jsx(Hb,{children:e.jsx(oD,{onLogout:s})})}function dD(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=cs(),[i,l]=h.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(h.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"),p=d==null?void 0:d.get("error");if(!m&&!p){console.log("🚪 AuthenticatedApp: Logout redirect detected, redirecting to home");const u=new URLSearchParams;return u.set("tanflow_logged_out","true"),u.set("logout",Date.now().toString()),window.location.replace(`/?${u.toString()}`),e.jsx("div",{className:"flex items-center justify-center min-h-screen bg-gradient-to-br from-slate-50 to-slate-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-slate-900 border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Redirecting..."})]})})}return(typeof window<"u"?sessionStorage.getItem("auth_provider"):null)==="tanflow"?e.jsx(hy,{}):e.jsx(Dh,{})}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(cD,{onLogout:c}),i&&e.jsx(gy,{isOpen:i,onClose:()=>l(!1)})]}):e.jsx(xy,{})}const Si=()=>{try{return!0}catch{return!1}},mD=()=>{if(Si())return null;try{return localStorage.getItem("token")}catch{return null}},uD={user:null,token:mD(),isAuthenticated:!1,isLoading:!1,error:null},M0=on({name:"auth",initialState:uD,reducers:{loginStart:t=>{t.isLoading=!0,t.error=null},loginSuccess:(t,s)=>{if(t.isLoading=!1,t.isAuthenticated=!0,t.user=s.payload.user,t.token=s.payload.token,t.error=null,!Si())try{localStorage.setItem("token",s.payload.token)}catch{}},loginFailure:(t,s)=>{if(t.isLoading=!1,t.isAuthenticated=!1,t.user=null,t.token=null,t.error=s.payload,!Si())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!Si())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:SD,loginSuccess:AD,loginFailure:TD,logout:kD,clearError:RD,updateUser:DD}=M0.actions,xD=Vb({reducer:{auth:M0.reducer,dashboard:Gh.reducer,requests:C0.reducer,myRequests:y0.reducer,openRequests:rp.reducer,closedRequests:f0.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});io.createRoot(document.getElementById("root")).render(e.jsx(Hf.StrictMode,{children:e.jsx(uj,{store:xD,children:e.jsx(Ej,{children:e.jsx(dD,{})})})}));export{je as a};
|