65 lines
1.6 MiB
65 lines
1.6 MiB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-BZ5VorhU.js","assets/radix-vendor-CLtqm-Ae.js","assets/charts-vendor-CmYZJIYl.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-DgwXkk2Y.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-HW_ujxKo.js"])))=>i.map(i=>d[i]);
|
||
var Xf=Object.defineProperty;var Zf=(t,s,a)=>s in t?Xf(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Ll=(t,s,a)=>Zf(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Ih,R as Ph,I as Eh,F as _h,a as Jf,T as qf,P as eb,C as tb,b as sb,O as Mh,c as Lh,d as ab,e as rb,f as nb,D as ib,g as lb,A as ob,h as cb,i as db,k as mb,l as ub,m as xb,n as hb,V as pb,o as gb,p as fb,q as bb,r as jb,s as yb,t as vb,u as Nb,v as wb,w as Cb,x as Sb,y as Ab,z as Tb,B as kb,E as Db,G as Rb,H as Fb,J as Ib,K as Pb,L as Eb,M as _b,N as Mb,Q as mc,U as uc,W as Lb,X as Oh,Y as $h,Z as Uh,_ as Bh,$ as Ob,a0 as $b,a1 as Ub,a2 as Bb,a3 as Vb,a4 as zb,a5 as Hb,a6 as Gb,a7 as Wb,a8 as cn,a9 as gr,aa as Zn,ab as Yb,ac as Qb,ad as Kb,ae as Xb}from"./radix-vendor-CLtqm-Ae.js";import{a as Zb,r as x,d as Vh,e as dn,B as Io,C as Yi,X as Qi,Y as Ki,T as mn,L as Xi,f as Ea,P as zh,g as Hh,h as Gh,i as Jb,j as cu,k as cl,l as dl,b as qb}from"./charts-vendor-CmYZJIYl.js";import{a as ml,f as Wh,s as ma,e as xc,b as du,c as ej,d as Oa,g as Jn,i as hc,h as Yh,j as ea,k as oa,l as Ol,m as Qa,n as tj,o as Po,p as sj,q as st,r as Eo,t as aj,u as rj,v as nj,w as ij,x as $l,y as mu,z as lj,A as Qh,B as Kh,C as pc,D as gc,E as oj,F as cj,G as Xh,H as Jr,I as Ul,J as dj,K as mj,L as uj}from"./utils-vendor-BTBPSQfW.js";import{u as W,A as js,S as fs,C as Je,a as ps,L as ze,X as yt,H as xj,b as Zh,U as Ht,F as Fe,c as Be,d as bn,R as Mt,e as jn,f as Ka,P as ms,g as hj,h as pj,B as _s,i as dr,j as Bl,k as fc,l as $a,m as ul,n as pn,o as ft,p as Ua,q as Et,I as Hr,T as ts,r as it,s as Ia,t as gj,v as ss,M as Ys,w as xl,x as Bt,y as _o,D as Tt,Z as hl,z as qt,E as fj,G as bj,J as jj,K as yj,N as vj,O as Nj,Q as wj,V as Cj,W as Sj,Y as Jh,_ as Aj,$ as Tj,a0 as qh,a1 as va,a2 as oi,a3 as mr,a4 as Zi,a5 as uu,a6 as wi,a7 as Ji,a8 as ep,a9 as St,aa as kj,ab as Qs,ac as bc,ad as ws,ae as pl,af as tp,ag as Nt,ah as Dj,ai as Rj,aj as sp,ak as gl,al as ap,am as Fj,an as jc,ao as ys,ap as Da,aq as rp,ar as fl,as as bl,at as Zt,au as Ij,av as Pj,aw as np,ax as ip,ay as Mi,az as or,aA as yc,aB as jl,aC as qn,aD as lp,aE as op,aF as vc,aG as yl,aH as vl,aI as Mo,aJ as Ej,aK as Vs,aL as cp,aM as qi,aN as _j,aO as Mj,aP as Lj,aQ as Nl,aR as wl,aS as Nc,aT as Oj,aU as xu,aV as Ba,aW as Gr,aX as $j,aY as sn,aZ as hu,a_ as Uj,a$ as Bj,b0 as dp,b1 as pu,b2 as mp,b3 as Vj,b4 as zj,b5 as Hj,b6 as Gj,b7 as up,b8 as Wj,b9 as Yj,ba as Qj,bb as Cl,bc as Kj,bd as Xj,be as Zj,bf as Jj}from"./ui-vendor-DgwXkk2Y.js";import{l as qj}from"./socket-vendor-TjCxX7sJ.js";import{c as yn,a as ey}from"./redux-vendor-tbZCm13o.js";import{u as Cs,a as Va,b as xp,c as ty,B as sy,R as ay,d as kt,O as ry}from"./router-vendor-HW_ujxKo.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 Lo={},gu=Zb;Lo.createRoot=gu.createRoot,Lo.hydrateRoot=gu.hydrateRoot;var hp={exports:{}},pp={};var ci=x;function ny(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var iy=typeof Object.is=="function"?Object.is:ny,ly=ci.useSyncExternalStore,oy=ci.useRef,cy=ci.useEffect,dy=ci.useMemo,my=ci.useDebugValue;pp.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=oy(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=dy(function(){function c(h){if(!d){if(d=!0,m=h,h=r(h),n!==void 0&&l.hasValue){var g=l.value;if(n(g,h))return p=g}return p=h}if(g=p,iy(m,h))return g;var f=r(h);return n!==void 0&&n(g,f)?(m=h,g):(m=h,p=f)}var d=!1,m,p,u=a===void 0?null:a;return[function(){return c(s())},u===null?void 0:function(){return c(u())}]},[s,a,r,n]);var o=ly(t,i[0],i[1]);return cy(function(){l.hasValue=!0,l.value=o},[o]),my(o),o};hp.exports=pp;var uy=hp.exports;function xy(t){t()}function hy(){let t=null,s=null;return{clear(){t=null,s=null},notify(){xy(()=>{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 fu={notify(){},get:()=>[]};function py(t,s){let a,r=fu,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=hy())}function p(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=fu)}function u(){i||(i=!0,m())}function h(){i&&(i=!1,p())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:u,tryUnsubscribe:h,getListeners:()=>r};return g}var gy=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",fy=gy(),by=()=>typeof navigator<"u"&&navigator.product==="ReactNative",jy=by(),yy=()=>fy||jy?x.useLayoutEffect:x.useEffect,vy=yy(),Vl=Symbol.for("react-redux-context"),zl=typeof globalThis<"u"?globalThis:{};function Ny(){if(!x.createContext)return{};const t=zl[Vl]??(zl[Vl]=new Map);let s=t.get(x.createContext);return s||(s=x.createContext(null),t.set(x.createContext,s)),s}var ur=Ny();function wy(t){const{children:s,context:a,serverState:r,store:n}=t,i=x.useMemo(()=>{const c=py(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=x.useMemo(()=>n.getState(),[n]);vy(()=>{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||ur;return x.createElement(o.Provider,{value:i},s)}var Cy=wy;function wc(t=ur){return function(){return x.useContext(t)}}var gp=wc();function fp(t=ur){const s=t===ur?gp:wc(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var Sy=fp();function Ay(t=ur){const s=t===ur?Sy:fp(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var Ty=Ay(),ky=(t,s)=>t===s;function Dy(t=ur){const s=t===ur?gp:wc(t),a=(r,n={})=>{const{equalityFn:i=ky}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;x.useRef(!0);const m=x.useCallback({[r.name](u){return r(u)}}[r.name],[r]),p=uy.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return x.useDebugValue(p),p};return Object.assign(a,{withTypes:()=>a}),a}var Ry=Dy(),Oo=function(t,s){return Oo=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])},Oo(t,s)};function Fy(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");Oo(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var el=function(){return el=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},el.apply(this,arguments)};var Ir=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Cc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Sc(t,s){return t(s={exports:{}},s.exports),s.exports}var kr=Sc(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()}});Cc(kr);var Iy=Cc(Sc(function(t,s){var a=Ir&&Ir.__awaiter||function(m,p,u,h){return new(u||(u=Promise))(function(g,f){function b(N){try{y(h.next(N))}catch(S){f(S)}}function j(N){try{y(h.throw(N))}catch(S){f(S)}}function y(N){N.done?g(N.value):new u(function(S){S(N.value)}).then(b,j)}y((h=h.apply(m,p||[])).next())})},r=Ir&&Ir.__generator||function(m,p){var u,h,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(N){return function(S){if(u)throw new TypeError("Generator is already executing.");for(;b;)try{if(u=1,h&&(g=2&S[0]?h.return:S[0]?h.throw||((g=h.return)&&g.call(h),0):h.next)&&!(g=g.call(h,S[1])).done)return g;switch(h=0,g&&(S=[2&S[0],g.value]),S[0]){case 0:case 1:g=S;break;case 4:return b.label++,{value:S[1],done:!1};case 5:b.label++,h=S[1],S=[0];continue;case 7:S=b.ops.pop(),b.trys.pop();continue;default:if(g=b.trys,!((g=g.length>0&&g[g.length-1])||S[0]!==6&&S[0]!==2)){b=0;continue}if(S[0]===3&&(!g||S[1]>g[0]&&S[1]<g[3])){b.label=S[1];break}if(S[0]===6&&b.label<g[1]){b.label=g[1],g=S;break}if(g&&b.label<g[2]){b.label=g[2],b.ops.push(S);break}g[2]&&b.ops.pop(),b.trys.pop();continue}S=p.call(m,b)}catch(A){S=[6,A],h=0}finally{u=g=0}if(5&S[0])throw S[1];return{value:S[0]?S[1]:void 0,done:!0}}([y,N])}}},n=Ir;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(u){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",u="",h=0;h<m;h++)u+=p[Math.floor(Math.random()*p.length)];return u}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,u){return u===void 0&&(u=5e3),a(this,void 0,void 0,function(){var h,g,f,b,j,y,N;return r(this,function(S){switch(S.label){case 0:h=Date.now()+c(4),g=Date.now()+u,f=i+"-"+p,b=this.storageHandler===void 0?l:this.storageHandler,S.label=1;case 1:return Date.now()<g?[4,o(30)]:[3,8];case 2:return S.sent(),b.getItemSync(f)!==null?[3,5]:(j=this.id+"-"+p+"-"+h,[4,o(Math.floor(25*Math.random()))]);case 3:return S.sent(),b.setItemSync(f,JSON.stringify({id:this.id,iat:h,timeoutKey:j,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,o(30)];case 4:return S.sent(),(y=b.getItemSync(f))!==null&&(N=JSON.parse(y)).id===this.id&&N.iat===h?(this.acquiredIatSet.add(h),this.refreshLockWhileAcquired(f,h),[2,!0]):[3,7];case 5:return m.lockCorrector(this.storageHandler===void 0?l:this.storageHandler),[4,this.waitForSomethingToChange(g)];case 6:S.sent(),S.label=7;case 7:return h=Date.now()+c(4),[3,1];case 8:return[2,!1]}})})},m.prototype.refreshLockWhileAcquired=function(p,u){return a(this,void 0,void 0,function(){var h=this;return r(this,function(g){return setTimeout(function(){return a(h,void 0,void 0,function(){var f,b,j;return r(this,function(y){switch(y.label){case 0:return[4,kr.default().lock(u)];case 1:return y.sent(),this.acquiredIatSet.has(u)?(f=this.storageHandler===void 0?l:this.storageHandler,(b=f.getItemSync(p))===null?(kr.default().unlock(u),[2]):((j=JSON.parse(b)).timeRefreshed=Date.now(),f.setItemSync(p,JSON.stringify(j)),kr.default().unlock(u),this.refreshLockWhileAcquired(p,u),[2])):(kr.default().unlock(u),[2])}})})},1e3),[2]})})},m.prototype.waitForSomethingToChange=function(p){return a(this,void 0,void 0,function(){return r(this,function(u){switch(u.label){case 0:return[4,new Promise(function(h){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 N=50-(Date.now()-f);N>0?setTimeout(h,N):h(null)}}window.addEventListener("storage",j),m.addToWaiting(j);var y=setTimeout(j,Math.max(0,p-Date.now()))})];case 1:return u.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(u){return u!==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(u){switch(u.label){case 0:return[4,this.releaseLock__private__(p)];case 1:return[2,u.sent()]}})})},m.prototype.releaseLock__private__=function(p){return a(this,void 0,void 0,function(){var u,h,g,f;return r(this,function(b){switch(b.label){case 0:return u=this.storageHandler===void 0?l:this.storageHandler,h=i+"-"+p,(g=u.getItemSync(h))===null?[2]:(f=JSON.parse(g)).id!==this.id?[3,2]:[4,kr.default().lock(f.iat)];case 1:b.sent(),this.acquiredIatSet.delete(f.iat),u.removeItemSync(h),kr.default().unlock(f.iat),m.notifyWaiters(),b.label=2;case 2:return[2]}})})},m.lockCorrector=function(p){for(var u=Date.now()-5e3,h=p,g=[],f=0;;){var b=h.keySync(f);if(b===null)break;g.push(b),f++}for(var j=!1,y=0;y<g.length;y++){var N=g[y];if(N.includes(i)){var S=h.getItemSync(N);if(S!==null){var A=JSON.parse(S);(A.timeRefreshed===void 0&&A.timeAcquired<u||A.timeRefreshed!==void 0&&A.timeRefreshed<u)&&(h.removeItemSync(N),j=!0)}}}j&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var Er=Sc(function(t,s){var a=Ir&&Ir.__assign||function(){return a=Object.assign||function(c){for(var d,m=1,p=arguments.length;m<p;m++)for(var u in d=arguments[m])Object.prototype.hasOwnProperty.call(d,u)&&(c[u]=d[u]);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 u=new Date;u.setMilliseconds(u.getMilliseconds()+864e5*p.expires),p.expires=u}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,u=0;u<m.length;u++){var h=m[u].split("="),g=h.slice(1).join("=");g.charAt(0)==='"'&&(g=g.slice(1,-1));try{d[h[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}))}});Cc(Er),Er.encode,Er.parse,Er.getAll;Er.get;Er.set;Er.remove;var bu;(function(t){t.Code="code",t.ConnectCode="connect_code"})(bu||(bu={}));var ju;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(ju||(ju={}));new Iy;var Py={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Zs=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},Ey=el(el({},Py),{buildAuthorizeUrl:Zs,buildLogoutUrl:Zs,getAccessTokenSilently:Zs,getAccessTokenWithPopup:Zs,getIdTokenClaims:Zs,loginWithRedirect:Zs,loginWithPopup:Zs,connectAccountWithRedirect:Zs,logout:Zs,handleRedirectCallback:Zs,getDpopNonce:Zs,setDpopNonce:Zs,generateDpopProof:Zs,createFetcher:Zs}),_y=x.createContext(Ey);(function(t){Fy(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 My=function(t){return t===void 0&&(t=_y),x.useContext(t)};const Hl="idToken",Gl="userData",Ly=()=>!0;class tt{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(Hl,s)}static getIdToken(){return sessionStorage.getItem(Hl)}static setUserData(s){localStorage.setItem(Gl,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(Gl);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(Gl),sessionStorage.removeItem(Hl)}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 Ly()}static setAuthError(s){s?sessionStorage.setItem("__auth_error__",s):sessionStorage.removeItem("__auth_error__")}static getAuthError(){return sessionStorage.getItem("__auth_error__")}}function Ci(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 bp="https://ssodev.rebridge.co.in/realms/RE",jp="REFLOW",yp=`${window.location.origin}/login/callback`,yu="https://reflow-uat.royalenfield.com/api/v1/".trim(),Oy=typeof window<"u"&&/^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname),$y=(!Oy&&/localhost:5000/i.test(yu)?"":yu.replace(/\/$/,""))||"/api/v1";function Uy(){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__"));const a=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","tanflow"),sessionStorage.setItem("tanflow_auth_state",a);let r=`${bp}/protocol/openid-connect/auth?client_id=${jp}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(yp)}&state=${a}`;s&&(r+="&prompt=login"),window.location.href=r}async function By(t,s){var a,r,n;try{const i=await ml.post(`${$y}/auth/tanflow/token-exchange`,{code:t,redirectUri:yp,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),l=((a=i.data)==null?void 0:a.data)||i.data;return l.accessToken&&tt.setAccessToken(l.accessToken),l.refreshToken&&tt.setRefreshToken(l.refreshToken),l.idToken&&tt.setIdToken(l.idToken),l.user&&tt.setUserData(l.user),l}catch(i){throw console.error("❌ Tanflow token exchange failed:",{message:i.message,response:(r=i.response)==null?void 0:r.data,status:(n=i.response)==null?void 0:n.status}),i}}function vp(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=new URL(`${bp}/protocol/openid-connect/logout`);s.searchParams.set("client_id",jp),s.searchParams.set("id_token_hint",t);const a=`${window.location.origin}/login/callback`;sessionStorage.setItem("__logout_type__","tanflow"),s.searchParams.set("post_logout_redirect_uri",a);const r=s.toString();sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),window.location.href=r}function Np(t){const s="https://royalenfield.okta.com",a=`${window.location.origin}/login/callback`;if(t){sessionStorage.setItem("__logout_type__","okta");const r=`${s}/oauth2/default/v1/logout?id_token_hint=${t}&post_logout_redirect_uri=${encodeURIComponent(a)}`;console.log("🚪 Initiating Okta logout redirect to callback (clean URI)"),window.location.href=r}else sessionStorage.setItem("__logout_type__","okta"),console.log("🚪 No id_token for Okta logout, redirecting to callback"),window.location.href=a}const vu="https://reflow-uat.royalenfield.com/api/v1/".trim(),Vy=typeof window<"u"&&/^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname),Ac=(!Vy&&/localhost:5000/i.test(vu)?"":vu.replace(/\/$/,""))||"/api/v1",ve=ml.create({baseURL:Ac,headers:{"Content-Type":"application/json"},withCredentials:!0});ve.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));ve.interceptors.response.use(t=>t,async t=>{var a,r,n,i;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){if(((i=(n=t.response)==null?void 0:n.data)==null?void 0:i.errorCode)==="SESSION_SUPERSEDED"){const l=tt.getIdToken(),o=sessionStorage.getItem("auth_provider")||(l!=null&&l.includes("tanflow")?"tanflow":"okta");return tt.setAuthError("SESSION_SUPERSEDED"),W.error("You have been logged out because an active session was detected from another device.",{duration:2e3,id:"session-superseded-toast"}),setTimeout(async()=>{sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),o==="tanflow"&&l?vp(l):Np(l||void 0)},1e3),Promise.reject(t)}if(!s._retry){s._retry=!0;const l=!0;try{const o=tt.getRefreshToken(),c=await ml.post(`${Ac}/auth/refresh`,l?{}:{refreshToken:o},{withCredentials:!0}),m=(c.data.data||c.data).accessToken;return ve(s)}catch(o){return tt.clearAll(),window.location.href="/",Promise.reject(o)}}}return Promise.reject(t)});async function zy(t,s){const r=(await ve.post("/auth/login",{username:t,password:s},{withCredentials:!0})).data,n=r.data||r;return n.user&&tt.setUserData(n.user),n.accessToken&&n.refreshToken&&(tt.setAccessToken(n.accessToken),tt.setRefreshToken(n.refreshToken)),n}async function Hy(t,s){var a,r;try{const n=await ve.post("/auth/token-exchange",{code:t,redirectUri:s},{responseType:"json",headers:{"Content-Type":"application/json",Accept:"application/json"}});if(Array.isArray(n.data))throw console.error("❌ Response is an array (buffer issue):",{arrayLength:n.data.length,firstFew:n.data.slice(0,10),rawResponse:n}),new Error("Invalid response format: received array instead of JSON. Check Content-Type header.");const i=n.data,l=i.data||i;return l.user&&tt.setUserData(l.user),l.idToken&&tt.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(tt.setAccessToken(l.accessToken),tt.setRefreshToken(l.refreshToken)),l}catch(n){throw console.error("❌ Token exchange failed:",{message:n.message,response:(a=n.response)==null?void 0:a.data,status:(r=n.response)==null?void 0:r.status,code:t?`${t.substring(0,10)}...`:"MISSING",redirectUri:s}),n}}async function Gy(){var r;const t={},a=(await ve.post("/auth/refresh",t)).data;if((r=a.data)!=null&&r.accessToken||a.accessToken,a.success!==!1)return"cookie-based-auth";throw new Error("Failed to refresh token")}async function Bn(){const s=(await ve.get("/auth/me")).data;return s.data||s}async function Wy(){var t,s;try{await ml.post(`${Ac}/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})}}let Sr=null;function Yy(){return"https://reflow-uat.royalenfield.com"}function Vr(t){const s=Yy();return Sr||(Sr=qj(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),Sr.on("connect",()=>{}),Sr.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),Sr.on("disconnect",a=>{}),Sr)}function $o(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function wp(t,s){t.emit("leave:request",s)}function Tc(t,s){t.emit("join:user",{userId:s})}const Qy=/^(localhost|127\.0\.0\.1)$/i;function Ky(){return typeof window>"u"?"":window.location.hostname||""}function Cp(){return Qy.test(Ky())}function Fn(){return!Cp()}function rr(t){return String(t||"").trim()}function Xy(t){const s=(t||"").toLowerCase();return s.includes("uat")||s.includes("dev")}function Zy(){const t=typeof window<"u"?window.location.hostname:"",s=Cp(),a=!s&&Xy(t),r=rr("https://royalenfield.okta.com"),n=rr("0oa18b98aari6I6eo2p8"),i=rr(void 0),l=rr(void 0),o=rr(void 0),c=rr(void 0),d=rr(void 0),m=rr(void 0);return s?{domain:i||r,clientId:l||n}:a?{domain:o||r,clientId:c||n}:{domain:d||r,clientId:m||n}}const Sp=x.createContext(void 0);function Jy({children:t}){const[s,a]=x.useState(!1),[r,n]=x.useState(!0),[i,l]=x.useState(null),[o,c]=x.useState(null),[d,m]=x.useState(!1),p=()=>{const A="https://reflow-uat.royalenfield.com".trim(),w="".trim(),I="".trim(),D=window.location.origin,T=window.location.hostname,v=/^(localhost|127\.0\.0\.1)$/i.test(T);return v&&I?I:w||(v?`${D}/login/callback`:/localhost|127\.0\.0\.1/i.test(A)?`${D}/login/callback`:`${(A||D).replace(/\/$/,"")}/login/callback`)};x.useEffect(()=>{const A=sessionStorage.getItem("__logout_in_progress__"),w=sessionStorage.getItem("__force_logout__");if(A==="true"||w==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),tt.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(L){console.error("Error clearing storage:",L)}a(!1),l(null),n(!1),c(null);return}const I=new URLSearchParams(window.location.search),D=I.has("code"),T=sessionStorage.getItem("__logout_type__");if((I.has("logout")||I.has("okta_logged_out")||I.has("tanflow_logged_out")||T)&&!D){console.log("🚪 Logout parameter detected in URL, clearing all tokens and backend session"),Wy().catch(L=>console.warn("🚪 Final backend logout cleanup failed:",L)),tt.clearAll(),sessionStorage.removeItem("__logout_type__"),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(L){console.warn("Could not set force reauth flag:",L)}window.history.replaceState({},document.title,"/");return}if(window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback")return;const M=tt.getAccessToken(),P=tt.getRefreshToken(),B=tt.getUserData(),k=M||P||B;if(Fn())d?n(!1):g();else{if(!k){a(!1),l(null),n(!1);return}d?n(!1):g()}},[d]),x.useEffect(()=>{if(!s)return;const A=Fn(),w=async()=>{if(A)try{await N()}catch(T){console.error("Silent refresh failed:",T)}else{const T=tt.getAccessToken();if(T&&Ci(T,5))try{await N()}catch(v){console.error("Silent refresh failed:",v)}}},I=A?10*60*1e3:5*60*1e3,D=setInterval(w,I);return()=>clearInterval(D)},[s]),x.useEffect(()=>{if(!s||!(i!=null&&i.userId))return;const A=Vr();Tc(A,i.userId);const w=I=>{console.log("📡 [Socket] Session superseded event received:",I),tt.setAuthError("SESSION_SUPERSEDED"),W.error("Session Expired",{description:"You have been logged out because another session was started on a different device.",duration:4e3,id:"session-superseded-socket"}),setTimeout(()=>{j()},1e3)};return A.on("SESSION_SUPERSEDED",w),()=>{A.off("SESSION_SUPERSEDED",w)}},[s,i==null?void 0:i.userId]);const u=x.useRef(!1),h=x.useRef(null);x.useEffect(()=>{if(u.current||window.location.pathname!=="/login/callback")return;(async()=>{var B,k,_,L;const w=new URLSearchParams(window.location.search);if(sessionStorage.getItem("auth_provider")==="tanflow")return;const D=sessionStorage.getItem("__logout_type__");if((w.has("logout")||w.has("tanflow_logged_out")||w.has("okta_logged_out")||D)&&!w.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const R=new URLSearchParams;(w.has("tanflow_logged_out")||D==="tanflow")&&R.set("tanflow_logged_out","true"),(w.has("okta_logged_out")||D==="okta")&&R.set("okta_logged_out","true"),w.has("logout")&&R.set("logout",w.get("logout")||Date.now().toString());const C=R.toString()?`/?${R.toString()}`:"/?logout="+Date.now();window.location.replace(C);return}u.current=!0;const v=w.get("code"),M=w.get("error");if(window.history.replaceState({},document.title,"/login/callback"),M){c(new Error(`Authentication error: ${M}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!v){n(!1),sessionStorage.removeItem("auth_provider");return}const P=sessionStorage.getItem("__okta_auth_code_consumed__");if(P&&P===v){c(new Error("Authorization code already used. Please login again.")),n(!1),sessionStorage.removeItem("auth_provider");return}if(h.current!==v){h.current=v,sessionStorage.setItem("__okta_auth_code_consumed__",v);try{n(!0),a(!1),c(null);const R=p(),C=await Hy(v,R);l(C.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(R){console.error("❌ Token exchange error in AuthContext:",R);const C=String(((k=(B=R==null?void 0:R.response)==null?void 0:B.data)==null?void 0:k.error)||"").toUpperCase(),G=String(((L=(_=R==null?void 0:R.response)==null?void 0:_.data)==null?void 0:L.message)||(R==null?void 0:R.message)||"").toLowerCase();if(C==="RELOGIN_REQUIRED"||G.includes("invalid or has expired")||G.includes("invalid_grant")||G.includes("authorization code already used")){a(!1),l(null),c(new Error("Login session expired. Please sign in again.")),sessionStorage.removeItem("auth_provider"),window.location.replace("/?relogin_required=1");return}c(R),a(!1),l(null),sessionStorage.removeItem("auth_provider"),u.current=!1}finally{n(!1)}}})()},[]);const g=async()=>{var w;if(d){n(!1);return}const A=Fn();try{if(n(!0),A){const T=tt.getUserData();try{const v=await Bn();l(v),tt.setUserData(v),a(!0)}catch(v){if(((w=v==null?void 0:v.response)==null?void 0:w.status)===401)try{await N();const M=await Bn();l(M),tt.setUserData(M),a(!0)}catch{tt.clearAll(),a(!1),l(null)}else v!=null&&v.isConnectionError?T?(l(T),a(!0)):(a(!1),l(null)):(tt.clearAll(),a(!1),l(null))}return}const I=tt.getAccessToken(),D=tt.getUserData();if(!I){a(!1),l(null),n(!1);return}if(Ci(I))try{await N();const T=tt.getAccessToken();if(T&&!Ci(T)){const v=tt.getUserData();if(v)l(v),a(!0);else try{const M=await Bn();l(M),tt.setUserData(M),a(!0)}catch{tt.clearAll(),a(!1),l(null)}}else tt.clearAll(),a(!1),l(null)}catch{tt.clearAll(),a(!1),l(null)}else if(D)l(D),a(!0);else try{const T=await Bn();l(T),tt.setUserData(T),a(!0)}catch{tt.clearAll(),a(!1),l(null)}}catch(I){console.error("Error checking auth status:",I),c(I),tt.clearAll(),a(!1),l(null)}finally{n(!1)}},f=async()=>{try{c(null);const{domain:A,clientId:w}=Zy();if(!A||!w)throw new Error("Missing Okta configuration (VITE_OKTA_DOMAIN / VITE_OKTA_CLIENT_ID).");const I=p(),D="code",T="openid profile email",v=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const M=new URLSearchParams(window.location.search),P=M.has("logout")||M.has("okta_logged_out")||M.has("tanflow_logged_out"),B=sessionStorage.getItem("__force_reauth_after_logout__")==="true",k=P||B;let _=`${A}/oauth2/default/v1/authorize?client_id=${w}&redirect_uri=${encodeURIComponent(I)}&response_type=${D}&scope=${encodeURIComponent(T)}&state=${v}`;k&&(_+="&prompt=login",sessionStorage.removeItem("__force_reauth_after_logout__")),window.location.href=_}catch(A){throw c(A),A}},b=async(A,w)=>{c(null),n(!0);try{const I=await zy(A,w);l(I.user),a(!0),window.history.replaceState({},document.title,"/")}catch(I){throw c(I),a(!1),l(null),I}finally{n(!1)}},j=async()=>{try{const A=tt.getIdToken(),w=sessionStorage.getItem("auth_provider")||(A&&A.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);const I=sessionStorage.getItem("__logout_in_progress__"),D=sessionStorage.getItem("__force_logout__"),T=sessionStorage.getItem("auth_provider");if(tt.clearAll(),I&&sessionStorage.setItem("__logout_in_progress__",I),D&&sessionStorage.setItem("__force_logout__",D),A&&tt.setIdToken(A),T&&sessionStorage.setItem("auth_provider",T),await new Promise(v=>setTimeout(v,100)),w==="tanflow"&&A){console.log("🚪 Initiating Tanflow logout...");try{vp(A);return}catch(v){console.error("🚪 Tanflow logout error:",v)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),Np(A||void 0)}catch(A){console.error("🚪 Logout error:",A);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const w=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(w)}catch{window.location.replace("/?logout="+Date.now())}}},y=async()=>{if(Fn()){if(s)return"cookie-based-auth";try{return await N(),s?"cookie-based-auth":null}catch{return null}}const w=tt.getAccessToken();if(w&&!Ci(w))return w;try{return await N(),tt.getAccessToken()}catch{return null}},N=async()=>{const A=Fn();try{const w=await Gy();if(A||w)return;throw new Error("Failed to refresh token")}catch(w){throw tt.clearAll(),a(!1),l(null),w}},S={isAuthenticated:s,isLoading:r,user:i,error:o,login:f,loginWithPassword:b,logout:j,getAccessTokenSilently:y,refreshTokenSilently:N};return e.jsx(Sp.Provider,{value:S,children:t})}function qy({children:t}){return e.jsx(Jy,{children:t})}function us(){const t=x.useContext(Sp);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Dr(t){return(t==null?void 0:t.role)==="ADMIN"}function In(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function Sl(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Nu=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,wu=Vh,kc=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return wu(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 u=Nu(m)||Nu(p);return n[d][u]}),o=a&&Object.entries(a).reduce((d,m)=>{let[p,u]=m;return u===void 0||(d[p]=u),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:p,className:u,...h}=m;return Object.entries(h).every(g=>{let[f,b]=g;return Array.isArray(b)?b.includes({...i,...o}[f]):{...i,...o}[f]===b})?[...d,p,u]:d},[]);return wu(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},Dc="-",ev=t=>{const s=sv(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(Dc);return o[0]===""&&o.length!==1&&o.shift(),Ap(o,s)||tv(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},Ap=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Ap(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Dc);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Cu=/^\[(.+)\]$/,tv=t=>{if(Cu.test(t)){const s=Cu.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},sv=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return rv(Object.entries(t.classGroups),a).forEach(([i,l])=>{Uo(l,r,i,s)}),r},Uo=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:Su(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(av(n)){Uo(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{Uo(l,Su(s,i),a,r)})})},Su=(t,s)=>{let a=t;return s.split(Dc).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},av=t=>t.isThemeGetter,rv=(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,nv=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)}}},Tp="!",iv=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 u=c.length===0?o:o.substring(m),h=u.startsWith(Tp),g=h?u.substring(1):u,f=p&&p>m?p-m:void 0;return{modifiers:c,hasImportantModifier:h,baseClassName:g,maybePostfixModifierPosition:f}};return a?o=>a({className:o,parseClassName:l}):l},lv=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},ov=t=>({cache:nv(t.cacheSize),parseClassName:iv(t),...ev(t)}),cv=/\s+/,dv=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(cv);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:p,baseClassName:u,maybePostfixModifierPosition:h}=a(d);let g=!!h,f=r(g?u.substring(0,h):u);if(!f){if(!g){o=d+(o.length>0?" "+o:o);continue}if(f=r(u),!f){o=d+(o.length>0?" "+o:o);continue}g=!1}const b=lv(m).join(":"),j=p?b+Tp:b,y=j+f;if(i.includes(y))continue;i.push(y);const N=n(f,g);for(let S=0;S<N.length;++S){const A=N[S];i.push(j+A)}o=d+(o.length>0?" "+o:o)}return o};function mv(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=kp(s))&&(r&&(r+=" "),r+=a);return r}const kp=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=kp(t[r]))&&(a&&(a+=" "),a+=s);return a};function uv(t,...s){let a,r,n,i=l;function l(c){const d=s.reduce((m,p)=>p(m),t());return a=ov(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=dv(c,a);return n(c,m),m}return function(){return i(mv.apply(null,arguments))}}const Kt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},Dp=/^\[(?:([a-z-]+):)?(.+)\]$/i,xv=/^\d+\/\d+$/,hv=new Set(["px","full","screen"]),pv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,gv=/\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$/,fv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,bv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,jv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ga=t=>un(t)||hv.has(t)||xv.test(t),nr=t=>vn(t,"length",Tv),un=t=>!!t&&!Number.isNaN(Number(t)),Wl=t=>vn(t,"number",un),Pn=t=>!!t&&Number.isInteger(Number(t)),yv=t=>t.endsWith("%")&&un(t.slice(0,-1)),jt=t=>Dp.test(t),ir=t=>pv.test(t),vv=new Set(["length","size","percentage"]),Nv=t=>vn(t,vv,Rp),wv=t=>vn(t,"position",Rp),Cv=new Set(["image","url"]),Sv=t=>vn(t,Cv,Dv),Av=t=>vn(t,"",kv),En=()=>!0,vn=(t,s,a)=>{const r=Dp.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},Tv=t=>gv.test(t)&&!fv.test(t),Rp=()=>!1,kv=t=>bv.test(t),Dv=t=>jv.test(t),Rv=()=>{const t=Kt("colors"),s=Kt("spacing"),a=Kt("blur"),r=Kt("brightness"),n=Kt("borderColor"),i=Kt("borderRadius"),l=Kt("borderSpacing"),o=Kt("borderWidth"),c=Kt("contrast"),d=Kt("grayscale"),m=Kt("hueRotate"),p=Kt("invert"),u=Kt("gap"),h=Kt("gradientColorStops"),g=Kt("gradientColorStopPositions"),f=Kt("inset"),b=Kt("margin"),j=Kt("opacity"),y=Kt("padding"),N=Kt("saturate"),S=Kt("scale"),A=Kt("sepia"),w=Kt("skew"),I=Kt("space"),D=Kt("translate"),T=()=>["auto","contain","none"],v=()=>["auto","hidden","clip","visible","scroll"],M=()=>["auto",jt,s],P=()=>[jt,s],B=()=>["",Ga,nr],k=()=>["auto",un,jt],_=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],R=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],C=()=>["start","end","center","between","around","evenly","stretch"],G=()=>["","0",jt],U=()=>["auto","avoid","all","avoid-page","page","left","right","column"],$=()=>[un,jt];return{cacheSize:500,separator:":",theme:{colors:[En],spacing:[Ga,nr],blur:["none","",ir,jt],brightness:$(),borderColor:[t],borderRadius:["none","","full",ir,jt],borderSpacing:P(),borderWidth:B(),contrast:$(),grayscale:G(),hueRotate:$(),invert:G(),gap:P(),gradientColorStops:[t],gradientColorStopPositions:[yv,nr],inset:M(),margin:M(),opacity:$(),padding:P(),saturate:$(),scale:$(),sepia:G(),skew:$(),space:P(),translate:P()},classGroups:{aspect:[{aspect:["auto","square","video",jt]}],container:["container"],columns:[{columns:[ir]}],"break-after":[{"break-after":U()}],"break-before":[{"break-before":U()}],"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:[..._(),jt]}],overflow:[{overflow:v()}],"overflow-x":[{"overflow-x":v()}],"overflow-y":[{"overflow-y":v()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],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",Pn,jt]}],basis:[{basis:M()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",jt]}],grow:[{grow:G()}],shrink:[{shrink:G()}],order:[{order:["first","last","none",Pn,jt]}],"grid-cols":[{"grid-cols":[En]}],"col-start-end":[{col:["auto",{span:["full",Pn,jt]},jt]}],"col-start":[{"col-start":k()}],"col-end":[{"col-end":k()}],"grid-rows":[{"grid-rows":[En]}],"row-start-end":[{row:["auto",{span:[Pn,jt]},jt]}],"row-start":[{"row-start":k()}],"row-end":[{"row-end":k()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",jt]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",jt]}],gap:[{gap:[u]}],"gap-x":[{"gap-x":[u]}],"gap-y":[{"gap-y":[u]}],"justify-content":[{justify:["normal",...C()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...C(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...C(),"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":[I]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[I]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",jt,s]}],"min-w":[{"min-w":[jt,s,"min","max","fit"]}],"max-w":[{"max-w":[jt,s,"none","full","min","max","fit","prose",{screen:[ir]},ir]}],h:[{h:[jt,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[jt,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[jt,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[jt,s,"auto","min","max","fit"]}],"font-size":[{text:["base",ir,nr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Wl]}],"font-family":[{font:[En]}],"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",jt]}],"line-clamp":[{"line-clamp":["none",un,Wl]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Ga,jt]}],"list-image":[{"list-image":["none",jt]}],"list-style-type":[{list:["none","disc","decimal",jt]}],"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:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Ga,nr]}],"underline-offset":[{"underline-offset":["auto",Ga,jt]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:P()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",jt]}],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",jt]}],"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:[..._(),wv]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Nv]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Sv]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],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:[...L(),"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:L()}],"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:["",...L()]}],"outline-offset":[{"outline-offset":[Ga,jt]}],"outline-w":[{outline:[Ga,nr]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:B()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[Ga,nr]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",ir,Av]}],"shadow-color":[{shadow:[En]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...R(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":R()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",ir,jt]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[N]}],sepia:[{sepia:[A]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[N]}],"backdrop-sepia":[{"backdrop-sepia":[A]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",jt]}],duration:[{duration:$()}],ease:[{ease:["linear","in","out","in-out",jt]}],delay:[{delay:$()}],animate:[{animate:["none","spin","ping","pulse","bounce",jt]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[Pn,jt]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[w]}],"skew-y":[{"skew-y":[w]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",jt]}],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",jt]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":P()}],"scroll-mx":[{"scroll-mx":P()}],"scroll-my":[{"scroll-my":P()}],"scroll-ms":[{"scroll-ms":P()}],"scroll-me":[{"scroll-me":P()}],"scroll-mt":[{"scroll-mt":P()}],"scroll-mr":[{"scroll-mr":P()}],"scroll-mb":[{"scroll-mb":P()}],"scroll-ml":[{"scroll-ml":P()}],"scroll-p":[{"scroll-p":P()}],"scroll-px":[{"scroll-px":P()}],"scroll-py":[{"scroll-py":P()}],"scroll-ps":[{"scroll-ps":P()}],"scroll-pe":[{"scroll-pe":P()}],"scroll-pt":[{"scroll-pt":P()}],"scroll-pr":[{"scroll-pr":P()}],"scroll-pb":[{"scroll-pb":P()}],"scroll-pl":[{"scroll-pl":P()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",jt]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Ga,nr,Wl]}],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"]}}},Fv=uv(Rv);function Le(...t){return Fv(Vh(t))}const ei=kc("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=x.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Ih:"button";return e.jsx(l,{"data-slot":"button",className:Le(ei({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:Le("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function ce({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:Le("@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 de({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:Le("leading-none",t),...s})}function we({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:Le("text-muted-foreground",t),...s})}function J({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:Le("px-6 [&:last-child]:pb-6",t),...s})}const Al="/assets/Re_Logo-By51taPS.png",Au="/assets/landing_page_image-ClTD-4qZ.jpg";function Iv(){var p,u;const{login:t,isLoading:s,error:a}=us(),[r,n]=x.useState(!1),[i,l]=x.useState(null),[o,c]=x.useState(!1);x.useEffect(()=>{const h=new Image;h.src=Au,h.onload=()=>c(!0),h.complete&&c(!0)},[]);const d=async()=>{const h=sessionStorage.getItem("__force_reauth_after_logout__");localStorage.clear(),sessionStorage.clear(),h&&sessionStorage.setItem("__force_reauth_after_logout__",h);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{Uy()}catch(h){const g=h instanceof Error?h.message:"Dealer login failed. Check console for details.";console.error("TANFLOW LOGIN ERROR",h),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(${Au})`:"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(ce,{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:Al,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(J,{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"))||((u=a.message)==null?void 0:u.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(js,{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(fs,{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 Fp(){const{isAuthenticated:t,isLoading:s,error:a,user:r,login:n}=us(),[i,l]=x.useState("exchanging");x.useEffect(()=>{if(a){l("error");return}if(s){const d=new URLSearchParams(window.location.search).get("code");l(d&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&l("complete")},[t,s,a,r]);const o=()=>{switch(i){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:Al,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:i==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(Je,{className:"w-16 h-16 text-red-500"})}),e.jsx(Je,{className:"w-16 h-16 text-red-500 relative"})]}):i==="complete"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(ps,{className:"w-16 h-16 text-green-500"})}),e.jsx(ps,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(ze,{className:"w-16 h-16 animate-spin text-re-red"}),e.jsx("div",{className:"absolute inset-0 border-4 rounded-full border-re-red/20"}),e.jsx("div",{className:"absolute inset-0 border-4 border-transparent border-t-re-red rounded-full animate-spin"})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-white mb-2",children:i==="complete"?"Welcome Back!":i==="error"?"Authentication Error":"Authenticating"}),e.jsx("p",{className:"text-slate-300 text-sm",children:o()})]}),i!=="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 ${i==="exchanging"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${i==="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 ${i==="fetching"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${i==="fetching"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Loading your profile"})]}),i==="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"})]})]}),i==="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:async()=>{try{await n()}catch{window.location.href="/"}},className:"mt-4 text-sm text-red-400 hover:text-red-300 underline",children:"Retry Login"})]}),i!=="error"&&i!=="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:i==="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 Pv(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=us(),[n,i]=x.useState("exchanging"),[l,o]=x.useState(""),c=x.useRef(!1);x.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]),x.useEffect(()=>{if(c.current||window.location.pathname!=="/login/callback")return;const m=new URLSearchParams(window.location.search),p=m.get("code"),u=m.get("error");if(!p&&!u){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 N=sessionStorage.getItem("tanflow_auth_state");if(j&&j!==N){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 S=await By(b,j||"");sessionStorage.removeItem("tanflow_auth_state"),i("fetching");const A=S.user||await Bn();if(A)tt.setUserData(A),i("complete"),setTimeout(()=>{window.history.replaceState({},document.title,"/"),window.location.href="/"},1e3);else throw new Error("User data not received")}catch(S){console.error("Tanflow callback error:",S),i("error"),o(S.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:Al,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(Je,{className:"w-16 h-16 text-red-500"})}),e.jsx(Je,{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(ps,{className:"w-16 h-16 text-green-500"})}),e.jsx(ps,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(ze,{className:"w-16 h-16 animate-spin text-re-red"}),e.jsx("div",{className:"absolute inset-0 border-4 rounded-full border-re-red/20"}),e.jsx("div",{className:"absolute inset-0 border-4 border-transparent border-t-re-red rounded-full animate-spin"})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-white mb-2",children:n==="complete"?"Welcome Back!":n==="error"?"Authentication Error":"Authenticating"}),e.jsx("p",{className:"text-slate-300 text-sm",children:d()})]}),n!=="error"&&e.jsxs("div",{className:"space-y-3 mb-6",children:[e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="exchanging"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="exchanging"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Validating credentials"})]}),e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="fetching"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="fetching"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Loading your profile"})]}),n==="complete"&&e.jsxs("div",{className:"flex items-center gap-3 text-sm transition-all duration-500 text-white",children:[e.jsx("div",{className:"w-2 h-2 rounded-full transition-all duration-500 bg-green-500"}),e.jsx("span",{children:"Setting up your session"})]})]}),n==="error"&&l&&e.jsxs("div",{className:"mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx("p",{className:"text-red-400 text-sm",children:l}),e.jsx("button",{onClick:()=>{window.location.href="/"},className:"mt-4 text-sm text-red-400 hover:text-red-300 underline",children:"Return to login"})]}),n!=="error"&&n!=="complete"&&e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"h-1.5 bg-slate-700/50 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-re-red rounded-full animate-pulse",style:{animation:"progress 2s ease-in-out infinite"}})}),e.jsx("style",{children:`
|
||
@keyframes progress {
|
||
0%, 100% { width: 20%; }
|
||
50% { width: 80%; }
|
||
}
|
||
`})]})]}),e.jsx("p",{className:"mt-6 text-slate-500 text-xs",children:n==="complete"?"Loading dashboard...":"Please wait while we secure your session"})]}),e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute top-1/4 left-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-1/4 right-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse delay-1000"})]})]})}const Ev=kc("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 re({className:t,variant:s,asChild:a=!1,...r}){const n=a?Ih:"span";return e.jsx(n,{"data-slot":"badge",className:Le(Ev({variant:s}),t),...r})}function _v({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=My();return x.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(ce,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{children:"Authentication Debug Information"}),e.jsx(E,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(yt,{className:"h-4 w-4"})})]})}),e.jsxs(J,{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(re,{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 cs=x.forwardRef(({className:t,...s},a)=>e.jsx(Ph,{ref:a,"data-slot":"avatar",className:Le("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));cs.displayName=Ph.displayName;const Tl=x.forwardRef(({className:t,...s},a)=>e.jsx(Eh,{ref:a,"data-slot":"avatar-image",className:Le("aspect-square size-full",t),...s}));Tl.displayName=Eh.displayName;const ds=x.forwardRef(({className:t,...s},a)=>e.jsx(_h,{ref:a,"data-slot":"avatar-fallback",className:Le("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));ds.displayName=_h.displayName;function Tu({...t}){return e.jsx(Jf,{"data-slot":"dropdown-menu",...t})}function ku({...t}){return e.jsx(qf,{"data-slot":"dropdown-menu-trigger",...t})}function Du({className:t,sideOffset:s=4,...a}){return e.jsx(eb,{children:e.jsx(tb,{"data-slot":"dropdown-menu-content",sideOffset:s,className:Le("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 Yl({className:t,inset:s,variant:a="default",...r}){return e.jsx(sb,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:Le("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 Ip({...t}){return e.jsx(rb,{"data-slot":"alert-dialog",...t})}function Mv({...t}){return e.jsx(ab,{"data-slot":"alert-dialog-portal",...t})}const Pp=x.forwardRef(({className:t,...s},a)=>e.jsx(Mh,{"data-slot":"alert-dialog-overlay",className:Le("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}));Pp.displayName=Mh.displayName;const Rc=x.forwardRef(({className:t,...s},a)=>e.jsxs(Mv,{children:[e.jsx(Pp,{}),e.jsx(Lh,{"data-slot":"alert-dialog-content",ref:a,className:Le("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})]}));Rc.displayName=Lh.displayName;function Ep({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:Le("flex flex-col gap-2 text-center sm:text-left",t),...s})}function _p({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:Le("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function Mp({className:t,...s}){return e.jsx(nb,{"data-slot":"alert-dialog-title",className:Le("text-lg font-semibold",t),...s})}function Lp({className:t,...s}){return e.jsx(ib,{"data-slot":"alert-dialog-description",className:Le("text-muted-foreground text-sm",t),...s})}function Op({className:t,...s}){return e.jsx(ob,{className:Le(ei(),t),...s})}function $p({className:t,...s}){return e.jsx(lb,{className:Le(ei({variant:"outline"}),t),...s})}const cr={async list(t){return(await ve.get("/notifications",{params:t})).data},async getUnreadCount(){return(await ve.get("/notifications/unread-count")).data},async markAsRead(t){return(await ve.patch(`/notifications/${t}/read`)).data},async markAllAsRead(){return(await ve.post("/notifications/mark-all-read")).data},async delete(t){return(await ve.delete(`/notifications/${t}`)).data}},Lv=async()=>(await ve.get("/notifications/subscriptions")).data.data.subscriptions,Ru="https://reflow-uat.royalenfield.com/api/v1/".trim(),Ov=typeof window<"u"&&/^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname),Up=(!Ov&&/localhost:5000/i.test(Ru)?"":Ru.replace(/\/$/,""))||"/api/v1";async function Bp(t,s={}){const a=tt.getAccessToken(),r={...s.headers||{}};s.body instanceof FormData||(r["Content-Type"]="application/json"),a&&(r.Authorization=`Bearer ${a}`);const n=await fetch(`${Up}${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 Fc(){var a;const t=await ve.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 $v(){const{data:t}=await ve.get("/form16/26as/dashboard"),s=t&&typeof t=="object"&&"data"in t?t.data:t;if(!(s!=null&&s.overall)||!(s!=null&&s.kpi))throw new Error("Invalid Form16 dashboard response");return s}async function Vp(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 ve.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 zp(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/debit-notes?${a}`:"/form16/debit-notes",{data:n}=await ve.get(r),i=(n==null?void 0:n.data)??n;return{debitNotes:(i==null?void 0:i.debitNotes)??[],total:(i==null?void 0:i.total)??0,summary:i==null?void 0:i.summary}}async function Hp(t){const{data:s}=await ve.get(`/form16/debit-notes/${t}/sap-response`),a=s&&typeof s=="object"&&"data"in s?s.data:s;if(!(a!=null&&a.sapResponse))throw new Error("SAP response not available");return{...a,url:`/api/v1/form16/debit-notes/${t}/sap-response/csv`}}async function Ic(t){const{data:s}=await ve.get(`/form16/credit-notes/${t}/sap-response`),a=s&&typeof s=="object"&&"data"in s?s.data:s;if(!(a!=null&&a.sapResponse))throw new Error("SAP response not available");return{...a,url:`/api/v1/form16/credit-notes/${t}/sap-response/csv`}}async function Gp(t){const{data:s}=await ve.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 Uv(t){await ve.post(`/form16/requests/${encodeURIComponent(t)}/cancel-submission`)}async function Bv(t){await ve.post(`/form16/requests/${encodeURIComponent(t)}/resubmission-needed`)}async function Fu(t){const{data:s}=await ve.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 Vv(t){const s=new FormData;s.append("document",t);const a=await Bp("/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 zv(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 Bp("/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 Hv(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 ve.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 Gv(t){var l;const s=new URLSearchParams;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/upload-history?${a}`:"/form16/26as/upload-history",{data:n}=await ve.get(r),i=(n==null?void 0:n.data)??n;return{history:(i==null?void 0:i.history)??[],total:typeof(i==null?void 0:i.total)=="number"?i.total:((l=i==null?void 0:i.history)==null?void 0:l.length)??0}}const Wv=5*60*1e3;function Yv(t,s){return new Promise((a,r)=>{const n=new FormData;n.append("file",t);const i=new XMLHttpRequest,l=`${Up}/form16/26as/upload`,o=tt.getAccessToken(),c=setTimeout(()=>{i.abort(),r(new Error("Upload timed out. Try a smaller file or try again."))},Wv);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 u;try{u=m?JSON.parse(p):{message:p||"Request failed"}}catch{u={message:p||"Invalid response"}}if(i.status>=200&&i.status<300){const h=u.data??u;a({imported:(h==null?void 0:h.imported)??0,errors:Array.isArray(h==null?void 0:h.errors)?h.errors:[]})}else r(new Error(u.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 Qv(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 ve.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 Kv(t){var l;const s=String(t.dealerCode??"").trim(),a=String(t.dealerId??"").trim(),r=String(t.email??"").trim();if(!s&&!a&&!r)throw new Error("Dealer identifier missing");const{data:n}=await ve.post("/form16/non-submitted-dealers/notify",{dealerCode:s||void 0,dealerId:a||void 0,email:r||void 0,financialYear:t.financialYear||void 0}),i=(l=n==null?void 0:n.data)==null?void 0:l.dealer;if(!i)throw new Error("No dealer returned");return i}async function Xv(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 ve.get(r),i=(n==null?void 0:n.data)??n;return Array.isArray(i)?i:[]}async function Wp(){const{data:t}=await ve.get("/form16/dealer/pending-quarters"),s=(t==null?void 0:t.data)??t;return Array.isArray(s)?s:[]}function zt({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,l]=x.useState(!1),[o,c]=x.useState(()=>(s==null?void 0:s.startsWith("form16"))??!1),[d,m]=x.useState(!1),[p,u]=x.useState([]),[h,g]=x.useState(0),[f,b]=x.useState(!1),[j,y]=x.useState(null),{user:N}=us(),S=x.useMemo(()=>{try{const L=tt.getUserData();return(L==null?void 0:L.jobTitle)==="Dealer"}catch(L){return console.error("[PageLayout] Error checking dealer status:",L),!1}},[]),A=(N==null?void 0:N.role)==="ADMIN",w=()=>{var L,R;try{if(N!=null&&N.displayName&&typeof N.displayName=="string"){const C=N.displayName.split(" ").filter(Boolean);return C.length>=2?`${((L=C[0])==null?void 0:L[0])||""}${((R=C[C.length-1])==null?void 0:R[0])||""}`.toUpperCase():N.displayName.substring(0,2).toUpperCase()}return N!=null&&N.email&&typeof N.email=="string"?N.email.substring(0,2).toUpperCase():"U"}catch(C){return console.error("[PageLayout] Error getting user initials:",C),"U"}},I=x.useMemo(()=>{const L=[{id:"dashboard",label:"Dashboard",icon:xj},{id:"requests",label:"All Requests",icon:Zh,adminOnly:!1}];return S||L.push({id:"my-requests",label:"My Requests",icon:Ht}),L.push({id:"open-requests",label:"Open Requests",icon:Fe},{id:"closed-requests",label:"Closed Requests",icon:Be},{id:"shared-summaries",label:"Shared Summary",icon:bn}),L},[S,A]);x.useEffect(()=>{if(!(N!=null&&N.userId)){y(null);return}let L=!0;return Fc().then(R=>{L&&y(R)}).catch(R=>{L&&(y({canViewForm16Submission:!1,canView26AS:!1}),console.warn("[PageLayout] Form 16 permissions could not be loaded – Form 16 menu will be hidden.",R))}),()=>{L=!1}},[N==null?void 0:N.userId]);const D=!!j&&(S?!!j.canViewForm16Submission:!!j.canView26AS),T=!!(j!=null&&j.canViewForm16Submission),v=!!(j!=null&&j.canView26AS),M=s==="form16-credit-notes"||s==="form16-debit-notes"||s==="form16-transactions"||s==="form16-submit"||s==="form16-pending-submissions"||s==="form16-dashboard"||s==="form16-26as"||s==="form16-non-submitted-dealers",P=o||M,B=()=>{l(!i)},k=async L=>{var R;try{if(L.isRead||(await cr.markAsRead(L.notificationId),u(C=>C.map(G=>G.notificationId===L.notificationId?{...G,isRead:!0}:G)),g(C=>Math.max(0,C-1))),L.actionUrl&&a){const C=(R=L.metadata)==null?void 0:R.requestNumber;if(C){let G=`request/${C}`;(L.notificationType==="mention"||L.notificationType==="comment"||L.notificationType==="worknote")&&(G+="?tab=worknotes"),a(G)}}b(!1)}catch(C){console.error("[PageLayout] Error handling notification click:",C)}},_=async()=>{try{await cr.markAllAsRead(),u(L=>L.map(R=>({...R,isRead:!0}))),g(0)}catch(L){console.error("[PageLayout] Error marking all as read:",L)}};return x.useEffect(()=>{const L=N==null?void 0:N.userId;if(!L)return;let R=!0;(async()=>{var U,$;try{const F=await cr.list({page:1,limit:4,unreadOnly:!1});if(!R)return;const H=((U=F.data)==null?void 0:U.notifications)||[];u(H),g((($=F.data)==null?void 0:$.unreadCount)||0)}catch(F){console.error("[PageLayout] Failed to fetch notifications:",F)}})();const G=Vr();if(G){Tc(G,L);const U=$=>{R&&(u(F=>[$.notification,...F].slice(0,4)),g(F=>F+1))};return G.on("notification:new",U),()=>{R=!1,G.off("notification:new",U)}}return()=>{R=!1}},[N]),x.useEffect(()=>{const L=()=>{window.innerWidth>=768?l(!0):l(!1)};return L(),window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[]),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:Al,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:[I.filter(L=>!L.adminOnly||(N==null?void 0:N.role)==="ADMIN").map(L=>e.jsxs("button",{onClick:()=>{a==null||a(L.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===L.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(L.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:L.label})]},L.id)),D&&e.jsxs("div",{className:"pt-2 border-t border-gray-800",children:[e.jsxs("button",{type:"button",onClick:()=>c(!P),className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${M?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(Mt,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate flex-1 text-left",children:"Form 16"}),P?e.jsx(jn,{className:"w-4 h-4 shrink-0"}):e.jsx(Ka,{className:"w-4 h-4 shrink-0"})]}),P&&e.jsx("div",{className:"mt-1 ml-4 pl-2 border-l border-gray-700 space-y-0.5",children:S?e.jsx(e.Fragment,{children:T&&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(Fe,{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(Fe,{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(Mt,{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/dashboard"),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-dashboard"?"bg-re-green/80 text-white font-medium":"text-gray-400 hover:bg-gray-800 hover:text-white"}`,children:[e.jsx(Fe,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Form16A Dashboard"})]}),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(Fe,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"26AS Management"})]}),T&&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(Mt,{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/transactions"),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-transactions"?"bg-re-green/80 text-white font-medium":"text-gray-400 hover:bg-gray-800 hover:text-white"}`,children:[e.jsx(Mt,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Transactions"})]})]})]})})]})]}),!S&&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(ms,{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:B,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(hj,{className:"w-5 h-5 text-gray-600"}):e.jsx(pj,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[!S&&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(ms,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(Tu,{open:f,onOpenChange:b,children:[e.jsx(ku,{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"}),h>0&&e.jsx(re,{className:"absolute -top-1 -right-1 w-5 h-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center p-0",children:h>9?"9+":h})]})}),e.jsxs(Du,{align:"end",className:"w-96 max-h-[500px]",children:[e.jsxs("div",{className:"p-3 border-b flex items-center justify-between sticky top-0 bg-white z-10",children:[e.jsx("h4",{className:"font-semibold text-base",children:"Notifications"}),h>0&&e.jsx(E,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:L=>{L.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(L=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${L.isRead?"":"bg-blue-50"}`,onClick:()=>k(L),children:e.jsxs("div",{className:"flex gap-2",children:[!L.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 ${L.isRead?"font-medium":"font-semibold"}`,children:L.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:L.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:Wh(new Date(L.createdAt),{addSuffix:!0})})]})]})},L.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(Tu,{children:[e.jsx(ku,{asChild:!0,children:e.jsxs(cs,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Tl,{src:(N==null?void 0:N.picture)||""}),e.jsx(ds,{className:"bg-re-green text-white text-sm",children:w()})]})}),e.jsxs(Du,{align:"end",children:[e.jsxs(Yl,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(Ht,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(Yl,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(dr,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(Yl,{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(Ip,{open:d,onOpenChange:m,children:e.jsxs(Rc,{children:[e.jsxs(Ep,{children:[e.jsxs(Mp,{className:"flex items-center gap-2",children:[e.jsx(Bl,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(Lp,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(_p,{children:[e.jsx($p,{onClick:()=>m(!1),children:"Cancel"}),e.jsxs(Op,{onClick:async()=>{if(m(!1),n)try{await n()}catch(L){console.error("🔴 Error calling onLogout:",L)}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 di=()=>Ty(),Nn=Ry,Zv=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},Jv={viewAsUser:Zv()},Yp=yn({name:"dashboard",initialState:Jv,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:qv}=Yp.actions;function eN(){const[t,s]=x.useState("all"),[a,r]=x.useState(void 0),[n,i]=x.useState(void 0),[l,o]=x.useState(!1),c=x.useCallback(p=>{const u=p;s(u),u!=="custom"?(r(void 0),i(void 0),o(!1)):o(!0)},[]),d=x.useCallback(p=>{if(a&&n){if(a>n){const u=a;r(n),i(u),p(n,u)}else p(a,n);o(!1)}},[a,n]),m=x.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 tN(){const[t,s]=x.useState({page:1,totalPages:1,totalRecords:0}),[a,r]=x.useState({page:1,totalPages:1,totalRecords:0}),[n,i]=x.useState({page:1,totalPages:1,totalRecords:0}),[l,o]=x.useState({page:1,totalPages:1,totalRecords:0}),c=x.useCallback((b,j,y)=>{s({page:b,totalPages:j,totalRecords:y})},[]),d=x.useCallback((b,j,y)=>{r({page:b,totalPages:j,totalRecords:y})},[]),m=x.useCallback((b,j,y)=>{i({page:b,totalPages:j,totalRecords:y})},[]),p=x.useCallback((b,j,y)=>{o({page:b,totalPages:j,totalRecords:y})},[]),u=x.useCallback((b,j)=>{b>=1&&b<=t.totalPages&&(s(y=>({...y,page:b})),j(b))},[t.totalPages]),h=x.useCallback((b,j)=>{b>=1&&b<=a.totalPages&&(r(y=>({...y,page:b})),j(b))},[a.totalPages]),g=x.useCallback((b,j)=>{b>=1&&b<=n.totalPages&&(i(y=>({...y,page:b})),j(b))},[n.totalPages]),f=x.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:u,handleCriticalPageChange:h,handleDeadlinesPageChange:g,handleApproverPageChange:f}}class sN{async getKPIs(s,a,r,n){try{const i={dateRange:s};return s==="custom"&&a&&r&&(i.startDate=a.toISOString(),i.endDate=r.toISOString()),n&&(i.viewAsUser="true"),(await ve.get("/dashboard/kpis",{params:i})).data.data}catch(i){throw console.error("Failed to fetch KPIs:",i),i}}async getRequestStats(s,a,r,n,i,l,o,c,d,m,p,u,h){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),u&&u!=="all"&&(g.slaCompliance=u),h&&(g.viewAsUser="true"),(await ve.get("/dashboard/stats/requests",{params:g})).data.data}catch(g){throw console.error("Failed to fetch request stats:",g),g}}async getTATEfficiency(s){try{return(await ve.get("/dashboard/stats/tat-efficiency",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch TAT efficiency:",a),a}}async getApproverLoad(s){try{return(await ve.get("/dashboard/stats/approver-load",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch approver load:",a),a}}async getEngagementStats(s){try{return(await ve.get("/dashboard/stats/engagement",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch engagement stats:",a),a}}async getAIInsights(s){try{return(await ve.get("/dashboard/stats/ai-insights",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch AI insights:",a),a}}async getRecentActivity(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await ve.get("/dashboard/activity/recent",{params:n});return{activities:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch recent activity:",n),n}}async getCriticalRequests(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await ve.get("/dashboard/requests/critical",{params:n});return{criticalRequests:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch critical requests:",n),n}}async getUpcomingDeadlines(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await ve.get("/dashboard/deadlines/upcoming",{params:n});return{deadlines:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch upcoming deadlines:",n),n}}async getDepartmentStats(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await ve.get("/dashboard/stats/by-department",{params:n})).data.data}catch(n){throw console.error("Failed to fetch department stats:",n),n}}async getPriorityDistribution(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await ve.get("/dashboard/stats/priority-distribution",{params:n})).data.data}catch(n){throw console.error("Failed to fetch priority distribution:",n),n}}async getAIRemarkUtilization(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await ve.get("/dashboard/stats/ai-remark-utilization",{params:n})).data.data}catch(n){throw console.error("Failed to fetch AI remark utilization:",n),n}}async getApproverPerformance(s,a=1,r=10,n,i,l,o){try{const c={dateRange:s,page:a,limit:r||10};s==="custom"&&n&&i&&(c.startDate=n.toISOString(),c.endDate=i.toISOString()),l&&l!=="all"&&(c.priority=l),o&&o!=="all"&&(c.slaCompliance=o);const d=await ve.get("/dashboard/stats/approver-performance",{params:c});return{performance:d.data.data,pagination:d.data.pagination}}catch(c){throw console.error("Failed to fetch approver performance:",c),c}}async getLifecycleReport(s=1,a=50,r,n,i){try{const l={page:s,limit:a};r&&(l.dateRange=r),r==="custom"&&n&&i&&(l.startDate=n.toISOString(),l.endDate=i.toISOString());const o=await ve.get("/dashboard/reports/lifecycle",{params:l});return{lifecycleData:o.data.data,pagination:o.data.pagination}}catch(l){throw console.error("Failed to fetch lifecycle report:",l),l}}async getActivityLogReport(s=1,a=50,r,n,i,l,o,c,d){try{const m={page:s,limit:a,filterUserId:n,filterType:i,filterCategory:l,filterSeverity:o};r&&(m.dateRange=r),r==="custom"&&c&&d&&(m.startDate=c.toISOString(),m.endDate=d.toISOString());const p=await ve.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 ve.get("/dashboard/metadata/departments")).data.data.departments||[]}catch(s){throw console.error("Failed to fetch departments:",s),s}}async getWorkflowAgingReport(s=7,a=1,r=50,n,i,l){try{const o={threshold:s,page:a,limit:r};n&&(o.dateRange=n),n==="custom"&&i&&l&&(o.startDate=i.toISOString(),o.endDate=l.toISOString());const c=await ve.get("/dashboard/reports/workflow-aging",{params:o});return{agingData:c.data.data,pagination:c.data.pagination}}catch(o){throw console.error("Failed to fetch workflow aging report:",o),o}}async getSingleApproverStats(s,a,r,n,i,l){try{const o={approverId:s};return a&&(o.dateRange=a),a==="custom"&&r&&n&&(o.startDate=r.toISOString(),o.endDate=n.toISOString()),i&&i!=="all"&&(o.priority=i),l&&l!=="all"&&(o.slaCompliance=l),(await ve.get("/dashboard/stats/single-approver",{params:o})).data.data}catch(o){throw console.error("Failed to fetch single approver stats:",o),o}}async getRequestsByApprover(s,a=1,r=50,n,i,l,o,c,d,m){try{const 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 u=await ve.get("/dashboard/requests/by-approver",{params:p});return{requests:u.data.data,pagination:u.data.pagination}}catch(p){throw console.error("Failed to fetch requests by approver:",p),p}}}const Ot=new sN;function aN({isAdmin:t,viewAsUser:s=!1,userId:a,dateRange:r,customStartDate:n,customEndDate:i,onPaginationUpdate:l}){const[o,c]=x.useState(null),[d,m]=x.useState([]),[p,u]=x.useState([]),[h,g]=x.useState([]),[f,b]=x.useState([]),[j,y]=x.useState([]),[N,S]=x.useState(null),[A,w]=x.useState([]),[I,D]=x.useState(!0),[T,v]=x.useState(!1),M=x.useRef(l);M.current=l;const P=x.useCallback(async(R=!1)=>{try{R?v(!0):D(!0);const C=[Ot.getKPIs(r,n,i,s),Ot.getRecentActivity(1,10,s),Ot.getCriticalRequests(1,10,s),Ot.getUpcomingDeadlines(1,10,s)],G=!t&&a?Ot.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,U=t?[Ot.getDepartmentStats(r,n,i),Ot.getPriorityDistribution(r,n,i),Ot.getAIRemarkUtilization(r,n,i),Ot.getApproverPerformance(r,1,10,n,i)]:[],[$,F,H]=await Promise.all([Promise.all(C),G,Promise.all(U)]),K=$[0],z=$[1],O=$[2],V=$[3];if(!t&&F&&(K.requestVolume=F),c(K),m(z.activities),M.current.activity(z.pagination.currentPage,z.pagination.totalPages,z.pagination.totalRecords),u(O.criticalRequests),M.current.critical(O.pagination.currentPage,O.pagination.totalPages,O.pagination.totalRecords),y(V.deadlines),M.current.deadlines(V.pagination.currentPage,V.pagination.totalPages,V.pagination.totalRecords),t&&H.length>=4){const Q=H[0],q=H[1],ee=H[2],te=H[3];g(Q),b(q),S(ee),w(te.performance),M.current.approver(te.pagination.currentPage,te.pagination.totalPages,te.pagination.totalRecords)}else t||(g([]),b([]),S(null),w([]))}catch(C){console.error("Failed to fetch dashboard data:",C)}finally{D(!1),v(!1)}},[t,s,a,r,n,i]),B=x.useCallback(async(R=1)=>{try{const C=await Ot.getRecentActivity(R,10,s);m(C.activities),M.current.activity(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch recent activities:",C)}},[s]),k=x.useCallback(async(R=1)=>{try{const C=await Ot.getCriticalRequests(R,10,s);u(C.criticalRequests),M.current.critical(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch critical requests:",C)}},[s]),_=x.useCallback(async(R=1)=>{try{const C=await Ot.getUpcomingDeadlines(R,10,s);y(C.deadlines),M.current.deadlines(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch upcoming deadlines:",C)}},[s]),L=x.useCallback(async(R=1)=>{try{const C=await Ot.getApproverPerformance(r,R,10,n,i);w(C.performance),M.current.approver(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch approver performance:",C)}},[r,n,i]);return{kpis:o,recentActivity:d,criticalRequests:p,departmentStats:h,priorityDistribution:f,upcomingDeadlines:j,aiRemarkUtilization:N,approverPerformance:A,loading:I,refreshing:T,fetchDashboardData:P,fetchRecentActivities:B,fetchCriticalRequests:k,fetchUpcomingDeadlines:_,fetchApproverPerformance:L}}const Wa={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 rN{constructor(){Ll(this,"config",null);Ll(this,"loading",null)}async getConfig(){return this.config?this.config:this.loading?this.loading:(this.loading=this.fetchConfig(),this.config=await this.loading,this.loading=null,this.config)}async fetchConfig(){var s;try{const a=await ve.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...Wa,...r,workingHours:{...Wa.workingHours,...r.workingHours},tat:{...Wa.tat,...r.tat},upload:{...Wa.upload,...r.upload},workflow:{...Wa.workflow,...r.workflow},workNotes:{...Wa.workNotes,...r.workNotes},features:{...Wa.features,...r.features},ui:{...Wa.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),Wa}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const nN=new rN;let iN=9,lN=18,oN=1,cN=5,Iu=!1;async function dN(){if(!Iu)try{const t=await nN.getConfig();iN=t.workingHours.START_HOUR,lN=t.workingHours.END_HOUR,oN=t.workingHours.START_DAY,cN=t.workingHours.END_DAY,Iu=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}dN().catch(()=>{});function Xt(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 mN(t,s,a){const r=[];let n=1,i=!0;const l=100;for(;i&&n<=l;){const u=await Ot.getApproverPerformance(t,n,100,s,a);u.performance&&u.performance.length>0?(r.push(...u.performance),n++,i=n<=u.pagination.totalPages):i=!1}const o=[["Approver Name","Total Approved","TAT Compliance (%)","Avg Response Time","Pending Count"].join(",")];r.forEach(u=>{const h=[`"${(u.approverName||"Unknown").replace(/"/g,'""')}"`,u.totalApproved||0,u.tatCompliancePercent||0,Xt(u.avgResponseHours),u.pendingCount||0];o.push(h.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 uN(t,s,a){const r=await Ot.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 xN(){const[t,s]=x.useState(!1),[a,r]=x.useState(!1),n=x.useCallback(async(l,o,c)=>{try{s(!0),await uN(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=x.useCallback(async(l,o,c)=>{try{r(!0),await mN(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 os({className:t,...s}){return e.jsx(cb,{"data-slot":"switch",className:Le("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(db,{"data-slot":"switch-thumb",className:Le("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 se({className:t,...s}){return e.jsx(mb,{"data-slot":"label",className:Le("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 hN({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(J,{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(fc,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(se,{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(os,{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(Ht,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(se,{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 He({...t}){return e.jsx(ub,{"data-slot":"select",...t})}function Ge({...t}){return e.jsx(pb,{"data-slot":"select-value",...t})}function We({className:t,size:s="default",children:a,...r}){return e.jsxs(xb,{"data-slot":"select-trigger","data-size":s,className:Le("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(hb,{asChild:!0,children:e.jsx(jn,{className:"size-4 opacity-50"})})]})}function Ye({className:t,children:s,position:a="popper",...r}){return e.jsx(gb,{children:e.jsxs(fb,{"data-slot":"select-content",className:Le("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(pN,{}),e.jsx(bb,{className:Le("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(gN,{})]})})}function X({className:t,children:s,...a}){return e.jsxs(jb,{"data-slot":"select-item",className:Le("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(yb,{children:e.jsx($a,{className:"size-4"})})}),e.jsx(vb,{children:s})]})}function pN({className:t,...s}){return e.jsx(Nb,{"data-slot":"select-scroll-up-button",className:Le("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(ul,{className:"size-4"})})}function gN({className:t,...s}){return e.jsx(wb,{"data-slot":"select-scroll-down-button",className:Le("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(jn,{className:"size-4"})})}function Jt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(Cb,{"data-slot":"separator-root",decorative:a,orientation:s,className:Le("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 aa({...t}){return e.jsx(Sb,{"data-slot":"popover",...t})}function ra({...t}){return e.jsx(Ab,{"data-slot":"popover-trigger",...t})}function na({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(Tb,{children:e.jsx(kb,{"data-slot":"popover-content",align:s,sideOffset:a,className:Le("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 ct=function(){return ct=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},ct.apply(this,arguments)};function fN(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 Qp(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 mi(t){return t.mode==="multiple"}function ui(t){return t.mode==="range"}function kl(t){return t.mode==="single"}var bN={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 jN(t,s){return st(t,"LLLL y",s)}function yN(t,s){return st(t,"d",s)}function vN(t,s){return st(t,"LLLL",s)}function NN(t){return"".concat(t)}function wN(t,s){return st(t,"cccccc",s)}function CN(t,s){return st(t,"yyyy",s)}var SN=Object.freeze({__proto__:null,formatCaption:jN,formatDay:yN,formatMonthCaption:vN,formatWeekNumber:NN,formatWeekdayName:wN,formatYearCaption:CN}),AN=function(t,s,a){return st(t,"do MMMM (EEEE)",a)},TN=function(){return"Month: "},kN=function(){return"Go to next month"},DN=function(){return"Go to previous month"},RN=function(t,s){return st(t,"cccc",s)},FN=function(t){return"Week n. ".concat(t)},IN=function(){return"Year: "},PN=Object.freeze({__proto__:null,labelDay:AN,labelMonthDropdown:TN,labelNext:kN,labelPrevious:DN,labelWeekNumber:FN,labelWeekday:RN,labelYearDropdown:IN});function EN(){var t="buttons",s=bN,a=ej,r={},n={},i=1,l={},o=new Date;return{captionLayout:t,classNames:s,formatters:SN,labels:PN,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:l,today:o,mode:"default"}}function _N(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,l=t.toDate;return r?i=ma(r):s&&(i=new Date(s,0,1)),n?l=xc(n):a&&(l=new Date(a,11,31)),{fromDate:i?du(i):void 0,toDate:l?du(l):void 0}}var Kp=x.createContext(void 0);function MN(t){var s,a=t.initialProps,r=EN(),n=_N(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;(kl(a)||mi(a)||ui(a))&&(c=a.onSelect);var d=ct(ct(ct({},r),a),{captionLayout:o,classNames:ct(ct({},r.classNames),a.classNames),components:ct({},a.components),formatters:ct(ct({},r.formatters),a.formatters),fromDate:i,labels:ct(ct({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:ct(ct({},r.modifiers),a.modifiers),modifiersClassNames:ct(ct({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:ct(ct({},r.styles),a.styles),toDate:l});return e.jsx(Kp.Provider,{value:d,children:t.children})}function Yt(){var t=x.useContext(Kp);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function Xp(t){var s=Yt(),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 LN(t){return e.jsx("svg",ct({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 Zp(t){var s,a,r=t.onChange,n=t.value,i=t.children,l=t.caption,o=t.className,c=t.style,d=Yt(),m=(a=(s=d.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:LN;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 ON(t){var s,a=Yt(),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(ij(r,n))for(var u=ma(r),h=r.getMonth();h<=n.getMonth();h++)p.push($l(u,h));else for(var u=ma(new Date),h=0;h<=11;h++)p.push($l(u,h));var g=function(b){var j=Number(b.target.value),y=$l(ma(t.displayMonth),j);t.onChange(y)},f=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Zp;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 $N(t){var s,a=t.displayMonth,r=Yt(),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,u=[];if(!n)return e.jsx(e.Fragment,{});if(!i)return e.jsx(e.Fragment,{});for(var h=n.getFullYear(),g=i.getFullYear(),f=h;f<=g;f++)u.push(mu(lj(new Date),f));var b=function(y){var N=mu(ma(a),Number(y.target.value));t.onChange(N)},j=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Zp;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:u.map(function(y){return e.jsx("option",{value:y.getFullYear(),children:m(y,{locale:l})},y.getFullYear())})})}function UN(t,s){var a=x.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function BN(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&&Jn(i,n)<0){var d=-1*(c-1);n=Oa(i,d)}return l&&Jn(n,l)<0&&(n=l),ma(n)}function VN(){var t=Yt(),s=BN(t),a=UN(s,t.month),r=a[0],n=a[1],i=function(l){var o;if(!t.disableNavigation){var c=ma(l);n(c),(o=t.onMonthChange)===null||o===void 0||o.call(t,c)}};return[r,i]}function zN(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=ma(t),i=ma(Oa(n,r)),l=Jn(i,n),o=[],c=0;c<l;c++){var d=Oa(n,c);o.push(d)}return a&&(o=o.reverse()),o}function HN(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=ma(t);if(!a)return Oa(o,l);var c=Jn(a,t);if(!(c<i))return Oa(o,l)}}function GN(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=ma(t);if(!a)return Oa(o,-l);var c=Jn(o,a);if(!(c<=0))return Oa(o,-l)}}var Jp=x.createContext(void 0);function WN(t){var s=Yt(),a=VN(),r=a[0],n=a[1],i=zN(r,s),l=HN(r,s),o=GN(r,s),c=function(p){return i.some(function(u){return hc(p,u)})},d=function(p,u){c(p)||(u&&Yh(p,u)?n(Oa(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(Jp.Provider,{value:m,children:t.children})}function xi(){var t=x.useContext(Jp);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function Pu(t){var s,a=Yt(),r=a.classNames,n=a.styles,i=a.components,l=xi().goToMonth,o=function(m){l(Oa(m,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:Xp,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(ON,{onChange:o,displayMonth:t.displayMonth}),e.jsx($N,{onChange:o,displayMonth:t.displayMonth})]})}function YN(t){return e.jsx("svg",ct({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 QN(t){return e.jsx("svg",ct({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 tl=x.forwardRef(function(t,s){var a=Yt(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var l=i.join(" "),o=ct(ct({},n.button_reset),n.button);return t.style&&Object.assign(o,t.style),e.jsx("button",ct({},t,{ref:s,type:"button",className:l,style:o}))});function KN(t){var s,a,r=Yt(),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 u=d(t.previousMonth,{locale:i}),h=[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:QN,j=(a=p==null?void 0:p.IconLeft)!==null&&a!==void 0?a:YN;return e.jsxs("div",{className:l.nav,style:o.nav,children:[!t.hidePrevious&&e.jsx(tl,{name:"previous-month","aria-label":u,className:h,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(tl,{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 Eu(t){var s=Yt().numberOfMonths,a=xi(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,l=a.displayMonths,o=l.findIndex(function(g){return hc(t.displayMonth,g)}),c=o===0,d=o===l.length-1,m=s>1&&(c||!d),p=s>1&&(d||!c),u=function(){r&&i(r)},h=function(){n&&i(n)};return e.jsx(KN,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:p,nextMonth:n,previousMonth:r,onPreviousClick:u,onNextClick:h})}function XN(t){var s,a=Yt(),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:Xp,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):l==="dropdown"?d=e.jsx(Pu,{displayMonth:t.displayMonth,id:t.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Pu,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(Eu,{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(Eu,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function ZN(t){var s=Yt(),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 JN(t,s,a){for(var r=a?pc(new Date):gc(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var l=oa(r,i);n.push(l)}return n}function qN(){var t=Yt(),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=JN(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 ew(){var t,s=Yt(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:qN;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function tw(t){var s=Yt(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var Pc=x.createContext(void 0);function sw(t){if(!mi(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(Pc.Provider,{value:s,children:t.children})}return e.jsx(aw,{initialProps:t.initialProps,children:t.children})}function aw(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,l=function(d,m,p){var u,h;(u=s.onDayClick)===null||u===void 0||u.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?Qp([],r):[];if(m.selected){var j=b.findIndex(function(y){return ea(d,y)});b.splice(j,1)}else b.push(d);(h=s.onSelect)===null||h===void 0||h.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(u){return ea(u,d)});return!!(m&&!p)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(Pc.Provider,{value:c,children:a})}function Ec(){var t=x.useContext(Pc);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function rw(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?ea(n,t)&&ea(r,t)?void 0:ea(n,t)?{from:n,to:void 0}:ea(r,t)?void 0:Eo(r,t)?{from:t,to:n}:{from:r,to:t}:n?Eo(t,n)?{from:n,to:t}:{from:t,to:n}:r?Yh(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var _c=x.createContext(void 0);function nw(t){if(!ui(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(_c.Provider,{value:s,children:t.children})}return e.jsx(iw,{initialProps:t.initialProps,children:t.children})}function iw(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(h,g,f){var b,j;(b=s.onDayClick)===null||b===void 0||b.call(s,h,g,f);var y=rw(h,r);(j=s.onSelect)===null||j===void 0||j.call(s,y,h,g,f)},m={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(m.range_start=[i],l?(m.range_end=[l],ea(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:Ol(i,o-1),before:oa(i,o-1)}),i&&l&&m.disabled.push({after:i,before:oa(i,o-1)}),!i&&l&&m.disabled.push({after:Ol(l,o-1),before:oa(l,o-1)})),c){if(i&&!l&&(m.disabled.push({before:oa(i,-c+1)}),m.disabled.push({after:oa(i,c-1)})),i&&l){var p=Qa(l,i)+1,u=c-p;m.disabled.push({before:Ol(i,u)}),m.disabled.push({after:oa(l,u)})}!i&&l&&(m.disabled.push({before:oa(l,-c+1)}),m.disabled.push({after:oa(l,c-1)}))}return e.jsx(_c.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function Mc(){var t=x.useContext(_c);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function Li(t){return Array.isArray(t)?Qp([],t):t!==void 0?[t]:[]}function lw(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=Li(n)}),s}var Ra;(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"})(Ra||(Ra={}));var ow=Ra.Selected,Ya=Ra.Disabled,cw=Ra.Hidden,dw=Ra.Today,Ql=Ra.RangeEnd,Kl=Ra.RangeMiddle,Xl=Ra.RangeStart,mw=Ra.Outside;function uw(t,s,a){var r,n=(r={},r[ow]=Li(t.selected),r[Ya]=Li(t.disabled),r[cw]=Li(t.hidden),r[dw]=[t.today],r[Ql]=[],r[Kl]=[],r[Xl]=[],r[mw]=[],r);return t.fromDate&&n[Ya].push({before:t.fromDate}),t.toDate&&n[Ya].push({after:t.toDate}),mi(t)?n[Ya]=n[Ya].concat(s.modifiers[Ya]):ui(t)&&(n[Ya]=n[Ya].concat(a.modifiers[Ya]),n[Xl]=a.modifiers[Xl],n[Kl]=a.modifiers[Kl],n[Ql]=a.modifiers[Ql]),n}var qp=x.createContext(void 0);function xw(t){var s=Yt(),a=Ec(),r=Mc(),n=uw(s,a,r),i=lw(s.modifiers),l=ct(ct({},n),i);return e.jsx(qp.Provider,{value:l,children:t.children})}function eg(){var t=x.useContext(qp);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function hw(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function pw(t){return!!(t&&typeof t=="object"&&"from"in t)}function gw(t){return!!(t&&typeof t=="object"&&"after"in t)}function fw(t){return!!(t&&typeof t=="object"&&"before"in t)}function bw(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function jw(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=Qa(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var l=Qa(t,r)>=0&&Qa(n,t)>=0;return l}return n?ea(n,t):r?ea(r,t):!1}function yw(t){return Xh(t)}function vw(t){return Array.isArray(t)&&t.every(Xh)}function Nw(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(yw(a))return ea(t,a);if(vw(a))return a.includes(t);if(pw(a))return jw(t,a);if(bw(a))return a.dayOfWeek.includes(t.getDay());if(hw(a)){var r=Qa(a.before,t),n=Qa(a.after,t),i=r>0,l=n<0,o=Eo(a.before,a.after);return o?l&&i:i||l}return gw(a)?Qa(t,a.after)>0:fw(a)?Qa(a.before,t)>0:typeof a=="function"?a(t):!1})}function Lc(t,s,a){var r=Object.keys(s).reduce(function(i,l){var o=s[l];return Nw(t,o)&&i.push(l),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!hc(t,a)&&(n.outside=!0),n}function ww(t,s){for(var a=ma(t[0]),r=xc(t[t.length-1]),n,i,l=a;l<=r;){var o=Lc(l,s),c=!o.disabled&&!o.hidden;if(!c){l=oa(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),n||(n=l),l=oa(l,1)}return i||n}var Cw=365;function tg(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,u={day:oa,week:Po,month:Oa,year:aj,startOfWeek:function(b){return n.ISOWeek?pc(b):gc(b,{locale:p,weekStartsOn:c})},endOfWeek:function(b){return n.ISOWeek?Qh(b):Kh(b,{locale:p,weekStartsOn:c})}},h=u[a](t,r==="after"?1:-1);r==="before"&&d?h=rj([d,h]):r==="after"&&m&&(h=nj([m,h]));var g=!0;if(i){var f=Lc(h,i);g=!f.disabled&&!f.hidden}return g?h:o.count>Cw?o.lastFocused:tg(h,{moveBy:a,direction:r,context:n,modifiers:i,retry:ct(ct({},o),{count:o.count+1})})}var sg=x.createContext(void 0);function Sw(t){var s=xi(),a=eg(),r=x.useState(),n=r[0],i=r[1],l=x.useState(),o=l[0],c=l[1],d=ww(s.displayMonths,a),m=n??(o&&s.isDateDisplayed(o))?o:d,p=function(){c(n),i(void 0)},u=function(b){i(b)},h=Yt(),g=function(b,j){if(n){var y=tg(n,{moveBy:b,direction:j,context:h,modifiers:a});ea(n,y)||(s.goToDate(y,n),u(y))}},f={focusedDay:n,focusTarget:m,blur:p,focus:u,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(sg.Provider,{value:f,children:t.children})}function Oc(){var t=x.useContext(sg);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function Aw(t,s){var a=eg(),r=Lc(t,a,s);return r}var $c=x.createContext(void 0);function Tw(t){if(!kl(t.initialProps)){var s={selected:void 0};return e.jsx($c.Provider,{value:s,children:t.children})}return e.jsx(kw,{initialProps:t.initialProps,children:t.children})}function kw(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($c.Provider,{value:n,children:a})}function ag(){var t=x.useContext($c);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function Dw(t,s){var a=Yt(),r=ag(),n=Ec(),i=Mc(),l=Oc(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,m=l.focusWeekBefore,p=l.blur,u=l.focus,h=l.focusMonthBefore,g=l.focusMonthAfter,f=l.focusYearBefore,b=l.focusYearAfter,j=l.focusStartOfWeek,y=l.focusEndOfWeek,N=function(R){var C,G,U,$;kl(a)?(C=r.onDayClick)===null||C===void 0||C.call(r,t,s,R):mi(a)?(G=n.onDayClick)===null||G===void 0||G.call(n,t,s,R):ui(a)?(U=i.onDayClick)===null||U===void 0||U.call(i,t,s,R):($=a.onDayClick)===null||$===void 0||$.call(a,t,s,R)},S=function(R){var C;u(t),(C=a.onDayFocus)===null||C===void 0||C.call(a,t,s,R)},A=function(R){var C;p(),(C=a.onDayBlur)===null||C===void 0||C.call(a,t,s,R)},w=function(R){var C;(C=a.onDayMouseEnter)===null||C===void 0||C.call(a,t,s,R)},I=function(R){var C;(C=a.onDayMouseLeave)===null||C===void 0||C.call(a,t,s,R)},D=function(R){var C;(C=a.onDayPointerEnter)===null||C===void 0||C.call(a,t,s,R)},T=function(R){var C;(C=a.onDayPointerLeave)===null||C===void 0||C.call(a,t,s,R)},v=function(R){var C;(C=a.onDayTouchCancel)===null||C===void 0||C.call(a,t,s,R)},M=function(R){var C;(C=a.onDayTouchEnd)===null||C===void 0||C.call(a,t,s,R)},P=function(R){var C;(C=a.onDayTouchMove)===null||C===void 0||C.call(a,t,s,R)},B=function(R){var C;(C=a.onDayTouchStart)===null||C===void 0||C.call(a,t,s,R)},k=function(R){var C;(C=a.onDayKeyUp)===null||C===void 0||C.call(a,t,s,R)},_=function(R){var C;switch(R.key){case"ArrowLeft":R.preventDefault(),R.stopPropagation(),a.dir==="rtl"?o():c();break;case"ArrowRight":R.preventDefault(),R.stopPropagation(),a.dir==="rtl"?c():o();break;case"ArrowDown":R.preventDefault(),R.stopPropagation(),d();break;case"ArrowUp":R.preventDefault(),R.stopPropagation(),m();break;case"PageUp":R.preventDefault(),R.stopPropagation(),R.shiftKey?f():h();break;case"PageDown":R.preventDefault(),R.stopPropagation(),R.shiftKey?b():g();break;case"Home":R.preventDefault(),R.stopPropagation(),j();break;case"End":R.preventDefault(),R.stopPropagation(),y();break}(C=a.onDayKeyDown)===null||C===void 0||C.call(a,t,s,R)},L={onClick:N,onFocus:S,onBlur:A,onKeyDown:_,onKeyUp:k,onMouseEnter:w,onMouseLeave:I,onPointerEnter:D,onPointerLeave:T,onTouchCancel:v,onTouchEnd:M,onTouchMove:P,onTouchStart:B};return L}function Rw(){var t=Yt(),s=ag(),a=Ec(),r=Mc(),n=kl(t)?s.selected:mi(t)?a.selected:ui(t)?r.selected:void 0;return n}function Fw(t){return Object.values(Ra).includes(t)}function Iw(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(Fw(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function Pw(t,s){var a=ct({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=ct(ct({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function Ew(t,s,a){var r,n,i,l=Yt(),o=Oc(),c=Aw(t,s),d=Dw(t,c),m=Rw(),p=!!(l.onDayClick||l.mode!=="default");x.useEffect(function(){var w;c.outside||o.focusedDay&&p&&ea(o.focusedDay,t)&&((w=a.current)===null||w===void 0||w.focus())},[o.focusedDay,t,a,p,c.outside]);var u=Iw(l,c).join(" "),h=Pw(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:tw,b=e.jsx(f,{date:t,displayMonth:s,activeModifiers:c}),j={style:h,className:u,children:b,role:"gridcell"},y=o.focusTarget&&ea(o.focusTarget,t)&&!c.outside,N=o.focusedDay&&ea(o.focusedDay,t),S=ct(ct(ct({},j),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=N||y?0:-1,r)),d),A={isButton:p,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:S,divProps:j};return A}function _w(t){var s=x.useRef(null),a=Ew(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(tl,ct({name:"day",ref:s},a.buttonProps)):e.jsx("div",ct({},a.divProps))}function Mw(t){var s=t.number,a=t.dates,r=Yt(),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}),u=function(h){n(s,a,h)};return e.jsx(tl,{name:"week-number","aria-label":p,className:l.weeknumber,style:i.weeknumber,onClick:u,children:m})}function Lw(t){var s,a,r=Yt(),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:_w,d=(a=o==null?void 0:o.WeekNumber)!==null&&a!==void 0?a:Mw,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})},sj(p))})]})}function _u(t,s,a){for(var r=a!=null&&a.ISOWeek?Qh(s):Kh(s,a),n=a!=null&&a.ISOWeek?pc(t):gc(t,a),i=Qa(r,n),l=[],o=0;o<=i;o++)l.push(oa(n,o));var c=l.reduce(function(d,m){var p=a!=null&&a.ISOWeek?oj(m):cj(m,a),u=d.find(function(h){return h.weekNumber===p});return u?(u.dates.push(m),d):(d.push({weekNumber:p,dates:[m]}),d)},[]);return c}function Ow(t,s){var a=_u(ma(t),xc(t),s);if(s!=null&&s.useFixedWeeks){var r=tj(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],l=Po(i,6-r),o=_u(Po(i,1),l,s);a.push.apply(a,o)}}return a}function $w(t){var s,a,r,n=Yt(),i=n.locale,l=n.classNames,o=n.styles,c=n.hideHead,d=n.fixedWeeks,m=n.components,p=n.weekStartsOn,u=n.firstWeekContainsDate,h=n.ISOWeek,g=Ow(t.displayMonth,{useFixedWeeks:!!d,ISOWeek:h,locale:i,weekStartsOn:p,firstWeekContainsDate:u}),f=(s=m==null?void 0:m.Head)!==null&&s!==void 0?s:ew,b=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:Lw,j=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:ZN;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 Uw(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Bw=Uw()?x.useLayoutEffect:x.useEffect,Zl=!1,Vw=0;function Mu(){return"react-day-picker-".concat(++Vw)}function zw(t){var s,a=t??(Zl?Mu():null),r=x.useState(a),n=r[0],i=r[1];return Bw(function(){n===null&&i(Mu())},[]),x.useEffect(function(){Zl===!1&&(Zl=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function Hw(t){var s,a,r=Yt(),n=r.dir,i=r.classNames,l=r.styles,o=r.components,c=xi().displayMonths,d=zw(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],u=l.month,h=t.displayIndex===0,g=t.displayIndex===c.length-1,f=!h&&!g;n==="rtl"&&(s=[h,g],g=s[0],h=s[1]),h&&(p.push(i.caption_start),u=ct(ct({},u),l.caption_start)),g&&(p.push(i.caption_end),u=ct(ct({},u),l.caption_end)),f&&(p.push(i.caption_between),u=ct(ct({},u),l.caption_between));var b=(a=o==null?void 0:o.Caption)!==null&&a!==void 0?a:XN;return e.jsxs("div",{className:p.join(" "),style:u,children:[e.jsx(b,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx($w,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function Gw(t){var s=Yt(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function Ww(t){var s,a,r=t.initialProps,n=Yt(),i=Oc(),l=xi(),o=x.useState(!1),c=o[0],d=o[1];x.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=ct(ct({},n.styles.root),n.style),u=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,f){var b;return ct(ct({},g),(b={},b[f]=r[f],b))},{}),h=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:Gw;return e.jsx("div",ct({className:m.join(" "),style:p,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},u,{children:e.jsx(h,{children:l.displayMonths.map(function(g,f){return e.jsx(Hw,{displayIndex:f,displayMonth:g},f)})})}))}function Yw(t){var s=t.children,a=fN(t,["children"]);return e.jsx(MN,{initialProps:a,children:e.jsx(WN,{children:e.jsx(Tw,{initialProps:a,children:e.jsx(sw,{initialProps:a,children:e.jsx(nw,{initialProps:a,children:e.jsx(xw,{children:e.jsx(Sw,{children:s})})})})})})})}function Qw(t){return e.jsx(Yw,ct({},t,{children:e.jsx(Ww,{initialProps:t})}))}function Oi({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(Qw,{showOutsideDays:a,className:Le("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:Le(ei({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:Le("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:Le(ei({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(pn,{className:Le("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(Ka,{className:Le("size-4",n),...i})},...r})}function ta({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,u]=x.useState(!1),h=x.useMemo(()=>{if(t){if(t instanceof Date)return Jr(t)?t:void 0;if(typeof t=="string")try{const j=Ul(t,"yyyy-MM-dd",new Date);return Jr(j)?j:void 0}catch{return}}},[t]),g=x.useMemo(()=>{if(a){if(a instanceof Date)return Jr(a)?a:void 0;if(typeof a=="string"){const j=Ul(a,"yyyy-MM-dd",new Date);return Jr(j)?j:void 0}}},[a]),f=x.useMemo(()=>{if(r){if(r instanceof Date)return Jr(r)?r:void 0;if(typeof r=="string"){const j=Ul(r,"yyyy-MM-dd",new Date);return Jr(j)?j:void 0}}},[r]),b=j=>{if(u(!1),!!s){if(!j){s(null);return}s(st(j,"yyyy-MM-dd"))}};return e.jsx("div",{className:Le("relative",o),children:e.jsxs(aa,{open:p,onOpenChange:u,children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{id:m,disabled:i,variant:"outline",className:Le("w-full justify-start text-left font-normal",!h&&"text-muted-foreground",c&&"border-destructive ring-destructive/20",l),children:[e.jsx(ft,{className:"mr-2 h-4 w-4"}),h?st(h,d):e.jsx("span",{children:n})]})}),e.jsx(na,{className:"w-auto p-0",align:"start",children:e.jsx(Oi,{mode:"single",selected:h,onSelect:b,disabled:j=>!!(g&&j<g||f&&j>f),initialFocus:!0})})]})})}function Kw({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:u}){return e.jsx(Z,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(J,{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(Ua,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(re,{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(ft,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:s,onValueChange:l,"data-testid":"date-range-select",children:[e.jsx(We,{className:"w-[140px]",children:e.jsx(Ge,{placeholder:"Select period"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(aa,{open:n,onOpenChange:d,children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(ft,{className:"w-4 h-4"}),a&&r?`${st(a,"MMM d, yyyy")} - ${st(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(na,{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(se,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(ta,{value:a||null,onChange:h=>{const g=h?new Date(h):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(se,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(ta,{value:r||null,onChange:h=>{const g=h?new Date(h):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(ft,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:s,onValueChange:h=>l(h),"data-testid":"date-range-select-user",children:[e.jsx(We,{className:"w-[140px]",children:e.jsx(Ge,{placeholder:"Select period"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(aa,{open:n,onOpenChange:d,children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(ft,{className:"w-4 h-4"}),a&&r?`${st(a,"MMM d, yyyy")} - ${st(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(na,{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(se,{htmlFor:"start-date-user",className:"text-sm font-medium",children:"Start Date"}),e.jsx(ta,{value:a||null,onChange:h=>{const g=h?new Date(h):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(se,{htmlFor:"end-date-user",className:"text-sm font-medium",children:"End Date"}),e.jsx(ta,{value:r||null,onChange:h=>{const g=h?new Date(h):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(Jt,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(E,{variant:"outline",size:"sm",onClick:u,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx(Et,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function _r({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=u=>{u.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(ce,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(de,{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(Hr,{className:"h-4 w-4"})}),e.jsx("div",{className:`p-1.5 sm:p-2 rounded-lg ${r}`,"data-testid":`${o}-icon-wrapper`,children:e.jsx(a,{className:`h-4 w-4 sm:h-4 sm:w-4 ${n}`,"data-testid":`${o}-icon`})})]})]}),e.jsxs(J,{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 Ds({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 ia({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(Db,{"data-slot":"progress",className:Le("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(Rb,{"data-slot":"progress-indicator",className:Le("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function Xw({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(_r,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Fe,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(Ds,{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(Ds,{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(Ds,{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(Ds,{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(Ds,{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(_r,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:ts,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(ia,{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(Ds,{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(Ds,{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(_r,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?Xt(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:it,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(Ds,{label:"Express",value:(()=>{const o=s.find(d=>d.priority==="express"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Xt(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(Ds,{label:"Standard",value:(()=>{const o=s.find(d=>d.priority==="standard"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Xt(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:o=>{o.stopPropagation(),i({...l(),priority:"standard"})}})]})})})]})}function Zw({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 u=new URLSearchParams;u.set("approverId",o),u.set("approverName",c||"My Performance"),u.set("dateRange",a),a==="custom"&&r&&n&&(u.set("startDate",r.toISOString()),u.set("endDate",n.toISOString())),l==null||l(`/approver-performance?${u.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(_r,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Fe,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(Ds,{label:"Approved",value:(t==null?void 0:t.requestVolume.approvedRequests)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-user-approved",onClick:u=>{u.stopPropagation(),i({...d(),status:"approved"})}}),e.jsx(Ds,{label:"Pending",value:(t==null?void 0:t.requestVolume.openRequests)||0,bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-user-pending",onClick:u=>{u.stopPropagation(),i({...d(),status:"pending"})}}),e.jsx(Ds,{label:"Paused",value:(t==null?void 0:t.requestVolume.pausedRequests)||0,bgColor:"bg-amber-50",textColor:"text-amber-600",testId:"stat-user-paused",onClick:u=>{u.stopPropagation(),i({...d(),status:"paused"})}}),e.jsx(Ds,{label:"Rejected",value:(t==null?void 0:t.requestVolume.rejectedRequests)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-user-rejected",onClick:u=>{u.stopPropagation(),i({...d(),status:"rejected"})}}),e.jsx(Ds,{label:"Closed",value:(t==null?void 0:t.requestVolume.closedRequests)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-user-closed",onClick:u=>{u.stopPropagation(),i({...d(),status:"closed"})}})]})}),e.jsx(_r,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:it,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(Ds,{label:"Approved Today",value:(t==null?void 0:t.approverLoad.completedToday)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-today",onClick:u=>{u.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}}),e.jsx(Ds,{label:"This Week",value:(t==null?void 0:t.approverLoad.completedThisWeek)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-week",onClick:u=>{u.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}})]})}),e.jsx(_r,{title:"Critical Alerts",value:s.length,icon:Ia,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(Ds,{label:"Breached",value:s.filter(u=>u.breachCount>0).length,bgColor:"bg-orange-50",textColor:"text-red-600",testId:"stat-user-breached",onClick:u=>{u.stopPropagation(),i({...d(),targetPage:"open-requests"})}}),e.jsx(Ds,{label:"Warning",value:s.filter(u=>u.breachCount===0).length,bgColor:"bg-yellow-50",textColor:"text-orange-600",testId:"stat-user-warning",onClick:u=>{u.stopPropagation(),i({...d(),targetPage:"open-requests"})}})]})}),e.jsx(_r,{title:"Success Rate",value:`${p.toFixed(0)}%`,icon:Be,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(ia,{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 Jw=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)))},qw=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 e1({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=Jw(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(gj,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(re,{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(re,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:qw(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(ia,{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 t1(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 s1(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function a1(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 r1(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 rg(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 n1({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(ce,{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(Ia,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(we,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(re,{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(J,{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(Be,{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(e1,{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(js,{className:"h-3 w-3 rotate-180"})}),rg(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(js,{className:"h-3 w-3"})})]})]})})]})}const i1=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"}},l1=t=>{const s=new Date,a=new Date(t),r=dj(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=mj(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=uj(s,a);return`${i} day${i>1?"s":""} ago`},o1=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()},c1=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(Be,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-green-600"}):s.includes("reject")?e.jsx(ss,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-red-600"}):s.includes("comment")?e.jsx(Ys,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(Ia,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(Fe,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(xl,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(Bt,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function d1({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(cs,{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(Tl,{src:""}),e.jsx(ds,{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:c1(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(re,{variant:"outline",className:`text-xs ${i1(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:o1(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:l1(t.timestamp)})]})]}),e.jsx(js,{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 m1({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(ce,{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(Bt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(de,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(we,{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(Et,{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(J,{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(Bt,{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(d1,{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(js,{className:"h-3 w-3 rotate-180"})}),rg(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(js,{className:"h-3 w-3"})})]})]})})]})}function u1({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(ce,{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(Bt,{className:"h-4 w-4 text-blue-600"})}),e.jsx(de,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(J,{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(Jt,{}),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(ce,{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(Ys,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(de,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(J,{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(Jt,{}),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(ce,{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(_o,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(we,{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(Tt,{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(J,{children:e.jsx(dn,{width:"100%",height:400,children:e.jsxs(Io,{data:r,children:[e.jsx(Yi,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Qi,{dataKey:"department",stroke:"#999",tick:p=>{const{x:u,y:h,payload:g}=p;return e.jsx("g",{transform:`translate(${u},${h})`,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(mn,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Xi,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Ea,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(Ea,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(Ea,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function x1({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(ce,{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(Ys,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(de,{className:"text-sm",children:"My Activity"})]})}),e.jsx(J,{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(ce,{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(it,{className:"h-4 w-4 text-purple-600"})}),e.jsx(de,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(J,{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:Xt(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(Jt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function h1({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(ce,{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(ts,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(we,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(J,{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: ",Xt(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(dn,{width:"100%",height:300,children:e.jsxs(zh,{children:[e.jsx(Hh,{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(Gh,{fill:a.priority==="express"?"#ef4444":"#3b82f6",className:"cursor-pointer"},`cell-${r}`))}),e.jsx(mn,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"},formatter:(a,r,n)=>{var l;const i=((l=n.payload)==null?void 0:l.priority)||"";return[`${a} requests`,`Click for ${i}`]}})]})})})]})]})}function Wr({currentPage:t,totalPages:s,itemsPerPage:a,totalRecords:r,onPageChange:n,loading:i=!1,itemLabel:l="items",testIdPrefix:o="pagination"}){const c=()=>{const p=[];let h=Math.max(1,t-Math.floor(2.5)),g=Math.min(s,h+5-1);g-h<4&&(h=Math.max(1,g-5+1));for(let f=h;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(J,{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(J,{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(js,{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(js,{className:"h-4 w-4"})})]})]})})})}function p1(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${st(s,"MMM d, yyyy")} - ${st(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 g1(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${st(s,"MMM d, yyyy")} to ${st(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 f1({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(ce,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-red-50 p-2 sm:p-3 rounded-lg",children:e.jsx(ss,{className:"h-5 w-5 sm:h-6 sm:w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs(we,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",g1(a,r,n)]})]})]}),e.jsxs(re,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[s.totalRecords," ",s.totalRecords===1?"Breach":"Breaches"]})]})}),e.jsxs(J,{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 u=new URLSearchParams;u.set("approver",d.approverId),u.set("approverType","current"),u.set("slaCompliance","breached"),a&&u.set("dateRange",a),r&&u.set("startDate",r.toISOString()),n&&u.set("endDate",n.toISOString()),o(`requests?${u.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:a1(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(re,{variant:"outline",className:`text-xs font-medium ${d.priority==="express"?"bg-orange-100 text-orange-800 border-orange-200":"bg-blue-100 text-blue-800 border-blue-200"}`,children:d.priority})})]},m)})})]})}),e.jsx("div",{className:"mt-4",children:e.jsx(Wr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function b1({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(ce,{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(ft,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(we,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(J,{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(re,{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(re,{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(ia,{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:[Xt(c)," elapsed"]}),e.jsxs("span",{children:[Xt(d)," left"]})]})]})]},l)})}),e.jsx("div",{className:"mt-4",children:e.jsx(Wr,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function j1({aiRemarkUtilization:t}){return t?e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(ce,{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(hl,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(we,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(J,{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(dn,{width:"100%",height:250,children:e.jsxs(Jb,{data:t.monthlyTrends,children:[e.jsx(Yi,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Qi,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(Ki,{stroke:"#999",tick:{fontSize:11}}),e.jsx(mn,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Xi,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(cu,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(cu,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function y1({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(ce,{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(qt,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(we,{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(Et,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(J,{children:[e.jsx("div",{className:"space-y-3",children:t.map((m,p)=>{const u=m.tatCompliancePercent;return e.jsxs("div",{className:"border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{const h=new URLSearchParams;h.set("approverId",m.approverId),h.set("approverName",m.approverName),h.set("dateRange",a),a==="custom"&&r&&n&&(h.set("startDate",r.toISOString()),h.set("endDate",n.toISOString())),d==null||d(`/approver-performance?${h.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 ${r1(u)} flex-shrink-0`,children:[u,"% 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:Xt(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(Wr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:o,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function v1(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 N1(t,s,a,r){const n=[];return r||n.push({label:"New Request",icon:Fe,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"}),n.push({label:"View Pending",icon:it,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:dr,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:Bt,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),n}function w1({onNavigate:t,onNewRequest:s}){const{user:a}=us(),r=di(),n=Nn(Se=>Se.dashboard.viewAsUser),i=x.useMemo(()=>Sl(a),[a]),l=i&&!n,o=x.useCallback(Se=>{r(qv(Se))},[r]),c=eN(),{dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:u,handleDateRangeChange:h,handleApplyCustomDate:g,resetCustomDates:f,setCustomStartDate:b,setCustomEndDate:j,setShowCustomDatePicker:y}=c,N=tN(),{activity:S,critical:A,deadlines:w,approver:I,updateActivityPagination:D,updateCriticalPagination:T,updateDeadlinesPagination:v,updateApproverPagination:M,handleActivityPageChange:P,handleCriticalPageChange:B,handleDeadlinesPageChange:k,handleApproverPageChange:_}=N,L=aN({isAdmin:l,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:p,onPaginationUpdate:{activity:D,critical:T,deadlines:v,approver:M}}),{kpis:R,recentActivity:C,criticalRequests:G,departmentStats:U,priorityDistribution:$,upcomingDeadlines:F,aiRemarkUtilization:H,approverPerformance:K,loading:z,refreshing:O,fetchDashboardData:V,fetchRecentActivities:Q,fetchCriticalRequests:q,fetchUpcomingDeadlines:ee,fetchApproverPerformance:te}=L,ue=xN(),{exportingDeptStats:_e,exportingApproverPerformance:Ze,handleExportDepartmentStats:Ue,handleExportApproverPerformance:Pe}=ue,De=x.useMemo(()=>t1(G),[G]),le=x.useMemo(()=>s1(F),[F]),ye=x.useCallback(()=>{V(!0)},[d,m,p,V]),ae=x.useCallback(()=>{g(()=>{m&&p&&V(!1)})},[m,p,g,V]),he=x.useCallback(Se=>{P(Se,Q)},[P,Q]),ne=x.useCallback(Se=>{B(Se,q)},[B,q]),ge=x.useCallback(Se=>{k(Se,ee)},[k,ee]),ke=x.useCallback(Se=>{_(Se,()=>te(Se))},[_,te]);x.useEffect(()=>{d==="custom"?m&&p&&V(!1):V(!1)},[d,m,p,n]);const Oe=x.useMemo(()=>{try{const Se=tt.getUserData();return(Se==null?void 0:Se.jobTitle)==="Dealer"}catch(Se){return console.error("[Dashboard] Error checking dealer status:",Se),!1}},[]),je=x.useMemo(()=>N1(i,s,t,Oe),[i,s,t,Oe]),ie=x.useCallback(Se=>{const qe=v1(Se);t==null||t(qe)},[t]);return z?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Et,{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(hN,{isAdmin:i,effectiveIsAdmin:l,viewAsUser:n,onToggleView:o,quickActions:je,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(Kw,{isAdmin:l,dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:u,refreshing:O,onDateRangeChange:h,onCustomStartDateChange:b,onCustomEndDateChange:j,onShowCustomDatePickerChange:y,onApplyCustomDate:ae,onResetCustomDates:f,onRefresh:ye}),l?e.jsx(Xw,{kpis:R,priorityDistribution:$,dateRange:d,customStartDate:m,customEndDate:p,onKPIClick:ie}):e.jsx(Zw,{kpis:R,criticalRequests:G,dateRange:d,customStartDate:m,customEndDate:p,onKPIClick:ie,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(n1,{isAdmin:l,breachedRequests:De,pagination:A,onPageChange:ne,onNavigate:t}),e.jsx(m1,{isAdmin:l,recentActivity:C,pagination:S,refreshing:O,onPageChange:he,onRefresh:ye,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),l&&R&&e.jsx(u1,{kpis:R,upcomingDeadlines:F,criticalRequests:G,departmentStats:U,dateRange:d,customStartDate:m,customEndDate:p,exportingDeptStats:_e,onKPIClick:ie,onExportDepartmentStats:Ue}),!l&&R&&e.jsx(x1,{kpis:R}),l&&$.length>0&&e.jsx(h1,{priorityDistribution:$,onNavigate:t}),l&&De.length>0&&e.jsx(f1,{breachedRequests:De,pagination:A,dateRange:d,customStartDate:m,customEndDate:p,onPageChange:ne,onKPIClick:ie,onNavigate:t}),le.length>0&&e.jsx(b1,{isAdmin:l,upcomingDeadlines:le,pagination:w,onPageChange:ge,onNavigate:t}),l&&H&&e.jsx(j1,{aiRemarkUtilization:H}),l&&K.length>0&&e.jsx(y1,{approverPerformance:K,pagination:I,dateRange:d,customStartDate:m,customEndDate:p,loading:z,exportingApproverPerformance:Ze,onPageChange:ke,onExport:Pe,onNavigate:t})]})}const C1={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},ng=yn({name:"openRequests",initialState:C1,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:S1,setStatusFilter:A1,setPriorityFilter:T1,setTemplateTypeFilter:k1,setForm16FinancialYear:D1,setForm16Quarter:R1,setSortBy:F1,setSortOrder:I1,setCurrentPage:P1,clearFilters:E1}=ng.actions;function _1(){const t=di(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,form16FinancialYear:i,form16Quarter:l,sortBy:o,sortOrder:c,currentPage:d}=Nn(A=>A.openRequests),m=x.useCallback(A=>t(S1(A)),[t]),p=x.useCallback(A=>t(A1(A)),[t]),u=x.useCallback(A=>t(T1(A)),[t]),h=x.useCallback(A=>t(k1(A)),[t]),g=x.useCallback(A=>t(D1(A)),[t]),f=x.useCallback(A=>t(R1(A)),[t]),b=x.useCallback(A=>t(F1(A)),[t]),j=x.useCallback(A=>t(I1(A)),[t]),y=x.useCallback(A=>t(P1(A)),[t]),N=x.useCallback(()=>t(E1()),[t]),S=[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:u,setTemplateTypeFilter:h,setForm16FinancialYear:g,setForm16Quarter:f,setSortBy:b,setSortOrder:j,setCurrentPage:y,clearFilters:N,activeFiltersCount:S}}function Jl(){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 M1(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]||{},u=m+1,h=p.tat??"";let g=0;typeof h=="number"&&(g=p.tatType==="days"?h*24:h);const f=p.email||"",b=p.name&&p.name.trim()||f.split("@")[0]||`Approver ${u}`;return{levelNumber:u,levelName:`Level ${u}`,approverId:Jl(),approverEmail:f,approverName:b,tatHours:g>0?g:24,isFinalApprover:u===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:Jl(),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:Jl(),userEmail:c.email,userName:c.name||c.email.split("@")[0]||"CC",participantType:"CONSULTATION",canComment:!1,canViewDocuments:!0,canDownloadDocuments:!1,notificationEnabled:!0}))],n={templateType:t.templateType,title:t.title,description:t.description,priority:s,approvalLevels:a,participants:r.length?r:void 0,isDraft:t.isDraft},i=await ve.post("/workflows",n),l=((o=i.data)==null?void 0:o.data)||i.data;return{id:l.id||l.workflowId||""}}async function Uc(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 ve.post("/workflows/multipart",n,{headers:{"Content-Type":"multipart/form-data"}}),l=((o=i.data)==null?void 0:o.data)||i.data;return{id:l==null?void 0:l.requestId}}async function L1(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:u,dateRange:h,startDate:g,endDate:f}=t,b=await ve.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:u,dateRange:h,startDate:g,endDate:f}});return((j=b.data)==null?void 0:j.data)||b.data}async function O1(t={}){var y,N,S,A,w;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:u,slaCompliance:h,dateRange:g,startDate:f,endDate:b}=t,j=await ve.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:u,slaCompliance:h,dateRange:g,startDate:f,endDate:b}});return{data:((N=(y=j.data)==null?void 0:y.data)==null?void 0:N.data)||((S=j.data)==null?void 0:S.data)||[],pagination:((w=(A=j.data)==null?void 0:A.data)==null?void 0:w.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function $1(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:u}=t,h=await ve.get("/workflows/my",{params:{page:s,limit:a,search:r,status:n,priority:i,department:l,initiator:o,approver:c,slaCompliance:d,dateRange:m,startDate:p,endDate:u}});return{data:((f=(g=h.data)==null?void 0:g.data)==null?void 0:f.data)||((b=h.data)==null?void 0:b.data)||[],pagination:((y=(j=h.data)==null?void 0:j.data)==null?void 0:y.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function U1(t={}){var h,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,u=await ve.get("/workflows/my-initiated",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:c,dateRange:d,startDate:m,endDate:p}});return{data:((g=(h=u.data)==null?void 0:h.data)==null?void 0:g.data)||((f=u.data)==null?void 0:f.data)||[],pagination:((j=(b=u.data)==null?void 0:b.data)==null?void 0:j.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function B1(t={}){var u,h,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 ve.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:((h=(u=p.data)==null?void 0:u.data)==null?void 0:h.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 V1(t={}){var u,h,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 ve.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:((h=(u=p.data)==null?void 0:u.data)==null?void 0:h.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 ve.get(`/workflows/${t}/details`);return((r=a.data)==null?void 0:r.data)||a.data}async function xn(t){var a;const s=await ve.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function ig(t,s,a=[]){var i;const r=new FormData;r.append("payload",JSON.stringify(s||{})),a.forEach(l=>r.append("files",l));const n=await ve.post(`/workflows/${t}/work-notes`,r,{headers:{"Content-Type":"multipart/form-data"}});return((i=n.data)==null?void 0:i.data)||n.data}async function lg(t,s,a,r){var i;const n=await ve.post(`/workflows/${t}/approvers/at-level`,{email:s,tatHours:a,level:r});return((i=n.data)==null?void 0:i.data)||n.data}async function z1(t,s,a){var n;const r=await ve.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function og(t,s){var r;const a=await ve.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function H1(t,s,a,r){var i;const n=await ve.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function G1(t,s){var r;const a=await ve.post(`/workflows/${t}/resume`,{notes:s});return((r=a.data)==null?void 0:r.data)||a.data}async function W1(t){var a;const s=await ve.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function Lu(t){var a;const s=await ve.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function Y1(t){return`https://reflow-uat.royalenfield.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function wn(t){return`https://reflow-uat.royalenfield.com/api/v1/workflows/documents/${t}/preview`}function cg(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=cg(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 Ou(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=cg(c),m=document.createElement("a");m.href=o,m.download=d,document.body.appendChild(m),m.click(),document.body.removeChild(m),window.URL.revokeObjectURL(o)}catch(n){throw console.error("[Download] Failed:",n),n}}const Ks={createWorkflowFromForm:M1,createWorkflowMultipart:Uc,listWorkflows:L1,listParticipantRequests:O1,listMyWorkflows:$1,listMyInitiatedWorkflows:U1,listOpenForMe:B1,listClosedByMe:V1,submitWorkflow:dg,getWorkflowDetails:Ps,getWorkNotes:xn,createWorkNoteMultipart:ig,handleInitiatorAction:mg};async function dg(t){var a;const s=await ve.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function Q1(t,s){var r;const a=await ve.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function K1(t,s,a,r){var o;const n={...s,deleteDocumentIds:r||[]},i=new FormData;i.append("payload",JSON.stringify(n)),i.append("category","SUPPORTING"),a&&a.length>0&&a.forEach(c=>i.append("files",c));const l=await ve.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((o=l.data)==null?void 0:o.data)||l.data}async function Vn(t,s,a){var n;const r=await ve.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function Rr(t,s,a,r){var i;const n=await ve.patch(`/workflows/${t}/approvals/${s}/reject`,{action:"REJECT",rejectionReason:a||"",comments:r||""});return((i=n.data)==null?void 0:i.data)||n.data}async function X1(t,s){const a=await ve.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}async function mg(t,s,a){var n;const r=await ve.post(`/workflows/${t}/initiator-action`,{action:s,...a});return((n=r.data)==null?void 0:n.data)||r.data}async function Z1(t){var a;return((a=(await ve.get(`/workflows/${t}/history`)).data)==null?void 0:a.data)||[]}function bs(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 ug(t){return bs(t,{includeTime:!1,format:"short"})}function Fa(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 J1(t){return t?t.jobTitle==="Dealer"||t.jobTitle==="DEALER":!1}function Bc(t){return J1(t)?"DEALER":"STANDARD"}function _a(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 Si=[{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 hi({value:t,onChange:s,placeholder:a="Enter text...",className:r,minHeight:n="120px",...i}){const l=x.useRef(null),[o,c]=x.useState(!1),[d,m]=x.useState(new Set),[p,u]=x.useState(!1),[h,g]=x.useState(null),[f,b]=x.useState("#FFEB3B"),[j,y]=x.useState(!1),[N,S]=x.useState(null),[A,w]=x.useState("#000000");x.useEffect(()=>{l.current&&l.current.innerHTML!==t&&l.current.innerHTML!==t&&(l.current.innerHTML=_a(t||""))},[t]);const I=x.useCallback(R=>(R=R.replace(/<!--[\s\S]*?-->/g,""),R=R.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),R=R.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),R=R.replace(/<meta[^>]*>/gi,""),R=R.replace(/\s*class="Mso[^"]*"/gi,""),R=R.replace(/\s*class="mso[^"]*"/gi,""),R=R.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),R=R.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),R=R.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),R=R.replace(/<\/?o:p[^>]*>/gi,""),R=R.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),R=R.replace(/<v:[^>]*\/>/gi,""),R=R.replace(/<p[^>]*>\s*<\/p>/gi,""),R=R.replace(/<div[^>]*>\s*<\/div>/gi,""),R=R.replace(/\s+/g," "),R=R.trim(),R),[]),D=x.useCallback(R=>{R.preventDefault();const C=R.clipboardData;let G=C.getData("text/html")||C.getData("text/plain");if((G.includes("<!--")||G.includes("<style")||G.includes("MsoNormal"))&&(G=I(G)),!l.current)return;const U=window.getSelection();if(!U||U.rangeCount===0)return;const $=U.getRangeAt(0);$.deleteContents();const F=document.createElement("div");F.innerHTML=G;const H=document.createDocumentFragment();Array.from(F.childNodes).forEach(K=>{if(K.nodeType===Node.ELEMENT_NODE){const z=K;if(z.tagName==="UL"||z.tagName==="OL"){const O=z.cloneNode(!0);O.removeAttribute("style"),O.removeAttribute("class"),O.querySelectorAll("li").forEach(V=>{V.removeAttribute("style"),V.removeAttribute("class");const Q=V.textContent||"";Q.trim()&&(V.textContent=Q.trim())}),H.appendChild(O)}else if(z.tagName==="TABLE"){const O=z.cloneNode(!0);O.removeAttribute("style"),O.removeAttribute("class"),O.querySelectorAll("td, th").forEach(Q=>{Q.removeAttribute("style"),Q.removeAttribute("class")});const V=document.createElement("div");V.className="table-wrapper",V.appendChild(O),H.appendChild(V)}else if(z.tagName==="P"||z.tagName==="DIV"){const O=document.createElement("p"),Q=z.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");O.innerHTML=Q,O.removeAttribute("style"),O.removeAttribute("class"),H.appendChild(O)}else if(z.tagName==="BR")H.appendChild(z.cloneNode(!0));else{const O=z.textContent||"";if(O.trim()){const V=document.createElement("p");V.textContent=O.trim(),H.appendChild(V)}}}else if(K.nodeType===Node.TEXT_NODE){const z=K.textContent||"";if(z.trim()){const O=document.createElement("p");O.textContent=z.trim(),H.appendChild(O)}}}),H.childNodes.length===0&&C.getData("text/plain").split(`
|
||
`).forEach(O=>{if(O.trim()){const V=document.createElement("p");V.textContent=O.trim(),H.appendChild(V)}else H.appendChild(document.createElement("br"))}),$.insertNode(H),$.collapse(!1),U.removeAllRanges(),U.addRange($),l.current&&s(_a(l.current.innerHTML))},[s,I]),T=x.useCallback(()=>{if(!l.current||!o)return;const R=new Set,C=window.getSelection();if(C&&C.rangeCount>0){const U=C.getRangeAt(0).commonAncestorContainer;let $=null;for(U.nodeType===Node.TEXT_NODE?$=U.parentElement:$=U;$&&$!==l.current;){const F=$.tagName.toLowerCase();(F==="strong"||F==="b")&&R.add("bold"),(F==="em"||F==="i")&&R.add("italic"),F==="u"&&R.add("underline"),F==="h1"&&R.add("h1"),F==="h2"&&R.add("h2"),F==="h3"&&R.add("h3"),F==="ul"&&R.add("ul"),F==="ol"&&R.add("ol");const H=window.getComputedStyle($);H.textAlign==="center"&&R.add("center"),H.textAlign==="right"&&R.add("right"),H.textAlign==="left"&&R.add("left");const K=Q=>{if(Q.startsWith("#"))return Q.toUpperCase();const q=Q.match(/\d+/g);if(!q||q.length<3)return null;const ee=q[0],te=q[1],ue=q[2];if(!ee||!te||!ue)return null;const _e=parseInt(ee).toString(16).padStart(2,"0"),Ze=parseInt(te).toString(16).padStart(2,"0"),Ue=parseInt(ue).toString(16).padStart(2,"0");return`#${_e}${Ze}${Ue}`.toUpperCase()},z=H.backgroundColor;if(z&&z!=="rgba(0, 0, 0, 0)"&&z!=="transparent"&&z!=="rgb(255, 255, 255)"&&z!=="#ffffff"&&z!=="#FFFFFF"){R.add("highlight");const Q=K(z);if(Q){const q=Si.find(ee=>ee.value==="transparent"?!1:ee.value.toUpperCase()===Q);g(q?q.value:Q)}}else R.has("highlight")||g(null);const O=H.color,V=K(O);if(O&&V&&O!=="rgba(0, 0, 0, 0)"&&V!=="#000000"){R.add("textColor");const Q=Si.find(q=>q.value==="transparent"?!1:q.value.toUpperCase()===V);S(Q?Q.value:V)}else R.has("textColor")||S(V==="#000000"||!V?"#000000":null);$=$.parentElement}}m(R)},[o]),v=x.useCallback((R,C)=>{if(!l.current)return;o||l.current.focus();const G=window.getSelection();if(!G||G.rangeCount===0){l.current.focus();return}document.execCommand(R,!1,C),l.current&&s(_a(l.current.innerHTML)),setTimeout(T,10)},[o,s,T]),M=x.useCallback(R=>{if(!l.current)return;o||l.current.focus();const C=window.getSelection();if(!C||C.rangeCount===0){l.current.focus();return}let G=!1;if(C.rangeCount>0){const F=C.getRangeAt(0).commonAncestorContainer;let H=null;for(F.nodeType===Node.TEXT_NODE?H=F.parentElement:H=F;H&&H!==l.current;){const z=window.getComputedStyle(H).backgroundColor;if(z&&z!=="rgba(0, 0, 0, 0)"&&z!=="transparent"&&z!=="rgb(255, 255, 255)"&&z!=="#ffffff"&&z!=="#FFFFFF"){const V=(Q=>{if(Q.startsWith("#"))return Q.toUpperCase();const q=Q.match(/\d+/g);if(!q||q.length<3)return null;const ee=q[0],te=q[1],ue=q[2];if(!ee||!te||!ue)return null;const _e=parseInt(ee).toString(16).padStart(2,"0"),Ze=parseInt(te).toString(16).padStart(2,"0"),Ue=parseInt(ue).toString(16).padStart(2,"0");return`#${_e}${Ze}${Ue}`.toUpperCase()})(z);if(V&&V===R.toUpperCase()){G=!0;break}}H=H.parentElement}}if(R==="transparent"||G){const $=C.getRangeAt(0);if($.collapsed)document.execCommand("removeFormat",!1);else{const F=$.extractContents(),H=document.createDocumentFragment(),K=z=>{if(z.nodeType===Node.TEXT_NODE)return z.cloneNode(!0);if(z.nodeType===Node.ELEMENT_NODE){const O=z,V=document.createElement(O.tagName.toLowerCase());return Array.from(O.attributes).forEach(Q=>{Q.name!=="style"&&Q.name!=="class"&&V.setAttribute(Q.name,Q.value)}),Array.from(O.childNodes).forEach(Q=>{const q=K(Q);q&&V.appendChild(q)}),O.style.backgroundColor&&(V.style.backgroundColor=""),V}return null};Array.from(F.childNodes).forEach(z=>{const O=K(z);O&&H.appendChild(O)}),$.insertNode(H),document.execCommand("removeFormat",!1)}g(null),b("#FFEB3B")}else if(C.rangeCount>0&&!C.getRangeAt(0).collapsed)document.execCommand("backColor",!1,R),g(R),R!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(R)&&b(R);else return;const U=window.getSelection();U&&U.removeAllRanges(),l.current&&s(_a(l.current.innerHTML)),u(!1),setTimeout(()=>{l.current&&l.current.focus(),T()},50)},[o,s,T]),P=x.useCallback(R=>{if(!l.current)return;o||l.current.focus();const C=window.getSelection();if(!C||C.rangeCount===0){l.current.focus();return}let G=!1;if(C.rangeCount>0){const $=C.getRangeAt(0).commonAncestorContainer;let F=null;for($.nodeType===Node.TEXT_NODE?F=$.parentElement:F=$;F&&F!==l.current;){const K=window.getComputedStyle(F).color;if(K){const O=(V=>{if(V.startsWith("#"))return V.toUpperCase();const Q=V.match(/\d+/g);if(!Q||Q.length<3)return null;const q=Q[0],ee=Q[1],te=Q[2];if(!q||!ee||!te)return null;const ue=parseInt(q).toString(16).padStart(2,"0"),_e=parseInt(ee).toString(16).padStart(2,"0"),Ze=parseInt(te).toString(16).padStart(2,"0");return`#${ue}${_e}${Ze}`.toUpperCase()})(K);if(R==="#000000"){if(O==="#000000"||!O){G=!0;break}}else if(O&&O===R.toUpperCase()){G=!0;break}}F=F.parentElement}}if(R==="transparent"||R==="default"||G){if(R==="#000000"&&G){y(!1);return}document.execCommand("removeFormat",!1),S(null),w("#000000")}else document.execCommand("foreColor",!1,R),S(R),R!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(R)&&w(R);l.current&&s(_a(l.current.innerHTML)),y(!1),setTimeout(T,10)},[o,s,T]),B=x.useCallback(()=>{l.current&&s(_a(l.current.innerHTML)),T()},[s,T]),k=x.useCallback(R=>{if(R.ctrlKey&&R.key==="b"){R.preventDefault(),v("bold");return}if(R.ctrlKey&&R.key==="i"){R.preventDefault(),v("italic");return}if(R.ctrlKey&&R.key==="u"){R.preventDefault(),v("underline");return}},[v]),_=x.useCallback(()=>{c(!0)},[]),L=x.useCallback(()=>{c(!1),l.current&&s(_a(l.current.innerHTML))},[s]);return x.useEffect(()=>{if(!o)return;const R=()=>{T()};return document.addEventListener("selectionchange",R),()=>{document.removeEventListener("selectionchange",R)}},[o,T]),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:Le("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(fj,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:Le("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(bj,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:Le("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(jj,{className:"h-4 w-4"})}),e.jsxs(aa,{open:p,onOpenChange:u,children:[e.jsx(ra,{asChild:!0,children:e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("highlight")&&"bg-blue-100 text-blue-700"),title:"Text Highlight",children:e.jsx(yj,{className:"h-4 w-4"})})}),e.jsx(na,{className:"w-auto p-2",align:"start",onPointerDownOutside:R=>{R.target.closest("[data-popover-content]")&&R.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:R=>R.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:R=>{R.stopPropagation(),u(!1)},title:"Close",children:e.jsx(yt,{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:Si.map(R=>{const C=h===R.value,G=R.value==="transparent";return e.jsxs("button",{type:"button",onClick:U=>{U.preventDefault(),U.stopPropagation(),M(C&&!G?"transparent":R.value)},className:Le("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",R.class,C&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",G&&"border-gray-400 bg-white",!G&&!C&&"border-gray-300"),title:C&&!G?`${R.name} (Click to remove)`:R.name,style:G?{}:{backgroundColor:R.value},children:[G&&e.jsx("span",{className:"text-[10px] text-gray-600 font-bold",children:"×"}),C&&!G&&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"})})]},R.value)})}),h&&h!=="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:R=>{R.stopPropagation(),M("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:h&&h!=="transparent"?h:f,onChange:R=>{const C=R.target.value;b(C);const G=window.getSelection();G&&G.rangeCount>0&&!G.getRangeAt(0).collapsed&&M(C)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom color"}),e.jsx("input",{type:"text",value:h&&h!=="transparent"?h:f,onChange:R=>{R.stopPropagation();const C=R.target.value;b(C)},onKeyDown:R=>{if(R.stopPropagation(),R.key==="Enter"){R.preventDefault();const C=R.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(C)&&M(C)}},onPaste:R=>{R.stopPropagation();const C=R.clipboardData.getData("text").trim();R.preventDefault(),setTimeout(()=>{if(/^#[0-9A-Fa-f]{6}$/i.test(C)){b(C);const G=window.getSelection();G&&G.rangeCount>0&&!G.getRangeAt(0).collapsed&&M(C)}else{const G=C.match(/^([0-9A-Fa-f]{6})$/);if(G){const U=`#${G[1]}`;b(U);const $=window.getSelection();$&&$.rangeCount>0&&!$.getRangeAt(0).collapsed&&M(U)}}},0)},onClick:R=>{R.stopPropagation()},onFocus:R=>{R.stopPropagation(),R.target.select()},onBlur:R=>{const C=R.target.value.trim();if(/^#[0-9A-Fa-f]{6}$/i.test(C)){const G=window.getSelection();G&&G.rangeCount>0&&!G.getRangeAt(0).collapsed&&M(C)}else b(C===""?h||"#FFEB3B":C)},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 R=f.trim();/^#[0-9A-Fa-f]{6}$/i.test(R)?M(R):b(h||"#FFEB3B")},title:"Apply custom color",children:"Apply"})]})]})]})})]}),e.jsxs(aa,{open:j,onOpenChange:y,children:[e.jsx(ra,{asChild:!0,children:e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("textColor")&&"bg-blue-100 text-blue-700"),title:"Text Color",children:e.jsx(vj,{className:"h-4 w-4"})})}),e.jsx(na,{className:"w-auto p-2",align:"start",onPointerDownOutside:R=>{R.target.closest("[data-popover-content]")&&R.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:R=>R.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:R=>{R.stopPropagation(),y(!1)},title:"Close",children:e.jsx(yt,{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:R=>{R.preventDefault(),R.stopPropagation(),N==="#000000"||!N&&!d.has("textColor")||P("#000000")},className:Le("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center bg-black",(N==="#000000"||!N&&!d.has("textColor"))&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",N!=="#000000"&&(N||d.has("textColor"))&&"border-gray-300"),title:"Default (Black)",children:[e.jsx("span",{className:"text-[10px] text-white font-bold",children:"A"}),(N==="#000000"||!N&&!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"})})]}),Si.filter(R=>R.value!=="transparent").map(R=>{const C=N===R.value;return e.jsxs("button",{type:"button",onClick:G=>{G.preventDefault(),G.stopPropagation(),P(C?"#000000":R.value)},className:Le("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center relative",C&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",!C&&"border-gray-300"),title:C?`${R.name} (Click to reset to default)`:R.name,style:{color:R.value,borderColor:C?"#2563eb":R.value},children:[e.jsx("span",{className:"text-xs font-bold",children:"A"}),C&&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-${R.value}`)})]}),N&&N!=="#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:R=>{R.stopPropagation(),P("#000000")},title:"Reset to default black",children:"Reset to Default"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:N||A,onChange:R=>{const C=R.target.value;w(C),P(C)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom text color"}),e.jsx("input",{type:"text",value:N||A,onChange:R=>{const C=R.target.value;w(C)},onKeyDown:R=>{if(R.key==="Enter"){R.preventDefault();const C=R.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(C)&&P(C)}},onBlur:R=>{const C=R.target.value;/^#[0-9A-Fa-f]{6}$/.test(C)?P(C):C===""&&w(N||"#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:()=>P(A),title:"Apply custom text color",children:"Apply"})]})]})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:Le("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(Nj,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:Le("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(wj,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:Le("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(Cj,{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:Le("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>v("insertUnorderedList"),title:"Bullet List",children:e.jsx(Zh,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>v("insertOrderedList"),title:"Numbered List",children:e.jsx(Sj,{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:Le("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>v("justifyLeft"),title:"Align Left",children:e.jsx(Jh,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>v("justifyCenter"),title:"Align Center",children:e.jsx(Aj,{className:"h-4 w-4"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>v("justifyRight"),title:"Align Right",children:e.jsx(Tj,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:l,contentEditable:!0,onPaste:D,onInput:B,onFocus:_,onBlur:L,onKeyDown:k,onMouseUp:T,onKeyUp:T,"data-placeholder":a,className:Le("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=x.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>`),_a(r)},[t]);return t?e.jsx("div",{className:Le("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 xg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(cl,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",l="second",o="minute",c="hour",d="day",m="week",p="month",u="quarter",h="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(k){var _=["th","st","nd","rd"],L=k%100;return"["+k+(_[(L-20)%10]||_[L]||_[0])+"]"}},N=function(k,_,L){var R=String(k);return!R||R.length>=_?k:""+Array(_+1-R.length).join(L)+k},S={s:N,z:function(k){var _=-k.utcOffset(),L=Math.abs(_),R=Math.floor(L/60),C=L%60;return(_<=0?"+":"-")+N(R,2,"0")+":"+N(C,2,"0")},m:function k(_,L){if(_.date()<L.date())return-k(L,_);var R=12*(L.year()-_.year())+(L.month()-_.month()),C=_.clone().add(R,p),G=L-C<0,U=_.clone().add(R+(G?-1:1),p);return+(-(R+(L-C)/(G?C-U:U-C))||0)},a:function(k){return k<0?Math.ceil(k)||0:Math.floor(k)},p:function(k){return{M:p,y:h,w:m,d,D:g,h:c,m:o,s:l,ms:i,Q:u}[k]||String(k||"").toLowerCase().replace(/s$/,"")},u:function(k){return k===void 0}},A="en",w={};w[A]=y;var I="$isDayjsObject",D=function(k){return k instanceof P||!(!k||!k[I])},T=function k(_,L,R){var C;if(!_)return A;if(typeof _=="string"){var G=_.toLowerCase();w[G]&&(C=G),L&&(w[G]=L,C=G);var U=_.split("-");if(!C&&U.length>1)return k(U[0])}else{var $=_.name;w[$]=_,C=$}return!R&&C&&(A=C),C||!R&&A},v=function(k,_){if(D(k))return k.clone();var L=typeof _=="object"?_:{};return L.date=k,L.args=arguments,new P(L)},M=S;M.l=T,M.i=D,M.w=function(k,_){return v(k,{locale:_.$L,utc:_.$u,x:_.$x,$offset:_.$offset})};var P=function(){function k(L){this.$L=T(L.locale,null,!0),this.parse(L),this.$x=this.$x||L.x||{},this[I]=!0}var _=k.prototype;return _.parse=function(L){this.$d=function(R){var C=R.date,G=R.utc;if(C===null)return new Date(NaN);if(M.u(C))return new Date;if(C instanceof Date)return new Date(C);if(typeof C=="string"&&!/Z$/i.test(C)){var U=C.match(b);if(U){var $=U[2]-1||0,F=(U[7]||"0").substring(0,3);return G?new Date(Date.UTC(U[1],$,U[3]||1,U[4]||0,U[5]||0,U[6]||0,F)):new Date(U[1],$,U[3]||1,U[4]||0,U[5]||0,U[6]||0,F)}}return new Date(C)}(L),this.init()},_.init=function(){var L=this.$d;this.$y=L.getFullYear(),this.$M=L.getMonth(),this.$D=L.getDate(),this.$W=L.getDay(),this.$H=L.getHours(),this.$m=L.getMinutes(),this.$s=L.getSeconds(),this.$ms=L.getMilliseconds()},_.$utils=function(){return M},_.isValid=function(){return this.$d.toString()!==f},_.isSame=function(L,R){var C=v(L);return this.startOf(R)<=C&&C<=this.endOf(R)},_.isAfter=function(L,R){return v(L)<this.startOf(R)},_.isBefore=function(L,R){return this.endOf(R)<v(L)},_.$g=function(L,R,C){return M.u(L)?this[R]:this.set(C,L)},_.unix=function(){return Math.floor(this.valueOf()/1e3)},_.valueOf=function(){return this.$d.getTime()},_.startOf=function(L,R){var C=this,G=!!M.u(R)||R,U=M.p(L),$=function(q,ee){var te=M.w(C.$u?Date.UTC(C.$y,ee,q):new Date(C.$y,ee,q),C);return G?te:te.endOf(d)},F=function(q,ee){return M.w(C.toDate()[q].apply(C.toDate("s"),(G?[0,0,0,0]:[23,59,59,999]).slice(ee)),C)},H=this.$W,K=this.$M,z=this.$D,O="set"+(this.$u?"UTC":"");switch(U){case h:return G?$(1,0):$(31,11);case p:return G?$(1,K):$(0,K+1);case m:var V=this.$locale().weekStart||0,Q=(H<V?H+7:H)-V;return $(G?z-Q:z+(6-Q),K);case d:case g:return F(O+"Hours",0);case c:return F(O+"Minutes",1);case o:return F(O+"Seconds",2);case l:return F(O+"Milliseconds",3);default:return this.clone()}},_.endOf=function(L){return this.startOf(L,!1)},_.$set=function(L,R){var C,G=M.p(L),U="set"+(this.$u?"UTC":""),$=(C={},C[d]=U+"Date",C[g]=U+"Date",C[p]=U+"Month",C[h]=U+"FullYear",C[c]=U+"Hours",C[o]=U+"Minutes",C[l]=U+"Seconds",C[i]=U+"Milliseconds",C)[G],F=G===d?this.$D+(R-this.$W):R;if(G===p||G===h){var H=this.clone().set(g,1);H.$d[$](F),H.init(),this.$d=H.set(g,Math.min(this.$D,H.daysInMonth())).$d}else $&&this.$d[$](F);return this.init(),this},_.set=function(L,R){return this.clone().$set(L,R)},_.get=function(L){return this[M.p(L)]()},_.add=function(L,R){var C,G=this;L=Number(L);var U=M.p(R),$=function(K){var z=v(G);return M.w(z.date(z.date()+Math.round(K*L)),G)};if(U===p)return this.set(p,this.$M+L);if(U===h)return this.set(h,this.$y+L);if(U===d)return $(1);if(U===m)return $(7);var F=(C={},C[o]=r,C[c]=n,C[l]=a,C)[U]||1,H=this.$d.getTime()+L*F;return M.w(H,this)},_.subtract=function(L,R){return this.add(-1*L,R)},_.format=function(L){var R=this,C=this.$locale();if(!this.isValid())return C.invalidDate||f;var G=L||"YYYY-MM-DDTHH:mm:ssZ",U=M.z(this),$=this.$H,F=this.$m,H=this.$M,K=C.weekdays,z=C.months,O=C.meridiem,V=function(ee,te,ue,_e){return ee&&(ee[te]||ee(R,G))||ue[te].slice(0,_e)},Q=function(ee){return M.s($%12||12,ee,"0")},q=O||function(ee,te,ue){var _e=ee<12?"AM":"PM";return ue?_e.toLowerCase():_e};return G.replace(j,function(ee,te){return te||function(ue){switch(ue){case"YY":return String(R.$y).slice(-2);case"YYYY":return M.s(R.$y,4,"0");case"M":return H+1;case"MM":return M.s(H+1,2,"0");case"MMM":return V(C.monthsShort,H,z,3);case"MMMM":return V(z,H);case"D":return R.$D;case"DD":return M.s(R.$D,2,"0");case"d":return String(R.$W);case"dd":return V(C.weekdaysMin,R.$W,K,2);case"ddd":return V(C.weekdaysShort,R.$W,K,3);case"dddd":return K[R.$W];case"H":return String($);case"HH":return M.s($,2,"0");case"h":return Q(1);case"hh":return Q(2);case"a":return q($,F,!0);case"A":return q($,F,!1);case"m":return String(F);case"mm":return M.s(F,2,"0");case"s":return String(R.$s);case"ss":return M.s(R.$s,2,"0");case"SSS":return M.s(R.$ms,3,"0");case"Z":return U}return null}(ee)||U.replace(":","")})},_.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},_.diff=function(L,R,C){var G,U=this,$=M.p(R),F=v(L),H=(F.utcOffset()-this.utcOffset())*r,K=this-F,z=function(){return M.m(U,F)};switch($){case h:G=z()/12;break;case p:G=z();break;case u:G=z()/3;break;case m:G=(K-H)/6048e5;break;case d:G=(K-H)/864e5;break;case c:G=K/n;break;case o:G=K/r;break;case l:G=K/a;break;default:G=K}return C?G:M.a(G)},_.daysInMonth=function(){return this.endOf(p).$D},_.$locale=function(){return w[this.$L]},_.locale=function(L,R){if(!L)return this.$L;var C=this.clone(),G=T(L,R,!0);return G&&(C.$L=G),C},_.clone=function(){return M.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()},k}(),B=P.prototype;return v.prototype=B,[["$ms",i],["$s",l],["$m",o],["$H",c],["$W",d],["$M",p],["$y",h],["$D",g]].forEach(function(k){B[k[1]]=function(_){return this.$g(_,k[0],k[1])}}),v.extend=function(k,_){return k.$i||(k(_,P,v),k.$i=!0),v},v.locale=T,v.isDayjs=D,v.unix=function(k){return v(1e3*k)},v.en=w[A],v.Ls=w,v.p={},v})})(xg);var q1=xg.exports;const rs=dl(q1);var hg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(cl,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,u){return i.fromToBase(d,m,p,u)}n.en.relativeTime=l,i.fromToBase=function(d,m,p,u,h){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"}],N=y.length,S=0;S<N;S+=1){var A=y[S];A.d&&(g=u?n(d).diff(p,A.d,!0):p.diff(d,A.d,!0));var w=(a.rounding||Math.round)(Math.abs(g));if(b=g>0,w<=A.r||!A.r){w<=1&&S>0&&(A=y[S-1]);var I=j[A.l];h&&(w=h(""+w)),f=typeof I=="string"?I.replace("%d",w):I(w,m,A.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)}}})})(hg);var eC=hg.exports;const tC=dl(eC);rs.extend(tC);function sC({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:u,currentUserIsApprover:h=!1,pausedByUserId:g,currentUserId:f,generationAttempts:b=0,generationFailed:j=!1,maxAttemptsReached:y=!1}){var G,U,$,F,H,K,z,O;const{user:N}=us(),S=t==null?void 0:t.pauseInfo,A=(S==null?void 0:S.isPaused)||!1,w=(G=S==null?void 0:S.pausedBy)==null?void 0:G.userId,I=(N==null?void 0:N.userId)||"",D=A&&p&&(h||s),T=A&&s&&w&&w!==I&&u,M=((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"),P=t==null?void 0:t.form16Submission,B=M&&(P!=null&&P.ocrExtractedData)&&typeof P.ocrExtractedData=="object"?P.ocrExtractedData:null,k=M&&B&&Object.keys(B).length>0?B:M&&P?{deductorName:P.deductorName,deductor_name:P.deductorName,tanNumber:P.tanNumber,tan_number:P.tanNumber,financialYear:P.financialYear,financial_year:P.financialYear,quarter:P.quarter,form16aNumber:P.form16aNumber,form16a_number:P.form16aNumber,totalAmount:P.totalAmount,total_amount:P.totalAmount,tdsAmount:P.tdsAmount,tds_amount:P.tdsAmount,acknowledgementNumber:P.acknowledgementNumber,acknowledgement_number:P.acknowledgementNumber,dateOfIssue:P.dateOfIssue,date_of_issue:P.dateOfIssue,deduceeName:P.deduceeName,deducee_name:P.deduceeName,deduceePan:P.deduceePan,deducee_pan:P.deduceePan}:null,_=V=>V!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(Number(V)):"–",L=V=>V==null||V===""?"–":String(V),R=V=>{const Q=(V||"").toLowerCase();return Q==="completed"?"bg-emerald-100 text-emerald-800 border-emerald-200":Q==="duplicate"||Q==="duplicate submission"?"bg-amber-100 text-amber-800 border-amber-200":Q==="balance mismatch"||Q==="failed"?"bg-red-100 text-red-800 border-red-200":Q==="resubmission needed"||Q==="partial extracted data"?"bg-amber-50 text-amber-700 border-amber-200":"bg-gray-100 text-gray-700 border-gray-200"},C=V=>{const Q=((V==null?void 0:V.displayStatus)||"").toLowerCase(),q=((V==null?void 0:V.validationNotes)||"").toLowerCase();return Q==="balance mismatch"||Q==="failed"&&(q.includes("mismatch")||q.includes("26as")||q.includes("value"))?"Failed - data mismatch with 26AS, submit the form 16 with correct data":Q==="duplicate"||Q==="duplicate submission"?"Duplicate. A submission for this FY and quarter already exists.":Q==="resubmission needed"?(V==null?void 0:V.validationNotes)||"Resubmission needed. Please submit again with correct data.":Q==="failed"?(V==null?void 0:V.validationNotes)||"Submission failed. Please resubmit.":null};return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[M&&(P==null?void 0:P.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(re,{variant:"outline",className:R(P.displayStatus),children:P.displayStatus})]}),C(P)&&e.jsx("p",{className:`text-sm ${(P.displayStatus||"").toLowerCase()==="balance mismatch"||(P.displayStatus||"").toLowerCase()==="failed"?"text-red-700 font-medium":"text-gray-600"}`,children:C(P)})]}),M&&e.jsxs(Z,{"data-testid":"form16-certificate-details",className:"border-emerald-200 bg-emerald-50/30",children:[e.jsxs(ce,{className:"pb-3 sm:pb-4",children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base text-emerald-800",children:[e.jsx(Fe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-emerald-600"}),"Form 16A Certificate Details"]}),e.jsx(we,{className:"text-xs text-gray-600",children:"TDS Certificate as per Income Tax Act, 1961"})]}),e.jsx(J,{className:"space-y-4",children:P?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:P.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:P.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:P.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:P.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:P.quarter?`${P.quarter} (${P.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:"})," ",P.deductorName||"–"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TAN:"})," ",P.tanNumber||"–"]})]})]}),(P.deduceeName||P.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:[P.deduceeName&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Name:"})," ",P.deduceeName]}),P.deduceePan&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"PAN:"})," ",P.deduceePan]}),P.deduceeAddress&&e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("span",{className:"text-gray-500",children:"Address:"})," ",P.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:[P.section&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Section:"})," ",P.section]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Amount Paid:"})," ",_(P.totalAmount??P.amountPaid)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TDS Deducted:"})," ",_(P.tdsAmount)]}),P.dateOfPayment&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Date of Payment:"})," ",P.dateOfPayment]})]})]}),(P.bsrCode||P.challanSerialNo||P.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:[P.bsrCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"BSR Code:"})," ",P.bsrCode]}),P.challanSerialNo&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Challan Serial No.:"})," ",P.challanSerialNo]}),P.dateOfDeposit&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Date of Deposit:"})," ",P.dateOfDeposit]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Amount:"})," ",_(P.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:_(P.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."})]})})]}),M&&k&&Object.keys(k).length>0&&e.jsxs(Z,{"data-testid":"form16-ocr-extracted-data",className:"border-slate-200 bg-slate-50/50",children:[e.jsxs(ce,{className:"pb-3",children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base text-slate-800",children:[e.jsx(qh,{className:"w-4 h-4 text-slate-600"}),"OCR extracted data"]}),e.jsx(we,{className:"text-xs text-gray-600",children:"Data extracted from the uploaded Form 16A PDF."})]}),e.jsx(J,{children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm",children:[(k.deductorName??k.deductor_name??k.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:L(k.deductorName??k.deductor_name??k.nameAndAddressOfDeductor)})]}),(k.tanNumber??k.tan_number??k.tanOfDeductor)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"TAN"}),e.jsx("p",{className:"font-medium",children:L(k.tanNumber??k.tan_number??k.tanOfDeductor)})]}),(k.financialYear??k.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:L(k.financialYear??k.financial_year)})]}),k.quarter!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Quarter"}),e.jsx("p",{className:"font-medium",children:L(k.quarter)})]}),(k.form16aNumber??k.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:L(k.form16aNumber??k.form16a_number)})]}),(k.totalAmount??k.total_amount??k.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:_(k.totalAmount??k.total_amount??k.totalAmountPaid)})]}),(k.totalTaxDeducted??k.tdsAmount??k.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:_(k.totalTaxDeducted??k.tdsAmount??k.tds_amount)})]}),(k.natureOfPayment??k.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:L(k.natureOfPayment??k.nature_of_payment)})]}),(k.transactionDate??k.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:L(k.transactionDate??k.transaction_date)})]}),(k.assessmentYear??k.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:L(k.assessmentYear??k.assessment_year)})]}),(k.acknowledgementNumber??k.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:L(k.acknowledgementNumber??k.acknowledgement_number)})]}),(k.dateOfIssue??k.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:L(k.dateOfIssue??k.date_of_issue)})]}),(k.deduceeName??k.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:L(k.deduceeName??k.deducee_name)})]}),(k.deduceePan??k.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:L(k.deduceePan??k.deducee_pan)})]})]})})]}),e.jsxs(Z,{"data-testid":"initiator-card",children:[e.jsx(ce,{className:"pb-3 sm:pb-4",children:e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ht,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(J,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(cs,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(ds,{className:"bg-gray-700 text-white font-semibold text-sm",children:((U=t.initiator)==null?void 0:U.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:(($=t.initiator)==null?void 0:$.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((F=t.initiator)==null?void 0:F.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((H=t.initiator)==null?void 0:H.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(va,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((K=t.initiator)==null?void 0:K.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(oi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((z=t.initiator)==null?void 0:z.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(Z,{"data-testid":"request-details-card",children:[e.jsx(ce,{className:"pb-3 sm:pb-4",children:e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Fe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(J,{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:bs(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:bs(t.updatedAt)})]})]})]})]}),A&&S&&e.jsxs(Z,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(ce,{className:"pb-3 sm:pb-4",children:e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(mr,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(J,{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:[S.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:S.pauseReason,className:"text-sm text-gray-900 mt-1"})]}),S.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:S.pausedBy.name||S.pausedBy.email})]}),S.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:[bs(S.pauseResumeDate),rs(S.pauseResumeDate).isAfter(rs())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",rs(S.pauseResumeDate).fromNow(),")"]})]})]}),S.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:bs(S.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(Zi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),T&&u&&e.jsxs(E,{onClick:u,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(Je,{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(ce,{className:"pb-4",children:e.jsxs(de,{className:"flex items-center gap-2 text-base",children:[e.jsx(Fe,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(J,{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?ug(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(ce,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(de,{className:"flex items-center gap-2 text-base",children:[e.jsx(Be,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(we,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(J,{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 ",bs(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(ce,{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(de,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(Be,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(we,{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(Et,{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(J,{className:"pt-4",children:i?e.jsx("div",{className:"flex items-center justify-center py-8","data-testid":"conclusion-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ze,{className:"w-8 h-8 text-blue-600 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Preparing conclusion remark..."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Conclusion Remark"}),o&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),e.jsx(hi,{value:r,onChange:V=>n(V),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(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function Gn({delayDuration:t=0,...s}){return e.jsx(Fb,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function $i({...t}){return e.jsx(Gn,{children:e.jsx(Ib,{"data-slot":"tooltip",...t})})}function Ui({...t}){return e.jsx(Pb,{"data-slot":"tooltip-trigger",...t})}function Bi({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(Eb,{children:e.jsxs(_b,{"data-slot":"tooltip-content",sideOffset:s,className:Le("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(Mb,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function xt({...t}){return e.jsx(Bh,{"data-slot":"dialog",...t})}function aC({...t}){return e.jsx(Uh,{"data-slot":"dialog-portal",...t})}const pg=x.forwardRef(({className:t,...s},a)=>e.jsx(mc,{ref:a,"data-slot":"dialog-overlay",className:Le("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}));pg.displayName=mc.displayName;const dt=x.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(aC,{"data-slot":"dialog-portal",children:[e.jsx(pg,{}),e.jsxs(uc,{ref:r,"data-slot":"dialog-content",className:Le("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(Lb,{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(yt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));dt.displayName=uc.displayName;const ht=x.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:Le("flex flex-col gap-2 text-center sm:text-left",t),...s}));ht.displayName="DialogHeader";const Dt=x.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:Le("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));Dt.displayName="DialogFooter";const mt=x.forwardRef(({className:t,...s},a)=>e.jsx(Oh,{ref:a,"data-slot":"dialog-title",className:Le("text-lg leading-none font-semibold",t),...s}));mt.displayName=Oh.displayName;const _t=x.forwardRef(({className:t,...s},a)=>e.jsx($h,{ref:a,"data-slot":"dialog-description",className:Le("text-muted-foreground text-sm",t),...s}));_t.displayName=$h.displayName;function zs({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:Le("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 $u=t=>{if(t<8)return Xt(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${Xt(r)}`:`${a}d`},rC=(t,s)=>{if(s)return e.jsx(Je,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(Be,{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(ep,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(it,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(it,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(it,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function nC({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}=us(),[m,p]=x.useState(!1),[u,h]=x.useState(""),[g,f]=x.useState(!1),b=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";x.useEffect(()=>{m||h("")},[m]);const j=t.status==="pending"||t.status==="in-review",y=t.status==="approved",N=t.status==="rejected",S=t.status==="waiting",A=t.status==="paused",w=Number(t.tatHours||0),I=t.actualHours??0,D=y&&I?Math.max(0,w-I):0,T=w>0?I/w*100:0,v=T>=100,M=(d==null?void 0:d.role)==="ADMIN",P=Sl(d),B=t.approverId===(d==null?void 0:d.userId),k=M||P||B,_=async()=>{var L,R;if(!u.trim()){W.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}f(!0);try{await X1(t.levelId,u.trim()),p(!1),h(""),W.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(C){console.error("Error updating breach reason:",C);const G=((R=(L=C==null?void 0:C.response)==null?void 0:L.data)==null?void 0:R.error)||(C==null?void 0:C.message)||"Failed to update breach reason. Please try again.";W.error("Failed to Update Breach Reason",{description:G,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":N?"border-red-500 bg-red-50":S?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${c}-${t.step}`,children:[e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 md:gap-4",children:[e.jsx("div",{className:`p-2 sm:p-2.5 md:p-3 rounded-xl flex-shrink-0 ${t.isSkipped?"bg-orange-100":A?"bg-yellow-100":j?"bg-blue-100":y?"bg-green-100":N?"bg-red-100":S?"bg-gray-200":"bg-gray-100"}`,children:rC(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(re,{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":N?"bg-red-100 text-red-800 border-red-200":S?"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(Gn,{delayDuration:200,children:e.jsxs($i,{children:[e.jsx(Ui,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:L=>L.stopPropagation(),children:e.jsx(Je,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(Bi,{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(uu,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),y&&I&&e.jsx(re,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:$u(I)})]}),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:[w," hours"]})]})]}),y&&I!==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?bs(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:$u(I)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const L=Math.min(100,T),R=()=>v?"bg-red-600":T>=75?"bg-orange-500":T>=50?"bg-amber-500":"bg-green-600",C=()=>v?"text-red-600":T>=75?"text-orange-600":T>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(ia,{value:L,className:"h-2 bg-gray-200",indicatorClassName:R(),"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 ${C()}`,children:[Math.round(L),"% of TAT used"]}),v&&k&&e.jsx(Gn,{children:e.jsxs($i,{children:[e.jsx(Ui,{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:()=>{h(b),p(!0)},children:e.jsx(wi,{className:"w-3 h-3"})})}),e.jsx(Bi,{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 ",Xt(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(wi,{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(Ys,{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||A)&&(a==null?void 0:a.sla)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Due by:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.deadline?Fa(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${A?"bg-gray-100 border-gray-300":(a.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(a.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(a.sla.percentageUsed||0)>=50?"bg-amber-50 border-amber-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",A&&"(Paused)"]}),e.jsxs("div",{className:"space-y-2 text-xs mb-3",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time elapsed since assigned:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.elapsedText})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time used:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[a.sla.elapsedText," / ",Xt(w)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const L=a.sla.percentageUsed||0,R=()=>A?"bg-gray-500":L>=100?"bg-red-600":L>=75?"bg-orange-500":L>=50?"bg-amber-500":"bg-green-600",C=()=>A?"text-gray-600":L>=100?"text-red-600":L>=75?"text-orange-600":L>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(ia,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:R(),"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 ${C()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&k&&e.jsx(Gn,{children:e.jsxs($i,{children:[e.jsx(Ui,{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:()=>{h(b),p(!0)},children:e.jsx(wi,{className:"w-3 h-3"})})}),e.jsx(Bi,{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(Ji,{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(wi,{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(ss,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),S&&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(ep,{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 ",w," hours for approval"]})]})}),N&&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(uu,{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 ",bs(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((L,R)=>{var C,G,U,$,F,H;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${L.isBreached?"bg-red-50 border-red-200":(L.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${R}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(L.thresholdPercentage||0)===50&&e.jsx(kj,{className:"w-5 h-5 text-yellow-600"}),(L.thresholdPercentage||0)===75&&e.jsx(ss,{className:"w-5 h-5 text-orange-600"}),(L.thresholdPercentage||0)===100&&e.jsx(Ji,{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 ",R+1," - ",L.thresholdPercentage||0,"% TAT"]}),e.jsx(re,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${L.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:L.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[L.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:Xt(Number(L.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:[Xt(Number(L.tatHoursElapsed||0)),((C=L.metadata)==null?void 0:C.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(L.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 ${(L.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[Xt(Number(L.tatHoursRemaining||0)),((G=L.metadata)==null?void 0:G.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(L.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:L.expectedCompletionTime?Fa(L.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"}),(((U=L.metadata)==null?void 0:U.testMode)||(($=L.metadata)==null?void 0:$.tatTestMode))&&e.jsx(re,{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: ",L.alertSentAt?bs(L.alertSentAt):"N/A"]}),(((F=L.metadata)==null?void 0:F.testMode)||((H=L.metadata)==null?void 0:H.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},R)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[y?"Approved":N?"Rejected":"Actioned"," on ",bs(t.timestamp)]}),n&&!A&&(j||t.status==="pending")&&!y&&!N&&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(Je,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Skip This Approver"]}),e.jsx("p",{className:"text-[10px] sm:text-xs text-gray-500 mt-1 text-center",children:A?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(xt,{open:m,onOpenChange:p,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsxs(ht,{children:[e.jsx(mt,{children:b?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(_t,{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(zs,{placeholder:"Enter the reason for the breach...",value:u,onChange:L=>h(L.target.value),className:"min-h-[100px]",maxLength:500}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[u.length,"/500 characters"]})]}),e.jsxs(Dt,{children:[e.jsx(E,{variant:"outline",onClick:()=>{p(!1),h("")},disabled:g,children:"Cancel"}),e.jsx(E,{onClick:_,disabled:!u.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function iC({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(Z,{children:[e.jsx(ce,{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(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Qs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(we,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var h;const i=t.totalSteps||1,l=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,o=((h=t.approvalFlow)==null?void 0:h.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,u=Math.min(Math.max(1,l),i);return p?e.jsxs(re,{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(re,{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(re,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",u," of ",i," - ",o," completed"]})})()]})}),e.jsx(J,{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 h,g,f;const o=(h=t.approvals)==null?void 0:h.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,u=i.step===p;return e.jsx(nC,{step:i,index:l,approval:o,isCurrentUser:m,isInitiator:a,isCurrentLevel:u,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 Ar(t){return t==null?"–":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(Number(t))}function ha(t){return t==null||t===""?"–":String(t)}function lC(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 Uu="Failed - data mismatch with 26AS, submit the Form 16 with correct data.";function oC(t){const s=(t||"").toLowerCase();return/notnull|violation|sequelize|econnrefused|database|error\./i.test(s)}function Bu(t){const s=((t==null?void 0:t.displayStatus)||"").toLowerCase(),a=String((t==null?void 0:t.validationNotes)||"");return s==="balance mismatch"||s==="failed"?oC(a)?Uu:a.trim()||Uu: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 cC({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(re,{variant:"outline",className:lC(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:"})," ",Ar(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]})]}),Bu(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:Bu(s)})]}),e.jsxs(Z,{"data-testid":"form16-certificate-details",className:"border-emerald-200 bg-emerald-50/30",children:[e.jsxs(ce,{className:"pb-3 sm:pb-4",children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base text-emerald-800",children:[e.jsx(Fe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-emerald-600"}),"Form 16A Certificate Details"]}),e.jsx(we,{className:"text-xs text-gray-600",children:"TDS Certificate as per Income Tax Act, 1961"})]}),e.jsx(J,{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:"})," ",Ar(s.totalAmount??s.amountPaid)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TDS Deducted:"})," ",Ar(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:"})," ",Ar(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:Ar(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(ce,{className:"pb-3",children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base text-slate-800",children:[e.jsx(qh,{className:"w-4 h-4 text-slate-600"}),"OCR extracted data"]}),e.jsx(we,{className:"text-xs text-gray-600",children:"Data extracted from the uploaded Form 16A PDF (shown for all submission outcomes)."})]}),e.jsx(J,{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:ha(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:ha(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:ha(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:ha(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:ha(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:Ar(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:Ar(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:ha(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:ha(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:ha(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:ha(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:ha(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:ha(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:ha(r.deduceePan??r.deducee_pan)})]})]})})]}),e.jsxs(Z,{"data-testid":"form16-submission-context",children:[e.jsx(ce,{className:"pb-3",children:e.jsxs(de,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-emerald-600"}),"Submitted by"]})}),e.jsxs(J,{children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(cs,{className:"h-10 w-10 rounded-full flex-shrink-0",children:e.jsx(ds,{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(va,{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 dC=[{key:"submit",label:"Dealer submits Form 16",icon:Fe},{key:"ocr",label:"OCR extracts",icon:Fe},{key:"match",label:"Matching with 26AS",icon:Et},{key:"success",label:"Successfully match",icon:Be},{key:"credit",label:"Credit note generated",icon:Mt}];function mC({request:t,requestId:s}){const[a,r]=x.useState(null),[n,i]=x.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",u=c||m==="success"||m==="manually_approved";x.useEffect(()=>{if(!s){i(!1);return}let f=!1;return(async()=>{try{const b=await Gp(s);f||r(b)}catch{f||r(null)}finally{f||i(!1)}})(),()=>{f=!0}},[s]);const h={submit:!0,ocr:o,match:u,success:u,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(ce,{className:"pb-2",children:e.jsxs(de,{className:"text-base flex items-center gap-2 text-emerald-800",children:[e.jsx(Et,{className:"w-4 h-4"}),"Form 16 process"]})}),e.jsx(J,{className:"space-y-4",children:dC.map(f=>{const b=h[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(Be,{className:"w-4 h-4"}):e.jsx(bc,{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(ze,{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 Vc=x.createContext({});function zc(t){const s=x.useRef(null);return s.current===null&&(s.current=t()),s.current}const Hc=typeof window<"u",gg=Hc?x.useLayoutEffect:x.useEffect,Dl=x.createContext(null);function Gc(t,s){t.indexOf(s)===-1&&t.push(s)}function Wc(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const Xa=(t,s,a)=>a>s?s:a<t?t:a;let Yc=()=>{};const Za={},fg=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function bg(t){return typeof t=="object"&&t!==null}const jg=t=>/^0[^.\s]+$/u.test(t);function Qc(t){let s;return()=>(s===void 0&&(s=t()),s)}const ja=t=>t,uC=(t,s)=>a=>s(t(a)),pi=(...t)=>t.reduce(uC),ti=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class Kc{constructor(){this.subscriptions=[]}add(s){return Gc(this.subscriptions,s),()=>Wc(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 Ma=t=>t*1e3,fa=t=>t/1e3;function yg(t,s){return s?t*(1e3/s):0}const vg=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,xC=1e-7,hC=12;function pC(t,s,a,r,n){let i,l,o=0;do l=s+(a-s)/2,i=vg(l,r,n)-t,i>0?a=l:s=l;while(Math.abs(i)>xC&&++o<hC);return l}function gi(t,s,a,r){if(t===s&&a===r)return ja;const n=i=>pC(i,0,1,t,a);return i=>i===0||i===1?i:vg(n(i),s,r)}const Ng=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,wg=t=>s=>1-t(1-s),Cg=gi(.33,1.53,.69,.99),Xc=wg(Cg),Sg=Ng(Xc),Ag=t=>(t*=2)<1?.5*Xc(t):.5*(2-Math.pow(2,-10*(t-1))),Zc=t=>1-Math.sin(Math.acos(t)),Tg=wg(Zc),kg=Ng(Zc),gC=gi(.42,0,1,1),fC=gi(0,0,.58,1),Dg=gi(.42,0,.58,1),bC=t=>Array.isArray(t)&&typeof t[0]!="number",Rg=t=>Array.isArray(t)&&typeof t[0]=="number",jC={linear:ja,easeIn:gC,easeInOut:Dg,easeOut:fC,circIn:Zc,circInOut:kg,circOut:Tg,backIn:Xc,backInOut:Sg,backOut:Cg,anticipate:Ag},yC=t=>typeof t=="string",Vu=t=>{if(Rg(t)){Yc(t.length===4);const[s,a,r,n]=t;return gi(s,a,r,n)}else if(yC(t))return jC[t];return t},Ai=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function vC(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,u=!1)=>{const g=u&&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 NC=40;function Fg(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,l=Ai.reduce((N,S)=>(N[S]=vC(i),N),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:m,update:p,preRender:u,render:h,postRender:g}=l,f=()=>{const N=Za.useManualTiming?n.timestamp:performance.now();a=!1,Za.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(N-n.timestamp,NC),1)),n.timestamp=N,n.isProcessing=!0,o.process(n),c.process(n),d.process(n),m.process(n),p.process(n),u.process(n),h.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:Ai.reduce((N,S)=>{const A=l[S];return N[S]=(w,I=!1,D=!1)=>(a||b(),A.schedule(w,I,D)),N},{}),cancel:N=>{for(let S=0;S<Ai.length;S++)l[Ai[S]].cancel(N)},state:n,steps:l}}const{schedule:es,cancel:xr,state:Is,steps:ql}=Fg(typeof requestAnimationFrame<"u"?requestAnimationFrame:ja,!0);let Vi;function wC(){Vi=void 0}const sa={now:()=>(Vi===void 0&&sa.set(Is.isProcessing||Za.useManualTiming?Is.timestamp:performance.now()),Vi),set:t=>{Vi=t,queueMicrotask(wC)}},Ig=t=>s=>typeof s=="string"&&s.startsWith(t),Jc=Ig("--"),CC=Ig("var(--"),qc=t=>CC(t)?SC.test(t.split("/*")[0].trim()):!1,SC=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Cn={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},si={...Cn,transform:t=>Xa(0,1,t)},Ti={...Cn,default:1},Wn=t=>Math.round(t*1e5)/1e5,ed=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function AC(t){return t==null}const TC=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,td=(t,s)=>a=>!!(typeof a=="string"&&TC.test(a)&&a.startsWith(t)||s&&!AC(a)&&Object.prototype.hasOwnProperty.call(a,s)),Pg=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,l,o]=r.match(ed);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},kC=t=>Xa(0,255,t),eo={...Cn,transform:t=>Math.round(kC(t))},Mr={test:td("rgb","red"),parse:Pg("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+eo.transform(t)+", "+eo.transform(s)+", "+eo.transform(a)+", "+Wn(si.transform(r))+")"};function DC(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 Bo={test:td("#"),parse:DC,transform:Mr.transform},fi=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),lr=fi("deg"),La=fi("%"),ot=fi("px"),RC=fi("vh"),FC=fi("vw"),zu={...La,parse:t=>La.parse(t)/100,transform:t=>La.transform(t*100)},an={test:td("hsl","hue"),parse:Pg("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+La.transform(Wn(s))+", "+La.transform(Wn(a))+", "+Wn(si.transform(r))+")"},gs={test:t=>Mr.test(t)||Bo.test(t)||an.test(t),parse:t=>Mr.test(t)?Mr.parse(t):an.test(t)?an.parse(t):Bo.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Mr.transform(t):an.transform(t),getAnimatableNone:t=>{const s=gs.parse(t);return s.alpha=0,gs.transform(s)}},IC=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function PC(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(ed))==null?void 0:s.length)||0)+(((a=t.match(IC))==null?void 0:a.length)||0)>0}const Eg="number",_g="color",EC="var",_C="var(",Hu="${}",MC=/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 ai(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const o=s.replace(MC,c=>(gs.test(c)?(r.color.push(i),n.push(_g),a.push(gs.parse(c))):c.startsWith(_C)?(r.var.push(i),n.push(EC),a.push(c)):(r.number.push(i),n.push(Eg),a.push(parseFloat(c))),++i,Hu)).split(Hu);return{values:a,split:o,indexes:r,types:n}}function Mg(t){return ai(t).values}function Lg(t){const{split:s,types:a}=ai(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===Eg?i+=Wn(n[l]):o===_g?i+=gs.transform(n[l]):i+=n[l]}return i}}const LC=t=>typeof t=="number"?0:gs.test(t)?gs.getAnimatableNone(t):t;function OC(t){const s=Mg(t);return Lg(t)(s.map(LC))}const hr={test:PC,parse:Mg,createTransformer:Lg,getAnimatableNone:OC};function to(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 $C({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=to(c,o,t+1/3),i=to(c,o,t),l=to(c,o,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function sl(t,s){return a=>a>0?s:t}const ns=(t,s,a)=>t+(s-t)*a,so=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},UC=[Bo,Mr,an],BC=t=>UC.find(s=>s.test(t));function Gu(t){const s=BC(t);if(!s)return!1;let a=s.parse(t);return s===an&&(a=$C(a)),a}const Wu=(t,s)=>{const a=Gu(t),r=Gu(s);if(!a||!r)return sl(t,s);const n={...a};return i=>(n.red=so(a.red,r.red,i),n.green=so(a.green,r.green,i),n.blue=so(a.blue,r.blue,i),n.alpha=ns(a.alpha,r.alpha,i),Mr.transform(n))},Vo=new Set(["none","hidden"]);function VC(t,s){return Vo.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function zC(t,s){return a=>ns(t,s,a)}function sd(t){return typeof t=="number"?zC:typeof t=="string"?qc(t)?sl:gs.test(t)?Wu:WC:Array.isArray(t)?Og:typeof t=="object"?gs.test(t)?Wu:HC:sl}function Og(t,s){const a=[...t],r=a.length,n=t.map((i,l)=>sd(i)(i,s[l]));return i=>{for(let l=0;l<r;l++)a[l]=n[l](i);return a}}function HC(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=sd(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function GC(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 WC=(t,s)=>{const a=hr.createTransformer(s),r=ai(t),n=ai(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?Vo.has(t)&&!n.values.length||Vo.has(s)&&!r.values.length?VC(t,s):pi(Og(GC(r,n),n.values),a):sl(t,s)};function $g(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?ns(t,s,a):sd(t)(t,s)}const YC=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>es.update(s,a),stop:()=>xr(s),now:()=>Is.isProcessing?Is.timestamp:sa.now()}},Ug=(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)})`},al=2e4;function ad(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<al;)s+=a,r=t.next(s);return s>=al?1/0:s}function QC(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(ad(r),al);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:fa(n)}}const KC=5;function Bg(t,s,a){const r=Math.max(s-KC,0);return yg(a-t(r),s-r)}const ls={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},ao=.001;function XC({duration:t=ls.duration,bounce:s=ls.bounce,velocity:a=ls.velocity,mass:r=ls.mass}){let n,i,l=1-s;l=Xa(ls.minDamping,ls.maxDamping,l),t=Xa(ls.minDuration,ls.maxDuration,fa(t)),l<1?(n=d=>{const m=d*l,p=m*t,u=m-a,h=zo(d,l),g=Math.exp(-p);return ao-u/h*g},i=d=>{const p=d*l*t,u=p*a+a,h=Math.pow(l,2)*Math.pow(d,2)*t,g=Math.exp(-p),f=zo(Math.pow(d,2),l);return(-n(d)+ao>0?-1:1)*((u-h)*g)/f}):(n=d=>{const m=Math.exp(-d*t),p=(d-a)*t+1;return-ao+m*p},i=d=>{const m=Math.exp(-d*t),p=(a-d)*(t*t);return m*p});const o=5/t,c=JC(n,i,o);if(t=Ma(t),isNaN(c))return{stiffness:ls.stiffness,damping:ls.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:t}}}const ZC=12;function JC(t,s,a){let r=a;for(let n=1;n<ZC;n++)r=r-t(r)/s(r);return r}function zo(t,s){return t*Math.sqrt(1-s*s)}const qC=["duration","bounce"],e2=["stiffness","damping","mass"];function Yu(t,s){return s.some(a=>t[a]!==void 0)}function t2(t){let s={velocity:ls.velocity,stiffness:ls.stiffness,damping:ls.damping,mass:ls.mass,isResolvedFromDuration:!1,...t};if(!Yu(t,e2)&&Yu(t,qC))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*Xa(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:ls.mass,stiffness:n,damping:i}}else{const a=XC(t);s={...s,...a,mass:ls.mass},s.isResolvedFromDuration=!0}return s}function rl(t=ls.visualDuration,s=ls.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:u,isResolvedFromDuration:h}=t2({...a,velocity:-fa(a.velocity||0)}),g=u||0,f=d/(2*Math.sqrt(c*m)),b=l-i,j=fa(Math.sqrt(c/m)),y=Math.abs(b)<5;r||(r=y?ls.restSpeed.granular:ls.restSpeed.default),n||(n=y?ls.restDelta.granular:ls.restDelta.default);let N;if(f<1){const A=zo(j,f);N=w=>{const I=Math.exp(-f*j*w);return l-I*((g+f*j*b)/A*Math.sin(A*w)+b*Math.cos(A*w))}}else if(f===1)N=A=>l-Math.exp(-j*A)*(b+(g+j*b)*A);else{const A=j*Math.sqrt(f*f-1);N=w=>{const I=Math.exp(-f*j*w),D=Math.min(A*w,300);return l-I*((g+f*j*b)*Math.sinh(D)+A*b*Math.cosh(D))/A}}const S={calculatedDuration:h&&p||null,next:A=>{const w=N(A);if(h)o.done=A>=p;else{let I=A===0?g:0;f<1&&(I=A===0?Ma(g):Bg(N,A,w));const D=Math.abs(I)<=r,T=Math.abs(l-w)<=n;o.done=D&&T}return o.value=o.done?l:w,o},toString:()=>{const A=Math.min(ad(S),al),w=Ug(I=>S.next(A*I).value,A,30);return A+"ms "+w},toTransition:()=>{}};return S}rl.applyToOptions=t=>{const s=QC(t,100,rl);return t.ease=s.ease,t.duration=Ma(s.duration),t.type="keyframes",t};function Ho({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],u={done:!1,value:p},h=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),N=D=>j+y(D),S=D=>{const T=y(D),v=N(D);u.done=Math.abs(T)<=d,u.value=u.done?j:v};let A,w;const I=D=>{h(u.value)&&(A=D,w=rl({keyframes:[u.value,g(u.value)],velocity:Bg(N,D,u.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return I(0),{calculatedDuration:null,next:D=>{let T=!1;return!w&&A===void 0&&(T=!0,S(D),I(D)),A!==void 0&&D>=A?w.next(D-A):(!T&&S(D),u)}}}function s2(t,s,a){const r=[],n=a||Za.mix||$g,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]||ja:s;o=pi(c,o)}r.push(o)}return r}function a2(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(Yc(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=s2(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 u=ti(t[p],t[p+1],m);return o[p](u)};return a?m=>d(Xa(t[0],t[i-1],m)):d}function r2(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=ti(0,s,r);t.push(ns(a,1,n))}}function n2(t){const s=[0];return r2(s,t.length-1),s}function i2(t,s){return t.map(a=>a*s)}function l2(t,s){return t.map(()=>s||Dg).splice(0,t.length-1)}function Yn({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=bC(r)?r.map(Vu):Vu(r),i={done:!1,value:s[0]},l=i2(a&&a.length===s.length?a:n2(s),t),o=a2(l,s,{ease:Array.isArray(n)?n:l2(s,n)});return{calculatedDuration:t,next:c=>(i.value=o(c),i.done=c>=t,i)}}const o2=t=>t!==null;function rd(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(o2),o=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const c2={decay:Ho,inertia:Ho,tween:Yn,keyframes:Yn,spring:rl};function Vg(t){typeof t.type=="string"&&(t.type=c2[t.type])}class nd{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 d2=t=>t/100;class id extends nd{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!==sa.now()&&this.tick(sa.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;Vg(s);const{type:a=Yn,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:l=0}=s;let{keyframes:o}=s;const c=a||Yn;c!==Yn&&typeof o[0]!="number"&&(this.mixKeyframes=pi(d2,$g(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=ad(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:u,repeatDelay:h,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 N=this.currentTime,S=r;if(p){const D=Math.min(this.currentTime,n)/o;let T=Math.floor(D),v=D%1;!v&&D>=1&&(v=1),v===1&&T--,T=Math.min(T,p+1),!!(T%2)&&(u==="reverse"?(v=1-v,h&&(v-=h/o)):u==="mirror"&&(S=l)),N=Xa(0,1,v)*o}const A=y?{done:!1,value:m[0]}:S.next(N);i&&(A.value=i(A.value));let{done:w}=A;!y&&c!==null&&(w=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const I=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&w);return I&&g!==Ho&&(A.value=rd(m,this.options,b,this.speed)),f&&f(A.value),I&&this.finish(),A}then(s,a){return this.finished.then(s,a)}get duration(){return fa(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+fa(s)}get time(){return fa(this.currentTime)}set time(s){var a;s=Ma(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(sa.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=fa(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=YC,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(sa.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 m2(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const Lr=t=>t*180/Math.PI,Go=t=>{const s=Lr(Math.atan2(t[1],t[0]));return Wo(s)},u2={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=>Lr(Math.atan(t[1])),skewY:t=>Lr(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Wo=t=>(t=t%360,t<0&&(t+=360),t),Qu=Go,Ku=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Xu=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),x2={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ku,scaleY:Xu,scale:t=>(Ku(t)+Xu(t))/2,rotateX:t=>Wo(Lr(Math.atan2(t[6],t[5]))),rotateY:t=>Wo(Lr(Math.atan2(-t[2],t[0]))),rotateZ:Qu,rotate:Qu,skewX:t=>Lr(Math.atan(t[4])),skewY:t=>Lr(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Yo(t){return t.includes("scale")?1:0}function Qo(t,s){if(!t||t==="none")return Yo(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=x2,n=a;else{const o=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=u2,n=o}if(!n)return Yo(s);const i=r[s],l=n[1].split(",").map(p2);return typeof i=="function"?i(l):l[i]}const h2=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return Qo(a,s)};function p2(t){return parseFloat(t.trim())}const Sn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],An=new Set(Sn),Zu=t=>t===Cn||t===ot,g2=new Set(["x","y","z"]),f2=Sn.filter(t=>!g2.has(t));function b2(t){const s=[];return f2.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const Or={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})=>Qo(s,"x"),y:(t,{transform:s})=>Qo(s,"y")};Or.translateX=Or.x;Or.translateY=Or.y;const $r=new Set;let Ko=!1,Xo=!1,Zo=!1;function zg(){if(Xo){const t=Array.from($r).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=b2(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)})}Xo=!1,Ko=!1,$r.forEach(t=>t.complete(Zo)),$r.clear()}function Hg(){$r.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Xo=!0)})}function j2(){Zo=!0,Hg(),zg(),Zo=!1}class ld{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?($r.add(this),Ko||(Ko=!0,es.read(Hg),es.resolveKeyframes(zg))):(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])}m2(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),$r.delete(this)}cancel(){this.state==="scheduled"&&($r.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const y2=t=>t.startsWith("--");function v2(t,s,a){y2(s)?t.style.setProperty(s,a):t.style[s]=a}const N2=Qc(()=>window.ScrollTimeline!==void 0),w2={};function C2(t,s){const a=Qc(t);return()=>w2[s]??a()}const Gg=C2(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),zn=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,Ju={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:zn([0,.65,.55,1]),circOut:zn([.55,0,1,.45]),backIn:zn([.31,.01,.66,-.59]),backOut:zn([.33,1.53,.69,.99])};function Wg(t,s){if(t)return typeof t=="function"?Gg()?Ug(t,s):"ease-out":Rg(t)?zn(t):Array.isArray(t)?t.map(a=>Wg(a,s)||Ju.easeOut):Ju[t]}function S2(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=Wg(o,n);Array.isArray(p)&&(m.easing=p);const u={delay:r,duration:n,easing:Array.isArray(p)?"linear":p,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(u.pseudoElement=d),t.animate(m,u)}function Yg(t){return typeof t=="function"&&"applyToOptions"in t}function A2({type:t,...s}){return Yg(t)&&Gg()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class T2 extends nd{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,Yc(typeof s.type!="string");const d=A2(s);this.animation=S2(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=rd(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(m):v2(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 fa(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+fa(s)}get time(){return fa(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=Ma(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&&N2()?(this.animation.timeline=s,ja):a(this)}}const Qg={anticipate:Ag,backInOut:Sg,circInOut:kg};function k2(t){return t in Qg}function D2(t){typeof t.ease=="string"&&k2(t.ease)&&(t.ease=Qg[t.ease])}const qu=10;class R2 extends T2{constructor(s){D2(s),Vg(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 id({...l,autoplay:!1}),c=Ma(this.finishedTime??this.time);a.setWithVelocity(o.sample(c-qu).value,o.sample(c).value,qu),o.stop()}}const ex=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(hr.test(t)||t==="0")&&!t.startsWith("url("));function F2(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 I2(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=ex(n,s),o=ex(i,s);return!l||!o?!1:F2(t)||(a==="spring"||Yg(a))&&r}function Jo(t){t.duration=0,t.type="keyframes"}const P2=new Set(["opacity","clipPath","filter","transform"]),E2=Qc(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function _2(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 E2()&&a&&P2.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&l!=="inertia"}const M2=40;class L2 extends nd{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=sa.now();const u={autoplay:s,delay:a,type:r,repeat:n,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:m,...p},h=(m==null?void 0:m.KeyframeResolver)||ld;this.keyframeResolver=new h(o,(f,b,j)=>this.onKeyframesResolved(f,b,u,!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=sa.now(),I2(s,i,l,o)||((Za.instantAnimations||!c)&&(m==null||m(rd(s,r,a))),s[0]=s[s.length-1],Jo(r),r.repeat=0);const u={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>M2?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},h=!d&&_2(u)?new R2({...u,element:u.motionValue.owner.current}):new id(u);h.finished.then(()=>this.notifyFinished()).catch(ja),this.pendingTimeline&&(this.stopTimeline=h.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=h}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(),j2()),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 O2=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function $2(t){const s=O2.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Kg(t,s,a=1){const[r,n]=$2(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const l=i.trim();return fg(l)?parseFloat(l):l}return qc(n)?Kg(n,s,a+1):n}function od(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const Xg=new Set(["width","height","top","left","right","bottom",...Sn]),U2={test:t=>t==="auto",parse:t=>t},Zg=t=>s=>s.test(t),Jg=[Cn,ot,La,lr,FC,RC,U2],tx=t=>Jg.find(Zg(t));function B2(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||jg(t):!0}const V2=new Set(["brightness","contrast","saturate","opacity"]);function z2(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(ed)||[];if(!r)return t;const n=a.replace(r,"");let i=V2.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const H2=/\b([a-z-]*)\(.*?\)/gu,qo={...hr,getAnimatableNone:t=>{const s=t.match(H2);return s?s.map(z2).join(" "):t}},sx={...Cn,transform:Math.round},G2={rotate:lr,rotateX:lr,rotateY:lr,rotateZ:lr,scale:Ti,scaleX:Ti,scaleY:Ti,scaleZ:Ti,skew:lr,skewX:lr,skewY:lr,distance:ot,translateX:ot,translateY:ot,translateZ:ot,x:ot,y:ot,z:ot,perspective:ot,transformPerspective:ot,opacity:si,originX:zu,originY:zu,originZ:ot},cd={borderWidth:ot,borderTopWidth:ot,borderRightWidth:ot,borderBottomWidth:ot,borderLeftWidth:ot,borderRadius:ot,radius:ot,borderTopLeftRadius:ot,borderTopRightRadius:ot,borderBottomRightRadius:ot,borderBottomLeftRadius:ot,width:ot,maxWidth:ot,height:ot,maxHeight:ot,top:ot,right:ot,bottom:ot,left:ot,padding:ot,paddingTop:ot,paddingRight:ot,paddingBottom:ot,paddingLeft:ot,margin:ot,marginTop:ot,marginRight:ot,marginBottom:ot,marginLeft:ot,backgroundPositionX:ot,backgroundPositionY:ot,...G2,zIndex:sx,fillOpacity:si,strokeOpacity:si,numOctaves:sx},W2={...cd,color:gs,backgroundColor:gs,outlineColor:gs,fill:gs,stroke:gs,borderColor:gs,borderTopColor:gs,borderRightColor:gs,borderBottomColor:gs,borderLeftColor:gs,filter:qo,WebkitFilter:qo},qg=t=>W2[t];function e0(t,s){let a=qg(t);return a!==qo&&(a=hr),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const Y2=new Set(["auto","none","0"]);function Q2(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!Y2.has(i)&&ai(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=e0(a,n)}class K2 extends ld{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(),qc(d))){const m=Kg(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!Xg.has(r)||s.length!==2)return;const[n,i]=s,l=tx(n),o=tx(i);if(l!==o)if(Zu(l)&&Zu(o))for(let c=0;c<s.length;c++){const d=s[c];typeof d=="string"&&(s[c]=parseFloat(d))}else Or[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||B2(s[n]))&&r.push(n);r.length&&Q2(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=Or[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]=Or[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 X2(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 t0=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function s0(t){return bg(t)&&"offsetHeight"in t}const ax=30,Z2=t=>!isNaN(parseFloat(t));class J2{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=sa.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=sa.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=Z2(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 Kc);const r=this.events[s].add(a);return s==="change"?()=>{r(),es.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=sa.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>ax)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,ax);return yg(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 gn(t,s){return new J2(t,s)}const{schedule:dd}=Fg(queueMicrotask,!1),ka={x:!1,y:!1};function a0(){return ka.x||ka.y}function q2(t){return t==="x"||t==="y"?ka[t]?null:(ka[t]=!0,()=>{ka[t]=!1}):ka.x||ka.y?null:(ka.x=ka.y=!0,()=>{ka.x=ka.y=!1})}function r0(t,s){const a=X2(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function rx(t){return!(t.pointerType==="touch"||a0())}function eS(t,s,a={}){const[r,n,i]=r0(t,a),l=o=>{if(!rx(o))return;const{target:c}=o,d=s(c,o);if(typeof d!="function"||!c)return;const m=p=>{rx(p)&&(d(p),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(o=>{o.addEventListener("pointerenter",l,n)}),i}const n0=(t,s)=>s?t===s?!0:n0(t,s.parentElement):!1,md=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,tS=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function sS(t){return tS.has(t.tagName)||t.tabIndex!==-1}const zi=new WeakSet;function nx(t){return s=>{s.key==="Enter"&&t(s)}}function ro(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const aS=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=nx(()=>{if(zi.has(a))return;ro(a,"down");const n=nx(()=>{ro(a,"up")}),i=()=>ro(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 ix(t){return md(t)&&!a0()}function rS(t,s,a={}){const[r,n,i]=r0(t,a),l=o=>{const c=o.currentTarget;if(!ix(o))return;zi.add(c);const d=s(c,o),m=(h,g)=>{window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",u),zi.has(c)&&zi.delete(c),ix(h)&&typeof d=="function"&&d(h,{success:g})},p=h=>{m(h,c===window||c===document||a.useGlobalTarget||n0(c,h.target))},u=h=>{m(h,!1)};window.addEventListener("pointerup",p,n),window.addEventListener("pointercancel",u,n)};return r.forEach(o=>{(a.useGlobalTarget?window:o).addEventListener("pointerdown",l,n),s0(o)&&(o.addEventListener("focus",d=>aS(d,n)),!sS(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function i0(t){return bg(t)&&"ownerSVGElement"in t}function nS(t){return i0(t)&&t.tagName==="svg"}const Bs=t=>!!(t&&t.getVelocity),iS=[...Jg,gs,hr],lS=t=>iS.find(Zg(t)),ud=x.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function lx(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function oS(...t){return s=>{let a=!1;const r=t.map(n=>{const i=lx(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():lx(t[n],null)}}}}function cS(...t){return x.useCallback(oS(...t),t)}class dS extends x.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=s0(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 mS({children:t,isPresent:s,anchorX:a,root:r}){const n=x.useId(),i=x.useRef(null),l=x.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:o}=x.useContext(ud),c=cS(i,t==null?void 0:t.ref);return x.useInsertionEffect(()=>{const{width:d,height:m,top:p,left:u,right:h}=l.current;if(s||!i.current||!d||!m)return;const g=a==="left"?`left: ${u}`:`right: ${h}`;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(dS,{isPresent:s,childRef:i,sizeRef:l,children:x.cloneElement(t,{ref:c})})}const uS=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=zc(xS),m=x.useId();let p=!0,u=x.useMemo(()=>(p=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:h=>{d.set(h,!0);for(const g of d.values())if(!g)return;r&&r()},register:h=>(d.set(h,!1),()=>d.delete(h))}),[a,d,r]);return i&&p&&(u={...u}),x.useMemo(()=>{d.forEach((h,g)=>d.set(g,!1))},[a]),x.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(mS,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(Dl.Provider,{value:u,children:t})};function xS(){return new Map}function l0(t=!0){const s=x.useContext(Dl);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=x.useId();x.useEffect(()=>{if(t)return n(i)},[t]);const l=x.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const ki=t=>t.key||"";function ox(t){const s=[];return x.Children.forEach(t,a=>{x.isValidElement(a)&&s.push(a)}),s}const Rl=({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]=l0(l),p=x.useMemo(()=>ox(t),[t]),u=l&&!d?[]:p.map(ki),h=x.useRef(!0),g=x.useRef(p),f=zc(()=>new Map),[b,j]=x.useState(p),[y,N]=x.useState(p);gg(()=>{h.current=!1,g.current=p;for(let w=0;w<y.length;w++){const I=ki(y[w]);u.includes(I)?f.delete(I):f.get(I)!==!0&&f.set(I,!1)}},[y,u.length,u.join("-")]);const S=[];if(p!==b){let w=[...p];for(let I=0;I<y.length;I++){const D=y[I],T=ki(D);u.includes(T)||(w.splice(I,0,D),S.push(D))}return i==="wait"&&S.length&&(w=S),N(ox(w)),j(p),null}const{forceRender:A}=x.useContext(Vc);return e.jsx(e.Fragment,{children:y.map(w=>{const I=ki(w),D=l&&!d?!1:p===y||u.includes(I),T=()=>{if(f.has(I))f.set(I,!0);else return;let v=!0;f.forEach(M=>{M||(v=!1)}),v&&(A==null||A(),N(g.current),l&&(m==null||m()),r&&r())};return e.jsx(uS,{isPresent:D,initial:!h.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:D?void 0:T,anchorX:o,children:w},I)})})},o0=x.createContext({strict:!1}),cx={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"]},fn={};for(const t in cx)fn[t]={isEnabled:s=>cx[t].some(a=>!!s[a])};function hS(t){for(const s in t)fn[s]={...fn[s],...t[s]}}const pS=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 nl(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||pS.has(t)}let c0=t=>!nl(t);function gS(t){typeof t=="function"&&(c0=s=>s.startsWith("on")?!nl(s):t(s))}try{gS(require("@emotion/is-prop-valid").default)}catch{}function fS(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(c0(n)||a===!0&&nl(n)||!s&&!nl(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Fl=x.createContext({});function Il(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function ri(t){return typeof t=="string"||Array.isArray(t)}const xd=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],hd=["initial",...xd];function Pl(t){return Il(t.animate)||hd.some(s=>ri(t[s]))}function d0(t){return!!(Pl(t)||t.variants)}function bS(t,s){if(Pl(t)){const{initial:a,animate:r}=t;return{initial:a===!1||ri(a)?a:void 0,animate:ri(r)?r:void 0}}return t.inherit!==!1?s:{}}function jS(t){const{initial:s,animate:a}=bS(t,x.useContext(Fl));return x.useMemo(()=>({initial:s,animate:a}),[dx(s),dx(a)])}function dx(t){return Array.isArray(t)?t.join(" "):t}const ni={};function yS(t){for(const s in t)ni[s]=t[s],Jc(s)&&(ni[s].isCSSVariable=!0)}function m0(t,{layout:s,layoutId:a}){return An.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!ni[t]||t==="opacity")}const vS={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},NS=Sn.length;function wS(t,s,a){let r="",n=!0;for(let i=0;i<NS;i++){const l=Sn[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=t0(o,cd[l]);if(!c){n=!1;const m=vS[l]||l;r+=`${m}(${d}) `}a&&(s[l]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function pd(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(An.has(c)){l=!0;continue}else if(Jc(c)){n[c]=d;continue}else{const m=t0(d,cd[c]);c.startsWith("origin")?(o=!0,i[c]=m):r[c]=m}}if(s.transform||(l||a?r.transform=wS(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 gd=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function u0(t,s,a){for(const r in s)!Bs(s[r])&&!m0(r,a)&&(t[r]=s[r])}function CS({transformTemplate:t},s){return x.useMemo(()=>{const a=gd();return pd(a,s,t),Object.assign({},a.vars,a.style)},[s])}function SS(t,s){const a=t.style||{},r={};return u0(r,a,t),Object.assign(r,CS(t,s)),r}function AS(t,s){const a={},r=SS(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 TS={offset:"stroke-dashoffset",array:"stroke-dasharray"},kS={offset:"strokeDashoffset",array:"strokeDasharray"};function DS(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?TS:kS;t[i.offset]=ot.transform(-r);const l=ot.transform(s),o=ot.transform(a);t[i.array]=`${l} ${o}`}function x0(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(pd(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:p,style:u}=t;p.transform&&(u.transform=p.transform,delete p.transform),(u.transform||p.transformOrigin)&&(u.transformOrigin=p.transformOrigin??"50% 50%",delete p.transformOrigin),u.transform&&(u.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&&DS(p,n,i,l,!1)}const h0=()=>({...gd(),attrs:{}}),p0=t=>typeof t=="string"&&t.toLowerCase()==="svg";function RS(t,s,a,r){const n=x.useMemo(()=>{const i=h0();return x0(i,s,p0(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};u0(i,t.style,t),n.style={...i,...n.style}}return n}const FS=["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 fd(t){return typeof t!="string"||t.includes("-")?!1:!!(FS.indexOf(t)>-1||/[A-Z]/u.test(t))}function IS(t,s,a,{latestValues:r},n,i=!1){const o=(fd(t)?RS:AS)(s,r,n,t),c=fS(s,typeof t=="string",i),d=t!==x.Fragment?{...c,...o,ref:a}:{},{children:m}=s,p=x.useMemo(()=>Bs(m)?m.get():m,[m]);return x.createElement(t,{...d,children:p})}function mx(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function bd(t,s,a,r){if(typeof s=="function"){const[n,i]=mx(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]=mx(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Hi(t){return Bs(t)?t.get():t}function PS({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:ES(a,r,n,t),renderState:s()}}function ES(t,s,a,r){const n={},i=r(t,{});for(const u in i)n[u]=Hi(i[u]);let{initial:l,animate:o}=t;const c=Pl(t),d=d0(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"&&!Il(p)){const u=Array.isArray(p)?p:[p];for(let h=0;h<u.length;h++){const g=bd(t,u[h]);if(g){const{transitionEnd:f,transition:b,...j}=g;for(const y in j){let N=j[y];if(Array.isArray(N)){const S=m?N.length-1:0;N=N[S]}N!==null&&(n[y]=N)}for(const y in f)n[y]=f[y]}}}return n}const g0=t=>(s,a)=>{const r=x.useContext(Fl),n=x.useContext(Dl),i=()=>PS(t,s,r,n);return a?i():zc(i)};function jd(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(Bs(r[l])||s.style&&Bs(s.style[l])||m0(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const _S=g0({scrapeMotionValuesFromProps:jd,createRenderState:gd});function f0(t,s,a){const r=jd(t,s,a);for(const n in t)if(Bs(t[n])||Bs(s[n])){const i=Sn.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const MS=g0({scrapeMotionValuesFromProps:f0,createRenderState:h0}),LS=Symbol.for("motionComponentSymbol");function rn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function OS(t,s,a){return x.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):rn(a)&&(a.current=r))},[s])}const yd=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),$S="framerAppearId",b0="data-"+yd($S),j0=x.createContext({});function US(t,s,a,r,n){var f,b;const{visualElement:i}=x.useContext(Fl),l=x.useContext(o0),o=x.useContext(Dl),c=x.useContext(ud).reducedMotion,d=x.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=x.useContext(j0);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&BS(d.current,a,n,p);const u=x.useRef(!1);x.useInsertionEffect(()=>{m&&u.current&&m.update(a,o)});const h=a[b0],g=x.useRef(!!h&&!((f=window.MotionHandoffIsComplete)!=null&&f.call(window,h))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,h)));return gg(()=>{m&&(u.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),x.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var j;(j=window.MotionHandoffMarkAsComplete)==null||j.call(window,h)}),g.current=!1),m.enteringChildren=void 0)}),m}function BS(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:y0(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&rn(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function y0(t){if(t)return t.options.allowProjection!==!1?t.projection:y0(t.parent)}function no(t,{forwardMotionProps:s=!1}={},a,r){a&&hS(a);const n=fd(t)?MS:_S;function i(o,c){let d;const m={...x.useContext(ud),...o,layoutId:VS(o)},{isStatic:p}=m,u=jS(o),h=n(o,p);if(!p&&Hc){zS();const g=HS(m);d=g.MeasureLayout,u.visualElement=US(t,h,m,r,g.ProjectionNode)}return e.jsxs(Fl.Provider,{value:u,children:[d&&u.visualElement?e.jsx(d,{visualElement:u.visualElement,...m}):null,IS(t,o,OS(h,u.visualElement,c),h,p,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=x.forwardRef(i);return l[LS]=t,l}function VS({layoutId:t}){const s=x.useContext(Vc).id;return s&&t!==void 0?s+"-"+t:t}function zS(t,s){x.useContext(o0).strict}function HS(t){const{drag:s,layout:a}=fn;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 GS(t,s){if(typeof Proxy>"u")return no;const a=new Map,r=(i,l)=>no(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,no(l,void 0,t,s)),a.get(l))})}function v0({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function WS({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function YS(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 io(t){return t===void 0||t===1}function ec({scale:t,scaleX:s,scaleY:a}){return!io(t)||!io(s)||!io(a)}function Fr(t){return ec(t)||N0(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function N0(t){return ux(t.x)||ux(t.y)}function ux(t){return t&&t!=="0%"}function il(t,s,a){const r=t-a,n=s*r;return a+n}function xx(t,s,a,r,n){return n!==void 0&&(t=il(t,n,r)),il(t,a,r)+s}function tc(t,s=0,a=1,r,n){t.min=xx(t.min,s,a,r,n),t.max=xx(t.max,s,a,r,n)}function w0(t,{x:s,y:a}){tc(t.x,s.translate,s.scale,s.originPoint),tc(t.y,a.translate,a.scale,a.originPoint)}const hx=.999999999999,px=1.0000000000001;function QS(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&&ln(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),l&&(s.x*=l.x.scale,s.y*=l.y.scale,w0(t,l)),r&&Fr(i.latestValues)&&ln(t,i.latestValues))}s.x<px&&s.x>hx&&(s.x=1),s.y<px&&s.y>hx&&(s.y=1)}function nn(t,s){t.min=t.min+s,t.max=t.max+s}function gx(t,s,a,r,n=.5){const i=ns(t.min,t.max,n);tc(t,s,a,i,r)}function ln(t,s){gx(t.x,s.x,s.scaleX,s.scale,s.originX),gx(t.y,s.y,s.scaleY,s.scale,s.originY)}function C0(t,s){return v0(YS(t.getBoundingClientRect(),s))}function KS(t,s,a){const r=C0(t,a),{scroll:n}=s;return n&&(nn(r.x,n.offset.x),nn(r.y,n.offset.y)),r}const fx=()=>({translate:0,scale:1,origin:0,originPoint:0}),on=()=>({x:fx(),y:fx()}),bx=()=>({min:0,max:0}),hs=()=>({x:bx(),y:bx()}),sc={current:null},S0={current:!1};function XS(){if(S0.current=!0,!!Hc)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>sc.current=t.matches;t.addEventListener("change",s),s()}else sc.current=!1}const ZS=new WeakMap;function JS(t,s,a){for(const r in s){const n=s[r],i=a[r];if(Bs(n))t.addValue(r,n);else if(Bs(i))t.addValue(r,gn(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,gn(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const jx=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class qS{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=ld,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 u=sa.now();this.renderScheduledAt<u&&(this.renderScheduledAt=u,es.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=Pl(a),this.isVariantNode=d0(a),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(s&&s.current);const{willChange:m,...p}=this.scrapeMotionValuesFromProps(a,{},this);for(const u in p){const h=p[u];c[u]!==void 0&&Bs(h)&&h.set(c[u])}}mount(s){var a;this.current=s,ZS.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)),S0.current||XS(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:sc.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),xr(this.notifyUpdate),xr(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=An.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&es.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 fn){const a=fn[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):hs()}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<jx.length;r++){const n=jx[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=JS(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=gn(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"&&(fg(r)||jg(r))?r=parseFloat(r):!lS(r)&&hr.test(a)&&(r=e0(s,a)),this.setBaseTarget(s,Bs(r)?r.get():r)),Bs(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=bd(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&&!Bs(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 Kc),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){dd.render(this.render)}}class A0 extends qS{constructor(){super(...arguments),this.KeyframeResolver=K2}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;Bs(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function T0(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 eA(t){return window.getComputedStyle(t)}class tA extends A0{constructor(){super(...arguments),this.type="html",this.renderInstance=T0}readValueFromInstance(s,a){var r;if(An.has(a))return(r=this.projection)!=null&&r.isProjecting?Yo(a):h2(s,a);{const n=eA(s),i=(Jc(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return C0(s,a)}build(s,a,r){pd(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return jd(s,a,r)}}const k0=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 sA(t,s,a,r){T0(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(k0.has(n)?n:yd(n),s.attrs[n])}class aA extends A0{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=hs}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(An.has(a)){const r=qg(a);return r&&r.default||0}return a=k0.has(a)?a:yd(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return f0(s,a,r)}build(s,a,r){x0(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){sA(s,a,r,n)}mount(s){this.isSVGTag=p0(s.tagName),super.mount(s)}}const rA=(t,s)=>fd(t)?new aA(s):new tA(s,{allowProjection:t!==x.Fragment});function hn(t,s,a){const r=t.getProps();return bd(r,s,a!==void 0?a:r.custom,t)}const ac=t=>Array.isArray(t);function nA(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,gn(a))}function iA(t){return ac(t)?t[t.length-1]||0:t}function lA(t,s){const a=hn(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=iA(i[l]);nA(t,l,o)}}function oA(t){return!!(Bs(t)&&t.add)}function rc(t,s){const a=t.getValue("willChange");if(oA(a))return a.add(s);if(!a&&Za.WillChange){const r=new Za.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function D0(t){return t.props[b0]}const cA=t=>t!==null;function dA(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(cA),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const mA={type:"spring",stiffness:500,damping:25,restSpeed:10},uA=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),xA={type:"keyframes",duration:.8},hA={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},pA=(t,{keyframes:s})=>s.length>2?xA:An.has(t)?t.startsWith("scale")?uA(s[1]):mA:hA;function gA({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 vd=(t,s,a,r={},n,i)=>l=>{const o=od(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Ma(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:u=>{s.set(u),o.onUpdate&&o.onUpdate(u)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};gA(o)||Object.assign(m,pA(t,m)),m.duration&&(m.duration=Ma(m.duration)),m.repeatDelay&&(m.repeatDelay=Ma(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let p=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Jo(m),m.delay===0&&(p=!0)),(Za.instantAnimations||Za.skipAnimations)&&(p=!0,Jo(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,p&&!i&&s.get()!==void 0){const u=dA(m.keyframes,o);if(u!==void 0){es.update(()=>{m.onUpdate(u),m.onComplete()});return}}return o.isSync?new id(m):new L2(m)};function fA({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function R0(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),u=o[m];if(u===void 0||d&&fA(d,m))continue;const h={delay:a,...od(i||{},m)},g=p.get();if(g!==void 0&&!p.isAnimating&&!Array.isArray(u)&&u===g&&!h.velocity)continue;let f=!1;if(window.MotionHandoffAnimation){const j=D0(t);if(j){const y=window.MotionHandoffAnimation(j,m,es);y!==null&&(h.startTime=y,f=!0)}}rc(t,m),p.start(vd(m,p,u,t.shouldReduceMotion&&Xg.has(m)?{type:!1}:h,t,f));const b=p.animation;b&&c.push(b)}return l&&Promise.all(c).then(()=>{es.update(()=>{l&&lA(t,l)})}),c}function F0(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 nc(t,s,a={}){var c;const r=hn(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(R0(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:p,staggerDirection:u}=n;return bA(t,s,d,m,p,u,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 bA(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(nc(c,s,{...l,delay:a+(typeof r=="function"?0:r)+F0(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function jA(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>nc(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=nc(t,s,a);else{const n=typeof s=="function"?hn(t,s,a.custom):s;r=Promise.all(R0(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function I0(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 yA=hd.length;function P0(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?P0(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<yA;a++){const r=hd[a],n=t.props[r];(ri(n)||n===!1)&&(s[r]=n)}return s}const vA=[...xd].reverse(),NA=xd.length;function wA(t){return s=>Promise.all(s.map(({animation:a,options:r})=>jA(t,a,r)))}function CA(t){let s=wA(t),a=yx(),r=!0;const n=c=>(d,m)=>{var u;const p=hn(t,m,c==="exit"?(u=t.presenceContext)==null?void 0:u.custom:void 0);if(p){const{transition:h,transitionEnd:g,...f}=p;d={...d,...f,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=P0(t.parent)||{},p=[],u=new Set;let h={},g=1/0;for(let b=0;b<NA;b++){const j=vA[b],y=a[j],N=d[j]!==void 0?d[j]:m[j],S=ri(N),A=j===c?y.isActive:null;A===!1&&(g=b);let w=N===m[j]&&N!==d[j]&&S;if(w&&r&&t.manuallyAnimateOnMount&&(w=!1),y.protectedKeys={...h},!y.isActive&&A===null||!N&&!y.prevProp||Il(N)||typeof N=="boolean")continue;const I=SA(y.prevProp,N);let D=I||j===c&&y.isActive&&!w&&S||b>g&&S,T=!1;const v=Array.isArray(N)?N:[N];let M=v.reduce(n(j),{});A===!1&&(M={});const{prevResolvedValues:P={}}=y,B={...P,...M},k=R=>{D=!0,u.has(R)&&(T=!0,u.delete(R)),y.needsAnimating[R]=!0;const C=t.getValue(R);C&&(C.liveStyle=!1)};for(const R in B){const C=M[R],G=P[R];if(h.hasOwnProperty(R))continue;let U=!1;ac(C)&&ac(G)?U=!I0(C,G):U=C!==G,U?C!=null?k(R):u.add(R):C!==void 0&&u.has(R)?k(R):y.protectedKeys[R]=!0}y.prevProp=N,y.prevResolvedValues=M,y.isActive&&(h={...h,...M}),r&&t.blockInitialAnimation&&(D=!1);const _=w&&I;D&&(!_||T)&&p.push(...v.map(R=>{const C={type:j};if(typeof R=="string"&&r&&!_&&t.manuallyAnimateOnMount&&t.parent){const{parent:G}=t,U=hn(G,R);if(G.enteringChildren&&U){const{delayChildren:$}=U.transition||{};C.delay=F0(G.enteringChildren,t,$)}}return{animation:R,options:C}}))}if(u.size){const b={};if(typeof d.initial!="boolean"){const j=hn(t,Array.isArray(d.initial)?d.initial[0]:d.initial);j&&j.transition&&(b.transition=j.transition)}u.forEach(j=>{const y=t.getBaseTarget(j),N=t.getValue(j);N&&(N.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(u=>{var h;return(h=u.animationState)==null?void 0:h.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const u in a)a[u].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=yx()}}}function SA(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!I0(s,t):!1}function Tr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function yx(){return{animate:Tr(!0),whileInView:Tr(),whileHover:Tr(),whileTap:Tr(),whileDrag:Tr(),whileFocus:Tr(),exit:Tr()}}class fr{constructor(s){this.isMounted=!1,this.node=s}update(){}}class AA extends fr{constructor(s){super(s),s.animationState||(s.animationState=CA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Il(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 TA=0;class kA extends fr{constructor(){super(...arguments),this.id=TA++}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 DA={animation:{Feature:AA},exit:{Feature:kA}};function ii(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function bi(t){return{point:{x:t.pageX,y:t.pageY}}}const RA=t=>s=>md(s)&&t(s,bi(s));function Qn(t,s,a,r){return ii(t,s,RA(a),r)}const E0=1e-4,FA=1-E0,IA=1+E0,_0=.01,PA=0-_0,EA=0+_0;function Ws(t){return t.max-t.min}function _A(t,s,a){return Math.abs(t-s)<=a}function vx(t,s,a,r=.5){t.origin=r,t.originPoint=ns(s.min,s.max,t.origin),t.scale=Ws(a)/Ws(s),t.translate=ns(a.min,a.max,t.origin)-t.originPoint,(t.scale>=FA&&t.scale<=IA||isNaN(t.scale))&&(t.scale=1),(t.translate>=PA&&t.translate<=EA||isNaN(t.translate))&&(t.translate=0)}function Kn(t,s,a,r){vx(t.x,s.x,a.x,r?r.originX:void 0),vx(t.y,s.y,a.y,r?r.originY:void 0)}function Nx(t,s,a){t.min=a.min+s.min,t.max=t.min+Ws(s)}function MA(t,s,a){Nx(t.x,s.x,a.x),Nx(t.y,s.y,a.y)}function wx(t,s,a){t.min=s.min-a.min,t.max=t.min+Ws(s)}function Xn(t,s,a){wx(t.x,s.x,a.x),wx(t.y,s.y,a.y)}function ga(t){return[t("x"),t("y")]}const M0=({current:t})=>t?t.ownerDocument.defaultView:null,Cx=(t,s)=>Math.abs(t-s);function LA(t,s){const a=Cx(t.x,s.x),r=Cx(t.y,s.y);return Math.sqrt(a**2+r**2)}class L0{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 u=oo(this.lastMoveEventInfo,this.history),h=this.startEvent!==null,g=LA(u.offset,{x:0,y:0})>=this.distanceThreshold;if(!h&&!g)return;const{point:f}=u,{timestamp:b}=Is;this.history.push({...f,timestamp:b});const{onStart:j,onMove:y}=this.handlers;h||(j&&j(this.lastMoveEvent,u),this.startEvent=this.lastMoveEvent),y&&y(this.lastMoveEvent,u)},this.handlePointerMove=(u,h)=>{this.lastMoveEvent=u,this.lastMoveEventInfo=lo(h,this.transformPagePoint),es.update(this.updatePoint,!0)},this.handlePointerUp=(u,h)=>{this.end();const{onEnd:g,onSessionEnd:f,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=oo(u.type==="pointercancel"?this.lastMoveEventInfo:lo(h,this.transformPagePoint),this.history);this.startEvent&&g&&g(u,j),f&&f(u,j)},!md(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=bi(s),c=lo(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=Is;this.history=[{...d,timestamp:m}];const{onSessionStart:p}=a;p&&p(s,oo(c,this.history)),this.removeListeners=pi(Qn(this.contextWindow,"pointermove",this.handlePointerMove),Qn(this.contextWindow,"pointerup",this.handlePointerUp),Qn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),xr(this.updatePoint)}}function lo(t,s){return s?{point:s(t.point)}:t}function Sx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function oo({point:t},s){return{point:t,delta:Sx(t,O0(s)),offset:Sx(t,OA(s)),velocity:$A(s,.1)}}function OA(t){return t[0]}function O0(t){return t[t.length-1]}function $A(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=O0(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>Ma(s)));)a--;if(!r)return{x:0,y:0};const i=fa(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 UA(t,{min:s,max:a},r){return s!==void 0&&t<s?t=r?ns(s,t,r.min):Math.max(t,s):a!==void 0&&t>a&&(t=r?ns(a,t,r.max):Math.min(t,a)),t}function Ax(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 BA(t,{top:s,left:a,bottom:r,right:n}){return{x:Ax(t.x,a,n),y:Ax(t.y,s,r)}}function Tx(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 VA(t,s){return{x:Tx(t.x,s.x),y:Tx(t.y,s.y)}}function zA(t,s){let a=.5;const r=Ws(t),n=Ws(s);return n>r?a=ti(s.min,s.max-r,t.min):r>n&&(a=ti(t.min,t.max-n,s.min)),Xa(0,1,a)}function HA(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 ic=.35;function GA(t=ic){return t===!1?t=0:t===!0&&(t=ic),{x:kx(t,"left","right"),y:kx(t,"top","bottom")}}function kx(t,s,a){return{min:Dx(t,s),max:Dx(t,a)}}function Dx(t,s){return typeof t=="number"?t:t[s]||0}const WA=new WeakMap;class YA{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=hs(),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:u}=this.getProps();u?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(bi(p).point)},l=(p,u)=>{const{drag:h,dragPropagation:g,onDragStart:f}=this.getProps();if(h&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=q2(h),!this.openDragLock))return;this.latestPointerEvent=p,this.latestPanInfo=u,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ga(j=>{let y=this.getAxisMotionValue(j).get()||0;if(La.test(y)){const{projection:N}=this.visualElement;if(N&&N.layout){const S=N.layout.layoutBox[j];S&&(y=Ws(S)*(parseFloat(y)/100))}}this.originPoint[j]=y}),f&&es.postRender(()=>f(p,u)),rc(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},o=(p,u)=>{this.latestPointerEvent=p,this.latestPanInfo=u;const{dragPropagation:h,dragDirectionLock:g,onDirectionLock:f,onDrag:b}=this.getProps();if(!h&&!this.openDragLock)return;const{offset:j}=u;if(g&&this.currentDirection===null){this.currentDirection=QA(j),this.currentDirection!==null&&f&&f(this.currentDirection);return}this.updateAxis("x",u.point,j),this.updateAxis("y",u.point,j),this.visualElement.render(),b&&b(p,u)},c=(p,u)=>{this.latestPointerEvent=p,this.latestPanInfo=u,this.stop(p,u),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>ga(p=>{var u;return this.getAnimationState(p)==="paused"&&((u=this.getAxisMotionValue(p).animation)==null?void 0:u.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new L0(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:M0(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&&es.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=UA(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&&rn(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=BA(r.layoutBox,s):this.constraints=!1,this.elastic=GA(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&ga(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=HA(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!rn(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=KS(r,n.root,this.visualElement.getTransformPagePoint());let l=VA(n.layout.layoutBox,i);if(a){const o=a(WS(l));this.hasMutatedConstraints=!!o,o&&(l=v0(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=ga(m=>{if(!Di(m,a,this.currentDirection))return;let p=c&&c[m]||{};l&&(p={min:0,max:0});const u=n?200:1e6,h=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:u,bounceDamping:h,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 rc(this.visualElement,s),r.start(vd(s,r,0,a,this.visualElement,!1))}stopAnimation(){ga(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){ga(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){ga(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]-ns(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!rn(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};ga(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=zA({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(),ga(l=>{if(!Di(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(ns(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;WA.set(this.visualElement,this);const s=this.visualElement.current,a=Qn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();rn(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()),es.read(r);const l=ii(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(ga(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=ic,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 QA(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class KA extends fr{constructor(s){super(s),this.removeGroupControls=ja,this.removeListeners=ja,this.controls=new YA(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ja}unmount(){this.removeGroupControls(),this.removeListeners()}}const Rx=t=>(s,a)=>{t&&es.postRender(()=>t(s,a))};class XA extends fr{constructor(){super(...arguments),this.removePointerDownListener=ja}onPointerDown(s){this.session=new L0(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:M0(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Rx(s),onStart:Rx(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&es.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=Qn(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 Gi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Fx(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const _n={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(ot.test(t))t=parseFloat(t);else return t;const a=Fx(t,s.target.x),r=Fx(t,s.target.y);return`${a}% ${r}%`}},ZA={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=hr.parse(t);if(n.length>5)return r;const i=hr.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=ns(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 co=!1;class JA extends x.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;yS(qA),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),co&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Gi.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,co=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||es.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),dd.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;co=!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 $0(t){const[s,a]=l0(),r=x.useContext(Vc);return e.jsx(JA,{...t,layoutGroup:r,switchLayoutGroup:x.useContext(j0),isPresent:s,safeToRemove:a})}const qA={borderRadius:{..._n,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:_n,borderTopRightRadius:_n,borderBottomLeftRadius:_n,borderBottomRightRadius:_n,boxShadow:ZA};function eT(t,s,a){const r=Bs(t)?t:gn(t);return r.start(vd("",r,s,a)),r.animation}const tT=(t,s)=>t.depth-s.depth;class sT{constructor(){this.children=[],this.isDirty=!1}add(s){Gc(this.children,s),this.isDirty=!0}remove(s){Wc(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(tT),this.isDirty=!1,this.children.forEach(s)}}function aT(t,s){const a=sa.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(xr(r),t(i-s))};return es.setup(r,!0),()=>xr(r)}const U0=["TopLeft","TopRight","BottomLeft","BottomRight"],rT=U0.length,Ix=t=>typeof t=="string"?parseFloat(t):t,Px=t=>typeof t=="number"||ot.test(t);function nT(t,s,a,r,n,i){n?(t.opacity=ns(0,a.opacity??1,iT(r)),t.opacityExit=ns(s.opacity??1,0,lT(r))):i&&(t.opacity=ns(s.opacity??1,a.opacity??1,r));for(let l=0;l<rT;l++){const o=`border${U0[l]}Radius`;let c=Ex(s,o),d=Ex(a,o);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||Px(c)===Px(d)?(t[o]=Math.max(ns(Ix(c),Ix(d),r),0),(La.test(d)||La.test(c))&&(t[o]+="%")):t[o]=d}(s.rotate||a.rotate)&&(t.rotate=ns(s.rotate||0,a.rotate||0,r))}function Ex(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const iT=B0(0,.5,Tg),lT=B0(.5,.95,ja);function B0(t,s,a){return r=>r<t?0:r>s?1:a(ti(t,s,r))}function _x(t,s){t.min=s.min,t.max=s.max}function pa(t,s){_x(t.x,s.x),_x(t.y,s.y)}function Mx(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Lx(t,s,a,r,n){return t-=s,t=il(t,1/a,r),n!==void 0&&(t=il(t,1/n,r)),t}function oT(t,s=0,a=1,r=.5,n,i=t,l=t){if(La.test(s)&&(s=parseFloat(s),s=ns(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=ns(i.min,i.max,r);t===i&&(o-=s),t.min=Lx(t.min,s,a,o,n),t.max=Lx(t.max,s,a,o,n)}function Ox(t,s,[a,r,n],i,l){oT(t,s[a],s[r],s[n],s.scale,i,l)}const cT=["x","scaleX","originX"],dT=["y","scaleY","originY"];function $x(t,s,a,r){Ox(t.x,s,cT,a?a.x:void 0,r?r.x:void 0),Ox(t.y,s,dT,a?a.y:void 0,r?r.y:void 0)}function Ux(t){return t.translate===0&&t.scale===1}function V0(t){return Ux(t.x)&&Ux(t.y)}function Bx(t,s){return t.min===s.min&&t.max===s.max}function mT(t,s){return Bx(t.x,s.x)&&Bx(t.y,s.y)}function Vx(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function z0(t,s){return Vx(t.x,s.x)&&Vx(t.y,s.y)}function zx(t){return Ws(t.x)/Ws(t.y)}function Hx(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class uT{constructor(){this.members=[]}add(s){Gc(this.members,s),s.scheduleRender()}remove(s){if(Wc(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 xT(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:u,skewX:h,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),p&&(r+=`rotateX(${p}deg) `),u&&(r+=`rotateY(${u}deg) `),h&&(r+=`skewX(${h}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 mo=["","X","Y","Z"],hT=1e3;let pT=0;function uo(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function H0(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=D0(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",es,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&H0(r)}function G0({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=pT++,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(bT),this.nodes.forEach(NT),this.nodes.forEach(wT),this.nodes.forEach(jT)},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 sT)}addEventListener(l,o){return this.eventHandlers.has(l)||this.eventHandlers.set(l,new Kc),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=i0(l)&&!nS(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 u=()=>this.root.updateBlockedByResize=!1;es.read(()=>{p=window.innerWidth}),t(l,()=>{const h=window.innerWidth;h!==p&&(p=h,this.root.updateBlockedByResize=!0,m&&m(),m=aT(u,250),Gi.hasAnimatedSinceResize&&(Gi.hasAnimatedSinceResize=!1,this.nodes.forEach(Yx)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:p,hasRelativeLayoutChanged:u,layout:h})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||kT,{onLayoutAnimationStart:f,onLayoutAnimationComplete:b}=d.getProps(),j=!this.targetLayout||!z0(this.targetLayout,h),y=!p&&u;if(this.options.layoutRoot||this.resumeFrom||y||p&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const N={...od(g,"layout"),onPlay:f,onComplete:b};(d.shouldReduceMotion||this.options.layoutRoot)&&(N.delay=0,N.type=!1),this.startAnimation(N),this.setAnimationOrigin(m,y)}else p||Yx(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=h})}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(),xr(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(CT),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&&H0(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(Gx);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Wx);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(vT),this.nodes.forEach(gT),this.nodes.forEach(fT)):this.nodes.forEach(Wx),this.clearAllSnapshots();const o=sa.now();Is.delta=Xa(0,1e3/60,o-Is.timestamp),Is.timestamp=o,Is.isProcessing=!0,ql.update.process(Is),ql.preRender.process(Is),ql.render.process(Is),Is.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,dd.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(yT),this.sharedNodes.forEach(ST)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,es.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){es.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ws(this.snapshot.measuredBox.x)&&!Ws(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=hs(),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&&!V0(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,m=d!==this.prevTransformTemplateValue;l&&this.instance&&(o||Fr(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)),DT(c),{animationId:this.root.animationId,measuredBox:o,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var d;const{visualElement:l}=this.options;if(!l)return hs();const o=l.measureViewportBox();if(!(((d=this.scroll)==null?void 0:d.wasRoot)||this.path.some(RT))){const{scroll:m}=this.root;m&&(nn(o.x,m.offset.x),nn(o.y,m.offset.y))}return o}removeElementScroll(l){var c;const o=hs();if(pa(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:u}=m;m!==this.root&&p&&u.layoutScroll&&(p.wasRoot&&pa(o,l),nn(o.x,p.offset.x),nn(o.y,p.offset.y))}return o}applyTransform(l,o=!1){const c=hs();pa(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&&ln(c,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),Fr(m.latestValues)&&ln(c,m.latestValues)}return Fr(this.latestValues)&&ln(c,this.latestValues),c}removeTransform(l){const o=hs();pa(o,l);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!Fr(d.latestValues))continue;ec(d.latestValues)&&d.updateSnapshot();const m=hs(),p=d.measurePageBox();pa(m,p),$x(o,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return Fr(this.latestValues)&&$x(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 u;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||(u=this.parent)!=null&&u.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 h=this.getClosestProjectingParent();h&&h.layout&&this.animationProgress!==1?(this.relativeParent=h,this.forceRelativeParentToResolveTarget(),this.relativeTarget=hs(),this.relativeTargetOrigin=hs(),Xn(this.relativeTargetOrigin,this.layout.layoutBox,h.layout.layoutBox),pa(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=hs(),this.targetWithTransforms=hs()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),MA(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):pa(this.target,this.layout.layoutBox),w0(this.target,this.targetDelta)):pa(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const h=this.getClosestProjectingParent();h&&!!h.resumingFrom==!!this.resumingFrom&&!h.options.layoutScroll&&h.target&&this.animationProgress!==1?(this.relativeParent=h,this.forceRelativeParentToResolveTarget(),this.relativeTarget=hs(),this.relativeTargetOrigin=hs(),Xn(this.relativeTargetOrigin,this.target,h.target),pa(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||ec(this.parent.latestValues)||N0(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;pa(this.layoutCorrected,this.layout.layoutBox);const p=this.treeScale.x,u=this.treeScale.y;QS(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=hs());const{target:h}=l;if(!h){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Mx(this.prevProjectionDelta.x,this.projectionDelta.x),Mx(this.prevProjectionDelta.y,this.projectionDelta.y)),Kn(this.projectionDelta,this.layoutCorrected,h,this.latestValues),(this.treeScale.x!==p||this.treeScale.y!==u||!Hx(this.projectionDelta.x,this.prevProjectionDelta.x)||!Hx(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",h))}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=on(),this.projectionDelta=on(),this.projectionDeltaWithTransform=on()}setAnimationOrigin(l,o=!1){const c=this.snapshot,d=c?c.latestValues:{},m={...this.latestValues},p=on();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!o;const u=hs(),h=c?c.source:void 0,g=this.layout?this.layout.source:void 0,f=h!==g,b=this.getStack(),j=!b||b.members.length<=1,y=!!(f&&!j&&this.options.crossfade===!0&&!this.path.some(TT));this.animationProgress=0;let N;this.mixTargetDelta=S=>{const A=S/1e3;Qx(p.x,l.x,A),Qx(p.y,l.y,A),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Xn(u,this.layout.layoutBox,this.relativeParent.layout.layoutBox),AT(this.relativeTarget,this.relativeTargetOrigin,u,A),N&&mT(this.relativeTarget,N)&&(this.isProjectionDirty=!1),N||(N=hs()),pa(N,this.relativeTarget)),f&&(this.animationValues=m,nT(m,d,this.latestValues,A,y,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=A},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(xr(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=es.update(()=>{Gi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=gn(0)),this.currentAnimation=eT(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(hT),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&&W0(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||hs();const p=Ws(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+p;const u=Ws(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+u}pa(o,c),ln(o,m),Kn(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new uT),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&&uo("z",l,d,this.animationValues);for(let m=0;m<mo.length;m++)uo(`rotate${mo[m]}`,l,d,this.animationValues),uo(`skew${mo[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=Hi(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=Hi(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!Fr(this.latestValues)&&(l.transform=c?c({},""):"none",this.hasProjected=!1);return}l.visibility="";const m=d.animationValues||d.latestValues;this.applyTransformsToTarget();let p=xT(this.projectionDeltaWithTransform,this.treeScale,m);c&&(p=c(m,p)),l.transform=p;const{x:u,y:h}=this.projectionDelta;l.transformOrigin=`${u.origin*100}% ${h.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 ni){if(m[g]===void 0)continue;const{correct:f,applyTo:b,isCSSVariable:j}=ni[g],y=p==="none"?m[g]:f(m[g],d);if(b){const N=b.length;for(let S=0;S<N;S++)l[b[S]]=y}else j?this.options.visualElement.renderState.vars[g]=y:l[g]=y}this.options.layoutId&&(l.pointerEvents=d===this?Hi(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(Gx),this.root.sharedNodes.clear()}}}function gT(t){t.updateLayout()}function fT(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"?ga(p=>{const u=l?s.measuredBox[p]:s.layoutBox[p],h=Ws(u);u.min=r[p].min,u.max=u.min+h}):W0(i,s.layoutBox,r)&&ga(p=>{const u=l?s.measuredBox[p]:s.layoutBox[p],h=Ws(r[p]);u.max=u.min+h,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[p].max=t.relativeTarget[p].min+h)});const o=on();Kn(o,r,s.layoutBox);const c=on();l?Kn(c,t.applyTransform(n,!0),s.measuredBox):Kn(c,r,s.layoutBox);const d=!V0(o);let m=!1;if(!t.resumeFrom){const p=t.getClosestProjectingParent();if(p&&!p.resumeFrom){const{snapshot:u,layout:h}=p;if(u&&h){const g=hs();Xn(g,s.layoutBox,u.layoutBox);const f=hs();Xn(f,r,h.layoutBox),z0(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 bT(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 jT(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function yT(t){t.clearSnapshot()}function Gx(t){t.clearMeasurements()}function Wx(t){t.isLayoutDirty=!1}function vT(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function Yx(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function NT(t){t.resolveTargetDelta()}function wT(t){t.calcProjection()}function CT(t){t.resetSkewAndRotation()}function ST(t){t.removeLeadSnapshot()}function Qx(t,s,a){t.translate=ns(s.translate,0,a),t.scale=ns(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function Kx(t,s,a,r){t.min=ns(s.min,a.min,r),t.max=ns(s.max,a.max,r)}function AT(t,s,a,r){Kx(t.x,s.x,a.x,r),Kx(t.y,s.y,a.y,r)}function TT(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const kT={duration:.45,ease:[.4,0,.1,1]},Xx=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Zx=Xx("applewebkit/")&&!Xx("chrome/")?Math.round:ja;function Jx(t){t.min=Zx(t.min),t.max=Zx(t.max)}function DT(t){Jx(t.x),Jx(t.y)}function W0(t,s,a){return t==="position"||t==="preserve-aspect"&&!_A(zx(s),zx(a),.2)}function RT(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const FT=G0({attachResizeListener:(t,s)=>ii(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),xo={current:void 0},Y0=G0({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!xo.current){const t=new FT({});t.mount(window),t.setOptions({layoutScroll:!0}),xo.current=t}return xo.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),IT={pan:{Feature:XA},drag:{Feature:KA,ProjectionNode:Y0,MeasureLayout:$0}};function qx(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&&es.postRender(()=>i(s,bi(s)))}class PT extends fr{mount(){const{current:s}=this.node;s&&(this.unmount=eS(s,(a,r)=>(qx(this.node,r,"Start"),n=>qx(this.node,n,"End"))))}unmount(){}}class ET extends fr{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=pi(ii(this.node.current,"focus",()=>this.onFocus()),ii(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function eh(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&&es.postRender(()=>i(s,bi(s)))}class _T extends fr{mount(){const{current:s}=this.node;s&&(this.unmount=rS(s,(a,r)=>(eh(this.node,r,"Start"),(n,{success:i})=>eh(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const lc=new WeakMap,ho=new WeakMap,MT=t=>{const s=lc.get(t.target);s&&s(t)},LT=t=>{t.forEach(MT)};function OT({root:t,...s}){const a=t||document;ho.has(a)||ho.set(a,{});const r=ho.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(LT,{root:t,...s})),r[n]}function $T(t,s,a){const r=OT(s);return lc.set(t,a),r.observe(t),()=>{lc.delete(t),r.unobserve(t)}}const UT={some:0,all:1};class BT extends fr{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:UT[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(),u=d?m:p;u&&u(c)};return $T(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(VT(s,a))&&this.startObserver()}unmount(){}}function VT({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const zT={inView:{Feature:BT},tap:{Feature:_T},focus:{Feature:ET},hover:{Feature:PT}},HT={layout:{ProjectionNode:Y0,MeasureLayout:$0}},GT={...DA,...zT,...IT,...HT},Wt=GS(GT,rA),Mn=[{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:Mt,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:tp,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 WT({open:t,onClose:s,onSelectTemplate:a}){var d,m,p;const[r,n]=x.useState(null),[i,l]=x.useState(!1);x.useEffect(()=>{const u=tt.getUserData();l((u==null?void 0:u.jobTitle)==="Dealer")},[]);const o=u=>{if(i)return;const h=Mn.find(g=>g.id===u);h!=null&&h.disabled||n(u)},c=()=>{r&&(a(r),s())};return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"!fixed !inset-0 !top-0 !left-0 !right-0 !bottom-0 !w-screen !h-screen !max-w-none !translate-x-0 !translate-y-0 p-0 gap-0 border-0 !rounded-none bg-gradient-to-br from-gray-50 to-white [&>button]:hidden !m-0",children:[e.jsx(mt,{className:"sr-only",children:"Select a Template"}),e.jsx(_t,{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(Wt.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(pl,{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:Mn.map((u,h)=>{const g=u.icon,f=r===u.id,b=i||u.disabled;return e.jsx(Wt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:h*.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(u.id),children:[e.jsxs(ce,{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 ${u.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),f&&e.jsx(Wt.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($a,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(de,{className:"text-xl mb-2",children:u.name}),e.jsx(we,{className:"text-sm leading-relaxed",children:u.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(Je,{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"})]}),u.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(Je,{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(J,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(re,{variant:"secondary",className:"text-xs",children:u.category})}),e.jsx(Jt,{}),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(it,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:u.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ts,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[u.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:[u.features.slice(0,3).map((j,y)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(Be,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:j})]},y)),u.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",u.features.length-3," more features"]})]})]})]})]})},u.id)})}),e.jsxs(Wt.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=Mn.find(u=>u.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=Mn.find(u=>u.id===r))!=null&&m.disabled)?"bg-blue-600 hover:bg-blue-700":"bg-gray-400 cursor-not-allowed"}`,children:["Continue with Template",e.jsx(js,{className:"w-4 h-4"})]})]}),e.jsx(Rl,{children:r&&e.jsx(Wt.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=Mn.find(u=>u.id===r))==null?void 0:p.name})]})})})]})})]})})}function Yr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=x.useState(100),[m,p]=x.useState(0),[u,h]=x.useState(null),[g,f]=x.useState(!1),[b,j]=x.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"),N=s.toLowerCase().includes("pdf"),S=y||N;x.useEffect(()=>{if(!l||!S||!a){h(null);return}return(async()=>{f(!0),j(null);try{let P=a;a.startsWith("/")&&!a.startsWith("//")&&(P=`${window.location.origin}${a}`);const k=await fetch(P,{headers:{Accept:N?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!k.ok){const R=await k.text().catch(()=>"");throw new Error(`Failed to load file: ${k.status} ${k.statusText}. ${R}`)}const _=await k.blob();if(_.size===0)throw new Error("File is empty or could not be loaded");N&&!_.type.includes("pdf")&&_.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${_.type}`);const L=window.URL.createObjectURL(_);h(L)}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)}})(),()=>{u&&(window.URL.revokeObjectURL(u),h(null))}},[l,a,S,N]);const A=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},w=()=>d(T=>Math.min(T+25,200)),I=()=>d(T=>Math.max(T-25,50)),D=()=>p(T=>(T+90)%360);return e.jsx(xt,{open:l,onOpenChange:o,children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ht,{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(Nt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`• ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[y&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:I,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(Dj,{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:w,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(Rj,{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(sp,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(E,{variant:"outline",size:"sm",onClick:A,className:"gap-2 h-9",children:[e.jsx(Tt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})]})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:g?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx(ze,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):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(yt,{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:A,className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",t]})]}):S&&u?e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:u,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"})}),N&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:u,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(Nt,{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:A,className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function ji({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(_t,{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(Dt,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const ua=async t=>{const s=t?{category:t}:{};return(await ve.get("/users/configurations",{params:s})).data.data},El=async t=>{const s=t?{category:t}:{};return(await ve.get("/admin/configurations",{params:s})).data.data},Gs=async(t,s)=>{await ve.put(`/admin/configurations/${t}`,{configValue:s})},YT=async t=>{await ve.post(`/admin/configurations/${t}/reset`)},QT=async()=>{const t=await ve.get("/admin/form16-config");return t.data.data??t.data},KT=async t=>{await ve.put("/admin/form16-config",t)},XT=async t=>{const s=t?{year:t}:{};return(await ve.get("/admin/holidays",{params:s})).data.data},ZT=async t=>(await ve.post("/admin/holidays",t)).data.data,JT=async(t,s)=>(await ve.put(`/admin/holidays/${t}`,s)).data.data,qT=async t=>{await ve.delete(`/admin/holidays/${t}`)},e5=async()=>(await ve.get("/config/activity-types")).data.data,t5=async t=>{const s={activeOnly:t.toString()};return(await ve.get("/admin/activity-types",{params:s})).data.data},s5=async t=>(await ve.post("/admin/activity-types",t)).data.data,a5=async(t,s)=>(await ve.put(`/admin/activity-types/${t}`,s)).data.data,r5=async t=>{await ve.delete(`/admin/activity-types/${t}`)},n5={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 i5(t,s,a){const[r,n]=x.useState(n5),[i,l]=x.useState(null),[o,c]=x.useState(t),[d,m]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[p,u]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[h,g]=x.useState([]);return x.useEffect(()=>{(async()=>{var j;try{const y=await ua("DOCUMENT_POLICY"),N={};y.forEach(M=>{N[M.configKey]=M.configValue});const S=parseInt(N.MAX_FILE_SIZE_MB||"10"),w=(N.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(M=>M.trim().toLowerCase());u({maxFileSizeMB:S,allowedFileTypes:w});const I=await ua("SYSTEM_SETTINGS"),D=await ua("WORKFLOW_SHARING"),T=[...I,...D],v={};T.forEach(M=>{v[M.configKey]=M.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)}})()},[]),x.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||{},N=Array.isArray(j.approvals)?j.approvals:[],S=Array.isArray(j.participants)?j.participants:[],A=Array.isArray(j.documents)?j.documents.filter(P=>!P.isDeleted):[];g(A);const w=(y.priority||"").toString().toLowerCase(),I={standard:"standard",express:"express"},D=y.templateType==="TEMPLATE"?"existing-template":"custom",T=a.find(P=>P.id===D)||a[0]||null;l(T);const v=N.sort((P,B)=>(P.levelNumber||0)-(B.levelNumber||0)).map(P=>{const B=Number(P.tatHours||24),k=Math.floor(B/24),_=B%24;return{id:P.approverId||`temp-${P.levelNumber}`,name:P.approverName||P.approverEmail||"",email:P.approverEmail||"",role:P.levelName||`Level ${P.levelNumber}`,department:"",avatar:(P.approverName||P.approverEmail||"XX").substring(0,2).toUpperCase(),level:P.levelNumber||1,canClose:!1,tat:k>0?k:_,tatType:k>0?"days":"hours",userId:P.approverId}}),M=S.filter(P=>(P.participantType||P.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(P.userEmail||P.user_email||P.email):!1).map((P,B)=>{const k=P.userId||P.user_id||P.id,_=P.userName||P.user_name||P.name||"",L=P.userEmail||P.user_email||P.email||"",C=(_||L||"XX").split(" ").map(G=>G[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:k||`spectator-${s}-${B}-${Date.now()}`,userId:k,name:_||L||"Spectator",email:L,role:"Spectator",department:P.department||"",avatar:C,level:1,canClose:!1}});n(P=>({...P,template:D,title:y.title||"",description:y.description||"",priority:I[w]||"standard",approvers:v,approverCount:v.length||1,spectators:M,maxLevel:Math.max(...v.map(B=>B.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:h,setExistingDocuments:g}}const th=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function l5(t,s,a){const[r,n]=x.useState(t?2:1),i=th.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 u=p.tatType||"hours";return u==="hours"?p.tat&&p.tat>0&&p.tat<=720:u==="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:th,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 o5(){const[t,s]=x.useState({open:!1,type:"error",email:"",message:""}),[a,r]=x.useState({open:!1,violations:[]}),[n,i]=x.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(u,h,g="")=>{s({open:!0,type:u,email:h,message:g})},closeValidationModal:()=>{s(u=>({...u,open:!1}))},openPolicyViolationModal:u=>{r({open:!0,violations:u})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:u=>{i({open:!0,errors:u})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function c5(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function d5(t,s,a){var n;const r=c5(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 m5(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return d5(a,n,n===s)})}function sh(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 ah(t,s,a,r=!1){const n=m5(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 u5(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 rh(t,s){return{id:(await Uc(t,s||[],"SUPPORTING")).id}}async function nh(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await K1(t,s,a||[],r):await Q1(t,s)}function x5({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=x.useState(!1),[m,p]=x.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var f,b;if(c||m)return;const g=u5(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const j=ah(t,n,r,!1);await nh(l,j,a,r),W.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=sh(t,s,n,!1),y=await rh(j,a);W.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),W.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=ah(t,n,r,!0);await nh(l,b,a,r),W.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=sh(t,s,n,!0),j=await rh(b,a);W.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),W.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 Na(t,s=10,a="default"){return await ve.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ya(t){var a;const s=await ve.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function h5(t,s){return await ve.post("/admin/users/assign-role",{email:t,role:s})}async function p5(t,s){return await ve.put(`/admin/users/${t}/role`,{role:s})}async function g5(t,s=1,a=10){return await ve.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function f5(){return await ve.get("/admin/users/role-statistics")}async function b5(t){var a;const s=await ve.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function j5(){var s,a;return((a=(s=(await ve.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const da={searchUsers:Na,getUserById:b5,ensureUserExists:ya,assignRole:h5,updateUserRole:p5,getUsersByRole:g5,getRoleStatistics:f5,getAllUsers:j5};async function y5(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 Na(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 ya({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 v5(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 y5(l,s);if(!o.success)return{success:!1,error:o.error};try{const m=(((n=(await Na(l.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const p=await ya({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 N5({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:u}){const h=Cs(),[g,f]=x.useState(!1),[b,j]=x.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 T=new Date;T.setDate(T.getDate()+D.suggestedSLA),a("slaEndDate",T),D.id!=="custom"&&D.id!=="existing-template"&&h(`/create-admin-request/${D.id}`)},handleTemplateSelection:D=>{D==="claim-management"?h("/claim-management"):D==="vendor-payment"?h("/vendor-payment"):u&&u({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 M=r.approverCount||1;if(M>m.maxApprovalLevels){p([{type:"Maximum Approval Levels Exceeded",message:`The request has ${M} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:M,maxValue:m.maxApprovalLevels}]);return}}const T=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",v=await v5(r.approvers,T);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,T)=>{if(T){const v=D.documentId||D.document_id||"";j({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:wn(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 ih=[{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:gl,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:Fe,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let Ur=null;const lh=()=>Ur,w5=async t=>{const a=(await ve.post("/templates",t)).data.data,r={id:a.templateId||a.id,name:a.templateName||a.name,description:a.templateDescription||a.description,category:a.templateCategory||a.category,priority:a.priority||"medium",estimatedTime:a.estimatedTime||"Variable",approvers:a.approvalLevelsConfig||a.approvers||[],suggestedSLA:a.defaultTatHours||a.suggestedSLA||24,isActive:a.isActive,fields:a.userFieldMappings||a.fields};return Ur&&Ur.push(r),r},_l=async()=>{var r;const a=(((r=(await ve.get("/templates")).data)==null?void 0:r.data)||[]).map(n=>({id:n.templateId||n.id,name:n.templateName||n.name,description:n.templateDescription||n.description,category:n.templateCategory||n.category,priority:n.priority||"medium",estimatedTime:n.estimatedTime||"Variable",approvers:n.approvalLevelsConfig||n.approvers||[],suggestedSLA:n.defaultTatHours||n.suggestedSLA||24,isActive:n.isActive,fields:n.userFieldMappings||n.fields}));return Ur=a,a},C5=async(t,s)=>{const r=(await ve.put(`/templates/${t}`,s)).data.data,n={id:r.templateId||r.id,name:r.templateName||r.name,description:r.templateDescription||r.description,category:r.templateCategory||r.category,priority:r.priority||"medium",estimatedTime:r.estimatedTime||"Variable",approvers:r.approvalLevelsConfig||r.approvers||[],suggestedSLA:r.defaultTatHours||r.suggestedSLA||24,isActive:r.isActive,fields:r.userFieldMappings||r.fields};return Ur&&(Ur=Ur.map(i=>i.id===t?n:i)),n};function Q0({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($a,{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 S5({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(ze,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),e.jsx("span",{children:m?"Updating...":"Saving..."})]}):e.jsx("span",{children:m?"Update Draft":"Save Draft"})}),t===s?e.jsx(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(ze,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ap,{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(js,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const oh=t=>{switch(t){case"high":return e.jsx(Ia,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(ts,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Qs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ts,{className:"w-4 h-4 text-gray-600"})}};function A5({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=x.useState("main"),l=Cs(),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(Wt.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(Fj,{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 u=m.id==="admin-templates-category",h=(s==null?void 0:s.id)===m.id;return e.jsx(Wt.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 ${h?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer":u?"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(ce,{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 ${h||u?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${h||u?"text-blue-600":"text-gray-600"}`})}),h&&e.jsx(Wt.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($a,{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(de,{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(re,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),oh(m.priority)]})]})]}),e.jsxs(J,{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}),!u&&e.jsxs(e.Fragment,{children:[e.jsx(Jt,{}),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(it,{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(qt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[((g=m.commonApprovers)==null?void 0:g.length)||0," approvers"]})]})]})]}),u&&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(Rl,{children:s&&e.jsx(Wt.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(ce,{children:e.jsxs(de,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Hr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(J,{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(se,{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(se,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[oh(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(se,{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(se,{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(re,{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 Re({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:Le("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 T5({className:t,...s}){return e.jsx(Ob,{"data-slot":"radio-group",className:Le("grid gap-3",t),...s})}function ch({className:t,...s}){return e.jsx($b,{"data-slot":"radio-group-item",className:Le("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(Ub,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(bc,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function k5({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(Wt.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(Fe,{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(se,{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(Re,{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(se,{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(hi,{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(se,{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(T5,{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(ch,{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(hl,{className:"w-4 h-4 text-red-600"}),e.jsx(se,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(re,{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(ch,{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(it,{className:"w-4 h-4 text-blue-600"}),e.jsx(se,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(re,{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(se,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Re,{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(se,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(He,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(We,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"USD",children:"USD ($)"}),e.jsx(X,{value:"EUR",children:"EUR (€)"}),e.jsx(X,{value:"GBP",children:"GBP (£)"}),e.jsx(X,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(se,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Re,{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(se,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Re,{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(se,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Re,{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 K0(){const[t,s]=x.useState([]),[a,r]=x.useState(!1),n=x.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),h=((m=(await Na(p,d)).data)==null?void 0:m.data)||[];s(h)}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 ya({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 X0(){const[t,s]=x.useState({}),[a,r]=x.useState({}),n=x.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),h=((m=(await Na(p,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:h}))}catch(p){console.error(`User search failed for index ${o}:`,p),s(u=>({...u,[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 D5({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var p;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=X0();x.useEffect(()=>{const u=t.approverCount||1,h=t.approvers||[];if(h.length<u){const g=[...h];for(let f=h.length;f<u;f++)g[f]||(g[f]={email:"",name:"",level:f+1,tat:""});s("approvers",g)}else h.length>u&&s("approvers",h.slice(0,u))},[t.approverCount,s]);const d=(u,h)=>{var j,y,N,S,A;const g=[...t.approvers],b=((j=g[u])==null?void 0:j.email)!==h;if(g[u]={...g[u],email:h,level:u+1,userId:b||(y=g[u])==null?void 0:y.userId,name:b||(N=g[u])==null?void 0:N.name,department:b||(S=g[u])==null?void 0:S.department,avatar:b||(A=g[u])==null?void 0:A.avatar},s("approvers",g),!h||!h.startsWith("@")||h.length<2){c(u);return}o(u,h,10)},m=async(u,h)=>{var g,f;try{if((g=t.approvers)==null?void 0:g.some((S,A)=>{var w,I;return A!==u&&(S.userId===h.userId||((w=S.email)==null?void 0:w.toLowerCase())===((I=h.email)==null?void 0:I.toLowerCase()))})){a({type:"error",email:h.email,message:"This user is already added as an approver in another level."});return}if((f=t.spectators)==null?void 0:f.some(S=>{var A,w;return S.userId===h.userId||((A=S.email)==null?void 0:A.toLowerCase())===((w=h.email)==null?void 0:w.toLowerCase())})){a({type:"error",email:h.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const y=await ya({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}),N=[...t.approvers];N[u]={...N[u],email:h.email,name:h.displayName||[h.firstName,h.lastName].filter(Boolean).join(" "),userId:y.userId,level:u+1},s("approvers",N),c(u)}catch(b){console.error("Failed to ensure user exists:",b),a({type:"error",email:h.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(Wt.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(qt,{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(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(dr,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(we,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(J,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(se,{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 u=t.approverCount||1,h=Math.max(1,u-1);s("approverCount",h),t.approvers.length>h&&s("approvers",t.approvers.slice(0,h))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(jc,{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 h=(t.approverCount||1)+1;if(h>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:h,maxValue:r.maxApprovalLevels}]);return}s("approverCount",h)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(ms,{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(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(fs,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(we,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(J,{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(Ht,{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(re,{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},(u,h)=>{var j,y;const g=h+1,f=g===(t.approverCount||1),b=t.approvers[h]||{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(re,{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(se,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),b.email&&b.userId&&e.jsxs(re,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Be,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Re,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:b.email||"",onChange:N=>d(h,N.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[h]||(((j=i[h])==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[h]?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[h])==null?void 0:y.map(N=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(h,N),"data-testid":`approval-workflow-approver-${g}-search-result-${N.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:N.displayName||N.email}),e.jsx("div",{className:"text-xs text-gray-600",children:N.email})]},N.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-tat-field`,children:[e.jsx(se,{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(Re,{id:`tat-${g}`,type:"number",placeholder:b.tatType==="days"?"7":"24",min:"1",max:b.tatType==="days"?"30":"720",value:b.tat||"",onChange:N=>{const S=[...t.approvers];S[h]={...S[h],tat:parseInt(N.target.value)||"",level:g,tatType:b.tatType||"hours"},s("approvers",S)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(He,{value:b.tatType||"hours",onValueChange:N=>{const S=[...t.approvers];S[h]={...S[h],tatType:N,level:g,tat:""},s("approvers",S)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(We,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"hours",children:"Hours"}),e.jsx(X,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Hr,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," → ",Array.from({length:t.approverCount||1},(u,h)=>`Level ${h+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(it,{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 u=((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,h=Math.ceil(u);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[h," ",h===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((u,h)=>{const g=Number(u.tat||0),b=(u.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 ",h+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[b," ",b===1?"hour":"hours"]})]})},h):null})}),(()=>{var g;const u=((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,h=Math.ceil(u/8);return u===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:[u,"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:h}),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 R5({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=x.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=K0(),p=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},u=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(N=>{var S,A;return N.userId===g.userId||((S=N.email)==null?void 0:S.toLowerCase())===((A=g.email)==null?void 0:A.toLowerCase())}),y=(f=t.approvers)==null?void 0:f.some(N=>{var S,A;return N.userId===g.userId||((S=N.email)==null?void 0:S.toLowerCase())===((A=g.email)==null?void 0:A.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 N=await m(g),S={id:N.userId,userId:N.userId,name:N.displayName||g.email.split("@")[0],email:N.email,avatar:(N.displayName||N.email).substring(0,2).toUpperCase(),role:"Spectator",department:N.department||"",level:1,canClose:!1},A=[...t.spectators,S];s("spectators",A),i(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const j=t.spectators.some(N=>{var S;return((S=N.email)==null?void 0:S.toLowerCase())===n.toLowerCase()}),y=(b=t.approvers)==null?void 0:b.some(N=>{var S;return((S=N.email)==null?void 0:S.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}}},h=g=>{const f=t.spectators.filter(b=>b.id!==g);s("spectators",f)};return e.jsxs(Wt.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(Nt,{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(ce,{children:[e.jsxs(de,{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(Nt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(re,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(we,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(J,{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(Re,{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 u())},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:()=>u(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:()=>u(),disabled:!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"data-testid":"participants-spectators-add-button",children:"Add"})]}),e.jsxs("p",{className:"text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1",children:[e.jsx(Hr,{className:"w-3 h-3 flex-shrink-0"}),e.jsxs("span",{children:["Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users, or type email directly (will be validated against organization directory)"]})]})]}),e.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto","data-testid":"participants-spectators-list",children:t.spectators.map(g=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-teal-50 rounded-lg","data-testid":`participants-spectator-${g.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"h-6 w-6",children:e.jsx(ds,{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:()=>h(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(yt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function F5({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=[],N=[];b.forEach(S=>{if(S.size>j){y.push({fileName:S.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(S.size/1048576).toFixed(2)}MB`});return}const A=S.name.toLowerCase(),w=A.substring(A.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(w)){y.push({fileName:S.name,reason:`File type "${w}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}N.push(S)}),N.length>0&&i([...a,...N]),y.length>0&&d&&d(y),f.target&&(f.target.value="")},u=f=>{const b=a.filter((j,y)=>y!==f);i(b)},h=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(Wt.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(ys,{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(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Fe,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(we,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(J,{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(ys,{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(ms,{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(ce,{children:e.jsxs(de,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(re,{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(J,{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(Fe,{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(Nt,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>h(b),"data-testid":`documents-existing-${b}-delete`,children:e.jsx(yt,{className:"h-4 w-4 text-red-600"})})]})]},b)})})})]}),a.length>0&&e.jsxs(Z,{"data-testid":"documents-new-card",children:[e.jsx(ce,{children:e.jsxs(de,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(re,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(J,{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(Fe,{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(Nt,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(b),"data-testid":`documents-new-${b}-remove`,children:e.jsx(yt,{className:"h-4 w-4"})})]})]},b))})})]})]})]})}const I5=t=>{switch(t){case"high":return e.jsx(Ia,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(ts,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Qs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ts,{className:"w-4 h-4 text-gray-600"})}};function P5({formData:t,selectedTemplate:s}){return e.jsxs(Wt.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(Be,{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(ce,{children:e.jsxs(de,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(ap,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(J,{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(se,{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(re,{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(se,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[I5(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(se,{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(se,{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(ce,{children:e.jsxs(de,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Fe,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(se,{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(Da,{className:"w-4 h-4 text-blue-600"}),e.jsx(se,{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(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(qt,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(we,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(J,{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(re,{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(ce,{children:e.jsxs(de,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(Nt,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(J,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(se,{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(re,{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(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(ys,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(we,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(J,{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(Fe,{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(J,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Be,{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 E5({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 _5({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(Rl,{mode:"wait",children:t})})})}function M5({modal:t,onClose:s}){return e.jsx(xt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(_t,{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(gl,{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(Dt,{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 L5({modal:t,documentPolicy:s,onClose:a}){return e.jsx(xt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(_t,{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(Dt,{children:e.jsx(E,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function dh({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Va(),i=Cs(),l=n.requestId||a||"",o=r&&!!l,{user:c}=us(),[d,m]=x.useState([]);x.useEffect(()=>{(async()=>{try{const je=(await _l()).map(ie=>({id:ie.id,name:ie.name,description:ie.description,category:ie.category,icon:Fe,estimatedTime:ie.estimatedTime,commonApprovers:ie.approvers.map(Se=>Se.name),workflowApprovers:ie.approvers,suggestedSLA:ie.suggestedSLA,priority:ie.priority,fields:ie.fields||{}}));m(je)}catch(Oe){console.error("Failed to fetch admin templates:",Oe)}})()},[]);const p=x.useMemo(()=>[...ih,...d],[d]),{formData:u,updateFormData:h,selectedTemplate:g,setSelectedTemplate:f,loadingDraft:b,systemPolicy:j,documentPolicy:y,existingDocuments:N,setExistingDocuments:S}=i5(o,l,p),{currentStep:A,totalSteps:w,stepNames:I,isStepValid:D,nextStep:T,prevStep:v}=l5(o,g,u),[M,P]=x.useState([]),[B,k]=x.useState([]),_=x.useRef(null),{validationModal:L,policyViolationModal:R,documentErrorModal:C,openValidationModal:G,closeValidationModal:U,openPolicyViolationModal:$,closePolicyViolationModal:F,openDocumentErrorModal:H,closeDocumentErrorModal:K}=o5(),{submitting:z,savingDraft:O,handleSubmit:V,handleSaveDraft:Q}=x5({formData:u,selectedTemplate:g,documents:M,documentsToDelete:B,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:q,setShowTemplateModal:ee,previewDocument:te,selectTemplate:ue,handleTemplateSelection:_e,nextStep:Ze,prevStep:Ue,handlePreviewDocument:Pe,closePreview:De}=N5({selectedTemplate:g,setSelectedTemplate:f,updateFormData:h,formData:u,currentStep:A,isStepValid:D,wizardNextStep:T,wizardPrevStep:v,user:c,openValidationModal:G,systemPolicy:j,onPolicyViolation:$,onSubmit:s}),le=x.useCallback(()=>{if(A===1){i("/dashboard",{replace:!0});return}A===3||A===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Ue()},[A,t,i,Ue]),ye=x.useRef(!0),ae=x.useRef(!1);x.useEffect(()=>{ye.current&&u.documents&&u.documents.length>0&&!ae.current&&(P(u.documents),ae.current=!0),ye.current=!1},[u.documents]);const he=x.useRef(!1),ne=x.useRef(M);x.useEffect(()=>{if(he.current){he.current=!1,ne.current=M;return}ne.current!==M&&(h("documents",M),ne.current=M)},[M]);const ge=()=>{switch(A){case 1:return e.jsx(A5,{templates:ih,selectedTemplate:g,onSelectTemplate:ue,adminTemplates:d});case 2:return e.jsx(k5,{formData:u,selectedTemplate:g,updateFormData:h});case 3:return e.jsx(D5,{formData:u,updateFormData:h,systemPolicy:j,onValidationError:ke=>G(ke.type,ke.email,ke.message),onPolicyViolation:$});case 4:return e.jsx(R5,{formData:u,updateFormData:h,onValidationError:ke=>G(ke.type,ke.email,ke.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(F5,{documentPolicy:y,isEditing:o,documents:M,existingDocuments:N,documentsToDelete:B,onDocumentsChange:P,onExistingDocumentsChange:S,onDocumentsToDeleteChange:k,onPreviewDocument:Pe,onDocumentErrors:ke=>H(ke),fileInputRef:_});case 6:return e.jsx(P5,{formData:u,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(E5,{isEditing:o,currentStep:A,totalSteps:w,stepNames:I,onBack:le}),e.jsx(Q0,{currentStep:A,totalSteps:w,stepNames:I}),e.jsx(_5,{children:ge()}),e.jsx(S5,{currentStep:A,totalSteps:w,isStepValid:D(),onPrev:Ue,onNext:Ze,onSubmit:V,onSaveDraft:Q,submitting:z,savingDraft:O,loadingDraft:b,isEditing:o}),e.jsx(WT,{open:q,onClose:()=>ee(!1),onSelectTemplate:_e}),te&&e.jsx(Yr,{fileName:te.fileName,fileType:te.fileType,fileUrl:te.fileUrl,fileSize:te.fileSize,open:!!te,onClose:De,onDownload:async()=>{if(te.file){const ke=document.createElement("a");ke.href=te.fileUrl,ke.download=te.fileName,document.body.appendChild(ke),ke.click(),document.body.removeChild(ke)}else te.documentId&&await Ms(te.documentId)},attachmentId:te.documentId}),e.jsx(M5,{modal:L,onClose:U}),e.jsx(L5,{modal:C,documentPolicy:y,onClose:K}),e.jsx(ji,{open:R.open,onClose:F,violations:R.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}function yi({className:t,...s}){return e.jsx(Bb,{"data-slot":"tabs",className:Le("flex flex-col gap-2",t),...s})}function vi({className:t,...s}){return e.jsx(Vb,{"data-slot":"tabs-list",className:Le("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function $t({className:t,...s}){return e.jsx(zb,{"data-slot":"tabs-trigger",className:Le("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 Ut({className:t,...s}){return e.jsx(Hb,{"data-slot":"tabs-content",className:Le("flex-1 outline-none",t),...s})}function li(t){if(!t)return!1;const s=t.request||t;return s.workflowType==="CLAIM_MANAGEMENT"||s.templateType==="claim-management"||s.template==="claim-management"||s.templateName==="Claim Management"||s.templateCode==="CLAIM_MANAGEMENT"}function Nd(t,s=[],a){const[r,n]=x.useState(null),[i,l]=x.useState(!1),[o,c]=x.useState(!0),[d,m]=x.useState(null),[p,u]=x.useState(null),[h,g]=x.useState(!1),f=(w,I)=>(w||I||"NA").toString().split(" ").map(T=>T[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),b=w=>{const I=(w||"").toUpperCase();return I==="IN_PROGRESS"?"in-review":I==="PENDING"?"pending":I==="APPROVED"?"approved":I==="REJECTED"?"rejected":I==="CLOSED"?"closed":I==="SKIPPED"?"skipped":(w||"").toLowerCase()},j=w=>{const I=String(w||"").trim();if(!I)return"Document";const D=I.lastIndexOf("."),T=D>0&&D<I.length-1,v=T?I.slice(0,D):I,M=T?I.slice(D):"";return`${v.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[redacted-email]").replace(/(?:\+?\d[\d\s().-]{8,}\d)/g,"[redacted-phone]").replace(/\s{2,}/g," ").trim()||"Document"}${M}`},y=x.useCallback(async()=>{var w,I,D,T,v,M,P,B,k,_,L,R,C,G,U;l(!0);try{const $=await Ks.getWorkflowDetails(t);if(!$){console.warn("[useRequestDetails] No details returned from API");return}const F=$.workflow||{},H=Array.isArray($.approvals)?$.approvals:[],K=Array.isArray($.participants)?$.participants:[],z=Array.isArray($.documents)?$.documents:[],O=$.summary||{},V=Array.isArray($.tatAlerts)?$.tatAlerts:[];V.length>0;const Q=(O==null?void 0:O.currentLevel)||F.currentLevel||1,q=H.map(je=>{const ie=je.levelNumber||0,Se=(je.status||"").toString().toUpperCase(),qe=je.levelId||je.level_id;let rt=b(je.status);ie>Q&&Se!=="APPROVED"&&Se!=="REJECTED"?rt="waiting":ie===Q&&Se==="PENDING"&&(rt="pending");const gt=V.filter(It=>It.levelId===qe);return{step:ie,levelId:qe,role:je.levelName||je.approverName||"Approver",status:rt,approver:je.approverName||je.approverEmail,approverId:je.approverId||je.approver_id,approverEmail:je.approverEmail,tatHours:Number(je.tatHours||0),elapsedHours:Number(je.elapsedHours||0),remainingHours:Number(je.remainingHours||0),tatPercentageUsed:Number(je.tatPercentageUsed||0),actualHours:je.levelEndTime&&je.levelStartTime?Math.max(0,(new Date(je.levelEndTime).getTime()-new Date(je.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:je.comments||void 0,timestamp:je.actionDate||void 0,levelStartTime:je.levelStartTime||je.tatStartTime,tatAlerts:gt,skipReason:je.skipReason||void 0,isSkipped:Se==="SKIPPED"||je.isSkipped||!1}}),ee=K.filter(je=>(je.participantType||je.participant_type||"").toUpperCase()==="SPECTATOR").map(je=>({name:je.userName||je.user_name||je.userEmail||je.user_email,role:"Spectator",email:je.userEmail||je.user_email,avatar:f(je.userName||je.user_name,je.userEmail||je.user_email)})),te=je=>{var Se,qe;if(!je)return;const ie=K.find(rt=>rt.userId===je||rt.user_id===je);return ie!=null&&ie.userName||ie!=null&&ie.user_name?ie.userName||ie.user_name:F.initiatorId===je?((Se=F.initiator)==null?void 0:Se.displayName)||((qe=F.initiator)==null?void 0:qe.email):je},ue=z.map(je=>{const ie=Number(je.fileSize||je.file_size||0),Se=(ie/(1024*1024)).toFixed(2)+" MB";return{documentId:je.documentId||je.document_id,name:j(je.originalFileName||je.fileName||je.file_name),fileType:je.fileType||je.file_type||"",size:Se,sizeBytes:ie,uploadedBy:te(je.uploadedBy||je.uploaded_by),uploadedAt:je.uploadedAt||je.uploaded_at}}),_e=Array.isArray($.activities)?$.activities.filter(je=>(je.type||"").toLowerCase()!=="sla_warning"):[];let Ze=null;if(F.isPaused||!1)try{Ze=await Lu(F.requestId)}catch{}let Pe=null,De=null,le=null,ye=null,ae=[],he=null;if(li(F)){try{const je=await ve.get(`/dealer-claims/${F.requestId}/credit-note-wfm`),ie=je.data??je;he=Array.isArray(ie==null?void 0:ie.data)?ie.data:Array.isArray(ie)?ie:[]}catch(je){console.warn("[useRequestDetails] Error fetching credit note WFM data:",je)}try{const je=await ve.get(`/dealer-claims/${F.requestId}`),ie=((w=je.data)==null?void 0:w.data)||je.data;if(ie){Pe=ie.claimDetails||ie.claim_details,De=ie.proposalDetails||ie.proposal_details,le=ie.completionDetails||ie.completion_details,ye=ie.internalOrder||ie.internal_order||null,ae=ie.internalOrders||ie.internal_orders||[];const Se=ie.budgetTracking||ie.budget_tracking||null,qe=ie.invoice||null,rt=ie.creditNote||ie.credit_note||null,gt=ie.completionExpenses||ie.completion_expenses||null;Pe&&(Pe.budgetTracking=Se,Pe.invoice=qe,Pe.creditNote=rt,Pe.completionExpenses=gt,Pe.creditNoteWfmData=he)}else console.warn("[useRequestDetails] No claimData found in response")}catch(je){console.error("[useRequestDetails] Error fetching claim details:",{error:(je==null?void 0:je.message)||je,status:(I=je==null?void 0:je.response)==null?void 0:I.status,statusText:(D=je==null?void 0:je.response)==null?void 0:D.statusText,responseData:(T=je==null?void 0:je.response)==null?void 0:T.data,requestId:F.requestId})}}const ne={...F,id:F.requestNumber||F.requestId,requestId:F.requestId,requestNumber:F.requestNumber,initiatorId:F.initiatorId||F.initiator_id,title:F.title,description:F.description,status:b(F.status),priority:(F.priority||"").toString().toLowerCase(),workflowType:F.workflowType||(F.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:q,approvals:H,participants:K,documents:ue,spectators:ee,summary:O,sla:(O==null?void 0:O.sla)||F.sla||null,initiator:{userId:((v=F.initiator)==null?void 0:v.userId)||((M=F.initiator)==null?void 0:M.user_id)||F.initiatorId||F.initiator_id,name:((P=F.initiator)==null?void 0:P.displayName)||((B=F.initiator)==null?void 0:B.email),role:((k=F.initiator)==null?void 0:k.designation)||void 0,department:((_=F.initiator)==null?void 0:_.department)||void 0,email:((L=F.initiator)==null?void 0:L.email)||void 0,phone:((R=F.initiator)==null?void 0:R.phone)||void 0,avatar:f((C=F.initiator)==null?void 0:C.displayName,(G=F.initiator)==null?void 0:G.email)},createdAt:F.createdAt,updatedAt:F.updatedAt,totalSteps:F.totalLevels||1,currentStepRaw:(O==null?void 0:O.currentLevel)||F.currentLevel||1,currentStep:Math.min(Math.max(1,(O==null?void 0:O.currentLevel)||F.currentLevel||1),F.totalLevels||1),auditTrail:_e,conclusionRemark:F.conclusionRemark||null,closureDate:F.closureDate||null,pauseInfo:Ze||null,claimDetails:Pe||null,proposalDetails:De||null,completionDetails:le||null,internalOrder:ye||null,internalOrders:ae||[],budgetTracking:(Pe==null?void 0:Pe.budgetTracking)||null,invoice:(Pe==null?void 0:Pe.invoice)||(Pe==null?void 0:Pe.invoice)||null,creditNote:(Pe==null?void 0:Pe.creditNote)||null,creditNoteWfmData:he||(Pe==null?void 0:Pe.creditNoteWfmData)||null,completionExpenses:(Pe==null?void 0:Pe.completionExpenses)||null,templateType:F.templateType||F.template_type,form16Submission:$.form16Submission||null};n(ne);const ge=(U=a==null?void 0:a.email)==null?void 0:U.toLowerCase(),ke=H.find(je=>{const ie=(je.status||"").toString().toUpperCase(),Se=(je.approverEmail||"").toLowerCase(),qe=je.levelNumber||0;return(ie==="PENDING"||ie==="IN_PROGRESS"||ie==="PAUSED")&&Se===ge&&qe===Q});u(ke||null);const Oe=a==null?void 0:a.userId;if(Oe){const je=K.some(ie=>(ie.participantType||ie.participant_type||"").toUpperCase()==="SPECTATOR"&&(ie.userId||ie.user_id)===Oe);g(je)}else g(!1)}catch($){console.error("[useRequestDetails] Error refreshing details:",$),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);x.useEffect(()=>{if(!t){c(!1);return}let w=!0;return c(!0),m(null),(async()=>{var I,D,T,v,M,P,B,k,_,L,R,C,G,U;try{const $=await Ks.getWorkflowDetails(t);if(!w||!$){w&&c(!1);return}const F=$.workflow||{},H=Array.isArray($.approvals)?$.approvals:[],K=Array.isArray($.participants)?$.participants:[],z=Array.isArray($.documents)?$.documents:[],O=$.summary||{},V=Array.isArray($.tatAlerts)?$.tatAlerts:[],Q=(F.priority||"").toString().toLowerCase(),q=(O==null?void 0:O.currentLevel)||F.currentLevel||1,ee=H.map(ie=>{const Se=ie.levelNumber||0,qe=(ie.status||"").toString().toUpperCase(),rt=ie.levelId||ie.level_id;let gt=b(ie.status);qe==="PAUSED"?gt="paused":Se>q&&qe!=="APPROVED"&&qe!=="REJECTED"?gt="waiting":Se===q&&(qe==="PENDING"||qe==="IN_PROGRESS")&&(gt=qe==="IN_PROGRESS"?"in-review":"pending");const It=V.filter(oe=>oe.levelId===rt);return{step:Se,levelId:rt,role:ie.levelName||ie.approverName||"Approver",status:gt,approver:ie.approverName||ie.approverEmail,approverId:ie.approverId||ie.approver_id,approverEmail:ie.approverEmail,tatHours:Number(ie.tatHours||0),elapsedHours:Number(ie.elapsedHours||0),remainingHours:Number(ie.remainingHours||0),tatPercentageUsed:Number(ie.tatPercentageUsed||0),actualHours:ie.elapsedHours!==void 0&&ie.elapsedHours!==null?Number(ie.elapsedHours):void 0,comment:ie.comments||void 0,timestamp:ie.actionDate||void 0,levelStartTime:ie.levelStartTime||ie.tatStartTime,tatAlerts:It}}),te=K.filter(ie=>(ie.participantType||"").toUpperCase()==="SPECTATOR").map(ie=>({name:ie.userName||ie.userEmail,role:"Spectator",avatar:f(ie.userName,ie.userEmail)})),ue=ie=>{var qe,rt;if(!ie)return;const Se=K.find(gt=>gt.userId===ie);return Se!=null&&Se.userName?Se.userName:F.initiatorId===ie?((qe=F.initiator)==null?void 0:qe.displayName)||((rt=F.initiator)==null?void 0:rt.email):ie},_e=z.map(ie=>{const Se=Number(ie.fileSize||0),qe=(Se/(1024*1024)).toFixed(2)+" MB";return{documentId:ie.documentId||ie.document_id,name:j(ie.originalFileName||ie.fileName),fileType:ie.fileType||ie.file_type||"",size:qe,sizeBytes:Se,uploadedBy:ue(ie.uploadedBy),uploadedAt:ie.uploadedAt}}),Ze=Array.isArray($.activities)?$.activities.filter(ie=>(ie.type||"").toLowerCase()!=="sla_warning"):[];let Ue=null;if(F.isPaused||!1)try{Ue=await Lu(F.requestId)}catch{}let De=null,le=null,ye=null,ae=null,he=[],ne=null;if(li(F)){try{const ie=await ve.get(`/dealer-claims/${F.requestId}/credit-note-wfm`),Se=ie.data??ie;ne=Array.isArray(Se==null?void 0:Se.data)?Se.data:Array.isArray(Se)?Se:[]}catch(ie){console.warn("[useRequestDetails] Error fetching credit note WFM data:",ie)}try{const ie=await ve.get(`/dealer-claims/${F.requestId}`),Se=((I=ie.data)==null?void 0:I.data)||ie.data;if(Se){De=Se.claimDetails||Se.claim_details,le=Se.proposalDetails||Se.proposal_details,ye=Se.completionDetails||Se.completion_details,ae=Se.internalOrder||Se.internal_order||null,he=Se.internalOrders||Se.internal_orders||[];const qe=Se.budgetTracking||Se.budget_tracking||null,rt=Se.invoice||null,gt=Se.creditNote||Se.credit_note||null,It=Se.completionExpenses||Se.completion_expenses||null;De&&(De.budgetTracking=qe,De.invoice=rt,De.creditNote=gt,De.completionExpenses=It,De.creditNoteWfmData=ne)}}catch(ie){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(ie==null?void 0:ie.message)||ie,status:(D=ie==null?void 0:ie.response)==null?void 0:D.status,requestId:F.requestId})}}const ge={id:F.requestNumber||F.requestId,requestId:F.requestId,title:F.title,description:F.description,priority:Q,status:b(F.status),workflowType:F.workflowType||(F.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:O,initiator:{name:((T=F.initiator)==null?void 0:T.displayName)||((v=F.initiator)==null?void 0:v.email),role:((M=F.initiator)==null?void 0:M.designation)||void 0,department:((P=F.initiator)==null?void 0:P.department)||void 0,email:((B=F.initiator)==null?void 0:B.email)||void 0,phone:((k=F.initiator)==null?void 0:k.phone)||void 0,avatar:f((_=F.initiator)==null?void 0:_.displayName,(L=F.initiator)==null?void 0:L.email)},createdAt:F.createdAt,updatedAt:F.updatedAt,totalSteps:F.totalLevels||1,currentStepRaw:(O==null?void 0:O.currentLevel)||F.currentLevel||1,currentStep:Math.min(Math.max(1,(O==null?void 0:O.currentLevel)||F.currentLevel||1),F.totalLevels||1),approvalFlow:ee,approvals:H,documents:_e,spectators:te,auditTrail:Ze,conclusionRemark:F.conclusionRemark||null,closureDate:F.closureDate||null,pauseInfo:Ue||null,claimDetails:De||null,proposalDetails:le||null,completionDetails:ye||null,internalOrder:ae||null,internalOrders:he||[],budgetTracking:(De==null?void 0:De.budgetTracking)||null,invoice:(De==null?void 0:De.invoice)||null,creditNote:(De==null?void 0:De.creditNote)||null,creditNoteWfmData:ne||(De==null?void 0:De.creditNoteWfmData)||null,completionExpenses:(De==null?void 0:De.completionExpenses)||null,templateType:F.templateType||F.template_type,form16Submission:$.form16Submission||null};n(ge);const ke=(R=a==null?void 0:a.email)==null?void 0:R.toLowerCase(),Oe=H.find(ie=>{const Se=(ie.status||"").toString().toUpperCase(),qe=(ie.approverEmail||"").toLowerCase(),rt=ie.levelNumber||0;return(Se==="PENDING"||Se==="IN_PROGRESS"||Se==="PAUSED")&&qe===ke&&rt===q});u(Oe||null);const je=a==null?void 0:a.userId;if(je){const ie=K.some(Se=>(Se.participantType||"").toUpperCase()==="SPECTATOR"&&Se.userId===je);g(ie)}else g(!1)}catch($){if(console.error("[useRequestDetails] Error loading request details:",$),w){if(((C=$==null?void 0:$.response)==null?void 0:C.status)===403){const F=((U=(G=$==null?void 0:$.response)==null?void 0:G.data)==null?void 0:U.message)||"You do not have permission to view this request. Access is restricted to the initiator, approvers, and spectators of this request.";m({denied:!0,message:F})}n(null)}}finally{w&&c(!1)}})(),()=>{w=!1}},[t,a]);const N=x.useMemo(()=>{if(r)return r;const w=s.find(I=>I.id===t||I.requestNumber===t||I.request_number===t);return w||null},[t,s,r]),S=x.useMemo(()=>{var D,T,v;if(!N||!a)return!1;const w=(D=a==null?void 0:a.email)==null?void 0:D.toLowerCase(),I=(v=(T=N.initiator)==null?void 0:T.email)==null?void 0:v.toLowerCase();return w===I},[N,a]),A=x.useMemo(()=>{var I;if(!N)return[];const w=[];return(I=N.initiator)!=null&&I.email&&w.push({email:N.initiator.email.toLowerCase(),participantType:"INITIATOR",name:N.initiator.name}),N.approvalFlow&&Array.isArray(N.approvalFlow)&&N.approvalFlow.forEach(D=>{D.approverEmail&&w.push({email:D.approverEmail.toLowerCase(),participantType:"APPROVER",name:D.approver})}),N.spectators&&Array.isArray(N.spectators)&&N.spectators.forEach(D=>{D.email&&w.push({email:D.email.toLowerCase(),participantType:"SPECTATOR",name:D.name})}),N.participants&&Array.isArray(N.participants)&&N.participants.forEach(D=>{const T=(D.userEmail||D.email||"").toLowerCase(),v=(D.participantType||D.participant_type||"").toUpperCase(),M=D.userName||D.user_name||D.name;T&&v&&!w.find(P=>P.email===T)&&w.push({email:T,participantType:v,name:M})}),w},[N]);return x.useEffect(()=>{if(!t||!r)return;const w=Vr();if(!w)return;const I=D=>{((D==null?void 0:D.requestId)===r.requestId||(D==null?void 0:D.requestNumber)===t)&&y()};return w.on("request:updated",I),()=>{w.off("request:updated",I)}},[t,r,y]),{request:N,apiRequest:r,loading:o,refreshing:i,refreshDetails:y,currentApprovalLevel:p,isSpectator:h,isInitiator:S,existingParticipants:A,accessDenied:d}}function Z0(t,s,a,r){const[n,i]=x.useState([]),[l,o]=x.useState(0),[c,d]=x.useState([]);return x.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 Ks.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 u=Vr();if(!u){console.error("[useRequestSocket] Socket not available");return}const h=r==null?void 0:r.userId,g=()=>{$o(u,p,h)};return u.connected?g():u.on("connect",g),()=>{m&&(u.off("connect",g),wp(u,p))}})(),()=>{m=!1}},[t,r]),x.useEffect(()=>{!t||!s||(async()=>{try{const m=await xn(t),p=s.auditTrail||[],u=[...m,...p];u.sort((h,g)=>{const f=new Date(h.createdAt||h.created_at||h.timestamp||0).getTime(),b=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return f-b}),i(u)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),x.useEffect(()=>{if(!t)return;const m=Vr();if(!m)return;const p=h=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await xn(t),f=(s==null?void 0:s.auditTrail)||[],b=[...g,...f].sort((j,y)=>{const N=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime(),S=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime();return N-S});i(b)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},u=h=>{const g=h.type==="breach"?"⏰":h.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const f=await Ks.getWorkflowDetails(t);f&&(Array.isArray(f.tatAlerts)&&f.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:h.message,icon:"/favicon.ico",tag:`tat-${h.requestId}-${h.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",u),()=>{m.off("noteHandler",p),m.off("worknote:new",p),m.off("tat:alert",u)}},[t,a,s]),x.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function Hn(t,s,a="SUPPORTING"){var l;const r=new FormData;r.append("file",t),r.append("requestId",s),r.append("category",a);const n=await ve.post("/documents",r,{headers:{"Content-Type":"multipart/form-data"}}),i=((l=n.data)==null?void 0:l.data)||n.data;return{documentId:(i==null?void 0:i.documentId)||(i==null?void 0:i.document_id)||"",storageUrl:(i==null?void 0:i.storageUrl)||(i==null?void 0:i.storage_url),fileName:(i==null?void 0:i.fileName)||(i==null?void 0:i.file_name)||t.name,originalFileName:(i==null?void 0:i.originalFileName)||(i==null?void 0:i.original_file_name)||t.name}}const O5=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],$5={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 wd(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(!O5.includes(a))return!1;const r=$5[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(", "))),W.error(r,{description:i||n,duration:8e3,style:{background:"#fef2f2",border:"1px solid #fca5a5",color:"#991b1b"}}),!0}function J0(t,s){const[a,r]=x.useState(!1),[n,i]=x.useState(null),[l,o]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=x.useState({show:!1,errors:[]});x.useEffect(()=>{(async()=>{try{const g=await ua("DOCUMENT_POLICY"),f={};g.forEach(N=>{f[N.configKey]=N.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(N=>N.trim().toLowerCase());o({maxFileSizeMB:b,allowedFileTypes:y})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=h=>{const g=l.maxFileSizeMB*1024*1024;if(h.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(h.size/(1024*1024)).toFixed(2)}MB`};const f=h.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 h=>{var y,N;const g=h.target.files;if(!g||g.length===0)return;const f=Array.from(g),b=[],j=[];if(f.forEach(S=>{const A=m(S);A.valid?j.push(S):b.push({fileName:S.name,reason:A.reason||"Unknown validation error"})}),b.length>0&&d({show:!0,errors:b}),j.length===0){h.target&&(h.target.value="");return}r(!0);try{const S=j[0],A=t==null?void 0:t.requestId;if(!A){W.error("Request ID not found");return}S&&await Hn(S,A,"SUPPORTING"),await s(),j.length<f.length?W.warning(`${j.length} of ${f.length} file(s) were uploaded. ${b.length} file(s) were rejected.`):W.success("Document uploaded successfully")}catch(S){console.error("[useDocumentUpload] Upload error:",S),wd(S)||W.error(((N=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:N.message)||"Failed to upload document")}finally{r(!1),h.target&&(h.target.value="")}};return{uploadingDocument:a,handleDocumentUpload:p,triggerFileInput:()=>{const h=document.createElement("input");h.type="file",h.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),h.onchange=p,h.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const U5="modulepreload",B5=function(t){return"/"+t},mh={},po=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=B5(c),c in mh)return;mh[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":U5,d||(p.as="script"),p.crossOrigin="",p.href=c,o&&p.setAttribute("nonce",o),document.head.appendChild(p),d)return new Promise((u,h)=>{p.addEventListener("load",u),p.addEventListener("error",()=>h(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 q0(t,s,a,r,n,i,l){const[o,c]=x.useState(""),[d,m]=x.useState(!1),[p,u]=x.useState(!1),[h,g]=x.useState(!1),[f,b]=x.useState(0),[j,y]=x.useState(!1),[N,S]=x.useState(!1),[A,w]=x.useState(0),I=async()=>{var P;const v=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),M=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(v||M){c(v||M),g(!!M);return}try{const{getConclusion:B}=await po(async()=>{const{getConclusion:_}=await import("./conclusionApi-BZ5VorhU.js");return{getConclusion:_}},__vite__mapDeps([0,1,2,3,4,5,6,7])),k=await B(t.requestId||s);k&&(k.aiGeneratedRemark||k.finalRemark)&&(c(k.finalRemark||k.aiGeneratedRemark||""),g(!!k.aiGeneratedRemark))}catch(B){((P=B==null?void 0:B.response)==null?void 0:P.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",B)}},D=async()=>{if(!N)try{m(!0),y(!1);const{generateConclusion:v}=await po(async()=>{const{generateConclusion:k}=await import("./conclusionApi-BZ5VorhU.js");return{generateConclusion:k}},__vite__mapDeps([0,1,2,3,4,5,6,7])),M=await v(t.requestId||s),P=f+1;if(b(P),!(M!=null&&M.aiGeneratedRemark)||M.aiGeneratedRemark.toLowerCase().includes("unable to generate")||M.aiGeneratedRemark.toLowerCase().includes("sorry")){const k=A+1;w(k),k>=2?(S(!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((M==null?void 0:M.aiGeneratedRemark)||""),g(!1);return}c(M.aiGeneratedRemark),g(!0),w(0),P>=2&&(S(!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 M=A+1;w(M),g(!1),M>=2?(S(!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)}},T=async()=>{var M,P;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{u(!0);const{finalizeConclusion:B}=await po(async()=>{const{finalizeConclusion:k}=await import("./conclusionApi-BZ5VorhU.js");return{finalizeConclusion:k}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await B(t.requestId||s,o),i==null||i({success:!0,title:"Request Closed with Successful Completion",message:"The request has been finalized and moved to Closed Requests."}),l==null||l(!0),await r(),setTimeout(()=>{n?(n(),setTimeout(()=>{window.location.hash="#/closed-requests"},100)):window.location.hash="#/closed-requests"},2e3)}catch(B){i==null||i({success:!1,title:"Error",message:((P=(M=B.response)==null?void 0:M.data)==null?void 0:P.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{u(!1)}};return x.useEffect(()=>{var k;const v=(k=t==null?void 0:t.status)==null?void 0:k.toLowerCase();if(!((v==="approved"||v==="rejected"||v==="closed")&&a&&!o))return;const P=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),B=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);P||B?(c(P||B),g(!!B)):I()},[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:h,handleGenerateConclusion:D,handleFinalizeConclusion:T,generationAttempts:f,generationFailed:j,maxAttemptsReached:N}}function ef(t,s,a){const[r,n]=x.useState(!1),[i,l]=x.useState(!1),[o,c]=x.useState(!1),[d,m]=x.useState(!1),[p,u]=x.useState(!1),[h,g]=x.useState(!1),[f,b]=x.useState(null),[j,y]=x.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:p,setShowSkipApproverModal:u,showActionStatusModal:h,setShowActionStatusModal:g,skipApproverData:f,setSkipApproverData:b,actionStatus:j,setActionStatus:y,handleApproveConfirm:async D=>{var v,M;const T=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!T){alert("Approval level not found");return}await Vn(t,T,D||""),await new Promise(P=>setTimeout(P,500)),await a(),(v=window==null?void 0:window.closeModal)==null||v.call(window),(M=window==null?void 0:window.toast)==null||M.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var v,M;if(!(D!=null&&D.trim())){alert("Comments & remarks are required");return}const T=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!T){alert("Approval level not found");return}await Rr(t,T,D.trim(),D.trim()),await a(),(v=window==null?void 0:window.closeModal)==null||v.call(window),(M=window==null?void 0:window.toast)==null||M.call(window,"Rejected successfully")},handleAddApprover:async(D,T,v)=>{var M,P;try{await lg(t,D,T,v),await a(),c(!1),y==null||y({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${v} with ${T}h TAT`}),g==null||g(!0)}catch(B){throw y==null||y({success:!1,title:"Failed to Add Approver",message:((P=(M=B==null?void 0:B.response)==null?void 0:M.data)==null?void 0:P.error)||"Failed to add approver. Please try again."}),g==null||g(!0),B}},handleSkipApprover:async D=>{var T,v;if(f)try{await z1(t,f.levelId,D),await a(),u(!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(M){throw y==null||y({success:!1,title:"Failed to Skip Approver",message:((v=(T=M==null?void 0:M.response)==null?void 0:T.data)==null?void 0:v.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),M}},handleAddSpectator:async D=>{var T,v;try{await og(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(M){throw y==null||y({success:!1,title:"Failed to Add Spectator",message:((v=(T=M==null?void 0:M.response)==null?void 0:T.data)==null?void 0:v.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),M}}}}function V5({requestId:t,request:s,onRefresh:a}){const[r,n]=x.useState(null),[i,l]=x.useState(!0),[o,c]=x.useState(null),m=!!(s==null?void 0:s.form16Submission),p=!!r&&r.status!=="withdrawn";x.useEffect(()=>{if(!t){l(!1);return}let g=!1;return(async()=>{try{const f=await Gp(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 u=async()=>{if(!(!t||!window.confirm("Cancel this Form 16 submission? The request will be marked as rejected."))){c("cancel");try{await Uv(t),W.success("Submission cancelled"),a==null||a()}catch(g){W.error(g instanceof Error?g.message:"Failed to cancel submission")}finally{c(null)}}},h=async()=>{if(!(!t||!window.confirm("Mark this submission as resubmission needed? The dealer will need to resubmit Form 16."))){c("resubmit");try{await Bv(t),W.success("Marked as resubmission needed"),a==null||a()}catch(g){W.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(ce,{className:"pb-2",children:[e.jsxs(de,{className:"text-sm flex items-center gap-2 text-blue-800",children:[e.jsx(Mt,{className:"w-4 h-4"}),"Form 16 actions"]}),e.jsx(we,{className:"text-xs text-gray-600",children:"View the document in the Documents tab. Cancel submission or mark resubmission needed."})]}),e.jsxs(J,{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:u,disabled:!!o,children:[o==="cancel"?e.jsx(ze,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(yt,{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:h,disabled:!!o,children:[o==="resubmit"?e.jsx(ze,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(rp,{className:"w-3 h-3 mr-1"}),"Resubmission needed"]})]})]})}const z5=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 Br({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(Fe,{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 "]}),bs(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&z5(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(Nt,{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(Tt,{className:"w-4 h-4"})})]})]})}function H5({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l,isSpectator:o=!1}){var m,p,u,h;const c=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",d=g=>{const f=String(g||"").trim();if(!f)return"Document";const b=f.lastIndexOf("."),j=b>0&&b<f.length-1,y=j?f.slice(0,b):f,N=j?f.slice(b):"";return`${y.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[redacted-email]").replace(/(?:\+?\d[\d\s().-]{8,}\d)/g,"[redacted-phone]").replace(/\s{2,}/g," ").trim()||"Document"}${N}`};return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[c&&((p=(m=t==null?void 0:t.form16Submission)==null?void 0:m.previousDocuments)==null?void 0:p.length)>0&&e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base text-amber-800",children:[e.jsx(Fe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-amber-600"}),"Previous submission(s) – same quarter"]}),e.jsxs(we,{className:"text-xs sm:text-sm mt-1",children:["Documents from earlier Form 16A submissions for this request's financial year and quarter only (",(u=t==null?void 0:t.form16Submission)==null?void 0:u.financialYear," ",(h=t==null?void 0:t.form16Submission)==null?void 0:h.quarter,")"]})]}),e.jsx(J,{children:e.jsx("div",{className:"space-y-4",children:(()=>{const g=new Map;for(const f of t.form16Submission.previousDocuments){const b=f.requestId||f.request_id,j=f.requestNumber||b;g.has(j)||g.set(j,[]),g.get(j).push(f)}return Array.from(g.entries()).map(([f,b])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600",children:["Request ",f]}),e.jsx("div",{className:"space-y-2 pl-2 border-l-2 border-amber-200",children:b.map((j,y)=>{const N=j.documentId??j.document_id,S=d(j.originalFileName??j.original_file_name??j.fileName??j.file_name??"Document"),A=Number(j.fileSize??j.file_size??0),w=A>0?(A/(1024*1024)).toFixed(2)+" MB":"—";return e.jsx(Br,{document:{documentId:N,name:S,fileType:j.fileType??j.file_type??"",size:w,sizeBytes:A,uploadedBy:j.uploadedBy??j.uploaded_by,uploadedAt:j.uploadedAt??j.uploaded_at},onPreview:I=>i(I),onDownload:l,testId:"form16-previous-document"},N||y)})})]},f))})()})})]}),e.jsxs(Z,{children:[e.jsx(ce,{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(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Fe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),c?"Current submission":"Request Documents"]}),e.jsx(we,{className:"text-xs sm:text-sm mt-1",children:c?"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"||o,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(ys,{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(J,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((g,f)=>e.jsx(Br,{document:g,onPreview:b=>i(b),onDownload:l,testId:"request-document"},f))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),!c&&e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ys,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(we,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(J,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((g,f)=>e.jsx(Br,{document:{documentId:g.attachmentId||"",name:g.name,fileType:g.type||"",size:g.size?`${(g.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:g.size,uploadedBy:g.uploadedBy,uploadedAt:g.uploadedAt},onPreview:b=>i(b),onDownload:async b=>{const{downloadWorkNoteAttachment:j}=require("@/services/workflowApi");await j(b)},testId:"worknote-attachment"},g.attachmentId||f))}):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 G5=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"}}},uh=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending",icon:it,iconColor:"text-yellow-600"};case"paused":return{color:"bg-gray-400 text-gray-100 border-gray-500",label:"paused",icon:ss,iconColor:"text-gray-600"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review",icon:Et,iconColor:"text-blue-600"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Be,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:Be,iconColor:"text-gray-600"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped",icon:Bt,iconColor:"text-orange-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:ss,iconColor:"text-gray-600"}}},W5=t=>{switch(t){case"approval":case"approved":return e.jsx(Be,{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(Ys,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Et,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(fl,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Fe,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(it,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(xl,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(ss,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(Bt,{className:"w-5 h-5 text-gray-600"})}};function Y5(t){const s=t==null?void 0:t.form16Submission;if(!s)return[];const a=[],r=Array.isArray(s.previousSubmissions)?s.previousSubmissions:[];for(const h of r){const g=h.requestNumber||h.requestId||"",f=h.submittedDate?new Date(h.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}),h.creditNoteNumber){const b=h.creditNoteIssueDate?new Date(h.creditNoteIssueDate).toISOString():f;a.push({type:"status_change",action:"Credit note issued",details:`Credit note ${h.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),u=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}):u?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 h=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:h})}return a.sort((h,g)=>new Date(h.timestamp).getTime()-new Date(g.timestamp).getTime())}function Q5({request:t}){const s=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",a=s?Y5(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(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Bt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(we,{className:"text-xs sm:text-sm",children:s?"Form 16 submission steps and audit trail":"Complete audit trail of all request activities"})]}),e.jsx(J,{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:W5(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:bs(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(Bt,{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 tf({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[a?e.jsx(Be,{className:"w-5 h-5 text-green-600"}):e.jsx(Je,{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(Be,{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(Dt,{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 sf({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=x.useState(""),[l,o]=x.useState(!1),[c,d]=x.useState([]),[m,p]=x.useState(!1),[u,h]=x.useState(null),g=x.useRef(null),f=x.useRef(null),[b,j]=x.useState({open:!1,type:"error",email:"",message:""}),[y,N]=x.useState({open:!1,violations:[]}),[S,A]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});x.useEffect(()=>{t&&(async()=>{var M;try{const P=await ua("WORKFLOW_SHARING"),B=await ua("TAT_SETTINGS"),k=[...P,...B],_={};k.forEach(L=>{_[L.configKey]=L.configValue}),A({maxApprovalLevels:parseInt(_.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(_.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((M=_.ALLOW_ADD_SPECTATOR)==null?void 0:M.toLowerCase())==="true",maxSpectators:parseInt(_.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(P){console.error("Failed to load system policy:",P)}})()},[t]);const w=async()=>{var R,C;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 P=r.find(G=>(G.email||"").toLowerCase()===v);if(P){const G=((R=P.participantType)==null?void 0:R.toUpperCase())||"PARTICIPANT",U=P.name||v;if(G==="INITIATOR"){j({open:!0,type:"error",email:v,message:`${U} is the request initiator and cannot be added as a spectator.`});return}else if(G==="APPROVER"){j({open:!0,type:"error",email:v,message:`${U} is already an approver on this request and cannot be added as a spectator.`});return}else if(G==="SPECTATOR"){j({open:!0,type:"error",email:v,message:`${U} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:v,message:`${U} is already a participant on this request.`});return}}const B=[];S.allowSpectators||B.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const _=r.filter(G=>(G.participantType||"").toUpperCase()==="SPECTATOR").length;_>=S.maxSpectators&&B.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:_,maxValue:S.maxSpectators});const L=r.length+1;if(L>S.maxParticipants&&B.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:L,maxValue:S.maxParticipants}),B.length>0){N({open:!0,violations:B});return}if(!u||u.email.toLowerCase()!==v)try{const U=((C=(await Na(v,1)).data)==null?void 0:C.data)||[];if(U.length===0){j({open:!0,type:"not-found",email:v,message:""});return}const $=U[0];await ya({userId:$.userId,email:$.email,displayName:$.displayName,firstName:$.firstName,lastName:$.lastName,department:$.department,phone:$.phone,mobilePhone:$.mobilePhone,designation:$.designation,jobTitle:$.jobTitle,manager:$.manager,employeeId:$.employeeId,employeeNumber:$.employeeNumber,secondEmail:$.secondEmail,location:$.location})}catch(G){console.error("Failed to validate spectator:",G),j({open:!0,type:"error",email:v,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(v),i(""),h(null),s()}catch(G){console.error("Failed to add spectator:",G)}finally{o(!1)}},I=()=>{l||(i(""),h(null),d([]),p(!1),s())};x.useEffect(()=>{c.length>0&&f.current&&f.current.scrollTo({top:f.current.scrollHeight,behavior:"smooth"})},[c.length]),x.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const D=v=>{if(i(v),u&&u.email.toLowerCase()!==v.toLowerCase()&&h(null),g.current&&clearTimeout(g.current),!v||!v.startsWith("@")||v.length<2){d([]),p(!1);return}p(!0),g.current=setTimeout(async()=>{var M;try{const P=v.slice(1),k=((M=(await Na(P,10)).data)==null?void 0:M.data)||[];d(k)}catch(P){console.error("Search failed:",P),d([])}finally{p(!1)}},300)},T=async v=>{try{await ya({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),h(v),d([]),p(!1)}catch(M){console.error("Failed to ensure user exists:",M),j({open:!0,type:"error",email:v.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(xt,{open:t,onOpenChange:I,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:I,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(yt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{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(Nt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref: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(bl,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Re,{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:()=>T(v),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(v.displayName||v.email).split(" ").map(M=>M[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:I,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:w,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(xt,{open:b.open,onOpenChange:v=>j(M=>({...M,open:v})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:b.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(_t,{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(gl,{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(Dt,{children:e.jsx(E,{onClick:()=>j(v=>({...v,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(ji,{open:y.open,onClose:()=>N({open:!1,violations:[]}),violations:y.violations,policyDetails:{maxApprovalLevels:S.maxApprovalLevels,maxParticipants:S.maxParticipants,allowSpectators:S.allowSpectators,maxSpectators:S.maxSpectators}})]})}function af({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=x.useState(""),[d,m]=x.useState(24),[p,u]=x.useState(null),[h,g]=x.useState(!1),[f,b]=x.useState([]),[j,y]=x.useState(!1),[N,S]=x.useState(null),A=x.useRef(null),w=x.useRef(null),[I,D]=x.useState({open:!1,type:"error",email:"",message:""}),T=n.filter(C=>C&&(C.status==="approved"||C.status==="rejected"||C.status==="skipped")),v=Math.max(1,T.length+1),M=Math.max(1,n.length+1),P=M>=v?Array.from({length:M-v+1},(C,G)=>v+G):[v];x.useEffect(()=>{P.length>0&&p===null&&u(P[0]||null)},[P.length,p]);const B=async()=>{var H,K;const C=o.trim().toLowerCase();if(!C){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(C)){D({open:!0,type:"error",email:C,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 U=n.length>0?Math.max(...n.map(z=>z.levelNumber),0):0,$=p>U?p:U+1;if(i&&$>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${p} would result in ${$} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:$,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${U} level(s).`});return}const F=r.find(z=>(z.email||"").toLowerCase()===C);if(F){const z=((H=F.participantType)==null?void 0:H.toUpperCase())||"PARTICIPANT",O=F.name||C;if(z==="INITIATOR"){D({open:!0,type:"error",email:C,message:`${O} is the request initiator and cannot be added as an approver.`});return}else if(z==="APPROVER"){D({open:!0,type:"error",email:C,message:`${O} is already an approver on this request.`});return}else if(z==="SPECTATOR"){D({open:!0,type:"error",email:C,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:C,message:`${O} is already a participant on this request.`});return}}if(!N||N.email.toLowerCase()!==C)try{const O=((K=(await Na(C,1)).data)==null?void 0:K.data)||[];if(O.length===0){D({open:!0,type:"not-found",email:C,message:""});return}const V=O[0];await ya({userId:V.userId,email:V.email,displayName:V.displayName,firstName:V.firstName,lastName:V.lastName,department:V.department,phone:V.phone,mobilePhone:V.mobilePhone,designation:V.designation,jobTitle:V.jobTitle,manager:V.manager,employeeId:V.employeeId,employeeNumber:V.employeeNumber,secondEmail:V.secondEmail,location:V.location})}catch(z){console.error("Failed to validate approver:",z),D({open:!0,type:"error",email:C,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(C,d,p),c(""),m(24),u(null),S(null),s()}catch(z){console.error("Failed to add approver:",z)}finally{g(!1)}},k=()=>{h||(c(""),m(24),u(null),S(null),b([]),y(!1),s())},_=C=>{const G=C.toLowerCase();return G==="approved"?e.jsx(Be,{className:"w-4 h-4 text-green-600"}):G==="rejected"?e.jsx(St,{className:"w-4 h-4 text-red-600"}):G==="skipped"?e.jsx(Je,{className:"w-4 h-4 text-orange-600"}):G==="in-review"||G==="pending"?e.jsx(it,{className:"w-4 h-4 text-blue-600"}):e.jsx(it,{className:"w-4 h-4 text-gray-400"})};x.useEffect(()=>{f.length>0&&w.current&&w.current.scrollTo({top:w.current.scrollHeight,behavior:"smooth"})},[f.length]),x.useEffect(()=>()=>{A.current&&clearTimeout(A.current)},[]);const L=C=>{if(c(C),N&&N.email.toLowerCase()!==C.toLowerCase()&&S(null),A.current&&clearTimeout(A.current),!C||!C.startsWith("@")||C.length<2){b([]),y(!1);return}y(!0),A.current=setTimeout(async()=>{var G;try{const U=C.slice(1),F=((G=(await Na(U,10)).data)==null?void 0:G.data)||[];b(F)}catch(U){console.error("Search failed:",U),b([])}finally{y(!1)}},300)},R=async C=>{try{await ya({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}),c(C.email),S(C),b([]),y(!1)}catch(G){console.error("Failed to ensure user exists:",G),D({open:!0,type:"error",email:C.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(xt,{open:t,onOpenChange:k,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:k,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:h,children:[e.jsx(yt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{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(qt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:w,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(C=>C.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(C=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${C.status==="approved"?"bg-green-100 border border-green-200":C.status==="rejected"?"bg-red-100 border border-red-200":C.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:C.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:C.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[C.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[_(C.status),e.jsx(re,{variant:"outline",className:`text-xs ${C.status==="approved"?"bg-green-50 text-green-700 border-green-300":C.status==="rejected"?"bg-red-50 text-red-700 border-red-300":C.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:C.status})]})]},C.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(se,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(He,{value:(p==null?void 0:p.toString())||"",onValueChange:C=>u(Number(C)),disabled:h,children:[e.jsx(We,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select level"})}),e.jsx(Ye,{children:P.map(C=>e.jsx(X,{value:C.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",C]}),C<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",C,")"]})]})},C))})]}),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(se,{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(Re,{type:"number",min:"1",max:"720",value:d,onChange:C=>m(Number(C.target.value)),className:"h-11 border-gray-300 flex-1",disabled:h,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(it,{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(bl,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Re,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:C=>L(C.target.value),className:"pl-10 h-11 border-gray-300",disabled:h,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(C=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>R(C),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(C.displayName||C.email).split(" ").map(G=>G[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:C.displayName||[C.firstName,C.lastName].filter(Boolean).join(" ")||C.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:C.email}),C.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:C.designation})]})]})},C.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:k,className:"flex-1 h-11 border-gray-300",disabled:h,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:B,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:h||!o.trim()||!p||!d,children:[e.jsx(qt,{className:"w-4 h-4 mr-2"}),h?"Adding...":`Add at Level ${p||"?"}`]})]})]}),e.jsx(xt,{open:I.open,onOpenChange:C=>D(G=>({...G,open:C})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:I.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[I.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:I.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(gl,{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."]})})]}),I.type==="error"&&e.jsxs(e.Fragment,{children:[I.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:I.email}),"."]}),I.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:I.message})})]})]})})]}),e.jsx(Dt,{children:e.jsx(E,{onClick:()=>D(C=>({...C,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const K5=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"}},X5=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},Z5=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 _a(s)},J5=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",xh=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Fe,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(ip,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Fe,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Fe,{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(Mi,{className:`${s} text-purple-600`}):e.jsx(xl,{className:`${s} text-gray-600`})};function rf({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 u=Va(),h=t||u.requestId||"",[g,f]=x.useState(""),[b,j]=x.useState(""),[y,N]=x.useState(!1),[S,A]=x.useState([]),[w,I]=x.useState(!1),[D,T]=x.useState([]),[v,M]=x.useState(null),[P,B]=x.useState(null),[k,_]=x.useState(!1),[L,R]=x.useState(!1),[C,G]=x.useState(!1),[U,$]=x.useState({success:!0,title:"",message:""}),F=x.useRef(null),H=x.useRef(null),K=x.useRef(null),z=x.useRef(!1),[O,V]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[Q,q]=x.useState({open:!1,errors:[]}),ee=x.useMemo(()=>({id:h,title:n||"Request Details"}),[h,n]),[te,ue]=x.useState([]),_e=te.filter(oe=>oe.status==="online"),Ze=S.filter(oe=>oe.content.toLowerCase().includes(b.toLowerCase())||oe.user.name.toLowerCase().includes(b.toLowerCase())),Ue=x.useMemo(()=>o!==void 0?o:!v||te.length===0?!1:te.some(oe=>{const Me=oe.userId||oe.user_id,me=(oe.role||"").toString().toUpperCase(),Xe=(oe.participantType||oe.participant_type||"").toString().toUpperCase();return Me===v&&(me==="SPECTATOR"||Xe==="SPECTATOR")}),[o,v,te]);x.useEffect(()=>{},[te]),x.useEffect(()=>{!h||!v||s||(async()=>{try{const oe=await xn(h),Me=Array.isArray(oe)?oe.map(me=>{const Xe=me.userId||me.user_id;return{id:me.noteId||me.id||String(Math.random()),user:{name:me.userName||"User",avatar:(me.userName||"U").slice(0,2).toUpperCase(),role:me.userRole||"Participant"},content:me.message||"",timestamp:me.createdAt||new Date().toISOString(),isCurrentUser:Xe===v,attachments:Array.isArray(me.attachments)?me.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}}):[];A(Me)}catch(oe){console.error("[WorkNoteChat] Failed to load messages:",oe)}})()},[h,v,s]);const Pe=x.useMemo(()=>{const oe=[];return S.forEach(Me=>{Me.attachments&&Me.attachments.length>0&&Me.attachments.forEach(me=>{oe.push({attachmentId:me.attachmentId||me.attachment_id,name:me.fileName||me.file_name||me.name||"Untitled",fileName:me.fileName||me.file_name||me.name||"Untitled",size:me.fileSize||me.file_size,type:me.fileType||me.file_type||me.type||"file",uploadedBy:Me.user.name,uploadedAt:Me.timestamp,url:me.storageUrl||me.storage_url||me.url||"#"})})}),oe},[S]);x.useEffect(()=>{i&&Pe.length>=0&&i(Pe)},[Pe,i]);const De=x.useMemo(()=>te.map(oe=>({email:(oe.email||"").toLowerCase(),participantType:oe.role==="Initiator"?"INITIATOR":oe.role==="Approver"?"APPROVER":oe.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:oe.name})),[te]),le=oe=>{if(!oe)return"Participant";switch(oe.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return oe.charAt(0).toUpperCase()+oe.slice(1).toLowerCase()}},ye=()=>{var oe;(oe=F.current)==null||oe.scrollIntoView({behavior:"smooth"})};x.useEffect(()=>{ye()},[S]);const ae=oe=>{switch(oe.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return oe.charAt(0).toUpperCase()+oe.slice(1).toLowerCase()}};x.useEffect(()=>{z.current||h&&(async()=>{try{const oe=await Ps(h),Me=Array.isArray(oe==null?void 0:oe.participants)?oe.participants:[];if(Me.length===0)return;const me=Me.map(Ke=>{const lt=Ke.participantType||Ke.participant_type||"participant",et=Ke.userId||Ke.user_id||"";return{name:Ke.userName||Ke.user_name||Ke.user_email||Ke.userEmail||"User",avatar:(Ke.userName||Ke.user_name||Ke.user_email||"U").toString().split(" ").map(ut=>ut[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:ae(lt.toString()),status:"offline",email:Ke.userEmail||Ke.user_email||"",permissions:["read","write","mention"],userId:et}});z.current=!0,ue(me);let Xe=0;const Qe=3,nt=()=>{K.current&&K.current.connected?(K.current.emit("request:online-users",{requestId:h}),Xe++,Xe<Qe&&setTimeout(nt,500)):(Xe++,Xe<Qe&&setTimeout(nt,200))};setTimeout(nt,100)}catch(oe){console.error("[WorkNoteChat] ❌ Failed to load participants:",oe)}})()},[h]),x.useEffect(()=>()=>{h&&(z.current=!1)},[h]),x.useEffect(()=>{const oe=localStorage.getItem("userData");if(oe)try{const Me=JSON.parse(oe),me=(Me==null?void 0:Me.id)||(Me==null?void 0:Me.userId)||(Me==null?void 0:Me.user_id)||null;M(me)}catch(Me){console.error("[WorkNoteChat] Failed to parse userData:",Me)}},[]),x.useEffect(()=>{(async()=>{try{const Me=await ua("DOCUMENT_POLICY"),me={};Me.forEach(Ke=>{me[Ke.configKey]=Ke.configValue});const Xe=parseInt(me.MAX_FILE_SIZE_MB||"10"),nt=(me.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Ke=>Ke.trim().toLowerCase());V({maxFileSizeMB:Xe,allowedFileTypes:nt})}catch(Me){console.error("Failed to load document policy:",Me)}})()},[]),x.useEffect(()=>{if(!v)return;let oe=h;return(async()=>{var Me;try{const me=await Ps(h);(Me=me==null?void 0:me.workflow)!=null&&Me.requestId&&(oe=me.workflow.requestId)}catch{}try{const me=Vr();r?ue(vt=>vt.map(Pt=>Pt.userId===v?{...Pt,status:"online"}:Pt)):($o(me,oe,v),ue(vt=>vt.map(Pt=>Pt.userId===v?{...Pt,status:"online"}:Pt)));const Xe=vt=>{const pt=(vt==null?void 0:vt.note)||vt;if(!pt)return;const Pt=pt.noteId||pt.id;A(Ss=>{if(Ss.some(Lt=>Lt.id===Pt))return Ss;const as=pt.userName||pt.user_name||"User",za=pt.userRole||pt.user_role,Ha=le(za),br=pt.userId||pt.user_id,wa={id:Pt||String(Date.now()),user:{name:as,avatar:as.split(" ").map(Lt=>Lt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ha},content:pt.message||"",timestamp:pt.createdAt||new Date().toISOString(),isCurrentUser:br===v,attachments:Array.isArray(pt.attachments)?pt.attachments.map(Lt=>({attachmentId:Lt.attachmentId||Lt.attachment_id,name:Lt.fileName||Lt.file_name||Lt.name,fileName:Lt.fileName||Lt.file_name||Lt.name,url:Lt.storageUrl||Lt.storage_url||Lt.url||"#",type:Lt.fileType||Lt.file_type||Lt.type||"file",fileType:Lt.fileType||Lt.file_type||Lt.type||"file",fileSize:Lt.fileSize||Lt.file_size})):void 0};return[...Ss,wa]})},Qe=vt=>{ue(pt=>pt.length===0||!pt.find(as=>as.userId===vt.userId)?pt:pt.map(as=>as.userId===vt.userId?{...as,status:"online"}:as))},nt=vt=>{vt.userId!==v&&ue(pt=>pt.length===0||!pt.find(as=>as.userId===vt.userId)?pt:pt.map(as=>as.userId===vt.userId?{...as,status:"offline"}:as))},Ke=vt=>{ue(pt=>pt.length===0?pt:pt.map(Ss=>{const as=Ss.userId||"";if(as===v)return{...Ss,status:"online"};const Ha=vt.userIds.includes(as);return{...Ss,status:Ha?"online":"offline"}}))},lt=()=>{ue(vt=>vt.map(Pt=>Pt.userId===v?{...Pt,status:"online"}:Pt)),r||$o(me,oe,v),z.current&&(me.emit("request:online-users",{requestId:oe}),setTimeout(()=>me.emit("request:online-users",{requestId:oe}),300),setTimeout(()=>me.emit("request:online-users",{requestId:oe}),800))},et=vt=>{console.error("[WorkNoteChat] ❌ Socket error:",vt)},ut=vt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",vt),ue(pt=>pt.map(Pt=>Pt.userId===v?Pt:{...Pt,status:"offline"}))},Hs=vt=>{vt.includes("presence")||vt.includes("worknote")||vt.includes("request")};me.on("connect",lt),me.on("disconnect",ut),me.on("error",et),me.on("worknote:new",Xe),me.on("presence:join",Qe),me.on("presence:leave",nt),me.on("presence:online",Ke),me.onAny(Hs),K.current=me,me.connected&&z.current&&(me.emit("request:online-users",{requestId:oe}),setTimeout(()=>{me.emit("request:online-users",{requestId:oe})},300),setTimeout(()=>{me.emit("request:online-users",{requestId:oe})},800),setTimeout(()=>{me.emit("request:online-users",{requestId:oe})},1500));const is=()=>{me.off("connect",lt),me.off("disconnect",ut),me.off("error",et),me.off("worknote:new",Xe),me.off("presence:join",Qe),me.off("presence:leave",nt),me.off("presence:online",Ke),me.offAny(Hs),r||wp(me,oe),K.current=null};window.__wn_cleanup=is}catch{}})(),()=>{var Me;try{(Me=window.__wn_cleanup)==null||Me.call(window)}catch{}}},[h,v,r]);const he=async()=>{if(g.trim()||D.length>0){const oe=rt(g),Me=oe.map(Qe=>{const nt=te.find(Ke=>Ke.name.toLowerCase().includes(Qe.toLowerCase()));return nt==null?void 0:nt.userId}).filter(Boolean),me=D.map(Qe=>({name:Qe.name,url:URL.createObjectURL(Qe),type:Qe.type.split("/")[1]||"file"})),Xe={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:oe,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:me.length>0?me:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await ig(h,{message:g,mentions:Me},D);const Qe=await xn(h),nt=Array.isArray(Qe)?Qe.map(Ke=>{const lt=Ke.userId||Ke.user_id;return{id:Ke.noteId||Ke.id||String(Math.random()),user:{name:Ke.userName||"User",avatar:(Ke.userName||"U").slice(0,2).toUpperCase(),role:Ke.userRole||"Participant"},content:Ke.message||"",timestamp:Ke.createdAt||new Date().toISOString(),isCurrentUser:lt===v,attachments:Array.isArray(Ke.attachments)?Ke.attachments.map(et=>({attachmentId:et.attachmentId||et.attachment_id,name:et.fileName||et.file_name||et.name,fileName:et.fileName||et.file_name||et.name,url:et.storageUrl||et.storage_url||et.url||"#",type:et.fileType||et.file_type||et.type||"file",fileType:et.fileType||et.file_type||et.type||"file",fileSize:et.fileSize||et.file_size})):void 0}}):[];A(nt)}catch{A(Qe=>[...Qe,Xe])}f(""),T([])}};x.useEffect(()=>{if(s&&Array.isArray(s))try{const Me=s.filter(me=>(me.type||"").toLowerCase()!=="sla_warning").map(me=>{var Qe;if(me.type||me.activityType||me.isSystem)return{id:me.id||`activity-${me.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:me.details||me.action||me.content||"",timestamp:me.timestamp||me.createdAt||me.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const nt=me.userName||me.user_name||((Qe=me.user)==null?void 0:Qe.name)||"User",Ke=me.userRole||me.user_role,lt=le(Ke),et=me.userId||me.user_id;return{id:me.noteId||me.note_id||me.id||String(Math.random()),user:{name:nt,avatar:nt.split(" ").map(ut=>ut[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:lt},content:me.message||me.content||"",timestamp:me.createdAt||me.created_at||me.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(me.attachments)?me.attachments.map(ut=>({attachmentId:ut.attachmentId||ut.attachment_id,name:ut.fileName||ut.file_name||ut.name,fileName:ut.fileName||ut.file_name||ut.name,url:ut.storageUrl||ut.storage_url||ut.url||"#",type:ut.fileType||ut.file_type||ut.type||"file",fileType:ut.fileType||ut.file_type||ut.type||"file",fileSize:ut.fileSize||ut.file_size})):void 0,isCurrentUser:et===v}}}).sort((me,Xe)=>new Date(me.timestamp).getTime()-new Date(Xe.timestamp).getTime());A(Me)}catch(oe){console.error("[WorkNoteChat] Error mapping messages:",oe)}else(async()=>{try{const oe=await xn(h),Me=Array.isArray(oe)?oe.map(me=>{const Xe=me.userName||me.user_name||"User",Qe=me.userRole||me.user_role,nt=le(Qe),Ke=me.userId||me.user_id;return{id:me.noteId||me.note_id||me.id||String(Math.random()),user:{name:Xe,avatar:Xe.split(" ").map(lt=>lt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:nt},content:me.message||"",timestamp:me.createdAt||me.created_at||new Date().toISOString(),attachments:Array.isArray(me.attachments)?me.attachments.map(lt=>({attachmentId:lt.attachmentId||lt.attachment_id,name:lt.fileName||lt.file_name||lt.name,fileName:lt.fileName||lt.file_name||lt.name,url:lt.storageUrl||lt.storage_url||lt.url||"#",type:lt.fileType||lt.file_type||lt.type||"file",fileType:lt.fileType||lt.file_type||lt.type||"file",fileSize:lt.fileSize||lt.file_size})):void 0,isCurrentUser:Ke===v}}):[];A(Me)}catch(oe){console.error("[WorkNoteChat] Error loading work notes:",oe)}})()},[s,h,te]);const ne=oe=>{const Me=O.maxFileSizeMB*1024*1024;if(oe.size>Me)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${O.maxFileSizeMB}MB. Current size: ${(oe.size/(1024*1024)).toFixed(2)}MB`};const me=oe.name.toLowerCase(),Xe=me.substring(me.lastIndexOf(".")+1);return O.allowedFileTypes.includes(Xe)?{valid:!0}:{valid:!1,reason:`File type "${Xe}" is not allowed. Allowed types: ${O.allowedFileTypes.join(", ")}`}},ge=oe=>{if(!oe.target.files||oe.target.files.length===0)return;const Me=Array.from(oe.target.files),me=[],Xe=[];Me.forEach(Qe=>{const nt=ne(Qe);nt.valid?Xe.push(Qe):me.push({fileName:Qe.name,reason:nt.reason||"Unknown validation error"})}),me.length>0&&q({open:!0,errors:me}),Xe.length>0&&(T(Qe=>[...Qe,...Xe]),Xe.length<Me.length?W.warning(`${Xe.length} of ${Me.length} file(s) were added. ${me.length} file(s) were rejected.`):W.success(`${Xe.length} file(s) added successfully`)),oe.target&&(oe.target.value="")},ke=oe=>{T(Me=>Me.filter((me,Xe)=>Xe!==oe)),H.current&&(H.current.value="")},Oe=oe=>{f(Me=>Me+oe),N(!1)},je=()=>{var oe;(oe=H.current)==null||oe.click()},ie=async oe=>{var Me,me;try{await og(h,oe);const Xe=await Ps(h),Qe=Array.isArray(Xe==null?void 0:Xe.participants)?Xe.participants:[];if(Qe.length){const nt=Qe.map(Ke=>{const lt=Ke.participantType||Ke.participant_type||"participant",et=Ke.userId||Ke.user_id||"",ut=Ke.userName||Ke.user_name||Ke.userEmail||Ke.user_email||"User",Hs=Ke.userEmail||Ke.user_email||"",is=ut.split(" ").map(vt=>vt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ut,avatar:is,role:ae(lt),status:"offline",email:Hs,lastSeen:void 0,permissions:["read"],userId:et}});ue(nt),K.current&&K.current.connected&&K.current.emit("request:online-users",{requestId:h})}_(!1),$({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),G(!0)}catch(Xe){throw console.error("Failed to add spectator:",Xe),$({success:!1,title:"Failed to Add Spectator",message:((me=(Me=Xe==null?void 0:Xe.response)==null?void 0:Me.data)==null?void 0:me.error)||"Failed to add spectator. Please try again."}),G(!0),Xe}},Se=async(oe,Me,me)=>{var Xe,Qe;if(d)await d(oe,Me,me),R(!1);else try{await lg(h,oe,Me,me);const nt=await Ps(h),Ke=Array.isArray(nt==null?void 0:nt.participants)?nt.participants:[];if(Ke.length){const lt=Ke.map(et=>{const ut=et.participantType||et.participant_type||"participant",Hs=et.userId||et.user_id||"",is=et.userName||et.user_name||et.userEmail||et.user_email||"User",vt=et.userEmail||et.user_email||"",pt=is.split(" ").map(Pt=>Pt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:is,avatar:pt,role:ae(ut),status:"offline",email:vt,lastSeen:void 0,permissions:["read"],userId:Hs}});ue(lt),K.current&&K.current.connected&&K.current.emit("request:online-users",{requestId:h})}R(!1),$({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${me} with ${Me}h TAT`}),G(!0)}catch(nt){throw console.error("Failed to add approver:",nt),$({success:!1,title:"Failed to Add Approver",message:((Qe=(Xe=nt==null?void 0:nt.response)==null?void 0:Xe.data)==null?void 0:Qe.error)||"Failed to add approver. Please try again."}),G(!0),nt}},qe=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],rt=oe=>{const Me=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,me=[];let Xe;for(;(Xe=Me.exec(oe))!==null;)if(Xe[1]){const Qe=Xe.index+Xe[0].length,nt=oe.slice(Qe),Ke=oe[Qe];(nt.startsWith("@")||!Ke||/\s|[.,!?;:]|@/.test(Ke))&&me.push(Xe[1].trim())}return me},gt=oe=>{oe.key==="Enter"&&!oe.shiftKey&&(oe.preventDefault(),he())},It=(oe,Me)=>{A(me=>me.map(Xe=>{if(Xe.id===oe){const Qe=Xe.reactions||[],nt=Qe.find(Ke=>Ke.emoji===Me);if(nt)if(nt.users.includes("You")){if(nt.users=nt.users.filter(Ke=>Ke!=="You"),nt.users.length===0)return{...Xe,reactions:Qe.filter(Ke=>Ke.emoji!==Me)}}else nt.users.push("You");else Qe.push({emoji:Me,users:["You"]});return{...Xe,reactions:Qe}}return Xe}))};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(Ys,{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:ee.title}),e.jsx(re,{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:[_e.slice(0,3).map((oe,Me)=>e.jsx(cs,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(ds,{className:"bg-blue-500 text-white text-xs font-semibold",children:oe.avatar})},Me)),_e.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:["+",_e.length-3]})]})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>I(!w),className:"lg:hidden",children:e.jsx(qt,{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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Re,{placeholder:"Search messages...",value:b,onChange:oe=>j(oe.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:[Ze.map(oe=>{const Me=oe.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${oe.isSystem?"justify-center":Me?"justify-end":""}`,children:[!oe.isSystem&&!Me&&e.jsx(cs,{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(ds,{className:`text-white font-semibold text-xs sm:text-sm ${oe.user.role==="Initiator"?"bg-green-600":oe.user.role==="Current User"?"bg-blue-500":oe.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:oe.user.avatar})}),e.jsx("div",{className:`${Me?"max-w-[70%]":"flex-1"} min-w-0 ${oe.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:oe.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(Bt,{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:oe.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:bs(oe.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${Me?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[oe.user.name," ",Me&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(re,{variant:"outline",className:"text-xs flex-shrink-0",children:oe.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(it,{className:"w-3 h-3"}),bs(oe.timestamp)]}),oe.isHighPriority&&e.jsxs(re,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(Ij,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${Me?"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:Z5(oe.content)}}),oe.attachments&&oe.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:oe.attachments.map((me,Xe)=>{const Qe=me.fileSize||me.file_size,nt=me.fileName||me.file_name||me.name,Ke=me.fileType||me.file_type||me.type||"",lt=me.attachmentId||me.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(xh,{type:Ke})}),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:nt}),Qe&&e.jsx("p",{className:"text-xs text-gray-500",children:J5(Qe)})]}),lt&&(()=>{const et=(Ke||"").toLowerCase();return et.includes("image")||et.includes("pdf")||et.includes("jpg")||et.includes("jpeg")||et.includes("png")||et.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:et=>{et.preventDefault(),et.stopPropagation();const ut=Y1(lt);B({fileName:nt,fileType:Ke,fileUrl:ut,fileSize:Qe,attachmentId:lt})},title:"Preview file",children:e.jsx(Nt,{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 et=>{if(et.preventDefault(),et.stopPropagation(),!lt){W.error("Cannot download: Attachment ID missing");return}try{await Ou(lt)}catch{W.error("Failed to download file")}},title:"Download file",children:e.jsx(Tt,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Xe)})})}),oe.reactions&&oe.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:[oe.reactions.map((me,Xe)=>e.jsxs("button",{onClick:()=>It(oe.id,me.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${me.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:me.emoji}),e.jsx("span",{className:"text-xs font-medium",children:me.users.length})]},Xe)),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>N(!y),children:e.jsx(ms,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!oe.isSystem&&Me&&e.jsx(cs,{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(ds,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:oe.user.avatar})})]},oe.id)}),e.jsx("div",{ref:F})]})}),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:H,onChange:ge,className:"hidden",multiple:!0,accept:O.allowedFileTypes.map(oe=>`.${oe}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((oe,Me)=>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(xh,{type:oe.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:oe.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(oe.size/1024).toFixed(1)," KB"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>ke(Me),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(yt,{className:"h-3 w-3 text-red-600"})})]},Me))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const oe=g.lastIndexOf("@"),Me=oe>=0;if(!Me)return null;const me=g.slice(oe+1),Xe=me.trim(),Qe=me.endsWith(" "),nt=Xe.length>0,Ke=Xe.includes(" ")&&!Qe,lt=Qe&&nt;if(!(Me&&me.length<=20&&!Ke&&!lt))return null;const ut=Xe.toLowerCase(),Hs=te.filter(is=>is.userId===v?!1:ut?is.name.toLowerCase().includes(ut):!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:Hs.length>0?Hs.map((is,vt)=>e.jsxs("button",{type:"button",onClick:pt=>{pt.preventDefault(),pt.stopPropagation();const Pt=g.lastIndexOf("@"),Ss=g.slice(0,Pt);f(Ss+"@"+is.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(cs,{className:"h-10 w-10",children:e.jsx(ds,{className:`text-white text-sm font-semibold ${is.role==="Initiator"?"bg-green-600":is.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:is.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:is.name}),e.jsx("p",{className:"text-xs text-gray-600",children:is.role})]})]},vt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:ut?`No participants found matching "${ut}"`:"No other participants available"})})]})})(),e.jsx(zs,{placeholder:Ue?"Spectators cannot send messages":"Type your message... Use @username to mention someone",value:g,onChange:oe=>f(oe.target.value),onKeyPress:gt,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,disabled:Ue}),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:()=>N(!1),className:"h-6 w-6 p-0",children:e.jsx(yt,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:qe.map((oe,Me)=>e.jsx("button",{onClick:()=>Oe(oe),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:oe,children:oe},Me))})]})]}),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",onClick:je,disabled:Ue,title:Ue?"Spectators cannot attach files":"Attach file",children:e.jsx(xl,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>N(!y),disabled:Ue,title:Ue?"Spectators cannot add emojis":"Add emoji",children:e.jsx(Pj,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>f(oe=>oe+"@"),disabled:Ue,title:Ue?"Spectators cannot mention users":"Mention someone",children:e.jsx(bl,{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:he,disabled:!g.trim()&&D.length===0||Ue,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",title:Ue?"Spectators cannot send messages":"Send",children:[e.jsx(np,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),w&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>I(!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
|
||
${w?"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:()=>I(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(yt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:te.map((oe,Me)=>{const me=oe.userId===v;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(cs,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(ds,{className:`text-white font-semibold text-sm ${oe.role==="Initiator"?"bg-green-600":me?"bg-blue-500":"bg-slate-600"}`,children:oe.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${K5(oe.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:[oe.name," ",me&&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:oe.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:X5(oe.status)})]}),oe.lastSeen&&oe.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:oe.lastSeen})]})]},Me)})})]}),!Ue&&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:()=>R(!0),children:[e.jsx(fl,{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(Nt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),P&&e.jsx(Yr,{fileName:P.fileName,fileType:P.fileType,fileUrl:P.fileUrl,fileSize:P.fileSize,attachmentId:P.attachmentId,onDownload:Ou,open:!!P,onClose:()=>B(null)}),!Ue&&e.jsx(sf,{open:k,onClose:()=>_(!1),onConfirm:ie,requestIdDisplay:h,requestTitle:ee.title,existingParticipants:De}),!Ue&&l&&e.jsx(af,{open:L,onClose:()=>R(!1),onConfirm:Se,requestIdDisplay:h,requestTitle:ee.title,existingParticipants:De,currentLevels:c,maxApprovalLevels:m,onPolicyViolation:p}),e.jsx(xt,{open:Q.open,onOpenChange:oe=>q(Me=>({...Me,open:oe})),children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(_t,{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:Q.errors.map((oe,Me)=>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:oe.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:oe.reason})]},Me))}),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(Dt,{children:e.jsx(E,{onClick:()=>q({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(tf,{open:C,onClose:()=>G(!1),success:U.success,title:U.title,message:U.message})]})}function q5({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(rf,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d})})}function ek({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const c=o.toLowerCase();return c==="approved"?e.jsx(Be,{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(it,{className:"h-4 w-4 text-orange-600"}):e.jsx(Fe,{className:"h-4 w-4 text-gray-600"})},i=o=>{const c=o.toLowerCase();return c==="approved"?"bg-green-100 text-green-700 border-green-300":c==="rejected"?"bg-red-100 text-red-700 border-red-300":c==="pending"||c==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},l=(o,c)=>o&&o.trim()&&o.trim().toUpperCase()!=="N/A"?o:c&&c.trim()&&c.trim().toUpperCase()!=="N/A"?c:"N/A";return s?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ze,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):t?e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:t.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",t.requestNumber]})]}),r&&a?e.jsxs(E,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(bn,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(re,{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:st(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:st(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(re,{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(Fe,{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 tk({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(or,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(Be,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(St,{className:"h-4 w-4 text-red-600"}):e.jsx(it,{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(or,{className:`h-4 w-4 ${c.icon}`}):e.jsx(it,{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(re,{className:`text-xs ${c.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(ia,{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:[Xt(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${d==="breached"||d==="critical"?c.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[Xt(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",Fa(t.deadline,!0)," • ",i,"% elapsed"]}),d==="critical"&&e.jsxs("p",{className:"text-xs text-orange-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-critical`,children:[e.jsx(ss,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),d==="breached"&&e.jsxs("p",{className:"text-xs text-red-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-breached`,children:[e.jsx(Ji,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function sk({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var g,f;const c=G5((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)),u=m&&String(m).toLowerCase()==="duplicate",h=d&&m?{color:p?"bg-red-100 !text-red-800 border-red-200":m==="Completed"?"bg-green-100 !text-green-800 border-green-200":u?"bg-amber-100 !text-amber-800 border-amber-200":"bg-gray-100 !text-gray-700 border-gray-200",icon:uh((t==null?void 0:t.status)||"pending").icon,label:m}:uh((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(Fe,{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(re,{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(re,{className:`${h.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:h.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())||"",N=y==="FORM_16",S=b==="CLAIM_MANAGEMENT"||j==="claim-management",A=b==="DEALER_CLAIM"||y==="DEALER CLAIM"||y==="DEALER_CLAIM";let w="Non-Templatized",I="bg-purple-100 !text-purple-600 border-purple-200";return N?(w="Form 16",I="bg-emerald-100 !text-emerald-700 border-emerald-200"):A?(w="Dealer Claim",I="bg-blue-100 !text-blue-700 border-blue-200"):S?(w="Claim Management",I="bg-blue-100 !text-blue-700 border-blue-200"):y==="TEMPLATE"&&(w="Template"),e.jsx(re,{className:`${I} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:w})})()]})]})]})]}),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(bn,{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(Et,{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(tk,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function Cd(t){return(await ve.get(`/summaries/${t}`)).data.data}async function ak(t,s){return(await ve.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function rk(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await ve.get("/summaries/shared",{params:{page:s,limit:a}});return{data:((n=r.data.data)==null?void 0:n.data)||r.data.data||[],pagination:((i=r.data.data)==null?void 0:i.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function nf(t){await ve.patch(`/summaries/shared/${t}/view`)}async function lf(t){var s;try{return(await ve.get(`/summaries/request/${t}`)).data.data}catch(a){return((s=a==null?void 0:a.response)==null?void 0:s.status)===404,null}}async function nk(t){return(await ve.get(`/summaries/${t}/recipients`)).data.data||[]}function ik({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(J,{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 st(new Date(l),"MMM d, yyyy")}catch{return l}};return e.jsxs(Z,{className:s,children:[e.jsx(ce,{children:e.jsxs(de,{className:"flex items-center gap-2 text-base",children:[e.jsx(ft,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(J,{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(yc,{className:"w-4 h-4 text-gray-400"}),t.location]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Requested Date"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:i(t.requestedDate)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Estimated Budget"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(Da,{className:"w-4 h-4 text-green-600"}),t.estimatedBudget!==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(Mt,{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:bs(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:bs(r)})]})]})]})]})}function lk({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(J,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(Z,{className:s,children:[e.jsx(ce,{children:e.jsxs(de,{className:"flex items-center gap-2 text-base",children:[e.jsx(jl,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(J,{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(va,{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(oi,{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(yc,{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(J,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function ok({dmsDetails:t,claimAmount:s,estimatedBudgetBreakdown:a,closedExpensesBreakdown:r,visibility:n,onEditClaimAmount:i,className:l}){const o=u=>u==null||Number.isNaN(u)?"₹0.00":`₹${u.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,c=u=>{if(!u)return"";try{return st(new Date(u),"MMM d, yyyy, h:mm a")}catch{return u||""}},d=u=>!u||u.length===0?0:u.reduce((h,g)=>h+(g.totalAmt??g.amount+(g.gstAmt??0)),0),m=!!(t!=null&&t.eInvoiceNumber||t!=null&&t.ackNo||t!=null&&t.eInvoiceDate||t!=null&&t.dmsNumber||t!=null&&t.ackDate||t!=null&&t.irn||t!=null&&t.signedInvoiceUrl);return n.showDMSDetails&&t||(t==null?void 0:t.creditNoteWfmData)&&t.creditNoteWfmData.length>0||n.showClaimAmount&&s&&s.amount!==void 0&&s.amount!==null||a&&a.length>0||r&&r.length>0?e.jsxs(Z,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${l}`,children:[e.jsxs(ce,{children:[e.jsxs(de,{className:"text-base flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(we,{children:"Workflow reference numbers"})]}),e.jsxs(J,{className:"space-y-3",children:[n.showDMSDetails&&t&&m&&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(Bt,{className:"w-4 h-4 text-purple-600"}),e.jsx(se,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice Details"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-2",children:[(t.eInvoiceNumber||t.ackNo)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Invoice Number"}),e.jsx("p",{className:"font-bold text-sm text-purple-700",children:t.eInvoiceNumber||t.ackNo})]}),t.eInvoiceDate&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Invoice Date"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:c(t.eInvoiceDate)})]}),t.dmsNumber&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"DMS Number"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:t.dmsNumber})]}),t.ackDate&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Ack Date"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:c(t.ackDate)})]}),t.ackNo&&t.eInvoiceNumber&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Ack No"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:t.ackNo})]})]}),t.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:t.irn})]}),t.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(t.signedInvoiceUrl,"_blank"),children:[e.jsx(Mt,{className:"w-3.5 h-3.5"}),"View E-Invoice"]}),t.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:t.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 ",t.createdByName||"System"]}),e.jsx("p",{className:"text-[10px] text-gray-500",children:c(t.createdAt)})]})]}),(t==null?void 0:t.creditNoteWfmData)&&t.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(Mt,{className:"w-4 h-4 text-pink-600"}),e.jsx(se,{className:"text-xs font-semibold text-pink-900 uppercase tracking-wide",children:"Credit Note Details"})]}),e.jsx("div",{className:"space-y-2",children:t.creditNoteWfmData.map((u,h)=>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.5 text-pink-900",children:[e.jsxs("span",{className:"font-semibold break-words flex-1 pr-2 uppercase",children:["CN No: ",u.DOC_NO||"N/A"]}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-sm text-white font-medium self-start whitespace-nowrap ${u.MSG_TYP==="E"?"bg-red-500":"bg-green-500"}`,children:u.MSG_TYP==="E"?"Error":u.MSG_TYP==="S"?"Success":u.MSG_TYP||"Processed"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1 mb-1.5 text-gray-600",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Txn No:"}),e.jsx("span",{className:"font-medium",children:u.TRNS_UNIQ_NO||"N/A"})]}),u.TDS_AMT!==void 0&&u.TDS_AMT!==null&&u.TDS_AMT!==""&&(Number.isNaN(Number(u.TDS_AMT))||Number(u.TDS_AMT)!==0)&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"TDS:"}),e.jsx("span",{className:"font-medium text-red-600",children:Number.isNaN(Number(u.TDS_AMT))?String(u.TDS_AMT):o(Number(u.TDS_AMT))})]}),e.jsxs("div",{className:"flex justify-between col-span-2 pt-1 border-t border-pink-100",children:[e.jsx("span",{className:"font-semibold",children:"Credit Amount:"}),e.jsx("span",{className:"font-bold text-pink-700",children:u.CREDITED_TOTAL_AMT!==void 0&&u.CREDITED_TOTAL_AMT!==null&&u.CREDITED_TOTAL_AMT!==""?Number.isNaN(Number(u.CREDITED_TOTAL_AMT))?String(u.CREDITED_TOTAL_AMT):o(Number(u.CREDITED_TOTAL_AMT)):o(0)})]})]}),u.MESSAGE&&e.jsx("div",{className:"text-gray-700 italic border-l-2 border-pink-200 pl-1.5 mt-1 leading-tight",children:u.MESSAGE})]},h))})]}),n.showClaimAmount&&s&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"w-4 h-4 text-green-600"}),e.jsx(se,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),n.canEditClaimAmount&&i&&e.jsxs(E,{variant:"outline",size:"sm",onClick:i,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(qn,{className:"w-3 h-3 mr-1 text-green-700"}),"Edit"]})]}),e.jsx("p",{className:"text-2xl font-bold text-green-700",children:o(s.amount)}),s.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 ",s.lastUpdatedBy]}),s.lastUpdatedAt&&e.jsx("p",{className:"text-xs text-gray-500",children:c(s.lastUpdatedAt)})]})]}),a&&a.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(Mt,{className:"w-4 h-4 text-amber-600"}),e.jsx(se,{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:[a.map((u,h)=>e.jsxs("div",{className:"space-y-0.5 pb-1.5 last:pb-0",children:[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 font-medium",title:u.description,children:u.description}),e.jsx("span",{className:"font-bold text-gray-900 whitespace-nowrap",children:o(u.totalAmt??u.amount+(u.gstAmt??0))})]}),(u.gstAmt??0)>0&&e.jsxs("div",{className:"flex justify-between items-center text-[9px] text-gray-500 pl-2 italic",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("span",{children:["Base: ",o(u.amount)]}),e.jsxs("span",{children:["GST: ",o(u.gstAmt)]})]}),u.hsnCode&&e.jsxs("span",{children:["HSN/SAC: ",u.hsnCode]})]}),!(u.gstAmt??0)&&u.hsnCode&&e.jsxs("div",{className:"text-[9px] text-gray-500 pl-2 italic",children:["HSN/SAC: ",u.hsnCode]})]},h)),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:o(d(a))})]})]})]}),r&&r.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(Mt,{className:"w-4 h-4 text-indigo-600"}),e.jsx(se,{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:[r.map((u,h)=>e.jsxs("div",{className:"space-y-0.5 pb-1.5 last:pb-0",children:[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 font-medium",title:u.description,children:u.description}),e.jsx("span",{className:"font-bold text-gray-900 whitespace-nowrap",children:o(u.totalAmt??u.amount+(u.gstAmt??0))})]}),(u.gstAmt??0)>0&&e.jsxs("div",{className:"flex justify-between items-center text-[9px] text-gray-500 pl-2 italic",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("span",{children:["Base: ",o(u.amount)]}),e.jsxs("span",{children:["GST: ",o(u.gstAmt)]})]}),u.hsnCode&&e.jsxs("span",{children:["HSN/SAC: ",u.hsnCode]})]}),!(u.gstAmt??0)&&u.hsnCode&&e.jsxs("div",{className:"text-[9px] text-gray-500 pl-2 italic",children:["HSN/SAC: ",u.hsnCode]})]},h)),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:o(d(r))})]})]})]})]})]}):null}function ck({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,u=m.gstAmt||0,h=m.totalAmt||Number(p)+Number(u);return d+(Number.isNaN(h)?0:h)},0):0)})(),n=o=>o==null||Number.isNaN(o)?"₹0.00":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,i=o=>{if(!o)return"";try{return st(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return st(new Date(o),"MMM d, yyyy")}catch{return o||"-"}};return e.jsxs(Z,{className:s,children:[e.jsxs(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-base",children:[e.jsx(Mt,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs(we,{children:["Submitted on ",i(t.submittedOn)]})]}),e.jsxs(J,{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(ft,{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 dk({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(ce,{children:e.jsx(de,{className:"text-base",children:"Request Initiator"})}),e.jsx(J,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(cs,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(ds,{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(va,{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(oi,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function of(t,s){var a,r,n,i,l;try{if(!li(t))return null;const o=t.claimDetails||{},c=t.proposalDetails||{},d=t.completionDetails||{},m=t.internalOrder||t.internal_order||{},p=t.budgetTracking||t.budget_tracking||{},u=t.invoice||{},h=t.creditNote||t.credit_note||{},g=t.completionExpenses||t.completion_expenses||[],f=o.periodStartDate||o.period_start_date,b=o.periodEndDate||o.period_end_date,j=o.activityName||o.activity_name||"",y=o.activityType||o.activity_type||"",N=o.location||"",S=p.proposalEstimatedBudget??p.proposal_estimated_budget??p.initialEstimatedBudget??p.initial_estimated_budget??o.estimatedBudget??o.estimated_budget,A=(p==null?void 0:p.closedExpenses)??(p==null?void 0:p.closed_expenses)??(d==null?void 0:d.totalClosedExpenses)??(d==null?void 0:d.total_closed_expenses)??(o==null?void 0:o.closedExpenses)??(o==null?void 0:o.closed_expenses),w=A!=null?Number(A):void 0,I=Array.isArray(g)&&g.length>0?g.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,hsnCode:C.hsnCode||C.hsn_code||C.hsnCd||C.hsn_cd||""})):(d==null?void 0:d.closedExpenses)||(d==null?void 0:d.closed_expenses)||(d==null?void 0:d.closedExpensesBreakdown)||[],D={activityName:j,activityType:y,defaultGstRate:o.defaultGstRate||18,requestedDate:o.activityDate||o.activity_date||t.createdAt,location:N,period:f&&b?{startDate:f,endDate:b}:void 0,estimatedBudget:S,closedExpenses:w,closedExpensesBreakdown:I,description:t.description||""},T={dealerCode:(o==null?void 0:o.dealerCode)||(o==null?void 0:o.dealer_code)||(o==null?void 0:o.DealerCode)||"",dealerName:(o==null?void 0:o.dealerName)||(o==null?void 0:o.dealer_name)||(o==null?void 0:o.DealerName)||"",email:(o==null?void 0:o.dealerEmail)||(o==null?void 0:o.dealer_email)||(o==null?void 0:o.DealerEmail)||"",phone:(o==null?void 0:o.dealerPhone)||(o==null?void 0:o.dealer_phone)||(o==null?void 0:o.DealerPhone)||"",address:(o==null?void 0:o.dealerAddress)||(o==null?void 0:o.dealer_address)||(o==null?void 0:o.DealerAddress)||""};(!T.dealerCode||!T.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!o,dealerCode:T.dealerCode,dealerName:T.dealerName,rawClaimDetails:o,availableKeys:o?Object.keys(o):[]});const v=(c==null?void 0:c.expectedCompletionDate)||(c==null?void 0:c.expected_completion_date),P=!!(c&&Object.keys(c).length>0&&(Array.isArray(c.costItems||c.cost_items)&&(c.costItems||c.cost_items).length>0||Array.isArray(c.costBreakup||c.cost_breakup)&&(c.costBreakup||c.cost_breakup).length>0||c.proposalDocumentUrl||c.proposal_document_url||c.totalEstimatedBudget||c.total_estimated_budget||c.expectedCompletionDate||c.expected_completion_date||c.submittedAt||c.submitted_at))?{proposalDocumentUrl:c.proposalDocumentUrl||c.proposal_document_url,costBreakup:Array.isArray(c.costItems||c.cost_items)?(c.costItems||c.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),hsnCode:C.hsnCode||C.hsn_code||""})):Array.isArray(c.costBreakup||c.cost_breakup)?(c.costBreakup||c.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,hsnCode:C.hsnCode||C.hsn_code||""})):[],totalEstimatedBudget:c.totalEstimatedBudget||c.total_estimated_budget||0,timelineMode:c.timelineMode||c.timeline_mode,expectedCompletionDate:v,timelineForClosure:v,expectedCompletionDays:c.expectedCompletionDays||c.expected_completion_days,dealerComments:c.dealerComments||c.dealer_comments,submittedAt:c.submittedAt||c.submitted_at||c.submittedOn,submittedOn:c.submittedAt||c.submitted_at||c.submittedOn}:void 0,B={ioNumber:m.ioNumber||m.io_number||o.ioNumber||o.io_number,ioRemark:m.ioRemark||m.io_remark||"",availableBalance:m.ioAvailableBalance||m.io_available_balance||o.ioAvailableBalance||o.io_available_balance,blockedAmount:m.ioBlockedAmount||m.io_blocked_amount||o.ioBlockedAmount||o.io_blocked_amount,remainingBalance:m.ioRemainingBalance||m.io_remaining_balance||o.ioRemainingBalance||o.io_remaining_balance,organizedBy:((a=m.organizer)==null?void 0:a.displayName)||((r=m.organizer)==null?void 0:r.name)||m.organizedBy||"",organizedAt:m.organizedAt||m.organized_at||""},k=t.invoice||t.claimInvoice||t.claim_invoice||((n=t.claimRequest)==null?void 0:n.invoice)||((i=t.request)==null?void 0:i.invoice)||u||{},_=o||{},L={eInvoiceNumber:k.invoiceNumber||k.invoice_number||_.eInvoiceNumber||_.e_invoice_number||k.dmsNumber||k.dms_number,eInvoiceDate:k.invoiceDate||k.invoice_date||_.eInvoiceDate||_.e_invoice_date,dmsNumber:k.dmsNumber||k.dms_number||_.dmsNumber||_.dms_number,creditNoteNumber:h.creditNoteNumber||h.credit_note_number||_.creditNoteNumber||_.credit_note_number,creditNoteDate:h.creditNoteDate||h.credit_note_date||_.creditNoteDate||_.credit_note_date,creditNoteAmount:h.creditNoteAmount!==void 0&&h.creditNoteAmount!==null?Number(h.creditNoteAmount):h.credit_note_amount!==void 0&&h.credit_note_amount!==null?Number(h.credit_note_amount):_.creditNoteAmount!==void 0&&_.creditNoteAmount!==null?Number(_.creditNoteAmount):_.credit_note_amount!==void 0&&_.credit_note_amount!==null?Number(_.credit_note_amount):void 0,irn:k.irn||_.irn,ackNo:k.ackNo||k.ack_no||_.ackNo||_.ack_no,ackDate:k.ackDate||k.ack_date||_.ackDate||_.ack_date,signedInvoiceUrl:k.signedInvoiceUrl||k.signed_invoice_url||_.signedInvoiceUrl||_.signed_invoice_url,taxBreakdown:k.taxBreakdown||_.taxBreakdown,creditNoteWfmData:(((l=t.creditNote)==null?void 0:l.items)||t.creditNoteWfmData||o.creditNoteWfmData||[]).map(C=>{var G;return{...C,DOC_NO:C.creditNoteNumber||((G=t.creditNote)==null?void 0:G.creditNoteNumber)||C.DOC_NO,TRNS_UNIQ_NO:C.transactionNo||C.TRNS_UNIQ_NO,MESSAGE:C.description||C.MESSAGE,TDS_AMT:C.tdsAmount||C.TDS_AMT,CREDITED_TOTAL_AMT:C.creditAmount||C.amount||C.CREDITED_TOTAL_AMT}})},R={estimated:D.estimatedBudget||0,closed:D.closedExpenses||0};return{activityInfo:D,dealerInfo:T,proposalDetails:P,ioDetails:Object.keys(B).some(C=>B[C])?B:void 0,dmsDetails:Object.keys(L).some(C=>L[C])?L:void 0,claimAmount:R}}catch(o){return console.error("[claimDataMapper] Error mapping claim data:",o),null}}function cf(t,s){var a,r,n,i,l,o,c,d;try{const m=N=>(N||"").toString().trim().toLowerCase(),p=Array.isArray(t.participants)?t.participants:[],u=p.find(N=>{var S;return N.userId===s||N.user_id===s||((S=N.user)==null?void 0:S.userId)===s}),h=m((u==null?void 0:u.userEmail)||(u==null?void 0:u.user_email)||(u==null?void 0:u.email)||((a=u==null?void 0:u.user)==null?void 0:a.email)||(t.initiatorId===s?(r=t.initiator)==null?void 0:r.email:"")),g=m(((n=t==null?void 0:t.claimDetails)==null?void 0:n.dealerEmail)||((i=t==null?void 0:t.claimDetails)==null?void 0:i.dealer_email)||(t==null?void 0:t.dealerEmail)||((l=t==null?void 0:t.dealer)==null?void 0:l.email));if(g&&h&&h===g)return"DEALER";if(t.initiatorId===s||t.initiator_id===s||((o=t.initiator)==null?void 0:o.userId)===s||((c=t.initiator)==null?void 0:c.user_id)===s||((d=t.requestedBy)==null?void 0:d.userId)===s)return"INITIATOR";if(p.find(N=>{var S,A;return(N.userId===s||N.user_id===s||((S=N.user)==null?void 0:S.userId)===s||((A=N.user)==null?void 0:A.user_id)===s)&&(N.participantType||N.participant_type||N.type||"").toString().toUpperCase()==="DEALER"}))return"DEALER";const b=t.approvalLevels||[];return b.find(N=>{var S;return N.levelNumber===3&&(N.approverId===s||((S=N.approver)==null?void 0:S.userId)===s)})?"DEPARTMENT_LEAD":b.find(N=>{var S;return(N.approverId===s||((S=N.approver)==null?void 0:S.userId)===s)&&N.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(m){return console.error("[claimDataMapper] Error determining user role:",m),"SPECTATOR"}}function df(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:!0,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:!0,showProposalDetails:!0,showIODetails:!1,showDMSDetails:!0,showClaimAmount:!1,canEditClaimAmount:!1}}}function mk({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:u,pausedByUserId:h,currentUserId:g,apiRequest:f,onEditClaimAmount:b,hideApproveReject:j=!1}){var R,C,G,U,$;const{user:y}=us(),[N,S]=x.useState([]),[A,w]=x.useState(!1),[I,D]=x.useState(!1),T=(t==null?void 0:t.status)==="closed",v=((R=t==null?void 0:t.pauseInfo)==null?void 0:R.isPaused)||!1,M=h||((G=(C=t==null?void 0:t.pauseInfo)==null?void 0:C.pausedBy)==null?void 0:G.userId),P=g||(y==null?void 0:y.userId)||"",B=!v&&!T&&(r||s),k=v&&d&&(r||s),_=v&&s&&M&&M!==P&&m;x.useEffect(()=>{if(!v||!r||!(t!=null&&t.requestId)){D(!1);return}(async()=>{var H;try{const O=(((H=(await cr.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:H.notifications)||[]).some(V=>V.requestId===t.requestId&&V.notificationType==="pause_retrigger_request");D(O)}catch(K){console.error("Failed to check retrigger notifications:",K),D(!1)}})()},[v,r,t==null?void 0:t.requestId,u]),x.useEffect(()=>{(async()=>{if(!T||!p||!s){S([]);return}try{w(!0);const H=await nk(p);S(H)}catch(H){console.error("Failed to fetch shared recipients:",H),S([])}finally{w(!1)}})()},[T,p,s,u]);const L=x.useMemo(()=>{if(!f||!li(f))return null;const F=of(f);if(!F)return null;const H=cf(f,P),K=df(H);return{claimRequest:F,visibility:K}},[f,P]);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(ce,{className:"pb-2",children:e.jsx(de,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(J,{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(fl,{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(Nt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),B&&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(mr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),k&&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(Zi,{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(Je,{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(Be,{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:M===P?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[I&&e.jsx(Je,{className:"w-3.5 h-3.5"}),I?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:I?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&M!==P&&I?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(Je,{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&&M!==P?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Workflow is paused"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"You can resume to continue approval"})]}):s&&M&&M!==P?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Approver has paused this workflow"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:_?'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(ce,{className:"pb-2",children:e.jsx(de,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(J,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((F,H)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${H}`,children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:F.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:F.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:F.role})]})]},H)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),T&&s&&e.jsxs(Z,{"data-testid":"shared-recipients-card",children:[e.jsx(ce,{className:"pb-2",children:e.jsxs(de,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(bn,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(J,{className:"space-y-3",children:A?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):N.length>0?N.map((F,H)=>{const K=(F.displayName||"NA").split(" ").map(z=>z[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${H}`,children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:K})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:F.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:F.email}),F.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},F.userId||H)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),L&&e.jsx(ok,{ioDetails:L.claimRequest.ioDetails,dmsDetails:L.claimRequest.dmsDetails,claimAmount:{amount:L.claimRequest.claimAmount.closed||L.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(U=L.claimRequest.proposalDetails)==null?void 0:U.costBreakup,closedExpensesBreakdown:($=L.claimRequest.activityInfo)==null?void 0:$.closedExpensesBreakdown,visibility:L.visibility,onEditClaimAmount:b})]})}function uk({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(r),[d,m]=x.useState(!1),p=(o==null?void 0:o.length)||0,u=x.useMemo(()=>o.slice(0,500),[o]),h=async()=>{try{m(!0),await a(u),s()}finally{m(!1)}};return e.jsx(xt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(dt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ht,{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(Be,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(mt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide your approval comments and remarks"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:l||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(re,{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(zs,{value:u,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(Be,{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(Dt,{className:"mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(E,{onClick:h,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function xk({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(r),[d,m]=x.useState(!1),p=(o==null?void 0:o.length)||0,u=x.useMemo(()=>o.slice(0,500),[o]),h=async()=>{if(!u.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(u),s()}finally{m(!1)}};return e.jsx(xt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(dt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ht,{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(mt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide detailed reasons for rejection"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:l||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(re,{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(zs,{value:u,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(Je,{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(Dt,{className:"mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(E,{variant:"destructive",onClick:h,disabled:d,children:[e.jsx(St,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function hk({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(""),[d,m]=x.useState(!1),p=async()=>{if(o.trim())try{m(!0),await a(o.trim()),c(""),s()}catch(h){console.error("Failed to skip approver:",h)}finally{m(!1)}},u=()=>{d||(c(""),s())};return e.jsx(xt,{open:t,onOpenChange:u,children:e.jsxs(dt,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:u,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(yt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{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(Je,{className:"w-5 h-5 text-orange-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Skip Approver"})]})}),e.jsxs("div",{className:"space-y-4 px-6 py-4 overflow-y-auto flex-1",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{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(se,{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(se,{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(se,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(zs,{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:h=>c(h.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:u,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(Je,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function pk({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:u,maxApprovalLevels:h,onPolicyViolation:g,setShowApproveModal:f,setShowRejectModal:b,setShowAddApproverModal:j,setShowAddSpectatorModal:y,setShowSkipApproverModal:N,setShowActionStatusModal:S,setPreviewDocument:A,setDocumentError:w,setSkipApproverData:I,setActionStatus:D,handleApproveConfirm:T,handleRejectConfirm:v,handleAddApprover:M,handleAddSpectator:P,handleSkipApprover:B,downloadDocument:k,documentPolicy:_}){return e.jsxs(e.Fragment,{children:[e.jsx(uk,{open:t,onClose:()=>f(!1),onConfirm:T,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(xk,{open:s,onClose:()=>b(!1),onConfirm:v,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(af,{open:a,onClose:()=>j(!1),onConfirm:M,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p,currentLevels:u,maxApprovalLevels:h,onPolicyViolation:g}),e.jsx(sf,{open:r,onClose:()=>y(!1),onConfirm:P,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p}),e.jsx(hk,{open:n,onClose:()=>{N(!1),I(null)},onConfirm:B,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),l&&e.jsx(Yr,{fileName:l.fileName,fileType:l.fileType,fileUrl:wn(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:k,open:!!l,onClose:()=>A(null)}),m&&e.jsx(tf,{open:i,onClose:()=>{S(!1),D(null)},success:m.success,title:m.title,message:m.message}),e.jsx(xt,{open:o.show,onOpenChange:L=>w(R=>({...R,show:L})),children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(_t,{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((L,R)=>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:L.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:L.reason})]},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:"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(Dt,{children:e.jsx(E,{onClick:()=>w({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const mf={DocumentsTab:H5,ActivityTab:Q5,WorkNotesTab:q5,SummaryTab:ek,RequestDetailHeader:sk,QuickActionsSidebar:mk,RequestDetailModals:pk};function Sd({className:t,...s}){return e.jsx(Gb,{"data-slot":"checkbox",className:Le("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(Wb,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx($a,{className:"size-3.5"})})})}function uf({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,l]=x.useState(""),[o,c]=x.useState([]),[d,m]=x.useState(new Set),[p,u]=x.useState(!1),[h,g]=x.useState(!1);x.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),u(!1);return}const y=setTimeout(async()=>{var N;try{u(!0);const S=i.slice(1),A=await Na(S,10),w=((N=A==null?void 0:A.data)==null?void 0:N.data)||(A==null?void 0:A.data)||[];c(Array.isArray(w)?w:[])}catch(S){console.error("Failed to search users:",S),W.error("Failed to search users")}finally{u(!1)}},300);return()=>clearTimeout(y)},[i,t]);const f=y=>{m(N=>{const S=new Set(N);return S.has(y)?S.delete(y):S.add(y),S})},b=async()=>{var y,N;if(d.size===0){W.error("Please select at least one user to share with");return}try{g(!0),await ak(a,Array.from(d)),W.success(`Summary shared with ${d.size} user(s)`),m(new Set),l(""),c([]),n==null||n(),s()}catch(S){console.error("Failed to share summary:",S),W.error(((N=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:N.message)||"Failed to share summary")}finally{g(!1)}},j=()=>{m(new Set),l(""),c([]),s()};return e.jsx(xt,{open:t,onOpenChange:j,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(ht,{children:e.jsx(mt,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(se,{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(se,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Re,{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(ze,{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 N=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:S=>S.stopPropagation(),onMouseDown:S=>S.stopPropagation(),className:"flex items-center",children:e.jsx(Sd,{checked:N,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(Ht,{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 N=o.find(S=>S.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:(N==null?void 0:N.displayName)||(N==null?void 0:N.email)||y}),e.jsx("button",{onClick:()=>f(y),className:"ml-1 hover:text-red-600",children:e.jsx(yt,{className:"h-3 w-3"})})]},y)})})]})]}),e.jsxs(Dt,{children:[e.jsx(E,{variant:"outline",onClick:j,disabled:h,children:"Cancel"}),e.jsx(E,{onClick:b,disabled:h||d.size===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function xf({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=x.useState(""),[o,c]=x.useState(""),[d,m]=x.useState(!1),p=()=>rs().add(1,"month").format("YYYY-MM-DD"),u=()=>rs().add(1,"month").format("YYYY-MM-DD"),h=()=>rs().add(1,"day").format("YYYY-MM-DD");x.useEffect(()=>{t&&!o&&c(p())},[t]);const g=async()=>{var N,S,A,w;if(!i.trim()){W.error("Please provide a reason for pausing");return}if(!o){W.error("Please select a resume date");return}const b=rs(o),j=rs().add(1,"month"),y=rs().add(1,"day");if(b.isAfter(j)){W.error("Resume date cannot be more than 1 month from now");return}if(b.isBefore(y,"day")){W.error("Resume date must be at least 1 day from now");return}try{m(!0),await H1(a,r,i.trim(),b.toDate()),W.success("Workflow paused successfully"),n&&await n(),l(""),c(p()),s()}catch(I){console.error("Failed to pause workflow:",I),W.error(((S=(N=I==null?void 0:I.response)==null?void 0:N.data)==null?void 0:S.error)||((w=(A=I==null?void 0:I.response)==null?void 0:A.data)==null?void 0:w.message)||"Failed to pause workflow")}finally{m(!1)}},f=()=>{d||(l(""),c(p()),s())};return e.jsx(xt,{open:t,onOpenChange:f,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(mr,{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(se,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(zs,{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(se,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Re,{id:"resume-date",type:"date",value:o,onChange:b=>c(b.target.value),min:h(),max:u(),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(Dt,{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(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(mr,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function hf({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=x.useState(""),[l,o]=x.useState(!1),c=async()=>{var m,p,u,h;try{o(!0),await G1(a,n.trim()||void 0),W.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),W.error(((p=(m=g==null?void 0:g.response)==null?void 0:m.data)==null?void 0:p.error)||((h=(u=g==null?void 0:g.response)==null?void 0:u.data)==null?void 0:h.message)||"Failed to resume workflow")}finally{o(!1)}},d=()=>{l||(i(""),s())};return e.jsx(xt,{open:t,onOpenChange:d,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Zi,{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(se,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(zs,{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(Dt,{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(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Zi,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function pf({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=x.useState(!1),o=async()=>{var c,d,m,p;try{l(!0),await W1(a),W.success("Retrigger request sent to approver"),n&&await n(),s()}catch(u){console.error("Failed to retrigger pause:",u),W.error(((d=(c=u==null?void 0:u.response)==null?void 0:c.data)==null?void 0:d.error)||((p=(m=u==null?void 0:u.response)==null?void 0:m.data)==null?void 0:p.message)||"Failed to send retrigger request")}finally{l(!1)}};return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[450px]",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{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(Dt,{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(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:gk,ActivityTab:fk,WorkNotesTab:bk,SummaryTab:jk,RequestDetailHeader:yk,QuickActionsSidebar:vk,RequestDetailModals:Nk}=mf;let wk=class extends x.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("Custom RequestDetail Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(ss,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(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 Ck({requestId:t,onBack:s,dynamicRequests:a=[]}){var Xr,Ja,yr,qa,vr,Nr,er,Pa,tr;const n=Va().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=x.useState(l),[d,m]=x.useState(!1),[p,u]=x.useState(null),[h,g]=x.useState(null),[f,b]=x.useState(!1),[j,y]=x.useState(0),[N,S]=x.useState(!1),[A,w]=x.useState(!1),[I,D]=x.useState(!1),[T,v]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[M,P]=x.useState({open:!1,violations:[]}),{user:B}=us(),{request:k,apiRequest:_,loading:L,refreshing:R,refreshDetails:C,currentApprovalLevel:G,isSpectator:U,isInitiator:$,existingParticipants:F,accessDenied:H}=Nd(n,a,B),{mergedMessages:K,unreadWorkNotes:z,workNoteAttachments:O,setWorkNoteAttachments:V}=Z0(n,_,o,B),{uploadingDocument:Q,triggerFileInput:q,previewDocument:ee,setPreviewDocument:te,documentPolicy:ue,documentError:_e,setDocumentError:Ze}=J0(_,C),{showApproveModal:Ue,setShowApproveModal:Pe,showRejectModal:De,setShowRejectModal:le,showAddApproverModal:ye,setShowAddApproverModal:ae,showAddSpectatorModal:he,setShowAddSpectatorModal:ne,showSkipApproverModal:ge,setShowSkipApproverModal:ke,showActionStatusModal:Oe,setShowActionStatusModal:je,skipApproverData:ie,setSkipApproverData:Se,actionStatus:qe,setActionStatus:rt,handleApproveConfirm:gt,handleRejectConfirm:It,handleAddApprover:oe,handleSkipApprover:Me,handleAddSpectator:me}=ef(n,G,C),{conclusionRemark:Xe,setConclusionRemark:Qe,conclusionLoading:nt,conclusionSubmitting:Ke,aiGenerated:lt,handleGenerateConclusion:et,handleFinalizeConclusion:ut,generationAttempts:Hs,generationFailed:is,maxAttemptsReached:vt}=q0(k,n,$,C,s,rt,je);x.useEffect(()=>{(async()=>{var As;try{const la=await ua("SYSTEM_SETTINGS"),wr=await ua("WORKFLOW_SHARING"),Cr=[...la,...wr],Sa={};Cr.forEach(sr=>{Sa[sr.configKey]=sr.configValue}),v({maxApprovalLevels:parseInt(Sa.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Sa.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((As=Sa.ALLOW_ADD_SPECTATOR)==null?void 0:As.toLowerCase())==="true",maxSpectators:parseInt(Sa.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(la){console.error("Failed to load system policy:",la)}})()},[]),x.useEffect(()=>{const As=new URLSearchParams(window.location.search).get("tab");As&&c(As)},[n]);const pt=()=>{C()},Pt=()=>{S(!0)},Ss=()=>{w(!0)},as=async()=>{await C()},za=()=>{D(!0)},Ha=async()=>{await C()},br=async()=>{await C()},wa=async()=>{if(!(_!=null&&_.requestId)){W.error("Request ID not found");return}if(!p){W.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Lt=((k==null?void 0:k.status)==="approved"||(k==null?void 0:k.status)==="rejected")&&$,Ca=(k==null?void 0:k.status)==="closed"||(k==null?void 0:k.status)==="approved"&&!$||(k==null?void 0:k.status)==="rejected"&&!$,Us=((k==null?void 0:k.templateType)||(k==null?void 0:k.template_type)||"").toString().toUpperCase()==="FORM_16";x.useEffect(()=>{Us&&o==="worknotes"&&c("overview")},[Us,o]),x.useEffect(()=>{(async()=>{if(!Ca||!(_!=null&&_.requestId)){g(null),u(null);return}try{b(!0);const As=await lf(_.requestId);if(As!=null&&As.summaryId){u(As.summaryId);try{const la=await Cd(As.summaryId);g(la)}catch(la){console.error("Failed to fetch summary details:",la),g(null),u(null)}}else g(null),u(null)}catch{g(null),u(null)}finally{b(!1)}})()},[Ca,_==null?void 0:_.requestId]);const Qr=((k==null?void 0:k.approvalFlow)||[]).filter(Qt=>Qt&&typeof Qt.step=="number").map(Qt=>({levelNumber:Qt.step||0,approverName:Qt.approver||"Unknown",status:Qt.status||"pending",tatHours:Qt.tatHours||24}));if(L&&!k&&!_)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(Et,{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(H!=null&&H.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(lp,{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:H.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(!k)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(Fe,{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 Kr=(B==null?void 0:B.role)==="MANAGEMENT"||(B==null?void 0:B.role)==="ADMIN",jr=((Xr=tt.getUserData())==null?void 0:Xr.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(yk,{request:k,refreshing:R,onBack:s||(()=>window.history.back()),onRefresh:pt,onShareSummary:wa,isInitiator:$,slaData:((Ja=k==null?void 0:k.summary)==null?void 0:Ja.sla)||(k==null?void 0:k.sla)||null,isPaused:((yr=k==null?void 0:k.pauseInfo)==null?void 0:yr.isPaused)||!1}),e.jsxs(yi,{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(vi,{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($t,{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(op,{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"})]}),Ca&&h&&e.jsxs($t,{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(vc,{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($t,{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(Qs,{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($t,{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(Fe,{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($t,{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(Bt,{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($t,{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(Ys,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),z>0&&e.jsx(re,{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-red-500 text-white text-[10px] flex items-center justify-center p-0","data-testid":"worknotes-unread-badge",children:z>9?"9+":z})]})]})}),e.jsxs("div",{className:o==="worknotes"&&!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(Ut,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:Us?e.jsx(cC,{request:k}):e.jsx(sC,{request:k,isInitiator:$,needsClosure:Lt,conclusionRemark:Xe,setConclusionRemark:Qe,conclusionLoading:nt,conclusionSubmitting:Ke,aiGenerated:lt,handleGenerateConclusion:et,handleFinalizeConclusion:ut,onPause:Pt,onResume:Ss,onRetrigger:za,currentUserIsApprover:!!G,pausedByUserId:(vr=(qa=k==null?void 0:k.pauseInfo)==null?void 0:qa.pausedBy)==null?void 0:vr.userId,currentUserId:B==null?void 0:B.userId,generationAttempts:Hs,generationFailed:is,maxAttemptsReached:vt})}),Ca&&e.jsx(Ut,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(jk,{summary:h,loading:f,onShare:wa,isInitiator:$})}),e.jsx(Ut,{value:"workflow",className:"mt-0",children:Us?e.jsx(mC,{request:k,requestId:(_==null?void 0:_.requestId)||n,isReUser:Kr,onRefresh:C}):e.jsx(iC,{request:k,user:B,isInitiator:$,onSkipApprover:Qt=>{if(!Qt.levelId){alert("Level ID not available");return}Se(Qt),ke(!0)},onRefresh:C})}),e.jsx(Ut,{value:"documents",className:"mt-0",children:e.jsx(gk,{request:k,workNoteAttachments:O,uploadingDocument:Q,documentPolicy:ue,triggerFileInput:q,setPreviewDocument:te,downloadDocument:Ms,isSpectator:U})}),e.jsx(Ut,{value:"activity",className:"mt-0",children:e.jsx(fk,{request:k})}),!Us&&e.jsx(Ut,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(bk,{requestId:n,requestTitle:k.title,mergedMessages:K,setWorkNoteAttachments:V,isInitiator:$,isSpectator:U,currentLevels:Qr,onAddApprover:oe,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Qt=>P({open:!0,violations:Qt})})})]}),!jr&&o!=="worknotes"&&e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[Us&&Kr&&e.jsx(V5,{requestId:(_==null?void 0:_.requestId)||n,request:k,onRefresh:C}),e.jsx(vk,{request:k,isInitiator:$,isSpectator:U,currentApprovalLevel:G,onAddApprover:()=>ae(!0),onAddSpectator:()=>ne(!0),onApprove:()=>Pe(!0),onReject:()=>le(!0),onPause:Pt,onResume:Ss,onRetrigger:za,summaryId:p,refreshTrigger:j,pausedByUserId:(er=(Nr=k==null?void 0:k.pauseInfo)==null?void 0:Nr.pausedBy)==null?void 0:er.userId,currentUserId:B==null?void 0:B.userId,apiRequest:_,hideApproveReject:jr})]})]})]})]})}),d&&p&&e.jsx(uf,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(k==null?void 0:k.title)||"N/A",onSuccess:()=>{C(),y(Qt=>Qt+1)}}),N&&(_==null?void 0:_.requestId)&&e.jsx(xf,{isOpen:N,onClose:()=>S(!1),requestId:_.requestId,levelId:(G==null?void 0:G.levelId)||null,onSuccess:Ha}),A&&(_==null?void 0:_.requestId)&&e.jsx(hf,{isOpen:A,onClose:()=>w(!1),requestId:_.requestId,onSuccess:as}),I&&(_==null?void 0:_.requestId)&&e.jsx(pf,{isOpen:I,onClose:()=>D(!1),requestId:_.requestId,approverName:(tr=(Pa=k==null?void 0:k.pauseInfo)==null?void 0:Pa.pausedBy)==null?void 0:tr.name,onSuccess:br}),e.jsx(Nk,{showApproveModal:Ue,showRejectModal:De,showAddApproverModal:ye,showAddSpectatorModal:he,showSkipApproverModal:ge,showActionStatusModal:Oe,previewDocument:ee,documentError:_e,request:k,skipApproverData:ie,actionStatus:qe,existingParticipants:F,currentLevels:Qr,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Qt=>P({open:!0,violations:Qt}),setShowApproveModal:Pe,setShowRejectModal:le,setShowAddApproverModal:ae,setShowAddSpectatorModal:ne,setShowSkipApproverModal:ke,setShowActionStatusModal:je,setPreviewDocument:te,setDocumentError:Ze,setSkipApproverData:Se,setActionStatus:rt,handleApproveConfirm:gt,handleRejectConfirm:It,handleAddApprover:oe,handleAddSpectator:me,handleSkipApprover:Me,downloadDocument:Ms,documentPolicy:ue}),e.jsx(ji,{open:M.open,onClose:()=>P({open:!1,violations:[]}),violations:M.violations,policyDetails:{maxApprovalLevels:T.maxApprovalLevels,maxParticipants:T.maxParticipants,allowSpectators:T.allowSpectators,maxSpectators:T.maxSpectators}})]})}function Sk(t){return e.jsx(wk,{children:e.jsx(Ck,{...t})})}const Ak=[{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 Tk(){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 kk({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:u,onForm16QuarterChange:h,onSortByChange:g,onSortOrderChange:f,onClearFilters:b,activeFiltersCount:j}){const y=Tk(),N=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0",children:[e.jsx(ce,{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(Ua,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(we,{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(yt,{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(J,{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(Zt,{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(Re,{placeholder:"Search requests, IDs...",value:t,onChange:S=>c(S.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors"})]}),e.jsxs(He,{value:a,onValueChange:m,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"All Priorities"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Priorities"}),e.jsx(X,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ia,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(X,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:s,onValueChange:d,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"All Statuses"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Statuses"}),e.jsx(X,{value:"pending",children:"Pending (In Approval)"}),e.jsx(X,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs(He,{value:r,onValueChange:p,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Request type"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Templates"}),e.jsx(X,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(X,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(X,{value:"FORM_16",children:"Form 16"})]})]}),N&&u&&e.jsxs(He,{value:n||void 0,onValueChange:u,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Financial Year"})}),e.jsx(Ye,{children:y.map(S=>e.jsx(X,{value:S,children:S},S))})]}),N&&h&&e.jsxs(He,{value:i||void 0,onValueChange:h,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Quarter"})}),e.jsx(Ye,{children:Ak.map(S=>e.jsx(X,{value:S.value,children:S.label},S.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:l,onValueChange:S=>g(S),children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"due",children:"Due Date"}),e.jsx(X,{value:"created",children:"Date Created"}),e.jsx(X,{value:"priority",children:"Priority"}),e.jsx(X,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(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(yl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(vl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}const Dk=[{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 Rk(){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 Fk({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:u,onForm16FinancialYearChange:h,onForm16QuarterChange:g,onSortByChange:f,onSortOrderChange:b,onClearFilters:j}){const y=Rk(),N=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(ce,{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(Ua,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(we,{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(yt,{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(J,{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(Zt,{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(Re,{placeholder:"Search requests, IDs...",value:t,onChange:S=>d(S.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white transition-colors","data-testid":"closed-requests-search"})]}),e.jsxs(He,{value:s,onValueChange:m,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-priority-filter",children:e.jsx(Ge,{placeholder:"All Priorities"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Priorities"}),e.jsx(X,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ia,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(X,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:a,onValueChange:p,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-status-filter",children:e.jsx(Ge,{placeholder:"Closure Type"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Closures"}),e.jsx(X,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(X,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs(He,{value:r,onValueChange:u,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-template-type-filter",children:e.jsx(Ge,{placeholder:"Request type"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Templates"}),e.jsx(X,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(X,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(X,{value:"FORM_16",children:"Form 16"})]})]}),N&&h&&e.jsxs(He,{value:n||void 0,onValueChange:h,children:[e.jsx(We,{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(Ge,{placeholder:"Financial Year"})}),e.jsx(Ye,{children:y.map(S=>e.jsx(X,{value:S,children:S},S))})]}),N&&g&&e.jsxs(He,{value:i||void 0,onValueChange:g,children:[e.jsx(We,{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(Ge,{placeholder:"Quarter"})}),e.jsx(Ye,{children:Dk.map(S=>e.jsx(X,{value:S.value,children:S.label},S.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:l,onValueChange:S=>f(S),children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-sort-by",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"due",children:"Due Date"}),e.jsx(X,{value:"created",children:"Date Created"}),e.jsx(X,{value:"priority",children:"Priority"})]})]}),e.jsx(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(yl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(vl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function Ik({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:u,departments:h,loadingDepartments:g,initiatorSearch:f,approverSearch:b,showForm16Filter:j=!1,form16FinancialYear:y="all",form16Quarter:N="all",onForm16FinancialYearChange:S,onForm16QuarterChange:A,onSearchChange:w,onStatusChange:I,onPriorityChange:D,onTemplateTypeChange:T,onDepartmentChange:v,onSlaComplianceChange:M,onInitiatorChange:P,onApproverChange:B,onApproverTypeChange:k,onDateRangeChange:_,onCustomStartDateChange:L,onCustomEndDateChange:R,onShowCustomDatePickerChange:C,onApplyCustomDate:G,onClearFilters:U,hasActiveFilters:$}){return e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"user-all-requests-filters",children:e.jsx(J,{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(Ua,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),$&&e.jsx(re,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),$&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:U,className:"gap-2",children:[e.jsx(Et,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Jt,{}),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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Re,{placeholder:"Search requests...",value:t,onChange:F=>w(F.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:I,children:[e.jsx(We,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Status"}),e.jsx(X,{value:"pending",children:"Pending"}),e.jsx(X,{value:"paused",children:"Paused"}),e.jsx(X,{value:"approved",children:"Approved"}),e.jsx(X,{value:"rejected",children:"Rejected"}),e.jsx(X,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:D,children:[e.jsx(We,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"All Priority"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Priority"}),e.jsx(X,{value:"express",children:"Express"}),e.jsx(X,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:T,children:[e.jsx(We,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Templates"}),e.jsx(X,{value:"CUSTOM",children:"Custom"}),e.jsx(X,{value:"DEALER CLAIM",children:"Dealer Claim"}),j&&e.jsx(X,{value:"FORM_16",children:"Form 16"})]})]}),j&&r==="FORM_16"&&e.jsxs(e.Fragment,{children:[e.jsxs(He,{value:y,onValueChange:S??(()=>{}),children:[e.jsx(We,{className:"h-10","data-testid":"form16-financial-year-filter",children:e.jsx(Ge,{placeholder:"Financial Year"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Years"}),e.jsx(X,{value:"2024-25",children:"2024-25"}),e.jsx(X,{value:"2023-24",children:"2023-24"}),e.jsx(X,{value:"2022-23",children:"2022-23"})]})]}),e.jsxs(He,{value:N,onValueChange:A??(()=>{}),children:[e.jsx(We,{className:"h-10","data-testid":"form16-quarter-filter",children:e.jsx(Ge,{placeholder:"Quarter"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Quarters"}),e.jsx(X,{value:"Q1",children:"Q1"}),e.jsx(X,{value:"Q2",children:"Q2"}),e.jsx(X,{value:"Q3",children:"Q3"}),e.jsx(X,{value:"Q4",children:"Q4"})]})]})]}),e.jsxs(He,{value:n,onValueChange:v,disabled:g||h.length===0,children:[e.jsx(We,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ge,{placeholder:g?"Loading...":"All Departments"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Departments"}),h.map(F=>e.jsx(X,{value:F,children:F},F))]})]}),e.jsxs(He,{value:i,onValueChange:M,children:[e.jsx(We,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"All SLA Status"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All SLA Status"}),e.jsx(X,{value:"compliant",children:"Compliant"}),e.jsx(X,{value:"on-track",children:"On Track"}),e.jsx(X,{value:"approaching",children:"Approaching"}),e.jsx(X,{value:"critical",children:"Critical"}),e.jsx(X,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(se,{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(yt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{placeholder:"Search initiator...",value:f.searchQuery,onChange:F=>f.handleSearch(F.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(F=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(F),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:F.displayName||F.email}),F.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:F.email})]})},F.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{className:"text-sm font-medium text-gray-700",children:"Approver"}),o!=="all"&&k&&e.jsxs(He,{value:c,onValueChange:F=>k(F),children:[e.jsx(We,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"current",children:"Current Only"}),e.jsx(X,{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(yt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{placeholder:"Search approver...",value:b.searchQuery,onChange:F=>b.handleSearch(F.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(F=>e.jsx("button",{type:"button",onClick:()=>b.handleSelect(F),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:F.displayName||F.email}),F.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:F.email})]})},F.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(ft,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:d,onValueChange:F=>_(F),children:[e.jsx(We,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),d==="custom"&&e.jsxs(aa,{open:u,onOpenChange:C,children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ft,{className:"w-4 h-4"}),m&&p?`${st(m,"MMM d, yyyy")} - ${st(p,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(na,{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(se,{htmlFor:"start-date",children:"Start Date"}),e.jsx(ta,{value:m||null,onChange:F=>{const H=F?new Date(F):void 0;H?(L==null||L(H),p&&H>p&&(R==null||R(H))):L==null||L(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"end-date",children:"End Date"}),e.jsx(ta,{value:p||null,onChange:F=>{const H=F?new Date(F):void 0;H?(R==null||R(H),m&&H<m&&(L==null||L(H))):R==null||R(void 0)},minDate:m||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{size:"sm",onClick:G,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:()=>{C==null||C(!1),L==null||L(void 0),R==null||R(void 0),_("month")},children:"Cancel"})]})]})})]})]})]})})})}function Pk({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:u,handleFinalizeConclusion:h,generationAttempts:g=0,generationFailed:f=!1,maxAttemptsReached:b=!1}){var A,w,I,D,T,v,M,P,B;if(!li(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=of(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=cf(s,a),N=df(y),S={name:((A=s.initiator)==null?void 0:A.name)||((w=s.initiator)==null?void 0:w.displayName)||((I=s.initiator)==null?void 0:I.email)||"Unknown",role:((D=s.initiator)==null?void 0:D.role)||((T=s.initiator)==null?void 0:T.designation)||"Initiator",department:((v=s.initiator)==null?void 0:v.department)||s.department||"",email:((M=s.initiator)==null?void 0:M.email)||"N/A",phone:((P=s.initiator)==null?void 0:P.phone)||((B=s.initiator)==null?void 0:B.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(ik,{activityInfo:j.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(lk,{dealerInfo:j.dealerInfo}),N.showProposalDetails&&j.proposalDetails&&e.jsx(ck,{proposalDetails:j.proposalDetails}),e.jsx(dk,{initiatorInfo:S}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-base",children:[e.jsx(Be,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(we,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(J,{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 ",bs(s.closureDate)]}),e.jsxs("span",{children:["By ",S.name]})]})]})]}),l&&e.jsxs(Z,{"data-testid":"conclusion-remark-card",children:[e.jsx(ce,{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(de,{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(Be,{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(we,{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."})]}),u&&e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:u,disabled:d||b,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Et,{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(J,{className:"pt-4",children:d?e.jsx("div",{className:"flex items-center justify-center py-8","data-testid":"conclusion-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ze,{className:"w-8 h-8 text-blue-600 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Preparing conclusion remark..."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Conclusion Remark"}),p&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),c&&e.jsx(hi,{value:o,onChange:k=>c(k),placeholder:"Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals...",className:"text-sm",minHeight:"160px","data-testid":"conclusion-remark-textarea"}),e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"This will be the final summary for this request"}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":"character-count",children:[o?o.replace(/<[^>]*>/g,"").length:0," / 2000 characters"]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-blue-900 mb-1.5",children:"Finalizing this request will:"}),e.jsxs("ul",{className:"text-xs sm:text-sm text-blue-800 space-y-0.5 pl-4",children:[e.jsx("li",{className:"list-disc",children:'Change request status to "CLOSED"'}),e.jsx("li",{className:"list-disc",children:"Notify all participants of closure"}),e.jsx("li",{className:"list-disc",children:"Move request to Closed Requests"}),e.jsx("li",{className:"list-disc",children:"Save conclusion remark permanently"})]})]}),h&&e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(E,{onClick:h,disabled:m||!o.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function Ek({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]=x.useState(""),[p,u]=x.useState(!1),[h,g]=x.useState(null),f=async()=>{if(!d.trim()){W.error("Please provide approval comments");return}try{u(!0),g("approve"),await a(d),j(),s()}catch(N){console.error("Failed to approve request:",N),W.error("Failed to approve request. Please try again.")}finally{u(!1),g(null)}},b=async()=>{if(!d.trim()){W.error("Please provide rejection reason");return}try{u(!0),g("reject"),await r(d),j(),s()}catch(N){console.error("Failed to reject request:",N),W.error("Failed to reject request. Please try again.")}finally{u(!1),g(null)}},j=()=>{m(""),g(null)},y=()=>{p||(j(),s())};return t?e.jsx(xt,{open:t,onOpenChange:y,children:e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(ht,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(Be,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(_t,{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(Fe,{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(Ys,{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(zs,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:d,onChange:N=>m(N.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(Dt,{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&&h==="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&&h==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function _k({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:c,dueDate:d,taxationType:m}){const[p,u]=x.useState(!1),[h,g]=x.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?bs(n.creditNoteDate,{includeTime:!1,format:"short"}):"",N=(n==null?void 0:n.creditNoteAmount)||0,S=(n==null?void 0:n.transactionNo)||"",A=(n==null?void 0:n.tdsAmount)||0,w=(n==null?void 0:n.creditAmount)||0,I=(n==null?void 0:n.status)||"PENDING",D=(n==null?void 0:n.items)||[],T=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",v=(i==null?void 0:i.dealerCode)||"RE-JP-009",M=l||"Activity",P=o||"RE-REQ-2024-CM-101",B=d?bs(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",k=(()=>{var C,G;if(D.length>1){const U=(C=D[0])==null?void 0:C.transactionNo,$=(G=D[D.length-1])==null?void 0:G.transactionNo;return U&&$&&U!==$?`${U} - ${$}`:U||S||"N/A"}return S||"N/A"})(),_=async()=>{if(a)try{u(!0),await a(),W.success("Credit note downloaded successfully")}catch(C){console.error("Failed to download credit note:",C),W.error("Failed to download credit note. Please try again.")}finally{u(!1)}else W.info("Credit note will be automatically saved to Documents tab")},L=async()=>{if(r)try{g(!0),await r(),W.success("Credit note sent to dealer successfully"),s()}catch(C){console.error("Failed to send credit note to dealer:",C),W.error("Failed to send credit note. Please try again.")}finally{g(!1)}else W.info("Email notification will be sent to dealer with credit note attachment")},R=C=>`₹${C.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"font-semibold flex items-center gap-2 text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note Details"]}),m&&e.jsx(re,{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(_t,{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(re,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),I==="APPROVED"?"Approved":I==="ISSUED"?"Issued":I==="SENT"?"Sent":"Confirmed"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4 mt-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100 shadow-sm",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Mo,{className:"w-3 h-3"}),"Credit Note No"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1",children:j})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100 shadow-sm",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(ft,{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-white rounded-lg p-3 border border-green-100 shadow-sm col-span-2 md:col-span-1",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Fe,{className:"w-3 h-3"}),"Transaction ID"]}),e.jsx("p",{className:"font-bold text-emerald-700 mt-1 break-all",children:k})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-4",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(Da,{className:"w-3 h-3"}),"Gross Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-blue-700",children:R(N)})]}),e.jsxs("div",{className:"bg-orange-50 border-2 border-orange-200 rounded-lg p-4",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(Da,{className:"w-3 h-3"}),"TDS Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-orange-700",children:R(A)})]}),e.jsxs("div",{className:"bg-emerald-50 border-2 border-emerald-200 rounded-lg p-4",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(Da,{className:"w-3 h-3"}),"Net Credit Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-emerald-700",children:R(w)})]})]}),D&&D.length>0&&e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden mt-2",children:[e.jsxs("div",{className:"bg-slate-50 px-4 py-2 border-b border-slate-200 flex items-center justify-between",children:[e.jsxs("h4",{className:"font-semibold text-slate-900 text-sm flex items-center gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 text-slate-500"}),"Line Item Breakdown"]}),e.jsxs(re,{variant:"outline",className:"text-[10px] font-medium uppercase tracking-wider",children:[D.length," ",D.length===1?"Item":"Items"]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto",children:e.jsxs("table",{className:"w-full text-sm text-left border-collapse",children:[e.jsx("thead",{className:"bg-white sticky top-0 shadow-sm z-10",children:e.jsxs("tr",{className:"border-b border-slate-200",children:[e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"Sl No"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"Transaction Code"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"HSN/SAC"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"Claim Amount"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"TDS"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"Net Credit"})]})}),e.jsx("tbody",{children:D.map((C,G)=>e.jsxs("tr",{className:"border-b border-slate-100 hover:bg-slate-50/50 transition-colors",children:[e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:C.slNo}),e.jsx("td",{className:"px-4 py-2.5 font-medium text-slate-900 font-mono text-[11px]",children:C.transactionNo||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:C.hsnCd||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-right font-medium text-slate-700",children:R(C.claimAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-orange-600 font-medium",children:R(C.tdsAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-emerald-700 font-bold",children:R(C.creditAmount||0)})]},G))})]})})]})]}):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(Mt,{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(jl,{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(se,{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:T})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(se,{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:v})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(se,{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:M})]})]})]}),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(Fe,{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(se,{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:P})]}),e.jsxs("div",{children:[e.jsx(se,{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:B})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Fe,{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(Dt,{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||h,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:_,disabled:p||h,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),p?"Downloading...":"Download"]}),e.jsxs(E,{onClick:L,disabled:p||h,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(np,{className:"w-4 h-4 mr-2"}),h?"Sending...":"Send to Dealer"]})]})})]})]})})}var hh=1,Mk=.9,Lk=.8,Ok=.17,go=.1,fo=.999,$k=.9999,Uk=.99,Bk=/[\\\/_+.#"@\[\(\{&]/,Vk=/[\\\/_+.#"@\[\(\{&]/g,zk=/[\s-]/,gf=/[\s-]/g;function oc(t,s,a,r,n,i,l){if(i===s.length)return n===t.length?hh:Uk;var o=`${n},${i}`;if(l[o]!==void 0)return l[o];for(var c=r.charAt(i),d=a.indexOf(c,n),m=0,p,u,h,g;d>=0;)p=oc(t,s,a,r,d+1,i+1,l),p>m&&(d===n?p*=hh:Bk.test(t.charAt(d-1))?(p*=Lk,h=t.slice(n,d-1).match(Vk),h&&n>0&&(p*=Math.pow(fo,h.length))):zk.test(t.charAt(d-1))?(p*=Mk,g=t.slice(n,d-1).match(gf),g&&n>0&&(p*=Math.pow(fo,g.length))):(p*=Ok,n>0&&(p*=Math.pow(fo,d-n))),t.charAt(d)!==s.charAt(i)&&(p*=$k)),(p<go&&a.charAt(d-1)===r.charAt(i+1)||r.charAt(i+1)===r.charAt(i)&&a.charAt(d-1)!==r.charAt(i))&&(u=oc(t,s,a,r,d+1,i+2,l),u*go>p&&(p=u*go)),p>m&&(m=p),d=a.indexOf(c,d+1);return l[o]=m,m}function ph(t){return t.toLowerCase().replace(gf," ")}function Hk(t,s,a){return t=a&&a.length>0?`${t+" "+a.join(" ")}`:t,oc(t,s,ph(t),ph(s),0,0,{})}var Ln='[cmdk-group=""]',bo='[cmdk-group-items=""]',Gk='[cmdk-group-heading=""]',ff='[cmdk-item=""]',gh=`${ff}:not([aria-disabled="true"])`,cc="cmdk-item-select",en="data-value",Wk=(t,s,a)=>Hk(t,s,a),bf=x.createContext(void 0),Ni=()=>x.useContext(bf),jf=x.createContext(void 0),Ad=()=>x.useContext(jf),yf=x.createContext(void 0),vf=x.forwardRef((t,s)=>{let a=tn(()=>{var F,H;return{search:"",value:(H=(F=t.value)!=null?F:t.defaultValue)!=null?H:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=tn(()=>new Set),n=tn(()=>new Map),i=tn(()=>new Map),l=tn(()=>new Set),o=Nf(t),{label:c,children:d,value:m,onValueChange:p,filter:u,shouldFilter:h,loop:g,disablePointerSelection:f=!1,vimBindings:b=!0,...j}=t,y=cn(),N=cn(),S=cn(),A=x.useRef(null),w=a4();zr(()=>{if(m!==void 0){let F=m.trim();a.current.value=F,I.emit()}},[m]),zr(()=>{w(6,B)},[]);let I=x.useMemo(()=>({subscribe:F=>(l.current.add(F),()=>l.current.delete(F)),snapshot:()=>a.current,setState:(F,H,K)=>{var z,O,V,Q;if(!Object.is(a.current[F],H)){if(a.current[F]=H,F==="search")P(),v(),w(1,M);else if(F==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let q=document.getElementById(S);q?q.focus():(z=document.getElementById(y))==null||z.focus()}if(w(7,()=>{var q;a.current.selectedItemId=(q=k())==null?void 0:q.id,I.emit()}),K||w(5,B),((O=o.current)==null?void 0:O.value)!==void 0){let q=H??"";(Q=(V=o.current).onValueChange)==null||Q.call(V,q);return}}I.emit()}},emit:()=>{l.current.forEach(F=>F())}}),[]),D=x.useMemo(()=>({value:(F,H,K)=>{var z;H!==((z=i.current.get(F))==null?void 0:z.value)&&(i.current.set(F,{value:H,keywords:K}),a.current.filtered.items.set(F,T(H,K)),w(2,()=>{v(),I.emit()}))},item:(F,H)=>(r.current.add(F),H&&(n.current.has(H)?n.current.get(H).add(F):n.current.set(H,new Set([F]))),w(3,()=>{P(),v(),a.current.value||M(),I.emit()}),()=>{i.current.delete(F),r.current.delete(F),a.current.filtered.items.delete(F);let K=k();w(4,()=>{P(),(K==null?void 0:K.getAttribute("id"))===F&&M(),I.emit()})}),group:F=>(n.current.has(F)||n.current.set(F,new Set),()=>{i.current.delete(F),n.current.delete(F)}),filter:()=>o.current.shouldFilter,label:c||t["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:y,inputId:S,labelId:N,listInnerRef:A}),[]);function T(F,H){var K,z;let O=(z=(K=o.current)==null?void 0:K.filter)!=null?z:Wk;return F?O(F,a.current.search,H):0}function v(){if(!a.current.search||o.current.shouldFilter===!1)return;let F=a.current.filtered.items,H=[];a.current.filtered.groups.forEach(z=>{let O=n.current.get(z),V=0;O.forEach(Q=>{let q=F.get(Q);V=Math.max(q,V)}),H.push([z,V])});let K=A.current;_().sort((z,O)=>{var V,Q;let q=z.getAttribute("id"),ee=O.getAttribute("id");return((V=F.get(ee))!=null?V:0)-((Q=F.get(q))!=null?Q:0)}).forEach(z=>{let O=z.closest(bo);O?O.appendChild(z.parentElement===O?z:z.closest(`${bo} > *`)):K.appendChild(z.parentElement===K?z:z.closest(`${bo} > *`))}),H.sort((z,O)=>O[1]-z[1]).forEach(z=>{var O;let V=(O=A.current)==null?void 0:O.querySelector(`${Ln}[${en}="${encodeURIComponent(z[0])}"]`);V==null||V.parentElement.appendChild(V)})}function M(){let F=_().find(K=>K.getAttribute("aria-disabled")!=="true"),H=F==null?void 0:F.getAttribute(en);I.setState("value",H||void 0)}function P(){var F,H,K,z;if(!a.current.search||o.current.shouldFilter===!1){a.current.filtered.count=r.current.size;return}a.current.filtered.groups=new Set;let O=0;for(let V of r.current){let Q=(H=(F=i.current.get(V))==null?void 0:F.value)!=null?H:"",q=(z=(K=i.current.get(V))==null?void 0:K.keywords)!=null?z:[],ee=T(Q,q);a.current.filtered.items.set(V,ee),ee>0&&O++}for(let[V,Q]of n.current)for(let q of Q)if(a.current.filtered.items.get(q)>0){a.current.filtered.groups.add(V);break}a.current.filtered.count=O}function B(){var F,H,K;let z=k();z&&(((F=z.parentElement)==null?void 0:F.firstChild)===z&&((K=(H=z.closest(Ln))==null?void 0:H.querySelector(Gk))==null||K.scrollIntoView({block:"nearest"})),z.scrollIntoView({block:"nearest"}))}function k(){var F;return(F=A.current)==null?void 0:F.querySelector(`${ff}[aria-selected="true"]`)}function _(){var F;return Array.from(((F=A.current)==null?void 0:F.querySelectorAll(gh))||[])}function L(F){let H=_()[F];H&&I.setState("value",H.getAttribute(en))}function R(F){var H;let K=k(),z=_(),O=z.findIndex(Q=>Q===K),V=z[O+F];(H=o.current)!=null&&H.loop&&(V=O+F<0?z[z.length-1]:O+F===z.length?z[0]:z[O+F]),V&&I.setState("value",V.getAttribute(en))}function C(F){let H=k(),K=H==null?void 0:H.closest(Ln),z;for(;K&&!z;)K=F>0?t4(K,Ln):s4(K,Ln),z=K==null?void 0:K.querySelector(gh);z?I.setState("value",z.getAttribute(en)):R(F)}let G=()=>L(_().length-1),U=F=>{F.preventDefault(),F.metaKey?G():F.altKey?C(1):R(1)},$=F=>{F.preventDefault(),F.metaKey?L(0):F.altKey?C(-1):R(-1)};return x.createElement(gr.div,{ref:s,tabIndex:-1,...j,"cmdk-root":"",onKeyDown:F=>{var H;(H=j.onKeyDown)==null||H.call(j,F);let K=F.nativeEvent.isComposing||F.keyCode===229;if(!(F.defaultPrevented||K))switch(F.key){case"n":case"j":{b&&F.ctrlKey&&U(F);break}case"ArrowDown":{U(F);break}case"p":case"k":{b&&F.ctrlKey&&$(F);break}case"ArrowUp":{$(F);break}case"Home":{F.preventDefault(),L(0);break}case"End":{F.preventDefault(),G();break}case"Enter":{F.preventDefault();let z=k();if(z){let O=new Event(cc);z.dispatchEvent(O)}}}}},x.createElement("label",{"cmdk-label":"",htmlFor:D.inputId,id:D.labelId,style:n4},c),Ml(t,F=>x.createElement(jf.Provider,{value:I},x.createElement(bf.Provider,{value:D},F))))}),Yk=x.forwardRef((t,s)=>{var a,r;let n=cn(),i=x.useRef(null),l=x.useContext(yf),o=Ni(),c=Nf(t),d=(r=(a=c.current)==null?void 0:a.forceMount)!=null?r:l==null?void 0:l.forceMount;zr(()=>{if(!d)return o.item(n,l==null?void 0:l.id)},[d]);let m=wf(n,i,[t.value,t.children,i],t.keywords),p=Ad(),u=pr(w=>w.value&&w.value===m.current),h=pr(w=>d||o.filter()===!1?!0:w.search?w.filtered.items.get(n)>0:!0);x.useEffect(()=>{let w=i.current;if(!(!w||t.disabled))return w.addEventListener(cc,g),()=>w.removeEventListener(cc,g)},[h,t.onSelect,t.disabled]);function g(){var w,I;f(),(I=(w=c.current).onSelect)==null||I.call(w,m.current)}function f(){p.setState("value",m.current,!0)}if(!h)return null;let{disabled:b,value:j,onSelect:y,forceMount:N,keywords:S,...A}=t;return x.createElement(gr.div,{ref:Zn(i,s),...A,id:n,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!u,"data-disabled":!!b,"data-selected":!!u,onPointerMove:b||o.getDisablePointerSelection()?void 0:f,onClick:b?void 0:g},t.children)}),Qk=x.forwardRef((t,s)=>{let{heading:a,children:r,forceMount:n,...i}=t,l=cn(),o=x.useRef(null),c=x.useRef(null),d=cn(),m=Ni(),p=pr(h=>n||m.filter()===!1?!0:h.search?h.filtered.groups.has(l):!0);zr(()=>m.group(l),[]),wf(l,o,[t.value,t.heading,c]);let u=x.useMemo(()=>({id:l,forceMount:n}),[n]);return x.createElement(gr.div,{ref:Zn(o,s),...i,"cmdk-group":"",role:"presentation",hidden:p?void 0:!0},a&&x.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},a),Ml(t,h=>x.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":a?d:void 0},x.createElement(yf.Provider,{value:u},h))))}),Kk=x.forwardRef((t,s)=>{let{alwaysRender:a,...r}=t,n=x.useRef(null),i=pr(l=>!l.search);return!a&&!i?null:x.createElement(gr.div,{ref:Zn(n,s),...r,"cmdk-separator":"",role:"separator"})}),Xk=x.forwardRef((t,s)=>{let{onValueChange:a,...r}=t,n=t.value!=null,i=Ad(),l=pr(d=>d.search),o=pr(d=>d.selectedItemId),c=Ni();return x.useEffect(()=>{t.value!=null&&i.setState("search",t.value)},[t.value]),x.createElement(gr.input,{ref:s,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":o,id:c.inputId,type:"text",value:n?t.value:l,onChange:d=>{n||i.setState("search",d.target.value),a==null||a(d.target.value)}})}),Zk=x.forwardRef((t,s)=>{let{children:a,label:r="Suggestions",...n}=t,i=x.useRef(null),l=x.useRef(null),o=pr(d=>d.selectedItemId),c=Ni();return x.useEffect(()=>{if(l.current&&i.current){let d=l.current,m=i.current,p,u=new ResizeObserver(()=>{p=requestAnimationFrame(()=>{let h=d.offsetHeight;m.style.setProperty("--cmdk-list-height",h.toFixed(1)+"px")})});return u.observe(d),()=>{cancelAnimationFrame(p),u.unobserve(d)}}},[]),x.createElement(gr.div,{ref:Zn(i,s),...n,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},Ml(t,d=>x.createElement("div",{ref:Zn(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),Jk=x.forwardRef((t,s)=>{let{open:a,onOpenChange:r,overlayClassName:n,contentClassName:i,container:l,...o}=t;return x.createElement(Bh,{open:a,onOpenChange:r},x.createElement(Uh,{container:l},x.createElement(mc,{"cmdk-overlay":"",className:n}),x.createElement(uc,{"aria-label":t.label,"cmdk-dialog":"",className:i},x.createElement(vf,{ref:s,...o}))))}),qk=x.forwardRef((t,s)=>pr(a=>a.filtered.count===0)?x.createElement(gr.div,{ref:s,...t,"cmdk-empty":"",role:"presentation"}):null),e4=x.forwardRef((t,s)=>{let{progress:a,children:r,label:n="Loading...",...i}=t;return x.createElement(gr.div,{ref:s,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":100,"aria-label":n},Ml(t,l=>x.createElement("div",{"aria-hidden":!0},l)))}),Tn=Object.assign(vf,{List:Zk,Item:Yk,Input:Xk,Group:Qk,Separator:Kk,Dialog:Jk,Empty:qk,Loading:e4});function t4(t,s){let a=t.nextElementSibling;for(;a;){if(a.matches(s))return a;a=a.nextElementSibling}}function s4(t,s){let a=t.previousElementSibling;for(;a;){if(a.matches(s))return a;a=a.previousElementSibling}}function Nf(t){let s=x.useRef(t);return zr(()=>{s.current=t}),s}var zr=typeof window>"u"?x.useEffect:x.useLayoutEffect;function tn(t){let s=x.useRef();return s.current===void 0&&(s.current=t()),s}function pr(t){let s=Ad(),a=()=>t(s.snapshot());return x.useSyncExternalStore(s.subscribe,a,a)}function wf(t,s,a,r=[]){let n=x.useRef(),i=Ni();return zr(()=>{var l;let o=(()=>{var d;for(let m of a){if(typeof m=="string")return m.trim();if(typeof m=="object"&&"current"in m)return m.current?(d=m.current.textContent)==null?void 0:d.trim():n.current}})(),c=r.map(d=>d.trim());i.value(t,o,c),(l=s.current)==null||l.setAttribute(en,o),n.current=o}),n}var a4=()=>{let[t,s]=x.useState(),a=tn(()=>new Map);return zr(()=>{a.current.forEach(r=>r()),a.current=new Map},[t]),(r,n)=>{a.current.set(r,n),s({})}};function r4(t){let s=t.type;return typeof s=="function"?s(t.props):"render"in s?s.render(t.props):t}function Ml({asChild:t,children:s},a){return t&&x.isValidElement(s)?x.cloneElement(r4(s),{ref:s.ref},a(s.props.children)):a(s)}var n4={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function i4({className:t,...s}){return e.jsx(Tn,{"data-slot":"command",className:Le("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",t),...s})}function l4({className:t,wrapperClassName:s,...a}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:Le("flex h-9 items-center gap-2 border-b px-3",s),children:[e.jsx(Zt,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Tn.Input,{"data-slot":"command-input",className:Le("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",t),...a})]})}function o4({className:t,...s}){return e.jsx(Tn.List,{"data-slot":"command-list",className:Le("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",t),...s})}function c4({...t}){return e.jsx(Tn.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...t})}function d4({className:t,...s}){return e.jsx(Tn.Group,{"data-slot":"command-group",className:Le("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",t),...s})}function m4({className:t,...s}){return e.jsx(Tn.Item,{"data-slot":"command-item",className:Le("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_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=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}async function Cf(t=!1,s=1,a=10,r){var c,d;const n={active:t,page:s,limit:a};r&&(n.search=r);const i=await ve.get("/hsn-sac",{params:n}),l=(c=i.data)==null?void 0:c.data,o=(d=i.data)==null?void 0:d.pagination;return Array.isArray(l)&&o?{codes:l,pagination:o}:{codes:Array.isArray(l)?l:[],pagination:o||{totalRecords:0,totalPages:0,currentPage:1,limit:10}}}async function u4(t){var a;const s=await ve.post("/hsn-sac",t);return((a=s.data)==null?void 0:a.data)||s.data}async function x4(t,s){var r;const a=await ve.patch(`/hsn-sac/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function h4(t){await ve.delete(`/hsn-sac/${t}`)}async function p4(t){var a;const s=await ve.patch(`/hsn-sac/${t}/toggle-active`);return((a=s.data)==null?void 0:a.data)||s.data}function Sf({value:t,onChange:s,type:a,placeholder:r,disabled:n,className:i}){var p;const[l,o]=x.useState(!1),[c,d]=x.useState([]);x.useEffect(()=>{const u=async()=>{try{const h=await Cf(!0,1,1e3);d(h.codes)}catch(h){console.error("Failed to fetch HSN/SAC codes for selector:",h)}};l&&c.length===0&&u()},[l,c.length]);const m=x.useMemo(()=>c.filter(u=>u.type===a),[c,a]);return e.jsxs(aa,{open:l,onOpenChange:o,children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{variant:"outline",role:"combobox","aria-expanded":l,disabled:n,className:Le("w-full justify-between bg-white font-normal h-9 px-3 text-xs sm:text-sm border-slate-200 hover:bg-slate-50",i),children:[e.jsx("span",{className:"font-medium text-slate-900",children:t?((p=c.find(u=>u.code===t))==null?void 0:p.code)||t:r||`Select ${a}...`}),e.jsx(Ej,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(na,{className:"w-[320px] p-0 shadow-2xl border-slate-200",align:"start",children:e.jsxs(i4,{className:"rounded-lg border-0",children:[e.jsxs("div",{className:"bg-slate-50/80 p-2.5 flex items-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4 text-slate-400"}),e.jsx(l4,{placeholder:`Search ${a} code...`,wrapperClassName:"border-none p-0 h-auto flex-1",className:"h-8 border-none bg-transparent shadow-none ring-0 focus-visible:ring-0 placeholder:text-slate-400 text-sm"})]}),e.jsxs(o4,{className:"max-h-[350px] scrollbar-thin scrollbar-thumb-slate-200",children:[e.jsx(c4,{className:"py-8 text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Zt,{className:"h-8 w-8 text-slate-200"}),e.jsxs("p",{className:"text-sm font-medium text-slate-500",children:["No ",a," code found"]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Try a different search term"})]})}),e.jsx(d4,{className:"p-1.5",children:m.map(u=>e.jsxs(m4,{value:u.code,onSelect:h=>{s(h),o(!1)},className:"flex flex-col items-start gap-1 p-2.5 rounded-md aria-selected:bg-slate-100 transition-colors cursor-pointer mb-1 last:mb-0",children:[e.jsxs("div",{className:"flex items-center w-full justify-between",children:[e.jsx("span",{className:"font-bold text-sm text-slate-900 leading-none",children:u.code}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx($a,{className:Le("h-4 w-4 text-re-green transition-all",t===u.code?"opacity-100 scale-100":"opacity-0 scale-75")})})]}),u.description&&e.jsx("span",{className:"text-[11px] text-slate-500 line-clamp-2 leading-tight pr-4",children:u.description})]},u.id))})]})]})})]})}const ba=(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:""}},g4={"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"},f4="33",b4=new Set(["04","25","26","31","35","38"]),Af=t=>{if(!t||t.length<2)return null;const s=t.substring(0,2);return g4[s]?s:null},j4=t=>t?b4.has(t):!1,y4=t=>t?t!==f4:!1,Tf=t=>{if(!t)return{isIGST:!1,isCGST:!0,isSGST:!0,isUTGST:!1};if(y4(t))return{isIGST:!0,isCGST:!1,isSGST:!1,isUTGST:!1};const a=j4(t);return{isIGST:!1,isCGST:!0,isSGST:!a,isUTGST:a}};function v4({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 ae,he;const[m,p]=x.useState(""),[u,h]=x.useState(""),g=x.useMemo(()=>{const ne=Af(n);return Tf(ne)},[n]),f=x.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),[b,j]=x.useState([]),[y,N]=x.useState([]),[S,A]=x.useState([]),[w,I]=x.useState([]),[D,T]=x.useState(null),[v,M]=x.useState(""),[P,B]=x.useState(!1),[k,_]=x.useState(null),L=x.useRef(null),R=x.useRef(null),C=x.useRef(null),G=x.useRef(null),U=ne=>{const ge=ne.type.toLowerCase(),ke=ne.name.toLowerCase();return ge.includes("image")||ge.includes("pdf")||ke.endsWith(".pdf")||ke.endsWith(".jpg")||ke.endsWith(".jpeg")||ke.endsWith(".png")||ke.endsWith(".gif")||ke.endsWith(".webp")};x.useEffect(()=>()=>{k!=null&&k.url&&URL.revokeObjectURL(k.url)},[k]),x.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 $=ne=>{if(!U(ne)){W.error("Preview is only available for images and PDF files");return}k!=null&&k.url&&URL.revokeObjectURL(k.url);const ge=URL.createObjectURL(ne);_({file:ne,url:ge})},F=ne=>{const ge=URL.createObjectURL(ne),ke=document.createElement("a");ke.href=ge,ke.download=ne.name,document.body.appendChild(ke),ke.click(),document.body.removeChild(ke),URL.revokeObjectURL(ge)},H=x.useMemo(()=>b.reduce((ne,ge)=>ne+(ge.totalAmt||ge.amount||0),0),[b]),K=(ne,ge,ke=1)=>{const Oe=ne*ke,je=Oe*(ge.cgstRate||0)/100,ie=Oe*(ge.sgstRate||0)/100,Se=Oe*(ge.utgstRate||0)/100,qe=Oe*(ge.igstRate||0)/100,rt=je+ie+Se+qe,gt=Oe+rt;return{cgstRate:ge.cgstRate,cgstAmt:je,sgstRate:ge.sgstRate,sgstAmt:ie,utgstRate:ge.utgstRate,utgstAmt:Se,igstRate:ge.igstRate,igstAmt:qe,gstAmt:rt,gstRate:(ge.cgstRate||0)+(ge.sgstRate||0)+(ge.utgstRate||0)+(ge.igstRate||0),totalAmt:gt}},z=x.useMemo(()=>{const ne=m!=="",ge=y.length>0,ke=S.length>0,Oe=v.trim().length>0,je=b.length>0&&b.every(Se=>Se.description.trim()!==""&&Se.amount>0),ie=f?!1:b.some(Se=>{const{isValid:qe}=ba(Se.hsnCode,Se.isService);return!qe});return ne&&ge&&ke&&Oe&&je&&!ie},[m,y,S,v,f,b]),O=new Date().toISOString().split("T")[0],V=()=>{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}])},Q=(ne,ge,ke)=>{j(b.map(Oe=>{if(Oe.id===ne){let je={...Oe,[ge]:ke};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate","quantity"].includes(ge)){const ie=parseFloat(ke);if(!isNaN(ie)&&ie<0)return W.error("Value cannot be negative"),Oe;const Se=ge==="amount"?parseFloat(ke)||0:Oe.amount,qe=ge==="quantity"?parseInt(ke)||1:Oe.quantity;let rt=Oe.cgstRate,gt=Oe.sgstRate,It=Oe.utgstRate,oe=Oe.igstRate;if(ge==="cgstRate"){if(!g.isCGST)return Oe;rt=parseFloat(ke)||0,g.isUTGST?(It=rt,gt=0):(gt=rt,It=0),oe=0}else if(ge==="sgstRate"){if(!g.isSGST)return Oe;gt=parseFloat(ke)||0,rt=gt,It=0,oe=0}else if(ge==="utgstRate"){if(!g.isUTGST)return Oe;It=parseFloat(ke)||0,rt=It,gt=0,oe=0}else if(ge==="igstRate"){if(!g.isIGST)return Oe;oe=parseFloat(ke)||0,rt=0,gt=0,It=0}else if(ge==="gstRate"){const me=parseFloat(ke)||0;g.isIGST?(oe=me,rt=0,gt=0,It=0):(rt=me/2,g.isUTGST?(It=me/2,gt=0):(gt=me/2,It=0),oe=0)}const Me=K(Se,{cgstRate:rt,sgstRate:gt,igstRate:oe,utgstRate:It},qe);return ge==="isService"&&(je.hsnCode=""),{...je,amount:Se,quantity:qe,...Me}}return ge==="isService"&&(je.hsnCode=""),je}return Oe}))},q=ne=>{j(b.filter(ge=>ge.id!==ne))},ee=ne=>{const ge=Array.from(ne.target.files||[]);if(ge.length>0){const ke=[],Oe=c.maxFileSizeMB*1024*1024,je=[".pdf",".doc",".docx",".zip",".rar"];ge.forEach(ie=>{var rt,gt;const Se="."+((rt=ie.name.split(".").pop())==null?void 0:rt.toLowerCase()),qe=((gt=ie.name.split(".").pop())==null?void 0:gt.toLowerCase())||"";if(ie.size>Oe){W.error(`"${ie.name}" exceeds ${c.maxFileSizeMB}MB limit and was not added.`);return}if(!je.includes(Se)){W.error(`"${ie.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!c.allowedFileTypes.includes(qe)){W.error(`"${ie.name}" has an unallowed file type according to system policy.`);return}ke.push(ie)}),ke.length>0&&N([...y,...ke]),L.current&&(L.current.value="")}},te=ne=>{N(y.filter((ge,ke)=>ke!==ne))},ue=ne=>{const ge=Array.from(ne.target.files||[]);if(ge.length>0){const ke=[],Oe=c.maxFileSizeMB*1024*1024;ge.forEach(je=>{var Se;const ie=((Se=je.name.split(".").pop())==null?void 0:Se.toLowerCase())||"";if(je.size>Oe){W.error(`Photo "${je.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!je.type.startsWith("image/")){W.error(`"${je.name}" is not an image file.`);return}if(!c.allowedFileTypes.includes(ie)){W.error(`"${je.name}" has an unsupported image format.`);return}ke.push(je)}),ke.length>0&&A([...S,...ke]),R.current&&(R.current.value="")}},_e=ne=>{A(S.filter((ge,ke)=>ke!==ne))},Ze=ne=>{const ge=Array.from(ne.target.files||[]);if(ge.length>0){const ke=[],Oe=c.maxFileSizeMB*1024*1024,je=[".pdf",".jpg",".jpeg",".png"];ge.forEach(ie=>{var rt,gt;const Se="."+((rt=ie.name.split(".").pop())==null?void 0:rt.toLowerCase()),qe=((gt=ie.name.split(".").pop())==null?void 0:gt.toLowerCase())||"";if(ie.size>Oe){W.error(`Invoice "${ie.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!je.includes(Se)){W.error(`"${ie.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!c.allowedFileTypes.includes(qe)){W.error(`"${ie.name}" format is not allowed by system policy.`);return}ke.push(ie)}),ke.length>0&&I([...w,...ke]),C.current&&(C.current.value="")}},Ue=ne=>{I(w.filter((ge,ke)=>ke!==ne))},Pe=ne=>{var ke,Oe,je;const ge=(ke=ne.target.files)==null?void 0:ke[0];if(ge){const ie=c.maxFileSizeMB*1024*1024,Se=[".pdf",".xlsx",".xls",".csv"],qe="."+((Oe=ge.name.split(".").pop())==null?void 0:Oe.toLowerCase()),rt=((je=ge.name.split(".").pop())==null?void 0:je.toLowerCase())||"";if(ge.size>ie){W.error(`Attendance file exceeds ${c.maxFileSizeMB}MB limit.`),G.current&&(G.current.value="");return}if(!Se.includes(qe)){W.error("Please upload PDF, Excel, or CSV files only"),G.current&&(G.current.value="");return}if(!c.allowedFileTypes.includes(rt)){W.error(`"${ge.name}" format is not allowed by system policy.`),G.current&&(G.current.value="");return}T(ge)}},De=async()=>{if(!z){W.error("Please fill all required fields");return}if(b.some(Oe=>Oe.amount<0||Oe.quantity<1)){W.error("Please ensure all amounts are non-negative and quantity is at least 1");return}const ge=b.filter(Oe=>Oe.description.trim()!==""&&Oe.amount>0);if(!f&&ge.some(Oe=>Oe.description.trim()!==""&&Oe.amount>0&&(Oe.gstRate===0||!Oe.gstRate))&&!window.confirm(`One or more expenses have 0% GST. Are you sure you want to proceed?
|
||
|
||
Note: If these items are taxable, please provide a valid GST rate to ensure correct E-Invoice generation.`)){B(!1);return}try{B(!0),await a({activityCompletionDate:m,numberOfParticipants:u?parseInt(u):void 0,closedExpenses:ge,totalClosedExpenses:H,completionDocuments:y,activityPhotos:S,invoicesReceipts:w.length>0?w:void 0,attendanceSheet:D||void 0,completionDescription:v}),le(),s()}catch(Oe){console.error("Failed to submit completion documents:",Oe),wd(Oe)||W.error("Failed to submit completion documents. Please try again.")}finally{B(!1)}},le=()=>{k!=null&&k.url&&URL.revokeObjectURL(k.url),_(null),p(""),h(""),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}]),N([]),A([]),I([]),T(null),M(""),L.current&&(L.current.value=""),R.current&&(R.current.value=""),C.current&&(C.current.value=""),G.current&&(G.current.value="")},ye=()=>{P||(le(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(xt,{open:t,onOpenChange:ye,children:e.jsxs(dt,{className:"dealer-completion-documents-modal overflow-hidden flex flex-col",children:[e.jsxs(ht,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs(mt,{className:"font-semibold flex items-center gap-2 text-xl sm:text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{className:"w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]"}),"Activity Completion Documents"]}),d&&e.jsx(re,{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(_t,{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(se,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(ft,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Completion Date *"]}),e.jsx(ta,{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:V,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(ms,{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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item description"}),e.jsx(Re,{placeholder:"e.g., Venue rental, Refreshments",value:ne.description,onChange:ge=>Q(ne.id,"description",ge.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Re,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:ne.amount||"",onChange:ge=>Q(ne.id,"amount",ge.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Re,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:ne.amount||"",onChange:ge=>Q(ne.id,"amount",ge.target.value),className:"w-full bg-white text-sm pl-8"})]})]}),!f&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"w-32 sm:w-36 flex-shrink-0 relative pb-5",children:[e.jsx(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN/SAC Code"}),e.jsx(Sf,{value:ne.hsnCode||"",onChange:ge=>Q(ne.id,"hsnCode",ge),type:ne.isService?"SAC":"HSN",className:ba(ne.hsnCode,ne.isService).isValid?"":"border-red-500",placeholder:ne.isService?"SAC":"HSN"}),!ba(ne.hsnCode,ne.isService).isValid&&e.jsx("span",{className:"text-[10px] text-red-500 absolute left-0 bottom-0 block leading-tight",children:ba(ne.hsnCode,ne.isService).message})]}),e.jsxs("div",{className:"w-24 sm:w-28 flex-shrink-0",children:[e.jsx(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item Type"}),e.jsxs("select",{value:ne.isService?"SAC":"HSN",onChange:ge=>Q(ne.id,"isService",ge.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"CGST %"}),e.jsx(Re,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ne.cgstRate||"",onChange:ge=>Q(ne.id,"cgstRate",ge.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"SGST %"}),e.jsx(Re,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ne.sgstRate||"",onChange:ge=>Q(ne.id,"sgstRate",ge.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"UTGST %"}),e.jsx(Re,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ne.utgstRate||"",onChange:ge=>Q(ne.id,"utgstRate",ge.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"IGST %"}),e.jsx(Re,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ne.igstRate||"",onChange:ge=>Q(ne.id,"igstRate",ge.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:()=>q(ne.id),children:e.jsx(yt,{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(re,{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&&H>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:["₹",H.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(re,{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(se,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Fe,{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:L,type:"file",multiple:!0,accept:[".pdf",".doc",".docx",".zip",".rar"].filter(ne=>c.allowedFileTypes.includes(ne.replace(".",""))).join(","),className:"hidden",id:"completionDocs",onChange:ee}),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(ps,{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(ys,{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,ge)=>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(Fe,{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:[U(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:()=>$(ne),title:"Preview file",children:e.jsx(Nt,{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:()=>F(ne),title:"Download file",children:e.jsx(Tt,{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:()=>te(ge),title:"Remove document",children:e.jsx(yt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},ge))]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Mi,{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 ${S.length>0?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:R,type:"file",multiple:!0,accept:[".jpg",".jpeg",".png",".gif",".webp"].filter(ne=>c.allowedFileTypes.includes(ne.replace(".",""))).join(","),className:"hidden",id:"completionPhotos",onChange:ue}),e.jsx("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:S.length>0?e.jsxs(e.Fragment,{children:[e.jsx(ps,{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:[S.length," photo",S.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(Mi,{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)"})]})})]}),S.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 (",S.length,"):"]}),S.map((ne,ge)=>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(Mi,{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:[U(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:()=>$(ne),title:"Preview photo",children:e.jsx(Nt,{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:()=>F(ne),title:"Download photo",children:e.jsx(Tt,{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:()=>_e(ge),title:"Remove photo",children:e.jsx(yt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},ge))]})]})]})]}),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(re,{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(se,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Mt,{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 ${w.length>0?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:C,type:"file",multiple:!0,accept:[".pdf",".jpg",".jpeg",".png"].filter(ne=>c.allowedFileTypes.includes(ne.replace(".",""))).join(","),className:"hidden",id:"invoiceReceipts",onChange:Ze}),e.jsx("label",{htmlFor:"invoiceReceipts",className:"cursor-pointer flex flex-col items-center gap-2",children:w.length>0?e.jsxs(e.Fragment,{children:[e.jsx(ps,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-blue-700",children:[w.length," document",w.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-blue-600",children:"Click to add more documents"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Mt,{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)"})]})})]}),w.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",w.length,"):"]}),w.map((ne,ge)=>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(Mt,{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:[U(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:()=>$(ne),title:"Preview file",children:e.jsx(Nt,{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:()=>F(ne),title:"Download file",children:e.jsx(Tt,{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:()=>Ue(ge),title:"Remove document",children:e.jsx(yt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},ge))]})]}),e.jsxs("div",{children:[e.jsx(se,{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:G,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(ps,{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(ys,{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(Fe,{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:[U(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:()=>$(D),title:"Preview file",children:e.jsx(Nt,{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:()=>F(D),title:"Download file",children:e.jsx(Tt,{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:()=>{T(null),G.current&&(G.current.value="")},title:"Remove document",children:e.jsx(yt,{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(se,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(zs,{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=>M(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"]})]}),!z&&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(Je,{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 or Invalid Information"}),e.jsx("p",{children:"Please ensure completion date, documents/photos, description, and expense details (non-negative amounts and descriptions) are provided before submitting."})]})]})]}),e.jsxs(Dt,{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:ye,disabled:P,className:"border-2",children:"Cancel"}),e.jsx(E,{onClick:De,disabled:P||!z,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:P?"Submitting...":"Submit Documents"})]})]})}),k&&e.jsx(xt,{open:!!k,onOpenChange:()=>{k!=null&&k.url&&URL.revokeObjectURL(k.url),_(null)},children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ht,{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(Nt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:k.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[k.file.type||"Unknown type"," • ",(k.file.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>F(k.file),className:"gap-2 h-9",children:[e.jsx(Tt,{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:(ae=k.file.type)!=null&&ae.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:k.url,alt:k.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(he=k.file.type)!=null&&he.includes("pdf")||k.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:k.url,className:"w-full h-full rounded-lg border-0",title:k.file.name,style:{minHeight:"70vh",height:"100%"}})}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(Nt,{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:()=>F(k.file),className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",k.file.name]})]})})]})})})]})}function N4({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[u,h]=x.useState(null),g=x.useMemo(()=>{const le=Af(n);return Tf(le)},[n]),f=x.useMemo(()=>m==="Non GST"||m==="Non-GST",[m]),[b,j]=x.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=(le,ye,ae=1)=>{const he=le*ae,ne=he*(ye.cgstRate||0)/100,ge=he*(ye.sgstRate||0)/100,ke=he*(ye.utgstRate||0)/100,Oe=he*(ye.igstRate||0)/100,je=ne+ge+ke+Oe,ie=he+je;return{cgstRate:ye.cgstRate,cgstAmt:ne,sgstRate:ye.sgstRate,sgstAmt:ge,utgstRate:ye.utgstRate,utgstAmt:ke,igstRate:ye.igstRate,igstAmt:Oe,gstAmt:je,gstRate:(ye.cgstRate||0)+(ye.sgstRate||0)+(ye.utgstRate||0)+(ye.igstRate||0),totalAmt:ie}},[N,S]=x.useState("date"),[A,w]=x.useState(""),[I,D]=x.useState(""),[T,v]=x.useState([]),[M,P]=x.useState(""),[B,k]=x.useState(!1),[_,L]=x.useState(null),[R,C]=x.useState(!1),G=x.useRef(null),U=x.useRef(null),$=le=>{if(!le)return!1;const ye=le.toLowerCase();return ye.endsWith(".pdf")||!!ye.match(/\.(jpg|jpeg|png|gif|webp)$/i)},F=le=>$(le.name);x.useEffect(()=>()=>{_!=null&&_.fileUrl&&_.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(_.fileUrl)},[_]);const H=le=>{if(!F(le)){W.error("Preview is only available for images and PDF files");return}_!=null&&_.fileUrl&&_.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(_.fileUrl);const ye=URL.createObjectURL(le);L({fileName:le.name,fileType:le.type,documentId:"",fileUrl:ye,fileSize:le.size})},K=le=>{const ye=le.originalFileName||le.fileName||le.name||"Document",ae=le.documentId||le.id||"",he=ye.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let ne="";if(ae)ne=wn(ae);else if(ne=le.storageUrl||le.documentUrl||"",ne&&!ne.startsWith("http")){const ge="https://reflow-uat.royalenfield.com",ke=ge.endsWith("/")?ge.slice(0,-1):ge,Oe=ne.startsWith("/")?ne:`/${ne}`;ne=`${ke}${Oe}`}L({fileName:ye,fileType:he,documentId:ae,fileUrl:ne})},z=le=>{const ye=URL.createObjectURL(le),ae=document.createElement("a");ae.href=ye,ae.download=le.name,document.body.appendChild(ae),ae.click(),document.body.removeChild(ae),URL.revokeObjectURL(ye)};x.useEffect(()=>{if(t&&o){const le=p>0;if(o.costItems&&o.costItems.length>0){const ye=o.costItems.map((ae,he)=>({id:`original-${he}`,description:ae.itemDescription||ae.description||"",amount:Number(ae.amount)||0,quantity:Number(ae.quantity)||1,hsnCode:ae.hsnCode||"",isService:!!ae.isService,gstRate:Number(ae.gstRate)||c,cgstRate:Number(ae.cgstRate)||0,sgstRate:Number(ae.sgstRate)||0,utgstRate:Number(ae.utgstRate)||0,igstRate:Number(ae.igstRate)||0,gstAmt:Number(ae.gstAmt)||0,cgstAmt:Number(ae.cgstAmt)||0,sgstAmt:Number(ae.sgstAmt)||0,utgstAmt:Number(ae.utgstAmt)||0,igstAmt:Number(ae.igstAmt)||0,cessRate:Number(ae.cessRate)||0,cessAmt:Number(ae.cessAmt)||0,totalAmt:Number(ae.totalAmt)||0,isOriginal:le}));j(ye)}o.expectedCompletionDate&&(w(o.expectedCompletionDate.split("T")[0]),S("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}]),w(""),P(""))},[t,o,c,p]);const O=x.useMemo(()=>b.reduce((le,ye)=>le+(ye.totalAmt||ye.amount||0),0),[b]),V=x.useMemo(()=>{const le=u!==null,ye=b.length>0&&b.every(ge=>ge.description.trim()!==""&&ge.amount>0),ae=N==="date"?A!=="":I!==""&&parseInt(I)>0,he=M.trim().length>0,ne=f?!1:b.some(ge=>{const{isValid:ke}=ba(ge.hsnCode,ge.isService);return!ke});return le&&ye&&ae&&he&&!ne},[u,b,N,A,I,M,f]),Q=le=>{var ae,he,ne;const ye=(ae=le.target.files)==null?void 0:ae[0];if(ye){const ge=d.maxFileSizeMB*1024*1024;if(ye.size>ge){W.error(`File size exceeds the maximum allowed size of ${d.maxFileSizeMB}MB. Current size: ${(ye.size/(1024*1024)).toFixed(2)}MB`),G.current&&(G.current.value="");return}const ke=[".pdf",".doc",".docx"],Oe="."+((he=ye.name.split(".").pop())==null?void 0:he.toLowerCase()),je=((ne=ye.name.split(".").pop())==null?void 0:ne.toLowerCase())||"";if(!ke.includes(Oe)||!d.allowedFileTypes.includes(je)){W.error("Please upload a valid PDF, DOC, or DOCX file as per system policy"),G.current&&(G.current.value="");return}h(ye)}},q=le=>{const ye=Array.from(le.target.files||[]),ae=[],he=d.maxFileSizeMB*1024*1024;ye.forEach(ne=>{var ke;if(ne.size>he){W.error(`"${ne.name}" exceeds ${d.maxFileSizeMB}MB limit and was not added.`);return}const ge=((ke=ne.name.split(".").pop())==null?void 0:ke.toLowerCase())||"";if(!d.allowedFileTypes.includes(ge)){W.error(`"${ne.name}" has an unsupported file type and was not added.`);return}ae.push(ne)}),ae.length>0&&v(ne=>[...ne,...ae]),U.current&&(U.current.value="")},ee=()=>{j(le=>[...le,{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}])},te=le=>{b.length>1&&j(ye=>ye.filter(ae=>ae.id!==le))},ue=(le,ye,ae)=>{j(he=>he.map(ne=>{if(ne.id===le){let ge={...ne,[ye]:ae};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate"].includes(ye)){const ke=parseFloat(ae);if(!isNaN(ke)&&ke<0)return W.error("Value cannot be negative"),ne;const Oe=ye==="amount"?parseFloat(ae)||0:ne.amount,je=1;let ie=ne.cgstRate,Se=ne.sgstRate,qe=ne.utgstRate,rt=ne.igstRate;if(ye==="cgstRate"){if(!g.isCGST)return ne;ie=parseFloat(ae)||0,g.isUTGST?(qe=ie,Se=0):(Se=ie,qe=0),rt=0}else if(ye==="sgstRate"){if(!g.isSGST)return ne;Se=parseFloat(ae)||0,ie=Se,qe=0,rt=0}else if(ye==="utgstRate"){if(!g.isUTGST)return ne;qe=parseFloat(ae)||0,ie=qe,Se=0,rt=0}else if(ye==="igstRate"){if(!g.isIGST)return ne;rt=parseFloat(ae)||0,ie=0,Se=0,qe=0}else if(ye==="gstRate"){const It=parseFloat(ae)||0;g.isIGST?(rt=It,ie=0,Se=0,qe=0):(ie=It/2,g.isUTGST?(qe=It/2,Se=0):(Se=It/2,qe=0),rt=0)}const gt=y(Oe,{cgstRate:ie,sgstRate:Se,igstRate:rt,utgstRate:qe},je);return{...ge,amount:Oe,quantity:je,...gt}}return ge}return ne}))},_e=le=>{v(ye=>ye.filter((ae,he)=>he!==le))},Ze=async()=>{if(!V){W.error("Please fill all required fields");return}if(b.some(ae=>ae.amount<0)){W.error("Please ensure all amounts are non-negative");return}if(N==="days"&&(parseInt(I)<=0||isNaN(parseInt(I)))){W.error("Please enter a valid number of days greater than 0");return}let ye=A||"";if(N==="days"&&I){const ae=parseInt(I),he=new Date;he.setDate(he.getDate()+ae),ye=he.toISOString().split("T")[0]}try{if(k(!0),!f&&b.some(ge=>ge.description.trim()!==""&&ge.amount>0&&(ge.gstRate===0||!ge.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.`)){k(!1);return}const he=p>0,ne=b.filter(ge=>ge.description.trim()!==""&&ge.amount>0).map(ge=>({...ge,description:o&&he&&!ge.isOriginal?`[ADDITIONAL] ${ge.description}`:ge.description}));await a({proposalDocument:u,costBreakup:ne,totalEstimatedBudget:O,expectedCompletionDate:ye,timelineMode:N,expectedCompletionDays:N==="days"?parseInt(I):0,otherDocuments:T,dealerComments:M}),Ue(),s()}catch(ae){console.error("Failed to submit proposal:",ae),wd(ae)||W.error("Failed to submit proposal. Please try again.")}finally{k(!1)}},Ue=()=>{_!=null&&_.fileUrl&&_.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(_.fileUrl),L(null),h(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}]),S("date"),w(""),D(""),v([]),P(""),G.current&&(G.current.value=""),U.current&&(U.current.value="")},Pe=()=>{B||(Ue(),s())},De=new Date().toISOString().split("T")[0];return e.jsxs(xt,{open:t,onOpenChange:Pe,children:[e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(ht,{className:"flex-shrink-0 pb-3 lg:pb-4",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-xl lg:text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{className:"w-5 h-5 lg:w-6 lg:h-6 text-[--re-green]"}),"Dealer Proposal Submission"]}),m&&e.jsx(re,{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(_t,{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:()=>C(!R),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(Fe,{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(re,{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:R?e.jsx(jc,{className:"w-4 h-4"}):e.jsx(ms,{className:"w-4 h-4"})})]}),R&&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(ft,{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:$(o.documentUrl)?e.jsxs(e.Fragment,{children:[e.jsx(Nt,{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(Tt,{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(Fe,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:o.otherDocuments.map((le,ye)=>e.jsx(Br,{document:{documentId:le.documentId||le.id||"",name:le.originalFileName||le.fileName||le.name||"Supporting Document",fileType:(le.originalFileName||le.fileName||le.name||"").split(".").pop()||"file",uploadedAt:le.uploadedAt||new Date().toISOString()},onPreview:$(le.originalFileName||le.fileName||le.name||"")?()=>K(le):void 0,onDownload:async ae=>{if(ae)await Ms(ae);else{let he=le.storageUrl||le.documentUrl;if(he&&!he.startsWith("http")){const ne="https://reflow-uat.royalenfield.com",ge=ne.endsWith("/")?ne.slice(0,-1):ne,ke=he.startsWith("/")?he:`/${he}`;he=`${ge}${ke}`}he&&window.open(he,"_blank")}}},ye))})]})]}),(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((le,ye)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:le.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(le.amount).toLocaleString("en-IN")]})]},ye)),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(re,{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 ${u?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:[e.jsx("input",{ref:G,type:"file",accept:[".pdf",".doc",".docx"].filter(le=>d.allowedFileTypes.includes(le.replace(".",""))).join(","),className:"hidden",id:"proposalDoc",onChange:Q}),e.jsx("label",{htmlFor:"proposalDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:u?e.jsxs("div",{className:"flex flex-col items-center gap-2 w-full text-center",children:[e.jsx(ps,{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:u.name}),e.jsxs("div",{className:"flex gap-2",children:[F(u)&&e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>H(u),className:"h-7 text-[10px]",children:"Preview"}),e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>z(u),className:"h-7 text-[10px]",children:"Download"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ys,{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(re,{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:()=>S("date"),className:N==="date"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Date"}),e.jsx(E,{type:"button",onClick:()=>S("days"),className:N==="days"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Days"})]}),N==="date"?e.jsx(ta,{value:A||null,onChange:le=>w(le||""),minDate:De,placeholderText:"dd/mm/yyyy",className:"w-full"}):e.jsx(Re,{type:"number",placeholder:"Enter number of days",min:"1",value:I,onChange:le=>D(le.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(re,{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:ee,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(ms,{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(le=>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(se,{className:"text-[10px] uppercase text-gray-500 font-bold",children:"Item Description"}),le.isOriginal?e.jsx(re,{className:"text-[9px] h-4 bg-gray-200 text-gray-700 hover:bg-gray-200 border-none",children:"ORIGINAL"}):o&&p>0?e.jsx(re,{className:"text-[9px] h-4 bg-amber-100 text-amber-700 hover:bg-amber-100 border-none",children:"ADDITIONAL"}):null]}),e.jsx(Re,{placeholder:"e.g., Venue branding, Logistics, etc.",value:le.description,onChange:ye=>ue(le.id,"description",ye.target.value),className:`w-full bg-white shadow-sm ${le.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:le.isOriginal})]}),f&&e.jsxs("div",{className:"flex-1 min-w-[140px]",children:[e.jsx(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Re,{type:"number",value:le.amount||"",onChange:ye=>ue(le.id,"amount",ye.target.value),className:`pl-8 bg-white shadow-sm ${le.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:le.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:()=>te(le.id),disabled:b.length===1||le.isOriginal,children:e.jsx(yt,{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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Re,{type:"number",value:le.amount||"",onChange:ye=>ue(le.id,"amount",ye.target.value),className:`pl-8 bg-white shadow-sm ${le.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:le.isOriginal})]})]}),e.jsxs("div",{className:"w-28 sm:w-32 relative pb-5",children:[e.jsx(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN/SAC Code"}),e.jsx(Sf,{value:le.hsnCode||"",onChange:ye=>ue(le.id,"hsnCode",ye),type:le.isService?"SAC":"HSN",disabled:le.isOriginal,className:ba(le.hsnCode,le.isService).isValid?"":"border-red-500",placeholder:le.isService?"Select SAC":"Select HSN"}),!ba(le.hsnCode,le.isService).isValid&&e.jsx("span",{className:"text-[10px] text-red-500 absolute left-0 bottom-0 block leading-tight",children:ba(le.hsnCode,le.isService).message})]}),e.jsxs("div",{className:"w-28 sm:w-32",children:[e.jsx(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Type"}),e.jsxs("select",{value:le.isService?"SAC":"HSN",onChange:ye=>ue(le.id,"isService",ye.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] ${le.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:le.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"CGST %"}),e.jsx(Re,{type:"number",value:le.cgstRate||"",onChange:ye=>ue(le.id,"cgstRate",ye.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"SGST %"}),e.jsx(Re,{type:"number",value:le.sgstRate||"",onChange:ye=>ue(le.id,"sgstRate",ye.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"UTGST %"}),e.jsx(Re,{type:"number",value:le.utgstRate||"",onChange:ye=>ue(le.id,"utgstRate",ye.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"IGST %"}),e.jsx(Re,{type:"number",value:le.igstRate||"",onChange:ye=>ue(le.id,"igstRate",ye.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:["₹",le.cgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),le.sgstAmt>0&&e.jsxs("span",{children:["SGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",le.sgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),le.utgstAmt>0&&e.jsxs("span",{children:["UTGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",le.utgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs("span",{children:["IGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",le.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:["₹",le.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: ₹",le.totalAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]})]})},le.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(Vs,{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(re,{variant:"outline",className:"text-xs border-gray-300 text-gray-500 bg-gray-50 font-medium",children:"Optional"})]}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${T.length>0?"border-blue-500 bg-blue-50":"border-gray-300 bg-white"}`,children:[e.jsx("input",{ref:U,type:"file",multiple:!0,accept:d.allowedFileTypes.map(le=>`.${le}`).join(","),className:"hidden",id:"otherDocs",onChange:q}),e.jsxs("label",{htmlFor:"otherDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(ys,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:T.length>0?`${T.length} files selected`:"Upload supporting files"}),e.jsx("span",{className:"text-[10px] text-gray-400",children:"Click to add documents"})]})]}),T.length>0&&e.jsx("div",{className:"mt-2 space-y-2 max-h-[120px] overflow-y-auto",children:T.map((le,ye)=>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(Fe,{className:"w-3.5 h-3.5 text-blue-600 flex-shrink-0"}),e.jsx("span",{className:"text-gray-700 font-medium truncate",children:le.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[F(le)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",onClick:()=>H(le),children:e.jsx(Nt,{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:()=>z(le),children:e.jsx(Tt,{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:()=>_e(ye),children:e.jsx(yt,{className:"w-3 h-3"})})]})]},ye))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"font-semibold text-base lg:text-lg",children:"Dealer Comments *"}),e.jsx(zs,{placeholder:"Details about execution, special requirements, etc.",value:M,onChange:le=>P(le.target.value),className:"min-h-[100px] bg-white shadow-sm"})]})]}),!V&&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(Je,{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(Dt,{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:B,className:"border-2",children:"Cancel"}),e.jsx(E,{onClick:Ze,disabled:!V||B,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:B?"Submitting...":"Submit Documents"})]})]}),_&&e.jsx(Yr,{fileName:_.fileName||"",fileType:_.fileType||"",fileUrl:_.fileUrl||"",fileSize:_.fileSize||0,attachmentId:_.documentId||"",onDownload:Ms,open:!!_,onClose:()=>L(null)})]})}function w4({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n,requestId:i,preFilledIONumber:l,preFilledBlockedAmount:o,preFilledRemainingBalance:c,taxationType:d}){const[m,p]=x.useState("approve"),[u,h]=x.useState(""),[g,f]=x.useState(!1),b=x.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),j=l||"";x.useEffect(()=>{t&&(h(""),p("approve"))},[t]);const y=u.length,N=500,S=x.useMemo(()=>(m==="reject"||j.trim().length>0)&&u.trim().length>0,[m,j,u]),A=async()=>{if(!S){if(m==="approve"&&!j.trim()){W.error("IO number is required. Please block amount from IO tab first.");return}if(!u.trim()){W.error("Please provide comments");return}return}try{f(!0),m==="approve"?await a({ioNumber:j.trim(),comments:u.trim()}):await r(u.trim()),w(),s()}catch(D){console.error(`Failed to ${m} request:`,D),W.error(`Failed to ${m} request. Please try again.`)}finally{f(!1)}},w=()=>{p("approve"),h("")},I=()=>{g||(w(),s())};return e.jsx(xt,{open:t,onOpenChange:I,children:e.jsxs(dt,{className:"dept-lead-io-modal overflow-hidden flex flex-col",children:[e.jsxs(ht,{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(Be,{className:"w-5 h-5 lg:w-6 lg:h-6 text-green-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(mt,{className:"font-semibold text-lg lg:text-xl flex items-center gap-2 flex-wrap",children:["Review and Approve",d&&e.jsx(re,{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(_t,{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(re,{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(re,{className:"bg-green-100 text-green-800 border-green-200 text-xs",children:[e.jsx(Be,{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(Be,{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(Mt,{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(se,{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(Re,{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(se,{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(zs,{id:"comment",placeholder:m==="approve"?"Enter your approval comments and any conditions or notes...":"Enter detailed reasons for rejection...",value:u,onChange:D=>{const T=D.target.value;T.length<=N&&h(T)},rows:4,className:"text-xs lg:text-sm min-h-[80px] lg:min-h-[100px] resize-none"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ss,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[y,"/",N]})]})]})]})]})}),e.jsxs(Dt,{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:I,disabled:g,className:"text-sm lg:text-base",children:"Cancel"}),e.jsx(E,{onClick:A,disabled:!S||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(Be,{className:"w-4 h-4 mr-2"}),m==="approve"?"Approve Request":"Reject Request"]})})]})]})})}function C4({isOpen:t,onClose:s,onPush:a,onReQuotation:r,completionDetails:n,ioDetails:i,completionDocuments:l,requestTitle:o,requestNumber:c,taxationType:d}){var k,_;const m=x.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),[p,u]=x.useState(""),[h,g]=x.useState(!1),[f,b]=x.useState(null),[j,y]=x.useState(!1),N=p.length,S=500,A=x.useMemo(()=>n!=null&&n.totalClosedExpenses?n.totalClosedExpenses:n!=null&&n.closedExpenses&&Array.isArray(n.closedExpenses)?n.closedExpenses.reduce((L,R)=>{const C=typeof R=="object"&&R.amount||0,G=typeof R=="object"&&R.gstAmt||0,U=R.totalAmt||C+G;return L+(Number(U)||0)},0):0,[n]),w=L=>{if(!L)return"—";try{return new Date(L).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return L}},I=L=>`₹${L.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,D=L=>{if(!L.name)return!1;const R=L.name.toLowerCase();return R.endsWith(".pdf")||R.endsWith(".jpg")||R.endsWith(".jpeg")||R.endsWith(".png")||R.endsWith(".gif")||R.endsWith(".webp")},T=async L=>{if(!L.id){W.error("Document preview not available - document ID missing");return}y(!0);try{const R=wn(L.id),C=L.name.toLowerCase(),G=C.endsWith(".pdf"),U=C.match(/\.(jpg|jpeg|png|gif|webp)$/i),$=!0,F=$?null:localStorage.getItem("accessToken"),K=await fetch(R,{headers:{Accept:G?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!K.ok)throw new Error(`Failed to load file: ${K.status} ${K.statusText}`);const z=await K.blob();if(z.size===0)throw new Error("File is empty or could not be loaded");const O=window.URL.createObjectURL(z);b({name:L.name,url:O,type:z.type||(G?"application/pdf":U?"image":void 0),size:z.size})}catch(R){console.error("Failed to load document preview:",R),W.error("Failed to load document preview")}finally{y(!1)}};x.useEffect(()=>()=>{f!=null&&f.url&&f.url.startsWith("blob:")&&window.URL.revokeObjectURL(f.url)},[f]);const v=async()=>{if(!p.trim()){W.error("Please provide comments before proceeding");return}try{g(!0),await a(p.trim()),M(),s()}catch(L){console.error("Failed to generate e-invoice:",L),W.error("Failed to generate e-invoice. Please try again.")}finally{g(!1)}},M=()=>{u("")},P=async()=>{if(!p.trim()){W.error("Please provide comments (reason) for re-quotation request");return}if(!r){W.error("Re-quotation handler not provided");return}try{g(!0),await r(p.trim()),M(),s()}catch(L){console.error("Failed to request re-quotation:",L)}finally{g(!1)}},B=()=>{h||(M(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(xt,{open:t,onOpenChange:B,children:e.jsxs(dt,{className:"settlement-push-modal overflow-hidden flex flex-col w-full max-w-none",children:[e.jsxs(ht,{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(Bt,{className:"w-4 h-4 sm:w-5 sm:h-5 sm:w-6 sm:h-6 text-indigo-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(mt,{className:"font-semibold text-lg sm:text-xl flex items-center gap-2 flex-wrap",children:["E-Invoice Generation & Sync",d&&e.jsx(re,{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(_t,{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(re,{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(re,{className:"bg-indigo-100 text-indigo-800 border-indigo-200 text-xs",children:[e.jsx(Bt,{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(ce,{className:"pb-3",children:[e.jsxs(de,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(ps,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Details"]}),e.jsx(we,{className:"text-xs sm:text-sm",children:"Review activity completion information"})]}),e.jsxs(J,{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:w(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(ce,{className:"pb-3",children:[e.jsxs(de,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Mt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"IO Details"]}),e.jsx(we,{className:"text-xs sm:text-sm",children:"Internal Order information for budget reference"})]}),e.jsxs(J,{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(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(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(ce,{className:"pb-3",children:[e.jsxs(de,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Da,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Expense Breakdown"]}),e.jsx(we,{className:"text-xs sm:text-sm",children:"Review closed expenses breakdown (Base + GST)"})]}),e.jsxs(J,{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((L,R)=>{const C=typeof L=="object"&&L.amount||0,G=typeof L=="object"&&L.gstRate||0,U=typeof L=="object"&&L.gstAmt||0,$=typeof L=="object"?L.totalAmt||C+U: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:L.description||`Expense ${R+1}`}),e.jsx("span",{className:"font-bold text-gray-900",children:I($)})]}),e.jsxs("div",{className:"sm:hidden flex justify-between w-full text-xs text-gray-500",children:[e.jsxs("span",{children:["Base: ",I(C)]}),!m&&e.jsxs("span",{children:["GST: ",G,"% (",I(U),")"]})]}),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:L.description,children:L.description||`Expense ${R+1}`})}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:I(C)}),!m&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:[G,"%"]}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:I(U)})]}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right font-semibold text-gray-900",children:I($)})]},R)})}),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:I(A)})]})]})]})]}),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(ps,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Documents"]}),e.jsxs(re,{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((L,R)=>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(ps,{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:L.name,children:L.name})})]}),L.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[D(L)&&e.jsx("button",{type:"button",onClick:()=>T(L),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(ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(Nt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{L.id&&await Ms(L.id)}catch(C){console.error("Failed to download document:",C),W.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Tt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},R))})]}),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(Bt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Activity Photos"]}),e.jsxs(re,{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((L,R)=>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(Bt,{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:L.name,children:L.name})})]}),L.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[D(L)&&e.jsx("button",{type:"button",onClick:()=>T(L),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(ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(Nt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{L.id&&await Ms(L.id)}catch(C){console.error("Failed to download document:",C),W.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download photo",children:e.jsx(Tt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},R))})]}),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(Mt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Invoices / Receipts"]}),e.jsxs(re,{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((L,R)=>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(Mt,{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:L.name,children:L.name})})]}),L.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[D(L)&&e.jsx("button",{type:"button",onClick:()=>T(L),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(ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(Nt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{L.id&&await Ms(L.id)}catch(C){console.error("Failed to download document:",C),W.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Tt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},R))})]}),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(Bt,{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(Bt,{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:()=>T(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(ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(Nt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var L;try{(L=l.attendanceSheet)!=null&&L.id&&await Ms(l.attendanceSheet.id)}catch(R){console.error("Failed to download document:",R),W.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Tt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]})]})]}),e.jsx("div",{className:"p-2.5 sm:p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ss,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-yellow-900",children:"Please verify all details before 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(se,{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(zs,{id:"comment",placeholder:"Enter your comments about e-invoice generation (e.g., verified expenses, ready for settlement)...",value:p,onChange:L=>{const R=L.target.value;R.length<=S&&u(R)},rows:4,className:"text-sm min-h-[80px] resize-none"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ss,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[N,"/",S]})]})]})]})}),e.jsxs(Dt,{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:B,disabled:h,children:"Cancel"}),r&&e.jsxs(E,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:P,disabled:!p.trim()||h,children:[h?e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Et,{className:"w-4 h-4 mr-2"}),"Request Re-quotation"]}),e.jsx(E,{onClick:v,disabled:!p.trim()||h,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:h?"Processing...":e.jsxs(e.Fragment,{children:[e.jsx(Bt,{className:"w-4 h-4 mr-2"}),"Generate & Sync"]})})]})]})}),f&&e.jsx(xt,{open:!!f,onOpenChange:()=>b(null),children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ht,{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(Nt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children: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 L=document.createElement("a");L.href=f.url,L.download=f.name,L.click()},className:"gap-2 h-9",children:[e.jsx(Tt,{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(ze,{className:"w-8 h-8 animate-spin text-blue-600 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]})}):f.name.toLowerCase().endsWith(".pdf")||(k=f.type)!=null&&k.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(Nt,{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 L=document.createElement("a");L.href=f.url,L.download=f.name,L.click()},className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",f.name]})]})})]})})})]})}function S4({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(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(ht,{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(va,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(mt,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(_t,{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(Ht,{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(va,{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(jl,{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(ft,{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(re,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(re,{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(yt,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function A4({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 u=x.useMemo(()=>p==="Non GST"||p==="Non-GST",[p]),[h,g]=x.useState(""),[f,b]=x.useState(!1),[j,y]=x.useState(null),[N,S]=x.useState(!1),A=x.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const U=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(U)?U.reduce(($,F)=>{const H=typeof F=="object"&&F.amount||0,K=typeof F=="object"&&F.quantity||1,z=H*K,O=typeof F=="object"&&F.gstAmt||0,V=F.totalAmt||z+O;return $+(Number(V)||0)},0):0},[i]),w=x.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const U=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(U)?U.reduce(($,F)=>{const H=typeof F=="object"&&F.amount||0,K=typeof F=="object"&&F.quantity||1;return $+Number(H)*Number(K)},0):0},[i]),I=x.useMemo(()=>{const U=(d==null?void 0:d.internalOrders)||(d==null?void 0:d.internal_orders)||[];if(Array.isArray(U)&&U.length>0)return U.reduce((F,H)=>{const K=Number(H.ioBlockedAmount||H.io_blocked_amount||0);return F+K},0);const $=(d==null?void 0:d.internalOrder)||(d==null?void 0:d.internal_order);return Number(($==null?void 0:$.ioBlockedAmount)||($==null?void 0:$.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=I>=w-.01,T=Math.max(0,w-I),[v,M]=x.useState(null),P=U=>{if(!U)return"—";try{return new Date(U).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return U}},B=U=>{if(!U.name)return!1;const $=U.name.toLowerCase();return $.endsWith(".pdf")||$.endsWith(".jpg")||$.endsWith(".jpeg")||$.endsWith(".png")||$.endsWith(".gif")||$.endsWith(".webp")},k=U=>{let $=U.url||U.storageUrl||"";const F=U.id||U.documentId||"";if(!F&&!$){W.error("Document preview not available");return}if($&&!$.startsWith("http")&&!$.startsWith("blob:")){const H="https://reflow-uat.royalenfield.com",K=H.endsWith("/")?H.slice(0,-1):H,z=$.startsWith("/")?$:`/${$}`;$=`${K}${z}`}M({name:U.name||"Document",url:$||(F?wn(F):""),type:(U.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:F})};x.useEffect(()=>()=>{v!=null&&v.url&&v.url.startsWith("blob:")&&window.URL.revokeObjectURL(v.url)},[v]);const _=async()=>{if(!h.trim()){W.error("Please provide approval comments");return}try{b(!0),y("approve"),await a(h),C(),s()}catch(U){console.error("Failed to approve proposal:",U),W.error("Failed to approve proposal. Please try again.")}finally{b(!1),y(null)}},L=async()=>{if(!h.trim()){W.error("Please provide rejection reason");return}try{b(!0),y("reject"),await r(h),C(),s()}catch(U){console.error("Failed to reject proposal:",U),W.error("Failed to reject proposal. Please try again.")}finally{b(!1),y(null)}},R=async()=>{if(!h.trim()){W.error("Please provide reasons for requesting a revision");return}if(!n){W.error("Revision feature is not available");return}try{b(!0),y("revision"),await n(h),C(),s()}catch(U){console.error("Failed to request revision:",U),W.error("Failed to request revision. Please try again.")}finally{b(!1),y(null)}},C=()=>{g(""),y(null)},G=()=>{f||(C(),s())};return t?e.jsxs(xt,{open:t,onOpenChange:G,children:[e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(ht,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-lg lg:text-xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),p&&e.jsx(re,{className:`ml-2 border-none shadow-sm ${u?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:u?"Non-GST Claim":"GST Claim"})]}),e.jsx(_t,{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:()=>S(!N),children:[e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{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(re,{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:N?e.jsx(jc,{className:"w-4 h-4"}):e.jsx(ms,{className:"w-4 h-4"})})]}),N&&e.jsxs("div",{className:"px-4 pb-4 border-t border-amber-200 space-y-4 bg-white/50",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-xs mt-3",children:[m.expectedCompletionDate&&e.jsxs("div",{className:"flex items-center gap-1.5 text-gray-700",children:[e.jsx(ft,{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:B({name:m.documentUrl})?e.jsxs(e.Fragment,{children:[e.jsx(Nt,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:m.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"View Previous Document"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Tt,{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(Vs,{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((U,$)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:U.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(U.amount).toLocaleString("en-IN")]})]},$)),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(Fe,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:m.otherDocuments.map((U,$)=>e.jsx(Br,{document:{documentId:U.documentId||U.id||"",name:U.originalFileName||U.fileName||U.name||"Supporting Document",fileType:(U.originalFileName||U.fileName||U.name||"").split(".").pop()||"file",uploadedAt:U.uploadedAt||new Date().toISOString()},onPreview:B({name:U.originalFileName||U.fileName||U.name||""})?()=>k(U):void 0,onDownload:async F=>{if(F)await Ms(F);else{let H=U.storageUrl||U.documentUrl;if(H&&!H.startsWith("http")){const K="https://reflow-uat.royalenfield.com",z=K.endsWith("/")?K.slice(0,-1):K,O=H.startsWith("/")?H:`/${H}`;H=`${z}${O}`}H&&window.open(H,"_blank")}}},$))})]}),(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(Ys,{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(Fe,{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(Fe,{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 ",P(i.submittedAt)]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:i.proposalDocument.id&&e.jsxs(e.Fragment,{children:[B(i.proposalDocument)&&e.jsx("button",{type:"button",onClick:()=>k(i.proposalDocument),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(Nt,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var U;try{(U=i.proposalDocument)!=null&&U.id&&await Ms(i.proposalDocument.id)}catch($){console.error("Failed to download document:",$),W.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Tt,{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(Fe,{className:"w-4 h-4 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(re,{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((U,$)=>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(Fe,{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:U.name,children:U.name})]}),U.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[B(U)&&e.jsx("button",{type:"button",onClick:()=>k(U),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(Nt,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{U.id&&await Ms(U.id)}catch(F){console.error("Failed to download document:",F),W.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Tt,{className:"w-5 h-5 text-gray-600"})})]})]},$))})]})]}),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(Vs,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const U=i!=null&&i.costBreakup?Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[]:[];return U&&Array.isArray(U)&&U.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 ${u?"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"}),!u&&e.jsx("div",{className:"text-right",children:"GST"}),e.jsx("div",{className:"text-right",children:"Total"})]})}),e.jsx("div",{className:"divide-y",children:U.map(($,F)=>{var H,K;return e.jsxs("div",{className:`px-3 lg:px-4 py-2 lg:py-3 grid ${u?"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:(H=$==null?void 0:$.description)!=null&&H.startsWith("[ADDITIONAL]")?$.description.replace("[ADDITIONAL]","").trim():($==null?void 0:$.description)||"N/A"}),U.some(z=>{var O;return(O=z==null?void 0:z.description)==null?void 0:O.startsWith("[ADDITIONAL]")})&&((K=$==null?void 0:$.description)!=null&&K.startsWith("[ADDITIONAL]")?e.jsx(re,{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(re,{className:"text-[9px] h-3.5 px-1 bg-gray-100 text-gray-600 hover:bg-gray-100 border-none leading-none",children:"ORIGINAL"}))]}),!u&&($!=null&&$.gstRate)?e.jsxs("span",{className:"block text-[10px] text-gray-400",children:[$.gstRate,"% GST"]}):null]}),e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number($==null?void 0:$.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!u&&e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number($==null?void 0:$.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(($==null?void 0:$.totalAmt)||(($==null?void 0:$.amount)||0)*(($==null?void 0:$.quantity)||1)+(($==null?void 0:$.gstAmt)||0))||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},($==null?void 0:$.id)||($==null?void 0:$.description)||F)})})]}),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(Vs,{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:["₹",A.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(ft,{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?P(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(Ys,{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(zs,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:h,onChange:U=>g(U.target.value),className:"min-h-[150px] lg:min-h-[140px] text-xs lg:text-sm w-full"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[h.length," characters"]})]})]})}),!h.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2 lg:col-span-2",children:[e.jsx(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(Dt,{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:G,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:R,disabled:!h.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(Ys,{className:"w-4 h-4 mr-2"}),"Request Revised Quotation"]})}),e.jsx(E,{onClick:L,disabled:!h.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:!h.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(Be,{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:I>0?`Pending block: ₹${T.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(Yr,{fileName:v.name,fileType:v.type||"",fileUrl:v.url,fileSize:v.size,attachmentId:v.id,onDownload:Ms,open:!!v,onClose:()=>M(null)})]}):null}function T4({isOpen:t,onClose:s,snapshot:a,type:r,title:n}){const[i,l]=x.useState(null);if(!a)return null;const o=r==="PROPOSAL",c=h=>Number(h||0).toLocaleString("en-IN",{maximumFractionDigits:2,style:"currency",currency:"INR"}),d=h=>{if(!h)return null;try{return new Date(h).toLocaleDateString("en-IN",{day:"numeric",month:"short",year:"numeric"})}catch{return h}},m=h=>{if(!h)return!1;const g=h.toLowerCase();return g.endsWith(".pdf")||!!g.match(/\.(jpg|jpeg|png|gif|webp)$/i)},p=h=>{var f;const g=(f=(h||"").split(".").pop())==null?void 0:f.toLowerCase();return g==="pdf"?"pdf":["jpg","jpeg","png","gif","webp"].includes(g||"")?"image":"file"},u=h=>{const g=h.fileName||h.originalFileName||(o?"Proposal Document":"Completion Document"),f=h.documentId||"",b=g.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let j="";if(f)j=wn(f);else if(j=h.storageUrl||h.documentUrl||"",j&&!j.startsWith("http")){const y="https://reflow-uat.royalenfield.com",N=y.endsWith("/")?y.slice(0,-1):y,S=j.startsWith("/")?j:`/${j}`;j=`${N}${S}`}l({fileName:g,fileType:b,documentId:f,fileUrl:j,fileSize:h.sizeBytes})};return e.jsxs(e.Fragment,{children:[e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs(ht,{className:"px-6 py-4 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[o?e.jsx(Fe,{className:"w-5 h-5 text-blue-600"}):e.jsx(Mt,{className:"w-5 h-5 text-green-600"}),n||(o?"Proposal Snapshot Details":"Completion Snapshot Details")]}),e.jsxs(_t,{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(ft,{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(Br,{document:{documentId:"",name:o?"Proposal Document":"Completion Document",fileType:p(a.documentUrl),uploadedAt:new Date().toISOString()},onPreview:m(a.documentUrl)?()=>u({fileName:o?"Proposal Document":"Completion Document",documentUrl:a.documentUrl}):void 0,onDownload:async()=>{let h=a.documentUrl;if(!h.startsWith("http")){const g="https://reflow-uat.royalenfield.com",f=g.endsWith("/")?g.slice(0,-1):g,b=h.startsWith("/")?h:`/${h}`;h=`${f}${b}`}window.open(h,"_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(re,{variant:"secondary",className:"text-[10px] h-5",children:[a.otherDocuments.length," Files"]})]}),e.jsx("div",{className:"space-y-2",children:a.otherDocuments.map((h,g)=>e.jsx(Br,{document:{documentId:h.documentId||"",name:h.originalFileName||h.fileName||"Supporting Document",fileType:p(h.originalFileName||h.fileName||""),uploadedAt:h.uploadedAt||new Date().toISOString()},onPreview:m(h.originalFileName||h.fileName||"")?()=>u(h):void 0,onDownload:h.documentId?Ms:async()=>{let f=h.storageUrl||h.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((h,g)=>e.jsxs("tr",{className:"bg-white hover:bg-gray-50/50",children:[e.jsx("td",{className:"p-3 text-gray-800",children:h.description}),e.jsx("td",{className:"p-3 text-right text-gray-900 font-medium tabular-nums",children:c(h.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(Jh,{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(Yr,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:Ms,open:!!i,onClose:()=>l(null)})]})}async function k4(t){var s;try{const a=await ve.post("/dealer-claims",t);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error creating claim request:",a),a}}async function D4(t){var s;try{const a=await ve.get(`/dealer-claims/${t}`);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error fetching claim details:",a),a}}async function R4(t,s){var a;try{const r=new FormData;s.proposalDocument&&r.append("proposalDocument",s.proposalDocument),s.costBreakup&&r.append("costBreakup",JSON.stringify(s.costBreakup)),s.totalEstimatedBudget!==void 0&&r.append("totalEstimatedBudget",s.totalEstimatedBudget.toString()),s.timelineMode&&r.append("timelineMode",s.timelineMode),s.expectedCompletionDate&&r.append("expectedCompletionDate",s.expectedCompletionDate),s.expectedCompletionDays!==void 0&&r.append("expectedCompletionDays",s.expectedCompletionDays.toString()),s.dealerComments&&r.append("dealerComments",s.dealerComments);const n=await ve.post(`/dealer-claims/${t}/proposal`,r,{headers:{"Content-Type":"multipart/form-data"}});return((a=n.data)==null?void 0:a.data)||n.data}catch(r){throw console.error("[DealerClaimAPI] Error submitting proposal:",r),r}}async function F4(t,s){var a;try{const r=new FormData;r.append("activityCompletionDate",s.activityCompletionDate),s.numberOfParticipants!==void 0&&r.append("numberOfParticipants",s.numberOfParticipants.toString()),s.closedExpenses&&r.append("closedExpenses",JSON.stringify(s.closedExpenses)),s.totalClosedExpenses!==void 0&&r.append("totalClosedExpenses",s.totalClosedExpenses.toString()),s.completionDescription&&r.append("completionDescription",s.completionDescription),s.completionDocuments&&s.completionDocuments.forEach(i=>{r.append("completionDocuments",i)}),s.activityPhotos&&s.activityPhotos.forEach(i=>{r.append("activityPhotos",i)});const n=await ve.post(`/dealer-claims/${t}/completion`,r,{headers:{"Content-Type":"multipart/form-data"}});return((a=n.data)==null?void 0:a.data)||n.data}catch(r){throw console.error("[DealerClaimAPI] Error submitting completion:",r),r}}async function I4(t,s){var a;try{const r=await ve.get(`/dealer-claims/${t}/io/validate`,{params:{ioNumber:s}});return((a=r.data)==null?void 0:a.data)||r.data}catch(r){throw console.error("[DealerClaimAPI] Error validating IO:",r),r}}async function kf(t,s){var a;try{const r={ioNumber:s.ioNumber,ioRemark:s.ioRemark||""};s.ioAvailableBalance!==void 0&&(r.availableBalance=s.ioAvailableBalance),s.ioBlockedAmount!==void 0&&(r.blockedAmount=s.ioBlockedAmount),s.ioRemainingBalance!==void 0&&(r.remainingBalance=s.ioRemainingBalance);const n=await ve.put(`/dealer-claims/${t}/io`,r);return((a=n.data)==null?void 0:a.data)||n.data}catch(r){throw console.error("Error updating IO details:",r),r}}async function P4(t,s){var a;try{const r=await ve.put(`/dealer-claims/${t}/e-invoice`,s);return((a=r.data)==null?void 0:a.data)||r.data}catch(r){throw console.error("[DealerClaimAPI] Error updating e-invoice:",r),r}}async function E4(t){var s;try{const a=await ve.post(`/dealer-claims/${t}/credit-note/send`);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error sending credit note to dealer:",a),a}}async function _4(t,s,a){var r;try{const n={};t&&(n.dateRange=t),s&&(n.startDate=s),a&&(n.endDate=a);const i=await ve.get("/dealer-claims/dashboard",{params:n});return((r=i.data)==null?void 0:r.data)||i.data}catch(n){throw console.error("[DealerClaimAPI] Error fetching dealer dashboard:",n),n}}async function M4(t){var s;try{const a=await ve.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 qr=t=>{if(!t)return"";try{return bs(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}}},L4=t=>{switch(t){case"approved":return e.jsx(Be,{className:"w-5 h-5 text-green-600"});case"skipped":return e.jsx(Be,{className:"w-5 h-5 text-green-600"});case"pending":return e.jsx(it,{className:"w-5 h-5 text-blue-600"});case"rejected":return e.jsx(Be,{className:"w-5 h-5 text-red-600"});default:return e.jsx(it,{className:"w-5 h-5 text-gray-400"})}},O4=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"}},$4=(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",U4=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 B4({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i,isSpectator:l=!1}){var vr,Nr,er,Pa,tr,Qt,As,la,wr,Cr,Sa,sr,Rt,xs,Xs,xa,Zr,Aa,ar,kn,Dn,Rn,Dd,Rd,Fd,Id,Pd,Ed,_d,Md,Ld,Od,$d,Ud,Bd,Vd,zd,Hd,Gd,Wd,Yd,Qd,Kd,Xd,Zd,Jd,qd,em,tm,sm,am,rm,nm,im,lm,om,cm,dm,mm,um,xm,hm,pm,gm,fm,bm,jm,ym,vm,Nm,wm,Cm,Sm,Am,Tm,km,Dm,Rm,Fm,Im,Pm,Em,_m,Mm,Lm,Om,$m,Um,Bm,Vm,zm,Hm,Gm,Wm,Ym,Qm,Km,Xm,Zm,Jm,qm,eu,tu,su,au,ru,nu,iu,lu,ou;const[o,c]=x.useState(!1),[d,m]=x.useState(!1),[p,u]=x.useState(!1),[h,g]=x.useState(!1),[f,b]=x.useState(!1),[j,y]=x.useState(!1),[N,S]=x.useState(!1),[A,w]=x.useState(null),[I,D]=x.useState(!1),[T,v]=x.useState(null),[M,P]=x.useState([]),[B,k]=x.useState(!1),[_,L]=x.useState(new Set),[R,C]=x.useState(null),[G,U]=x.useState(null),[$,F]=x.useState(!1),[H,K]=x.useState(!1),[z,O]=x.useState([]),[V,Q]=x.useState(0);x.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const $e=t.id||t.requestId;try{const Ce=await Ps($e),xe=(Ce==null?void 0:Ce.approvalLevels)||(Ce==null?void 0:Ce.approvals)||[];if(xe&&xe.length>0){const Ne=xe.map(pe=>{var Ie;return{step:pe.levelNumber||pe.level_number||0,levelNumber:pe.levelNumber||pe.level_number||0,levelName:pe.levelName||pe.level_name,approver:pe.approverName||pe.approver_name||"",approverEmail:(pe.approverEmail||pe.approver_email||"").toLowerCase(),status:((Ie=pe.status)==null?void 0:Ie.toLowerCase())||"waiting",tatHours:pe.tatHours||pe.tat_hours||24,elapsedHours:pe.elapsedHours||pe.elapsed_hours,approvedAt:pe.actionDate||pe.action_date,comment:pe.comments||pe.comment,levelId:pe.levelId||pe.level_id}}).sort((pe,Ie)=>(pe.levelNumber||0)-(Ie.levelNumber||0));O(pe=>pe.length!==Ne.length||pe.some((Ee,Te)=>{const wt=Ne[Te];return!wt||Ee.levelNumber!==wt.levelNumber||Ee.levelName!==wt.levelName||Ee.approverEmail!==wt.approverEmail||Ee.status!==wt.status})?Ne:pe)}else O([])}catch(Ce){console.warn("Failed to load approval flows from API:",Ce),t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&O(t.approvalFlow)}}else t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&O(t.approvalFlow)})()},[t==null?void 0:t.id,t==null?void 0:t.requestId,t==null?void 0:t.totalLevels,V]),x.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Y=t.id||t.requestId;(async()=>{try{const Ce=await Ps(Y),xe=(Ce==null?void 0:Ce.approvalLevels)||(Ce==null?void 0:Ce.approvals)||[];if(xe&&xe.length>0){const Ne=xe.map(pe=>{var Ie;return{step:pe.levelNumber||pe.level_number||0,levelNumber:pe.levelNumber||pe.level_number||0,levelName:pe.levelName||pe.level_name,approver:pe.approverName||pe.approver_name||"",approverEmail:(pe.approverEmail||pe.approver_email||"").toLowerCase(),status:((Ie=pe.status)==null?void 0:Ie.toLowerCase())||"waiting",tatHours:pe.tatHours||pe.tat_hours||24,elapsedHours:pe.elapsedHours||pe.elapsed_hours,approvedAt:pe.actionDate||pe.action_date,comment:pe.comments||pe.comment,levelId:pe.levelId||pe.level_id}}).sort((pe,Ie)=>(pe.levelNumber||0)-(Ie.levelNumber||0));O(Ne)}}catch(Ce){console.warn("Failed to load approval flows from API:",Ce)}})()}},[t==null?void 0:t.currentStep,t==null?void 0:t.totalLevels]);const q=async()=>{Q(Y=>Y+1),await new Promise(Y=>setTimeout(Y,500)),n==null||n(),ee()},ee=async()=>{if(t!=null&&t.id||t!=null&&t.requestId)try{const $e=[...await Z1(t.id||t.requestId)||[]].sort((Ce,xe)=>new Date(xe.createdAt).getTime()-new Date(Ce.createdAt).getTime());P($e)}catch(Y){console.warn("Failed to load version history:",Y)}};x.useEffect(()=>{ee()},[t==null?void 0:t.id,t==null?void 0:t.requestId,V]);const te=(Y,$e,Ce)=>{var pe;const xe=((t==null?void 0:t.totalLevels)||0)>5||(((pe=t==null?void 0:t.approvalLevels)==null?void 0:pe.length)||0)>5;if($e&&$e.trim()&&($e.toLowerCase().includes("additional approver")||!/^step\s+\d+$/i.test($e)))return $e;const Ne=xe?{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 Ne[Y]?Ne[Y]:Ce&&Ce!=="Unknown"&&Ce!=="System"?`Additional Approver - ${Ce}`:`Additional Approver - Step ${Y}`},ue=(Y,$e,Ce)=>{var Ie;if($e&&$e.toLowerCase().includes("additional approver"))return Ce&&Ce!=="Unknown"&&Ce!=="System"?`${Ce} will review and approve this request as an additional approver.`:"Additional approver will review and approve this request.";const Ne=((t==null?void 0:t.totalLevels)||0)>5||(((Ie=t==null?void 0:t.approvalLevels)==null?void 0:Ie.length)||0)>5;if($e&&$e.trim()){const Ee=$e.toLowerCase();if(Ee.includes("dealer")&&Ee.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(Ee.includes("requestor")&&(Ee.includes("evaluation")||Ee.includes("confirmation")))return"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)";if(Ee.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(Ee.includes("activity creation"))return"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.";if(Ee.includes("dealer")&&(Ee.includes("completion")||Ee.includes("documents")))return"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description";if(Ee.includes("requestor")&&(Ee.includes("claim")||Ee.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(Ee.includes("e-invoice")||Ee.includes("invoice generation")||Ee.includes("dms"))return"E-Invoice will be generated upon settlement initiation.";if(Ee.includes("credit note")||Ee.includes("sap"))return"Got credit note from SAP. Review and send to dealer to complete the claim management process."}const pe=Ne?{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 pe[Y]?pe[Y]:Ce&&Ce!=="Unknown"&&Ce!=="System"?`${Ce} will review and approve this request.`:`Step ${Y} approval required.`},_e=Y=>{if(!M||M.length===0||!Y)return{current:null,previous:null};const xe=[...M.filter(Ie=>{var Ee;return!!(Ie.levelName&&Ie.levelName.trim()===Y.trim()||(Ee=Ie.snapshotData)!=null&&Ee.levelName&&Ie.snapshotData.levelName.trim()===Y.trim())})].sort((Ie,Ee)=>{if(Ee.version!==Ie.version)return Ee.version-Ie.version;const Te=Ie.snapshotType==="APPROVE"?1:Ie.snapshotType==="PROPOSAL"||Ie.snapshotType==="COMPLETION"?2:3,wt=Ee.snapshotType==="APPROVE"?1:Ee.snapshotType==="PROPOSAL"||Ee.snapshotType==="COMPLETION"?2:3;return Te-wt}).filter((Ie,Ee,Te)=>Ie.snapshotType==="WORKFLOW"?!Te.some(Ct=>Ct.snapshotType==="APPROVE"&&Ct.levelName===Ie.levelName&&Ct.version>=Ie.version):!0),Ne=xe.length>0?xe[0]:null,pe=xe.length>1?xe[1]:null;return{current:Ne,previous:pe,all:xe}},Ze=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),Ue=Ze!=null?Number(Ze):null,Pe=((t==null?void 0:t.status)||"").toUpperCase(),De=Pe==="REJECTED",le=Pe==="CLOSED",ye=!De&&!le&&(Pe==="PENDING"||Pe==="IN_PROGRESS"||Pe==="IN-PROGRESS"),ae=z.find(Y=>{var xe,Ne;const $e=Y.levelId||Y.level_id,Ce=(xe=t==null?void 0:t.approvals)==null?void 0:xe.find(pe=>pe.levelId===$e);return((Ne=Ce==null?void 0:Ce.status)==null?void 0:Ne.toLowerCase())==="rejected"}),he=ae?Number(ae.levelNumber||ae.level_number||ae.step||0):null,ne=z.map((Y,$e)=>{var Ta,Rs,fe,bt,Gt,vs,At;const Ce=Number(Y.levelNumber||Y.level_number||Y.step||$e+1),xe=Y.levelName||Y.level_name,Ne=(Ta=t==null?void 0:t.approvals)==null?void 0:Ta.find(Ve=>Ve.levelId===Y.levelId);let pe;if(xe&&xe.toLowerCase().includes("department lead")||Ce===3){const Ve=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);(Ve!=null&&Ve.ioNumber||Ve!=null&&Ve.io_number)&&(pe={ioNumber:Ve.ioNumber||Ve.io_number||"",blockedAmount:Ve.ioBlockedAmount||Ve.io_blocked_amount||0,availableBalance:Ve.ioAvailableBalance||Ve.io_available_balance||0,remainingBalance:Ve.ioRemainingBalance||Ve.io_remaining_balance||0,organizedBy:((Rs=Ve.organizer)==null?void 0:Rs.displayName)||((fe=Ve.organizer)==null?void 0:fe.name)||Ve.organizedBy||Y.approver||"N/A",organizedAt:Ve.organizedAt||Ve.organized_at||Y.approvedAt||(t==null?void 0:t.updatedAt)||""})}let Ee;Ce===6&&(Ne!=null&&Ne.dmsDetails?Ee={dmsNumber:Ne.dmsDetails.dmsNumber||"",dmsRemarks:Ne.dmsDetails.dmsRemarks||"",pushedBy:Ne.dmsDetails.pushedBy||Y.approver,pushedAt:Ne.dmsDetails.pushedAt||Y.approvedAt||""}:t!=null&&t.dmsNumber&&(Ee={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((bt=t.dmsDetails)==null?void 0:bt.dmsRemarks)||"",pushedBy:Y.approver,pushedAt:Y.approvedAt||t.updatedAt||""}));let Te;if(De||le)((Gt=Ne==null?void 0:Ne.status)==null?void 0:Gt.toLowerCase())==="rejected"?Te="rejected":he!==null&&Ce>he?Te="waiting":((vs=Ne==null?void 0:Ne.status)==null?void 0:vs.toLowerCase())==="approved"?Te="approved":he!==null&&Ce<he?((At=Ne==null?void 0:Ne.status)==null?void 0:At.toLowerCase())==="approved"?Te="approved":Te="waiting":(Ue!==null&&Ce>Ue,Te="waiting");else if(ye&&Ue!==null&&Ue>0)if(Ce>Ue)Te="waiting";else if(Ce<Ue)if(Ne!=null&&Ne.status){const Ve=Ne.status.toLowerCase();Ve==="approved"?Te="approved":Ve==="skipped"?Te="skipped":Ve==="rejected"?Te="rejected":Te="waiting"}else Te="waiting";else if(Ne!=null&&Ne.status){const Ve=Ne.status.toLowerCase();Ve==="approved"?Te="approved":Ve==="rejected"?Te="rejected":Te="in_progress"}else{const Ve=(Y.status||"pending").toLowerCase();Ve==="in-review"||Ve==="in_review"||Ve==="in review"||Ve==="pending"?Te="in_progress":Te=Ve}else if(Ne!=null&&Ne.status){const Ve=Ne.status.toLowerCase();Ve==="approved"?Te="approved":Ve==="rejected"?Te="rejected":Ve==="pending"||Ve==="in_progress"||Ve==="in-progress"?Te="in_progress":Te=(Y.status||"waiting").toLowerCase()}else{const Ve=(Y.status||"waiting").toLowerCase();Ve==="in-review"||Ve==="in_review"||Ve==="in review"||Ve==="pending"?Te="in_progress":Te=Ve}const Ct=Te==="waiting"?0:Y.elapsedHours||0,Ts=Y.approver||Y.approverName||"Unknown",Ft=xe?_e(xe):{current:null,previous:null};return{step:Ce,title:te(Ce,xe,Ts),approver:Ts,description:ue(Ce,xe,Ts)||Y.description||"",tatHours:Y.tatHours||24,status:Te,comment:Y.comment||(Ne==null?void 0:Ne.comment),approvedAt:Y.approvedAt||(Ne==null?void 0:Ne.timestamp),elapsedHours:Ct,ioDetails:pe,dmsDetails:Ee,einvoiceUrl:Ce===7?Ne==null?void 0:Ne.einvoiceUrl:void 0,emailTemplateUrl:(Ne==null?void 0:Ne.emailTemplateUrl)||void 0,versionHistory:Ft}});let ge=null,ke=1;if(De||le)he!==null?ke=he:Ue!==null?ke=Ue:ke=(t==null?void 0:t.currentStep)||1;else if(ye){const Y=Ue!==null?ne.find($e=>$e.step===Ue):null;ge=Y&&(Y.status==="pending"||Y.status==="in_progress")?Y:ne.find($e=>{var xe;const Ce=((xe=$e.status)==null?void 0:xe.toLowerCase())||"";return Ce==="pending"||Ce==="in_progress"||Ce==="in-review"||Ce==="in_review"}),ke=ge?ge.step:Ue||(t==null?void 0:t.currentStep)||1}else ke=Ue||(t==null?void 0:t.currentStep)||1;const Oe=((vr=s==null?void 0:s.email)==null?void 0:vr.toLowerCase())||"",je=((Nr=t==null?void 0:t.dealerEmail)==null?void 0:Nr.toLowerCase())||((Pa=(er=t==null?void 0:t.dealer)==null?void 0:er.email)==null?void 0:Pa.toLowerCase())||((Qt=(tr=t==null?void 0:t.claimDetails)==null?void 0:tr.dealerEmail)==null?void 0:Qt.toLowerCase())||((la=(As=t==null?void 0:t.claimDetails)==null?void 0:As.dealer_email)==null?void 0:la.toLowerCase())||"",ie=je&&Oe===je,Se=z.find(Y=>(Y.step||Y.levelNumber||Y.level_number)===ke),qe=((Se==null?void 0:Se.approverEmail)||"").toLowerCase(),rt=qe&&Oe===qe,gt=((Cr=(wr=t==null?void 0:t.initiator)==null?void 0:wr.email)==null?void 0:Cr.toLowerCase())||((Sa=t==null?void 0:t.initiatorEmail)==null?void 0:Sa.toLowerCase())||"",It=z.find(Y=>{const $e=(Y.approverEmail||"").toLowerCase(),Ce=(Y.levelName||"").toLowerCase();return gt&&$e===gt||Ce.includes("requestor evaluation")||Ce.includes("requestor")&&Ce.includes("confirmation")}),oe=It&&(It.step||It.levelNumber||It.level_number)||2,Me=It||z.find(Y=>(Y.step||Y.levelNumber||Y.level_number)===2),me=((Me==null?void 0:Me.approverEmail)||"").toLowerCase(),Xe=me&&Oe===me,Qe=z.find(Y=>(Y.step||Y.levelNumber||Y.level_number)===1),nt=((Qe==null?void 0:Qe.approverEmail)||"").toLowerCase(),Ke=nt&&Oe===nt,lt=z.find(Y=>(Y.levelName||"").toLowerCase().includes("department lead")),et=((lt==null?void 0:lt.approverEmail)||"").toLowerCase(),ut=et&&Oe===et,Hs=async Y=>{var $e,Ce;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const xe=t.id||t.requestId;Y.proposalDocument&&await Hn(Y.proposalDocument,xe,"APPROVAL");for(const pe of Y.otherDocuments)await Hn(pe,xe,"SUPPORTING");const Ne=Y.costBreakup.reduce((pe,Ie)=>pe+(Ie.totalAmt||Ie.amount||0),0);await R4(xe,{proposalDocument:Y.proposalDocument||void 0,costBreakup:Y.costBreakup.map(pe=>({description:pe.description,amount:pe.amount,gstRate:pe.gstRate,gstAmt:pe.gstAmt,cgstRate:pe.cgstRate,cgstAmt:pe.cgstAmt,sgstRate:pe.sgstRate,sgstAmt:pe.sgstAmt,igstRate:pe.igstRate,igstAmt:pe.igstAmt,utgstRate:pe.utgstRate,utgstAmt:pe.utgstAmt,cessRate:pe.cessRate,cessAmt:pe.cessAmt,totalAmt:pe.totalAmt,quantity:pe.quantity,hsnCode:pe.hsnCode,isService:pe.isService})),totalEstimatedBudget:Ne,expectedCompletionDate:Y.expectedCompletionDate,dealerComments:Y.dealerComments}),W.success("Proposal submitted successfully"),q()}catch(xe){console.error("Failed to submit proposal:",xe);const Ne=((Ce=($e=xe==null?void 0:xe.response)==null?void 0:$e.data)==null?void 0:Ce.message)||(xe==null?void 0:xe.message)||"Failed to submit proposal. Please try again.";throw W.error(Ne),xe}},is=async Y=>{var $e,Ce,xe,Ne,pe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Ie=t.id||t.requestId,Ee=await Ps(Ie),Te=(Ee==null?void 0:Ee.approvalLevels)||(Ee==null?void 0:Ee.approvals)||[],wt=((Ce=($e=t==null?void 0:t.initiator)==null?void 0:$e.email)==null?void 0:Ce.toLowerCase())||((xe=t==null?void 0:t.initiatorEmail)==null?void 0:xe.toLowerCase())||"",Ct=Te.find(Ft=>{const Ta=(Ft.approverEmail||Ft.approver_email||"").toLowerCase(),Rs=(Ft.levelName||Ft.level_name||"").toLowerCase(),fe=Ft.levelNumber||Ft.level_number;return wt&&Ta===wt||Rs.includes("requestor evaluation")||Rs.includes("requestor")&&Rs.includes("confirmation")||fe===oe})||Te.find(Ft=>(Ft.levelNumber||Ft.level_number)===2);if(!(Ct!=null&&Ct.levelId)&&!(Ct!=null&&Ct.level_id))throw new Error("Initiator approval level not found");const Ts=Ct.levelId||Ct.level_id;await Vn(Ie,Ts,Y),W.success("Proposal approved successfully"),q()}catch(Ie){console.error("Failed to approve proposal:",Ie);const Ee=((pe=(Ne=Ie==null?void 0:Ie.response)==null?void 0:Ne.data)==null?void 0:pe.message)||(Ie==null?void 0:Ie.message)||"Failed to approve proposal. Please try again.";throw W.error(Ee),Ie}},vt=async Y=>{var $e,Ce,xe,Ne,pe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Ie=t.id||t.requestId,Ee=await Ps(Ie),Te=(Ee==null?void 0:Ee.approvalLevels)||(Ee==null?void 0:Ee.approvals)||[],wt=((Ce=($e=t==null?void 0:t.initiator)==null?void 0:$e.email)==null?void 0:Ce.toLowerCase())||((xe=t==null?void 0:t.initiatorEmail)==null?void 0:xe.toLowerCase())||"",Ct=Te.find(Ft=>{const Ta=(Ft.approverEmail||Ft.approver_email||"").toLowerCase(),Rs=(Ft.levelName||Ft.level_name||"").toLowerCase(),fe=Ft.levelNumber||Ft.level_number;return wt&&Ta===wt||Rs.includes("requestor evaluation")||Rs.includes("requestor")&&Rs.includes("confirmation")||fe===oe})||Te.find(Ft=>(Ft.levelNumber||Ft.level_number)===2);if(!(Ct!=null&&Ct.levelId)&&!(Ct!=null&&Ct.level_id))throw new Error("Initiator approval level not found");const Ts=Ct.levelId||Ct.level_id;await Rr(Ie,Ts,"Proposal rejected by requestor",Y),W.success("Proposal rejected. Request has been cancelled."),q()}catch(Ie){console.error("Failed to reject proposal:",Ie);const Ee=((pe=(Ne=Ie==null?void 0:Ie.response)==null?void 0:Ne.data)==null?void 0:pe.message)||(Ie==null?void 0:Ie.message)||"Failed to reject proposal. Please try again.";throw W.error(Ee),Ie}},pt=async Y=>{var $e,Ce,xe,Ne,pe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Ie=t.id||t.requestId,Ee=await Ps(Ie),Te=(Ee==null?void 0:Ee.approvalLevels)||(Ee==null?void 0:Ee.approvals)||[],wt=((Ce=($e=t==null?void 0:t.initiator)==null?void 0:$e.email)==null?void 0:Ce.toLowerCase())||((xe=t==null?void 0:t.initiatorEmail)==null?void 0:xe.toLowerCase())||"",Ct=Te.find(Ft=>{const Ta=(Ft.approverEmail||Ft.approver_email||"").toLowerCase(),Rs=(Ft.levelName||Ft.level_name||"").toLowerCase(),fe=Ft.levelNumber||Ft.level_number;return wt&&Ta===wt||Rs.includes("requestor evaluation")||Rs.includes("requestor")&&Rs.includes("confirmation")||fe===oe})||Te.find(Ft=>(Ft.levelNumber||Ft.level_number)===2);if(!(Ct!=null&&Ct.levelId)&&!(Ct!=null&&Ct.level_id))throw new Error("Initiator approval level not found");const Ts=Ct.levelId||Ct.level_id;await Rr(Ie,Ts,"Revised Quotation Requested",Y),W.success("Revision requested. Request returned to dealer."),q()}catch(Ie){console.error("Failed to request revision:",Ie);const Ee=((pe=(Ne=Ie==null?void 0:Ie.response)==null?void 0:Ne.data)==null?void 0:pe.message)||(Ie==null?void 0:Ie.message)||"Failed to request revision. Please try again.";throw W.error(Ee),Ie}},Pt=async Y=>{var $e,Ce;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const xe=t.id||t.requestId,Ne=await Ps(xe),Ie=((Ne==null?void 0:Ne.approvalLevels)||(Ne==null?void 0:Ne.approvals)||[]).find(Te=>{const wt=(Te.levelName||Te.level_name||"").toLowerCase();return wt.includes("requestor claim")||wt.includes("requestor - claim")});if(!(Ie!=null&&Ie.levelId)&&!(Ie!=null&&Ie.level_id))throw new Error("Claim approval level not found");const Ee=Ie.levelId||Ie.level_id;await Rr(xe,Ee,"Revised Quotation Requested",Y),W.success("Re-quotation requested. Request returned to dealer."),q()}catch(xe){console.error("Failed to request re-quotation:",xe);const Ne=((Ce=($e=xe==null?void 0:xe.response)==null?void 0:$e.data)==null?void 0:Ce.message)||(xe==null?void 0:xe.message)||"Failed to request re-quotation. Please try again.";throw W.error(Ne),xe}},Ss=async Y=>{var $e,Ce;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const xe=t.id||t.requestId,Ne=await Ps(xe),pe=(Ne==null?void 0:Ne.approvalLevels)||(Ne==null?void 0:Ne.approvals)||[],Ie=pe.find(Te=>(Te.levelName||Te.level_name||"").toLowerCase().includes("department lead"))||pe.find(Te=>(Te.levelNumber||Te.level_number)===3);if(!(Ie!=null&&Ie.levelId)&&!(Ie!=null&&Ie.level_id))throw new Error("Department Lead approval level not found");const Ee=Ie.levelId||Ie.level_id;await kf(xe,{ioNumber:Y.ioNumber}),await Vn(xe,Ee,Y.comments),W.success("Request approved and IO organized successfully"),q()}catch(xe){console.error("Failed to approve and organize IO:",xe);const Ne=((Ce=($e=xe==null?void 0:xe.response)==null?void 0:$e.data)==null?void 0:Ce.message)||(xe==null?void 0:xe.message)||"Failed to approve request. Please try again.";throw W.error(Ne),xe}},as=async Y=>{var $e,Ce;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const xe=t.id||t.requestId,Ne=Y.closedExpenses.map(pe=>({description:pe.description,amount:pe.amount,gstRate:pe.gstRate,gstAmt:pe.gstAmt,cgstRate:pe.cgstRate,cgstAmt:pe.cgstAmt,sgstRate:pe.sgstRate,sgstAmt:pe.sgstAmt,igstRate:pe.igstRate,igstAmt:pe.igstAmt,utgstRate:pe.utgstRate,utgstAmt:pe.utgstAmt,cessRate:pe.cessRate,cessAmt:pe.cessAmt,totalAmt:pe.totalAmt,quantity:pe.quantity,hsnCode:pe.hsnCode,isService:pe.isService}));if(await F4(xe,{activityCompletionDate:Y.activityCompletionDate,numberOfParticipants:Y.numberOfParticipants,closedExpenses:Ne,totalClosedExpenses:Y.totalClosedExpenses,completionDocuments:Y.completionDocuments,activityPhotos:Y.activityPhotos,completionDescription:Y.completionDescription}),Y.invoicesReceipts&&Y.invoicesReceipts.length>0)for(const pe of Y.invoicesReceipts)await Hn(pe,xe,"SUPPORTING");Y.attendanceSheet&&await Hn(Y.attendanceSheet,xe,"SUPPORTING"),W.success("Completion documents submitted successfully"),q()}catch(xe){console.error("Failed to submit completion documents:",xe);const Ne=((Ce=($e=xe==null?void 0:xe.response)==null?void 0:$e.data)==null?void 0:Ce.message)||(xe==null?void 0:xe.message)||"Failed to submit completion documents. Please try again.";throw W.error(Ne),xe}},za=async Y=>{var $e,Ce;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const xe=t.id||t.requestId,Ne=new Date().toISOString().slice(0,10);await P4(xe,{eInvoiceDate:Ne}),W.success("E-Invoice generation initiated successfully."),q()}catch(xe){console.error("[DealerClaimWorkflowTab] Error generating e-invoice:",xe);let pe=((Ce=($e=xe==null?void 0:xe.response)==null?void 0:$e.data)==null?void 0:Ce.message)||(xe==null?void 0:xe.message)||"E-Invoice generation failed. Please try again.";throw pe.length>300&&(pe=pe.substring(0,300)+"..."),W.error(pe),xe}},Ha=async Y=>{var $e,Ce;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const xe=t.id||t.requestId,Ne=await Ps(xe),pe=(Ne==null?void 0:Ne.approvalLevels)||(Ne==null?void 0:Ne.approvals)||[],Ie=pe.find(Te=>(Te.levelName||Te.level_name||"").toLowerCase().includes("department lead"))||pe.find(Te=>(Te.levelNumber||Te.level_number)===3);if(!(Ie!=null&&Ie.levelId)&&!(Ie!=null&&Ie.level_id))throw new Error("Department Lead approval level not found");const Ee=Ie.levelId||Ie.level_id;await Rr(xe,Ee,"Dept Lead rejected - More clarification required",Y),W.success("Request rejected. Request has been cancelled."),q()}catch(xe){console.error("Failed to reject request:",xe);const Ne=((Ce=($e=xe==null?void 0:xe.response)==null?void 0:$e.data)==null?void 0:Ce.message)||(xe==null?void 0:xe.message)||"Failed to reject request. Please try again.";throw W.error(Ne),xe}},[br,wa]=x.useState(null);x.useEffect(()=>{if(!t){wa(null);return}(async()=>{try{const $e=t.id||t.requestId;if(!$e){wa(null);return}const Ce=await Ps($e),xe=(Ce==null?void 0:Ce.documents)||[],Ne=t.proposalDetails||(Ce==null?void 0:Ce.proposalDetails)||{},pe=xe.find(Te=>Te.category==="APPROVAL"||Te.type==="proposal"||Te.documentCategory==="APPROVAL"),Ie=xe.filter(Te=>Te.category==="SUPPORTING"||Te.type==="supporting"||Te.documentCategory==="SUPPORTING");let Ee=Ne.costBreakup||[];if(typeof Ee=="string")try{Ee=JSON.parse(Ee)}catch(Te){console.warn("Failed to parse costBreakup JSON:",Te),Ee=[]}Array.isArray(Ee)||(Ee=[]),wa({proposalDocument:pe?{name:pe.fileName||pe.file_name||pe.name,id:pe.documentId||pe.document_id||pe.id}:void 0,costBreakup:Ee,expectedCompletionDate:Ne.expectedCompletionDate||"",otherDocuments:Ie.map(Te=>({name:Te.fileName||Te.file_name||Te.name,id:Te.documentId||Te.document_id||Te.id})),dealerComments:Ne.dealerComments||"",submittedAt:Ne.submittedAt})}catch($e){console.warn("Failed to load proposal data:",$e);const Ce=t.proposalDetails||{};let xe=Ce.costBreakup||[];if(typeof xe=="string")try{xe=JSON.parse(xe)}catch(Ne){console.warn("Failed to parse costBreakup JSON:",Ne),xe=[]}Array.isArray(xe)||(xe=[]),wa({proposalDocument:void 0,costBreakup:xe,expectedCompletionDate:Ce.expectedCompletionDate||"",otherDocuments:[],dealerComments:Ce.dealerComments||"",submittedAt:Ce.submittedAt})}})()},[t]);const[Lt,Ca]=x.useState(null);x.useEffect(()=>{if(!t){Ca(null);return}(async()=>{try{const $e=t.id||t.requestId;if(!$e){Ca(null);return}const Ce=await Ps($e),xe=(Ce==null?void 0:Ce.documents)||[],Ne=[],pe=[],Ie=[];let Ee=null;xe.forEach(Te=>{const wt=(Te.category||Te.documentCategory||Te.type||"").toUpperCase(),Ct=(Te.fileName||Te.file_name||Te.name||"").toLowerCase(),Ts={name:Te.fileName||Te.file_name||Te.name,id:Te.documentId||Te.document_id||Te.id,url:Te.url||Te.storageUrl||Te.storage_url};wt==="COMPLETION"||wt==="COMPLETION_DOCUMENT"?Ne.push(Ts):wt==="ACTIVITY_PHOTO"||wt==="PHOTO"||wt==="IMAGE"?pe.push(Ts):wt==="ATTENDANCE"||wt==="ATTENDANCE_SHEET"?Ee=Ts:(wt==="SUPPORTING"||wt==="INVOICE"||wt==="RECEIPT")&&(!Ee&&(Ct.includes("attendance")||Ct.includes("participant"))?Ee=Ts:Ie.push(Ts))}),Ne.length===0&&pe.length===0&&t.completionDetails,Ca({completionDocuments:Ne,activityPhotos:pe,invoicesReceipts:Ie,attendanceSheet:Ee})}catch($e){console.warn("Failed to load completion documents:",$e),Ca(null)}})()},[t]);const Us=async()=>{try{W.loading("Retriggering WFM push...",{id:"wfm-retrigger"}),await M4(t.id),W.success("WFM push re-triggered successfully",{id:"wfm-retrigger"}),n?n():window.location.reload()}catch(Y){console.error("Error retriggering WFM push:",Y),W.error(Y.message||"Failed to re-trigger WFM push",{id:"wfm-retrigger"})}},Qr=async()=>{try{const Y=t.id||t.requestId;if(!Y){W.error("Request ID not found");return}const Ce=await fetch(`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${Y}/e-invoice/csv`,{headers:{Authorization:`Bearer ${tt.getAccessToken()||""}`},credentials:"include"});if(!Ce.ok)throw new Error("Failed to download CSV");const xe=await Ce.blob(),Ne=window.URL.createObjectURL(xe),pe=document.createElement("a");pe.href=Ne,pe.download=`Invoice_${t.requestNumber||"Export"}.csv`,document.body.appendChild(pe),pe.click(),window.URL.revokeObjectURL(Ne),document.body.removeChild(pe),W.success("CSV downloaded successfully")}catch(Y){console.error("Error downloading CSV:",Y),W.error("Failed to download CSV")}},Kr=async()=>{try{const Y=t.id||t.requestId;if(!Y){W.error("Request ID not found");return}if(!t.invoice&&!t.irn){W.error("Invoice not generated yet");return}K(!0),F(!0);const Ce=await fetch(`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${Y}/e-invoice/pdf`,{headers:{Authorization:`Bearer ${tt.getAccessToken()||""}`},credentials:"include"});if(!Ce.ok)throw new Error("Failed to fetch invoice PDF");const xe=await Ce.blob(),Ne=window.URL.createObjectURL(xe);G&&window.URL.revokeObjectURL(G),U(Ne)}catch(Y){console.error("Failed to preview invoice:",Y),W.error("Failed to load invoice preview"),F(!1)}finally{K(!1)}},jr=()=>{F(!1),G&&(window.URL.revokeObjectURL(G),U(null))},Xr=()=>{if(G){const Y=document.createElement("a");Y.href=G,Y.download=`Invoice_${t.requestNumber||"Download"}.pdf`,document.body.appendChild(Y),Y.click(),document.body.removeChild(Y),W.success("Invoice PDF downloaded")}},Ja=((sr=t==null?void 0:t.claimDetails)==null?void 0:sr.dealerName)||((Rt=t==null?void 0:t.dealerInfo)==null?void 0:Rt.name)||"Dealer",yr=((xs=t==null?void 0:t.claimDetails)==null?void 0:xs.dealerGstin)||((Xs=t==null?void 0:t.dealerInfo)==null?void 0:Xs.gstin)||((xa=t==null?void 0:t.dealerInfo)==null?void 0:xa.dealerGSTIN),qa=((Zr=t==null?void 0:t.claimDetails)==null?void 0:Zr.activityName)||((Aa=t==null?void 0:t.activityInfo)==null?void 0:Aa.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(Z,{children:[e.jsx(ce,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(we,{className:"mt-2",children:"Approval process for dealer claim management"})]})})}),e.jsxs(J,{children:[(t==null?void 0:t.status)==="rejected"&&!(t!=null&&t.closureDate||t!=null&&t.closure_date)&&a?e.jsxs("div",{className:"mb-6 p-4 bg-amber-50 border-l-4 border-amber-500 rounded-lg flex items-start gap-4 shadow-sm",children:[e.jsx("div",{className:"p-2 bg-amber-100 rounded-full",children:e.jsx(ss,{className:"w-5 h-5 text-amber-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-sm font-bold text-amber-900 mb-1",children:"Action Required: Request Returned"}),e.jsxs("p",{className:"text-xs text-amber-800 leading-relaxed mb-3",children:["This request has been returned to you by the department head.",a?"You can choose to resubmit, discuss with the dealer, request a revision, or cancel the request.":"The initiator needs to take action to proceed."]})]})]}):null,e.jsx("div",{className:"space-y-4",children:ne.map((Y,$e)=>{var Ct,Ts,Ft,Ta,Rs;const xe=(((Ct=Y.status)==null?void 0:Ct.toLowerCase())||"")==="in_progress",Ne=Y.step===ke,pe=ye&&xe&&Ne,Ie=Y.status==="approved"||Y.status==="skipped",Ee=z.find(fe=>(fe.step||fe.levelNumber||fe.level_number)===Y.step),Te=Ee!=null&&Ee.levelId?(Ts=t==null?void 0:t.approvals)==null?void 0:Ts.find(fe=>fe.levelId===Ee.levelId||fe.level_id===Ee.levelId):null,wt=(Te==null?void 0:Te.status)==="PAUSED"||((Ft=t==null?void 0:t.pauseInfo)==null?void 0:Ft.isPaused)&&(((Ta=t==null?void 0:t.pauseInfo)==null?void 0:Ta.levelId)===(Te==null?void 0:Te.levelId)||((Rs=t==null?void 0:t.pauseInfo)==null?void 0:Rs.level_id)===(Te==null?void 0:Te.levelId));return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${$4(Y.status,pe)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${U4(Y.status)}`,children:L4(Y.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:Y.title}),e.jsx(re,{className:O4(Y.status),children:Y.status.toLowerCase()}),Y.emailTemplateUrl&&Y.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:()=>{w({stepNumber:Y.step,stepName:Y.title}),S(!0)},children:e.jsx(va,{className:"w-3.5 h-3.5 text-blue-600"})}),Y.step===7&&Y.einvoiceUrl&&Ie&&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(Y.einvoiceUrl,"_blank"),children:e.jsx(Tt,{className:"w-3.5 h-3.5 text-green-600"})}),(()=>{const fe=(Y.levelName||Y.title||"").toLowerCase().includes("requestor claim")||(Y.levelName||Y.title||"").toLowerCase().includes("requestor - claim"),bt=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&Y.status==="approved";return fe&&bt&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-amber-100",title:"Preview Invoice",onClick:Kr,children:e.jsx(Mt,{className:"w-3.5 h-3.5 text-amber-600"})})})(),(()=>{var At,Ve,Ns,Vt;const fe=(Y.levelName||Y.title||"").toLowerCase().includes("requestor claim")||(Y.levelName||Y.title||"").toLowerCase().includes("requestor - claim"),bt=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&Y.status==="approved",Gt=((At=t==null?void 0:t.invoice)==null?void 0:At.wfmPushStatus)||((Ve=t==null?void 0:t.invoice)==null?void 0:Ve.wfmPushStatus),vs=((Ns=t==null?void 0:t.invoice)==null?void 0:Ns.wfmPushError)||((Vt=t==null?void 0:t.invoice)==null?void 0:Vt.wfmPushError);return fe&&bt&&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:Qr,children:e.jsx(ip,{className:"w-3.5 h-3.5 text-emerald-600"})}),Gt==="SUCCESS"?e.jsx("div",{title:"Pushed to WFM successfully",children:e.jsx(ps,{className:"w-3.5 h-3.5 text-green-500"})}):Gt==="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:Us,children:"Retry Push"})]}):e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{title:"WFM Push Pending",children:e.jsx(it,{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:Us,children:"Push Now"})]})]})})()]}),e.jsx("p",{className:"text-sm text-gray-600",children:Y.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:Y.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",Xt(Y.tatHours)]}),Y.elapsedHours&&(pe||Ie)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",Xt(Y.elapsedHours)]})]})]}),Y.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:Y.comment})}),Y.versionHistory&&Y.versionHistory.all&&Y.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 fe=new Set(_);fe.has(Y.step)?fe.delete(Y.step):fe.add(Y.step),L(fe)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cp,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"font-medium",children:"Version History"}),Y.versionHistory.all&&Y.versionHistory.all.length>0&&e.jsxs(re,{className:"bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0",children:[Y.versionHistory.all.length," Versions"]})]}),_.has(Y.step)?e.jsx(ul,{className:"w-4 h-4"}):e.jsx(jn,{className:"w-4 h-4"})]}),_.has(Y.step)&&Y.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:Y.versionHistory.all.map((fe,bt)=>{var Gt,vs,At,Ve;return e.jsxs("div",{className:`space-y-2 ${bt>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(re,{className:`${bt===0?"bg-amber-500":"bg-gray-400"} text-white text-[10px] px-2 py-0.5`,children:[bt===0?"Current":"Previous",": v",fe.version]}),e.jsx("span",{className:"text-[10px] text-gray-600 font-medium",children:qr(fe.createdAt)})]})}),e.jsx("p",{className:"text-xs text-gray-700 font-medium",children:fe.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${bt===0?"bg-blue-100":"bg-gray-100"} flex items-center justify-center`,children:e.jsx("span",{className:`text-[8px] font-bold ${bt===0?"text-blue-600":"text-gray-600"}`,children:((vs=(Gt=fe.changer)==null?void 0:Gt.displayName)==null?void 0:vs.charAt(0))||"U"})}),e.jsxs("span",{className:"text-[10px] text-gray-600",children:["By ",((At=fe.changer)==null?void 0:At.displayName)||((Ve=fe.changer)==null?void 0:Ve.email)||"Unknown User"]})]}),fe.snapshotType==="PROPOSAL"&&fe.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(fe.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>C({data:fe.snapshotData,type:"PROPOSAL",title:`Proposal (v${fe.version})`}),children:[e.jsx(Nt,{className:"w-3 h-3"}),"View Details"]})]}),fe.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",fe.snapshotData.comments]})]}),fe.snapshotType==="INTERNAL_ORDER"&&fe.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: ",fe.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Blocked Amount: ₹",Number(fe.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),fe.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-[10px] text-gray-600",children:["SAP Doc: ",fe.snapshotData.sapDocumentNumber]})]}),fe.snapshotType==="COMPLETION"&&fe.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(fe.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>C({data:fe.snapshotData,type:"COMPLETION",title:`Completion (v${fe.version})`}),children:[e.jsx(Nt,{className:"w-3 h-3"}),"View Details"]})]}),fe.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",fe.snapshotData.comments]})]}),fe.snapshotType==="APPROVE"&&fe.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:[fe.snapshotData.action==="APPROVE"?"Approval":"Rejection"," Snapshot:"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["By: ",fe.snapshotData.approverName||fe.snapshotData.approverEmail||"Unknown"]}),fe.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1",children:["Comments: ",fe.snapshotData.comments.substring(0,100),fe.snapshotData.comments.length>100?"...":""]}),fe.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-[10px] text-red-600 mt-1",children:["Rejection Reason: ",fe.snapshotData.rejectionReason.substring(0,100),fe.snapshotData.rejectionReason.length>100?"...":""]})]}),fe.snapshotType==="WORKFLOW"&&fe.snapshotData&&fe.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:[fe.snapshotData.comments.substring(0,100),fe.snapshotData.comments.length>100?"...":""]})]})]},bt)})})]}),pe&&(Te==null?void 0:Te.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:Te.sla.deadline?Fa(Te.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${wt?"bg-gray-100 border-gray-300":(Te.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(Te.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(Te.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(it,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",wt&&"(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:Te.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:[Te.sla.elapsedText||"0 hours"," / ",Xt(Y.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const fe=Te.sla.percentageUsed||0,bt=()=>wt?"bg-gray-500":fe>=100?"bg-red-600":fe>=75?"bg-orange-500":fe>=50?"bg-amber-500":"bg-green-600",Gt=()=>wt?"text-gray-600":fe>=100?"text-red-600":fe>=75?"text-orange-600":fe>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(ia,{value:fe,className:"h-3",indicatorClassName:bt()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${Gt()}`,children:["Progress: ",Math.min(100,fe),"% of TAT used"]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[Te.sla.remainingText||"0 hours"," remaining"]})]})]})})(),Te.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(Ji,{className:"w-4 h-4"}),"Deadline Breached"]}),Te.sla.status==="critical"&&e.jsxs("p",{className:"text-xs font-semibold text-center text-orange-600 flex items-center justify-center gap-1.5",children:[e.jsx(ss,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),(()=>{const fe=Y.levelName||Y.level_name;return(fe&&fe.toLowerCase().includes("department lead")||Y.title&&Y.title.toLowerCase().includes("department lead"))&&!ie&&Y.status==="approved"&&Y.ioDetails&&Y.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(Mt,{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:Y.ioDetails.ioNumber})]}),Y.ioDetails.blockedAmount!==void 0&&Y.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:["₹",Y.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),Y.ioDetails.remainingBalance!==void 0&&Y.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:["₹",Y.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 ",Y.ioDetails.organizedBy||Y.approver||"N/A"," on"," ",Y.ioDetails.organizedAt?qr(Y.ioDetails.organizedAt):Y.approvedAt?qr(Y.approvedAt):"N/A"]})]})]})})(),Y.step===6&&Y.dmsDetails&&Y.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(Bt,{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:Y.dmsDetails.dmsNumber})]}),Y.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:Y.dmsDetails.dmsRemarks})]}),Y.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Initiated by ",Y.dmsDetails.pushedBy," on"," ",qr(Y.dmsDetails.pushedAt)]})]})]}),(()=>{const fe=z.find(Ve=>(Ve.step||Ve.levelNumber||Ve.level_number)===Y.step),bt=((fe==null?void 0:fe.approverEmail)||"").toLowerCase(),Gt=bt&&Oe===bt,vs=Y.step===1||(fe==null?void 0:fe.levelName)&&fe.levelName.toLowerCase().includes("dealer");return pe&&(Gt||vs&&ie)&&!l})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[(()=>{const fe=((Ee==null?void 0:Ee.levelName)||Y.title||"").toLowerCase();return(Y.step===1||fe.includes("proposal")||fe.includes("submission"))&&(ie||Ke)})()&&e.jsxs(E,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{c(!0)},children:[e.jsx(ys,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),(()=>{const fe=((Ee==null?void 0:Ee.levelName)||Y.title||"").toLowerCase();return(fe.includes("requestor evaluation")||fe.includes("confirmation")||Y.step===oe)&&(a||Xe)})()&&e.jsxs(E,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{m(!0)},children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const fe=z.find(Ve=>(Ve.step||Ve.levelNumber||Ve.level_number)===Y.step);if(!((fe==null?void 0:fe.levelName)||Y.title||"").toLowerCase().includes("initiator action")||!(a||Oe===gt))return null;const At=async Ve=>{var Ns,Vt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Fs=t.requestId||t.id;await mg(Fs,Ve,{reason:""}),W.success(`Action "${Ve==="REVISE"?"Revision Requested":"Request Reopened"}" performed successfully`),q()}catch(Fs){console.error("Failed to perform initiator action:",Fs);const Kf=((Vt=(Ns=Fs==null?void 0:Fs.response)==null?void 0:Ns.data)==null?void 0:Vt.message)||(Fs==null?void 0:Fs.message)||"Failed to perform action";W.error(Kf)}};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(Et,{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(sp,{className:"w-4 h-4 mr-2"}),"Reopen"]})]})})(),(()=>{const fe=z.find(Vt=>(Vt.levelName||"").toLowerCase().includes("department lead"));if(!(fe&&Y.step===(fe.step||fe.levelNumber||fe.level_number)))return null;const Gt=((fe==null?void 0:fe.approverEmail)||"").toLowerCase();if(!(Gt&&Oe===Gt||ut||rt))return null;const At=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),Ve=(At==null?void 0:At.ioNumber)||(At==null?void 0:At.io_number)||(t==null?void 0:t.ioNumber)||"",Ns=Ve&&Ve.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:()=>{u(!0)},disabled:!Ns,children:[e.jsx(Be,{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 fe=z.find(Ve=>(Ve.step||Ve.levelNumber||Ve.level_number)===Y.step),bt=((fe==null?void 0:fe.approverEmail)||"").toLowerCase(),Gt=ie&&bt===je,vs=((fe==null?void 0:fe.levelName)||Y.title||"").toLowerCase(),At=vs.includes("dealer completion")||vs.includes("completion documents");return Gt&&At})()&&e.jsxs(E,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{g(!0)},children:[e.jsx(ys,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const fe=z.find(At=>{const Ve=(At.levelName||"").toLowerCase();return Ve.includes("requestor claim")||Ve.includes("requestor - claim")});if(!(fe&&Y.step===(fe.step||fe.levelNumber||fe.level_number)))return null;const Gt=((fe==null?void 0:fe.approverEmail)||"").toLowerCase();return a||Gt&&Oe===Gt?e.jsxs(E,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{b(!0)},children:[e.jsx(Bt,{className:"w-4 h-4 mr-2"}),"Generate E-Invoice & Sync"]}):null})(),(()=>{var Ns;const fe=((Ee==null?void 0:Ee.levelName)||Y.title||"").toLowerCase(),bt=fe.includes("credit note")||fe.includes("sap")||Y.step===8&&!fe.includes("additional"),Gt=((Ee==null?void 0:Ee.approverEmail)||"").toLowerCase(),vs=Gt&&Oe===Gt,At=((Ns=s==null?void 0:s.role)==null?void 0:Ns.toUpperCase())||"";return bt&&(vs||(At==="FINANCE"||At==="ADMIN"))})()&&e.jsxs(E,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{y(!0)},children:[e.jsx(Mt,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]}),(()=>{const fe=z.find(At=>(At.step||At.levelNumber||At.level_number)===Y.step),bt=((fe==null?void 0:fe.levelName)||Y.title||"").toLowerCase(),Gt=bt.includes("additional approver"),vs=Y.step===1||bt.includes("proposal")||bt.includes("submission")||bt.includes("requestor evaluation")||bt.includes("confirmation")||bt.includes("department lead")||bt.includes("dealer completion")||bt.includes("completion documents")||bt.includes("requestor claim")||bt.includes("requestor - claim")||bt.includes("credit note")||bt.includes("sap");if(Gt||!vs){const At=(fe==null?void 0:fe.levelId)||(fe==null?void 0:fe.level_id);if(At){const Ve=(fe==null?void 0:fe.levelName)||(fe==null?void 0:fe.level_name)||Y.title||"Approval Level",Ns=(fe==null?void 0:fe.approverName)||(fe==null?void 0:fe.approver_name)||Y.approver||"Approver";return e.jsxs(E,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{v({levelId:At,levelName:Ve,approverName:Ns}),D(!0)},children:[e.jsx(Be,{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 Ve,Ns;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Vt=t.id||t.requestId;if(!At){W.error("Approval level not found");return}await Vn(Vt,At,""),W.success("Request approved successfully"),q()}catch(Vt){console.error("Failed to approve:",Vt);const Fs=((Ns=(Ve=Vt==null?void 0:Vt.response)==null?void 0:Ve.data)==null?void 0:Ns.message)||(Vt==null?void 0:Vt.message)||"Failed to approve request. Please try again.";W.error(Fs)}},children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(E,{variant:"destructive",onClick:async()=>{var Ve,Ns;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Vt=t.id||t.requestId;if(!At){W.error("Approval level not found");return}const Fs=prompt("Please provide a reason for rejection:");if(Fs===null)return;await Rr(Vt,At,"Request rejected",Fs),W.success("Request rejected successfully"),q()}catch(Vt){console.error("Failed to reject:",Vt);const Fs=((Ns=(Ve=Vt==null?void 0:Vt.response)==null?void 0:Ve.data)==null?void 0:Ns.message)||(Vt==null?void 0:Vt.message)||"Failed to reject request. Please try again.";W.error(Fs)}},children:[e.jsx(St,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),Y.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",qr(Y.approvedAt)]})]})]})},$e)})})]})]}),e.jsx(N4,{isOpen:o,onClose:()=>c(!1),onSubmit:Hs,dealerName:Ja,dealerGSTIN:yr,activityName:qa,defaultGstRate:(ar=t==null?void 0:t.claimDetails)==null?void 0:ar.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),previousProposalData:(kn=M==null?void 0:M.find(Y=>Y.snapshotType==="PROPOSAL"))==null?void 0:kn.snapshotData,documentPolicy:i,taxationType:(Dn=t==null?void 0:t.claimDetails)==null?void 0:Dn.taxationType,totalBlockedAmount:((t==null?void 0:t.internalOrders)||[]).reduce((Y,$e)=>Y+Number($e.ioBlockedAmount||$e.io_blocked_amount||$e.blockedAmount||0),0)}),e.jsx(A4,{isOpen:d,onClose:()=>{m(!1)},onApprove:is,onReject:vt,onRequestRevision:pt,proposalData:br,dealerName:Ja,activityName:qa,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const Y=(M==null?void 0:M.filter($e=>$e.snapshotType==="PROPOSAL"))||[];return Y.length>1?Y[1].snapshotData:null})(),taxationType:(Rn=t==null?void 0:t.claimDetails)==null?void 0:Rn.taxationType}),e.jsx(w4,{isOpen:p,onClose:()=>u(!1),onApprove:Ss,onReject:Ha,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((Dd=t==null?void 0:t.internalOrder)==null?void 0:Dd.ioNumber)||((Rd=t==null?void 0:t.internalOrder)==null?void 0:Rd.io_number)||((Fd=t==null?void 0:t.internal_order)==null?void 0:Fd.ioNumber)||((Id=t==null?void 0:t.internal_order)==null?void 0:Id.io_number)||void 0,preFilledBlockedAmount:((Pd=t==null?void 0:t.internalOrder)==null?void 0:Pd.ioBlockedAmount)||((Ed=t==null?void 0:t.internalOrder)==null?void 0:Ed.io_blocked_amount)||((_d=t==null?void 0:t.internal_order)==null?void 0:_d.ioBlockedAmount)||((Md=t==null?void 0:t.internal_order)==null?void 0:Md.io_blocked_amount)||void 0,preFilledRemainingBalance:((Ld=t==null?void 0:t.internalOrder)==null?void 0:Ld.ioRemainingBalance)||((Od=t==null?void 0:t.internalOrder)==null?void 0:Od.io_remaining_balance)||(($d=t==null?void 0:t.internal_order)==null?void 0:$d.ioRemainingBalance)||((Ud=t==null?void 0:t.internal_order)==null?void 0:Ud.io_remaining_balance)||void 0,taxationType:(Bd=t==null?void 0:t.claimDetails)==null?void 0:Bd.taxationType}),e.jsx(v4,{isOpen:h,onClose:()=>g(!1),onSubmit:as,dealerName:Ja,dealerGSTIN:yr,activityName:qa,defaultGstRate:(Vd=t==null?void 0:t.claimDetails)==null?void 0:Vd.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i,taxationType:(zd=t==null?void 0:t.claimDetails)==null?void 0:zd.taxationType}),e.jsx(C4,{isOpen:f,onClose:()=>b(!1),onPush:za,completionDetails:{activityCompletionDate:((Hd=t==null?void 0:t.completionDetails)==null?void 0:Hd.activityCompletionDate)||((Gd=t==null?void 0:t.completionDetails)==null?void 0:Gd.activity_completion_date),numberOfParticipants:((Wd=t==null?void 0:t.completionDetails)==null?void 0:Wd.numberOfParticipants)||((Yd=t==null?void 0:t.completionDetails)==null?void 0:Yd.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((Qd=t==null?void 0:t.completionDetails)==null?void 0:Qd.closedExpenses)||((Kd=t==null?void 0:t.completionDetails)==null?void 0:Kd.closed_expenses),totalClosedExpenses:((Xd=t==null?void 0:t.budgetTracking)==null?void 0:Xd.closedExpenses)||((Zd=t==null?void 0:t.budgetTracking)==null?void 0:Zd.closed_expenses)||((Jd=t==null?void 0:t.completionDetails)==null?void 0:Jd.totalClosedExpenses)||((qd=t==null?void 0:t.completionDetails)==null?void 0:qd.total_closed_expenses),completionDescription:((em=t==null?void 0:t.completionDetails)==null?void 0:em.completionDescription)||((tm=t==null?void 0:t.completionDetails)==null?void 0:tm.completion_description)},ioDetails:{ioNumber:((sm=t==null?void 0:t.internalOrder)==null?void 0:sm.ioNumber)||((am=t==null?void 0:t.internalOrder)==null?void 0:am.io_number)||((rm=t==null?void 0:t.internal_order)==null?void 0:rm.ioNumber)||((nm=t==null?void 0:t.internal_order)==null?void 0:nm.io_number),blockedAmount:((im=t==null?void 0:t.internalOrder)==null?void 0:im.ioBlockedAmount)||((lm=t==null?void 0:t.internalOrder)==null?void 0:lm.io_blocked_amount)||((om=t==null?void 0:t.internal_order)==null?void 0:om.ioBlockedAmount)||((cm=t==null?void 0:t.internal_order)==null?void 0:cm.io_blocked_amount),availableBalance:((dm=t==null?void 0:t.internalOrder)==null?void 0:dm.ioAvailableBalance)||((mm=t==null?void 0:t.internalOrder)==null?void 0:mm.io_available_balance)||((um=t==null?void 0:t.internal_order)==null?void 0:um.ioAvailableBalance)||((xm=t==null?void 0:t.internal_order)==null?void 0:xm.io_available_balance),remainingBalance:((hm=t==null?void 0:t.internalOrder)==null?void 0:hm.ioRemainingBalance)||((pm=t==null?void 0:t.internalOrder)==null?void 0:pm.io_remaining_balance)||((gm=t==null?void 0:t.internal_order)==null?void 0:gm.ioRemainingBalance)||((fm=t==null?void 0:t.internal_order)==null?void 0:fm.io_remaining_balance)},completionDocuments:Lt,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:(bm=t==null?void 0:t.claimDetails)==null?void 0:bm.taxationType,onReQuotation:Pt}),e.jsx(_k,{isOpen:j,onClose:()=>y(!1),taxationType:(jm=t==null?void 0:t.claimDetails)==null?void 0:jm.taxationType,onDownload:async()=>{W.info("Download functionality will be implemented")},onSendToDealer:async()=>{var Y,$e;try{const Ce=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!Ce){W.error("Request ID not found");return}await E4(Ce),W.success("Credit note sent to dealer successfully. Step 8 has been approved."),n&&n()}catch(Ce){console.error("Failed to send credit note to dealer:",Ce);const xe=(($e=(Y=Ce==null?void 0:Ce.response)==null?void 0:Y.data)==null?void 0:$e.message)||(Ce==null?void 0:Ce.message)||"Failed to send credit note to dealer";W.error(xe)}},creditNoteData:{creditNoteNumber:((ym=t==null?void 0:t.creditNote)==null?void 0:ym.creditNoteNumber)||((vm=t==null?void 0:t.creditNote)==null?void 0:vm.credit_note_number)||((wm=(Nm=t==null?void 0:t.claimDetails)==null?void 0:Nm.creditNote)==null?void 0:wm.creditNoteNumber)||((Cm=t==null?void 0:t.claimDetails)==null?void 0:Cm.creditNoteNumber)||((Sm=t==null?void 0:t.claimDetails)==null?void 0:Sm.credit_note_number),creditNoteDate:((Am=t==null?void 0:t.creditNote)==null?void 0:Am.creditNoteDate)||((Tm=t==null?void 0:t.creditNote)==null?void 0:Tm.credit_note_date)||((Dm=(km=t==null?void 0:t.claimDetails)==null?void 0:km.creditNote)==null?void 0:Dm.creditNoteDate)||((Rm=t==null?void 0:t.claimDetails)==null?void 0:Rm.creditNoteDate)||((Fm=t==null?void 0:t.claimDetails)==null?void 0:Fm.credit_note_date),creditNoteAmount:(Im=t==null?void 0:t.creditNote)!=null&&Im.creditNoteAmount?Number((Pm=t==null?void 0:t.creditNote)==null?void 0:Pm.creditNoteAmount):(Em=t==null?void 0:t.creditNote)!=null&&Em.credit_note_amount?Number((_m=t==null?void 0:t.creditNote)==null?void 0:_m.credit_note_amount):(Lm=(Mm=t==null?void 0:t.claimDetails)==null?void 0:Mm.creditNote)!=null&&Lm.creditNoteAmount?Number(($m=(Om=t==null?void 0:t.claimDetails)==null?void 0:Om.creditNote)==null?void 0:$m.creditNoteAmount):(Um=t==null?void 0:t.claimDetails)!=null&&Um.creditNoteAmount?Number((Bm=t==null?void 0:t.claimDetails)==null?void 0:Bm.creditNoteAmount):(Vm=t==null?void 0:t.claimDetails)!=null&&Vm.credit_note_amount?Number((zm=t==null?void 0:t.claimDetails)==null?void 0:zm.credit_note_amount):void 0,transactionNo:((Hm=t==null?void 0:t.creditNote)==null?void 0:Hm.transactionNo)||((Gm=t==null?void 0:t.creditNote)==null?void 0:Gm.transaction_no),tdsAmount:((Wm=t==null?void 0:t.creditNote)==null?void 0:Wm.tdsAmount)||((Ym=t==null?void 0:t.creditNote)==null?void 0:Ym.tds_amount),creditAmount:((Qm=t==null?void 0:t.creditNote)==null?void 0:Qm.creditAmount)||((Km=t==null?void 0:t.creditNote)==null?void 0:Km.credit_amount),items:((Xm=t==null?void 0:t.creditNote)==null?void 0:Xm.items)||[],status:((Zm=t==null?void 0:t.creditNote)==null?void 0:Zm.status)||((qm=(Jm=t==null?void 0:t.claimDetails)==null?void 0:Jm.creditNote)==null?void 0:qm.status)||((eu=t==null?void 0:t.creditNote)!=null&&eu.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((tu=t==null?void 0:t.claimDetails)==null?void 0:tu.dealerName)||((su=t==null?void 0:t.claimDetails)==null?void 0:su.dealer_name),dealerCode:((au=t==null?void 0:t.claimDetails)==null?void 0:au.dealerCode)||((ru=t==null?void 0:t.claimDetails)==null?void 0:ru.dealer_code),dealerEmail:((nu=t==null?void 0:t.claimDetails)==null?void 0:nu.dealerEmail)||((iu=t==null?void 0:t.claimDetails)==null?void 0:iu.dealer_email)},activityName:((lu=t==null?void 0:t.claimDetails)==null?void 0:lu.activityName)||((ou=t==null?void 0:t.claimDetails)==null?void 0:ou.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(S4,{isOpen:N,onClose:()=>{S(!1),w(null)},stepNumber:(A==null?void 0:A.stepNumber)||4,stepName:(A==null?void 0:A.stepName)||"Activity Creation",requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.id)||(t==null?void 0:t.request_number),recipientEmail:"system@undefined"}),T&&e.jsx(Ek,{isOpen:I,onClose:()=>{D(!1),v(null)},onApprove:async Y=>{var $e,Ce;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const xe=t.id||t.requestId,Ne=T.levelId;if(!Ne){W.error("Approval level not found");return}await Vn(xe,Ne,Y),W.success("Request approved successfully"),q(),D(!1),v(null)}catch(xe){console.error("Failed to approve:",xe);const Ne=((Ce=($e=xe==null?void 0:xe.response)==null?void 0:$e.data)==null?void 0:Ce.message)||(xe==null?void 0:xe.message)||"Failed to approve request. Please try again.";throw W.error(Ne),xe}},onReject:async Y=>{var $e,Ce;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const xe=t.id||t.requestId,Ne=T.levelId;if(!Ne){W.error("Approval level not found");return}await Rr(xe,Ne,"Request rejected",Y),W.success("Request rejected successfully"),q(),D(!1),v(null)}catch(xe){console.error("Failed to reject:",xe);const Ne=((Ce=($e=xe==null?void 0:xe.response)==null?void 0:$e.data)==null?void 0:Ce.message)||(xe==null?void 0:xe.message)||"Failed to reject request. Please try again.";throw W.error(Ne),xe}},requestTitle:(t==null?void 0:t.title)||"Request",requestDescription:(t==null?void 0:t.description)||"",requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),levelName:T.levelName,approverName:T.approverName}),M&&M.length>0&&e.jsxs(Z,{className:"mt-6 border-amber-100 bg-amber-50/30",children:[e.jsxs(ce,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(de,{className:"text-sm font-bold flex items-center gap-2 text-amber-900",children:[e.jsx(Bt,{className:"w-4 h-4"}),"Revision History & Audit Trail"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>k(!B),className:"text-amber-700 hover:text-amber-800 hover:bg-amber-100",children:B?"Hide History":"View History"})]}),e.jsx(we,{className:"text-xs text-amber-700",children:"Records of all revisions and actions taken on this request"})]}),B&&e.jsx(J,{children:e.jsx("div",{className:"space-y-4",children:M.map((Y,$e)=>{var Ce,xe,Ne,pe;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 ",Y.version]}),Y.snapshotType&&e.jsx(re,{className:"bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0",children:Y.snapshotType}),Y.levelNumber&&e.jsxs(re,{className:"bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0",children:["Step ",Y.levelNumber]})]}),e.jsx("span",{className:"text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full",children:qr(Y.createdAt)})]}),e.jsx("p",{className:"text-xs font-medium text-gray-800",children:Y.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:((xe=(Ce=Y.changer)==null?void 0:Ce.displayName)==null?void 0:xe.charAt(0))||"U"})}),e.jsxs("span",{className:"text-xs text-gray-500",children:["By ",((Ne=Y.changer)==null?void 0:Ne.displayName)||((pe=Y.changer)==null?void 0:pe.email)||"Unknown User"]})]}),Y.snapshotType==="PROPOSAL"&&Y.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:"}),Y.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:()=>C({data:Y.snapshotData,type:"PROPOSAL",title:`Historical Proposal (Version ${Y.version})`}),children:["View Details",e.jsx(Nt,{className:"w-2 h-2"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Budget: ₹",Number(Y.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),Y.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",Y.snapshotData.comments.substring(0,80),Y.snapshotData.comments.length>80?"...":""]})]}),Y.snapshotType==="COMPLETION"&&Y.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:"}),Y.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:()=>C({data:Y.snapshotData,type:"COMPLETION",title:`Historical Completion (Version ${Y.version})`}),children:["View Details",e.jsx(Nt,{className:"w-3 h-3"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Total Expenses: ₹",Number(Y.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),Y.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",Y.snapshotData.comments.substring(0,80),Y.snapshotData.comments.length>80?"...":""]})]}),Y.snapshotType==="INTERNAL_ORDER"&&Y.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: ",Y.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-gray-600",children:["Blocked: ₹",Number(Y.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),Y.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-gray-600",children:["SAP Doc: ",Y.snapshotData.sapDocumentNumber]})]}),Y.snapshotType==="APPROVE"&&Y.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:[Y.snapshotData.action==="APPROVE"?"Approval":"Rejection",":"]}),e.jsxs("p",{className:"text-gray-600",children:["By: ",Y.snapshotData.approverName||Y.snapshotData.approverEmail||"Unknown"]}),Y.snapshotData.levelName&&e.jsxs("p",{className:"text-gray-600",children:["Level: ",Y.snapshotData.levelName]}),Y.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",Y.snapshotData.comments.substring(0,80),Y.snapshotData.comments.length>80?"...":""]}),Y.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-red-600 mt-1",children:["Rejection Reason: ",Y.snapshotData.rejectionReason.substring(0,80),Y.snapshotData.rejectionReason.length>80?"...":""]})]}),Y.snapshotType==="WORKFLOW"&&Y.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: ",Y.snapshotData.status||"N/A"]}),Y.snapshotData.currentLevel&&e.jsxs("p",{className:"text-gray-600",children:["Current Level: ",Y.snapshotData.currentLevel]})]})]})]},Y.historyId||$e)})})})]}),e.jsx(T4,{isOpen:!!R,onClose:()=>C(null),snapshot:R==null?void 0:R.data,type:(R==null?void 0:R.type)||"PROPOSAL",title:R==null?void 0:R.title}),$&&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:jr}),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(Mt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Invoice Preview"}),e.jsx(re,{className:"bg-amber-100 text-amber-800 text-xs",children:t.requestNumber})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[G&&e.jsxs(E,{variant:"outline",size:"sm",onClick:Xr,className:"gap-1.5 text-xs",children:[e.jsx(Tt,{className:"w-3.5 h-3.5"}),"Download"]}),e.jsx(E,{variant:"ghost",size:"icon",onClick:jr,className:"h-8 w-8 hover:bg-gray-200",children:e.jsx(yt,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:H?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3",children:[e.jsx(ze,{className:"w-8 h-8 text-amber-600 animate-spin"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading invoice..."})]}):G?e.jsx("iframe",{src:G,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 V4({request:t,apiRequest:s,onRefresh:a,isSpectator:r=!1}){const{user:n}=us(),i=(s==null?void 0:s.requestId)||(t==null?void 0:t.requestId),l=(s==null?void 0:s.proposalDetails)||{},o=(s==null?void 0:s.claimDetails)||s||{},d=x.useMemo(()=>{const B=(l==null?void 0:l.costBreakup)||(o==null?void 0:o.costBreakup)||[],k=Array.isArray(B)?B:typeof B=="string"?JSON.parse(B):[];return!Array.isArray(k)||k.length===0?Number((o==null?void 0:o.totalProposedTaxableAmount)||(l==null?void 0:l.totalEstimatedBudget)||(l==null?void 0:l.total_estimated_budget)||0):k.reduce((_,L)=>{const R=typeof L=="object"&&L.amount||0,C=typeof L=="object"&&L.quantity||1;return _+Number(R)*Number(C)},0)},[l==null?void 0:l.costBreakup,o==null?void 0:o.costBreakup,o==null?void 0:o.totalProposedTaxableAmount,l==null?void 0:l.totalEstimatedBudget]),m=(s==null?void 0:s.budgetTracking)||(t==null?void 0:t.budgetTracking)||{},p=(m==null?void 0:m.budgetStatus)||(m==null?void 0:m.budget_status)||"",u=(s==null?void 0:s.internalOrders)||(s==null?void 0:s.internal_orders)||(t==null?void 0:t.internalOrders)||[],h=x.useMemo(()=>u.reduce((B,k)=>B+Number(k.ioBlockedAmount||k.io_blocked_amount||0),0),[u]),g=p==="PROPOSED"&&u.length>0&&d-h>.01,[f,b]=x.useState(""),[j,y]=x.useState(!1),[N,S]=x.useState(null),[A,w]=x.useState(""),[I,D]=x.useState([]),[T,v]=x.useState(!1);x.useEffect(()=>{if(u.length>0){const B=u.map(k=>{const _=k.organizer||null,L=(_==null?void 0:_.displayName)||(_==null?void 0:_.display_name)||(_==null?void 0:_.name)||(_!=null&&_.firstName&&(_!=null&&_.lastName)?`${_.firstName} ${_.lastName}`.trim():null)||(_==null?void 0:_.email)||"Unknown User";return{ioNumber:k.ioNumber||k.io_number,blockedAmount:Number(k.ioBlockedAmount||k.io_blocked_amount||0),availableBalance:Number(k.ioAvailableBalance||k.io_available_balance||0),remainingBalance:Number(k.ioRemainingBalance||k.io_remaining_balance||0),blockedDate:k.organizedAt||k.organized_at||new Date().toISOString(),blockedBy:L,sapDocumentNumber:k.sapDocumentNumber||k.sap_document_number||"",status:k.status==="BLOCKED"?"blocked":k.status==="RELEASED"?"released":k.status==="PENDING"?"pending":"blocked"}});D(B),!g&&B.length>0&&b(B[B.length-1].ioNumber)}},[s,t,g,u]);const M=async()=>{var B,k;if(!f.trim()){W.error("Please enter an IO number");return}if(!i){W.error("Request ID not found");return}y(!0);try{const _=await I4(i,f.trim());if(_.isValid&&_.availableBalance>0){S(_.availableBalance);const L=I.reduce((C,G)=>C+G.blockedAmount,0),R=Math.max(0,d-L);R>0?w(String(R.toFixed(2))):d>0&&L===0?w(String(d.toFixed(2))):w(String(_.availableBalance.toFixed(2))),W.success(`IO fetched from SAP. Available balance: ₹${_.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)}else W.error("Invalid IO number or no available balance found"),S(null),w("")}catch(_){console.error("Failed to fetch IO budget:",_);const L=((k=(B=_==null?void 0:_.response)==null?void 0:B.data)==null?void 0:k.message)||(_==null?void 0:_.message)||"Failed to validate IO number or fetch budget from SAP";W.error(L),S(null)}finally{y(!1)}},P=async()=>{var R,C;if(!f.trim()||N===null){W.error("Please fetch IO amount first");return}if(!i){W.error("Request ID not found");return}const B=parseFloat(A);if(!A||isNaN(B)||B<=0){W.error("Please enter a valid amount to block");return}const k=parseFloat(B.toFixed(2));if(k>N){W.error("Amount to block exceeds available IO budget");return}const L=I.reduce((G,U)=>G+U.blockedAmount,0)+k;if(d>0){const G=parseFloat(d.toFixed(2)),U=parseFloat(L.toFixed(2));if(Math.abs(U-G)>.01){W.error(`Total blocked amount (₹${U.toLocaleString("en-IN")}) must be exactly equal to the estimated budget (₹${G.toLocaleString("en-IN")})`);return}}v(!0);try{const G=parseFloat(N.toFixed(2)),U=parseFloat((G-k).toFixed(2)),$={ioNumber:f.trim(),ioAvailableBalance:G,ioBlockedAmount:k,ioRemainingBalance:U};await kf(i,$);const F=await D4(i),H=(F==null?void 0:F.internalOrder)||(F==null?void 0:F.internal_order);if(H){const K=Number(H.ioBlockedAmount||H.io_blocked_amount||k),z=Number(H.ioRemainingBalance||H.io_remaining_balance||0),O=N-K;Math.abs(K-k)>.01&&console.warn("[IOTab] ⚠️ Amount mismatch! Sent:",k,"Saved:",K),Math.abs(z-O)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:N,blockedAmount:K,expectedRemaining:O,backendRemaining:z,difference:z-O});const V=n,Q=(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)||"Current User",q={ioNumber:H.ioNumber||H.io_number||f,blockedAmount:K,availableBalance:N,remainingBalance:z,blockedDate:H.organizedAt||H.organized_at||new Date().toISOString(),blockedBy:Q,sapDocumentNumber:H.sapDocumentNumber||H.sap_document_number||"",status:"blocked"};D(ee=>[...ee,q]),w(""),S(null),W.success("IO budget blocked successfully in SAP"),a==null||a()}else W.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(G){console.error("Failed to block IO budget:",G);const U=((C=(R=G==null?void 0:G.response)==null?void 0:R.data)==null?void 0:C.message)||(G==null?void 0:G.message)||"Failed to block IO budget in SAP";W.error(U)}finally{v(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(we,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Re,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:f,onChange:B=>b(B.target.value),disabled:j||I.length>0&&!g||r,className:"flex-1"}),e.jsxs(E,{onClick:M,disabled:!f.trim()||j||I.length>0&&!g||r,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),j?"Fetching...":"Fetch Amount"]})]})]}),!N&&I.length===0&&f.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.']})}),N!==null&&(I.length===0||g)&&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:["₹",N.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsx(Be,{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:"})," ",f]}),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(se,{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(Re,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:A,onChange:B=>{const k=B.target.value;if(parseFloat(k)<0){W.error("Amount cannot be negative");return}w(k)},className:"pl-8",disabled:r})]}),d>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:["₹",d.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs(E,{onClick:P,disabled:T||!A||parseFloat(A)<=0||parseFloat(A)>N||d>0&&Math.abs(I.reduce((B,k)=>B+k.blockedAmount,0)+parseFloat(A)-d)>.01||r,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(ts,{className:"w-4 h-4 mr-2"}),T?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(we,{children:"Details of IO blocked in SAP system"})]}),e.jsx(J,{children:I.length>0?e.jsxs("div",{className:"space-y-6",children:[g&&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(Je,{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 ₹",(d-I.reduce((B,k)=>B+k.blockedAmount,0)).toLocaleString("en-IN",{minimumFractionDigits:2}),"."]})]})]})}),I.slice().reverse().map((B,k)=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:`p-3 flex justify-between items-center ${k===0?"bg-green-50":"bg-gray-50"}`,children:[e.jsxs("span",{className:"font-semibold text-sm",children:["IO: ",B.ioNumber]}),e.jsx(re,{className:B.status==="blocked"?"bg-green-100 text-green-800":B.status==="pending"?"bg-amber-100 text-amber-800":"bg-blue-100 text-blue-800",children:B.status==="blocked"?"Blocked":B.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:["₹",B.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:B.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:B.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(B.blockedDate).toLocaleString()})]})]})]},k)),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:["₹",I.reduce((B,k)=>B+k.blockedAmount,0).toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Da,{className:"w-16 h-16 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-500 mb-2",children:"No IO blocked yet"}),e.jsx("p",{className:"text-xs text-gray-400",children:"Enter IO number and fetch amount to block budget"})]})})]})]})}async function z4(t){var s,a,r;try{const n=await ve.get(`/dealers/verify/${t}`);return((s=n.data)==null?void 0:s.data)||n.data}catch(n){const i=((r=(a=n.response)==null?void 0:a.data)==null?void 0:r.message)||n.message||"Dealer verification failed";throw console.error("[DealerAPI] Error verifying dealer login:",i),new Error(i)}}async function H4(t){var s;try{const a=await ve.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 Js=[{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 G4({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:u}=X0(),[h,g]=x.useState(!1),[f,b]=x.useState(""),[j,y]=x.useState(24),[N,S]=x.useState("hours"),[A,w]=x.useState(3),[I,D]=x.useState([]),[T,v]=x.useState(!1),[M,P]=x.useState(null),B=x.useRef(null),k=()=>{const O=t.approvers||[],V=[];return Js.forEach(Q=>{if(Q.isAuto||Q.approverType==="dealer"||Q.approverType==="initiator")return;const q=O.find(ee=>ee.level===Q.level);(!q||!q.email||!q.userId||!q.tat)&&V.push(`${Q.name}`)}),{isValid:V.length===0,missingSteps:V}};x.useEffect(()=>{if(l){const O=k();l(O.isValid)}},[t.approvers]),x.useEffect(()=>{const O=t.approvers||[];if(O.length>0){const V=[],Q=O.filter(ee=>ee.isAdditional);Js.forEach(ee=>{const te=O.find(ue=>ue.originalStepLevel===ee.level||!ue.originalStepLevel&&!ue.isAdditional&&ue.level===ee.level);if(te)V.push(te);else if(ee.isAuto){const ue=ee.level===8?"finance@royalenfield.com":"system@royalenfield.com",_e=ee.level===8?"System/Finance":"System";V.push({email:ue,name:_e,level:ee.level,tat:ee.defaultTat,tatType:"hours",originalStepLevel:ee.level})}else ee.approverType==="dealer"?V.push({email:t.dealerEmail||"",name:t.dealerName||"",level:ee.level,tat:ee.defaultTat,tatType:"hours",originalStepLevel:ee.level}):ee.approverType==="initiator"?V.push({email:r||"",name:i||r||"User",userId:n,level:ee.level,tat:ee.defaultTat,tatType:"hours",originalStepLevel:ee.level}):V.push({email:"",name:"",level:ee.level,tat:ee.defaultTat,tatType:"hours",originalStepLevel:ee.level})}),Q.forEach(ee=>{V.push(ee)}),V.sort((ee,te)=>ee.level-te.level),JSON.stringify(O.map(ee=>({level:ee.level,originalStepLevel:ee.originalStepLevel})))!==JSON.stringify(V.map(ee=>({level:ee.level,originalStepLevel:ee.originalStepLevel})))&&s("approvers",V)}else{const V=[];Js.forEach(Q=>{Q.isAuto||(Q.approverType==="dealer"?V.push({email:t.dealerEmail||"",name:t.dealerName||"",level:Q.level,tat:Q.defaultTat,tatType:"hours",originalStepLevel:Q.level}):Q.approverType==="initiator"?V.push({email:r||"",name:i||r||"User",userId:n,level:Q.level,tat:Q.defaultTat,tatType:"hours",originalStepLevel:Q.level}):V.push({email:"",name:"",level:Q.level,tat:Q.defaultTat,tatType:"hours",originalStepLevel:Q.level}))}),s("approvers",V)}},[t.dealerEmail,t.dealerName,r,n,i]);const _=(O,V)=>{const Q=[...t.approvers||[]],q=Q.findIndex(ee=>ee.originalStepLevel===O||!ee.originalStepLevel&&ee.level===O&&!ee.isAdditional);if(q===-1){const ee=Js.find(te=>te.level===O);Q.push({email:V,name:"",level:O,tat:(ee==null?void 0:ee.defaultTat)||48,tatType:"hours",originalStepLevel:O})}else{const ee=Q[q];if(ee){const te=ee.email;Q[q]={...ee,email:V,name:V!==te?"":ee.name,userId:V!==te?void 0:ee.userId}}}if(s("approvers",Q),!V||!V.startsWith("@")||V.length<2){u(O-1);return}p(O-1,V,10)},L=async(O,V)=>{var Q,q;try{const ee=Js.find(Pe=>Pe.level===O);if(ee&&!ee.isAuto&&ee.approverType!=="initiator"&&((Q=V.email)==null?void 0:Q.toLowerCase())===(r==null?void 0:r.toLowerCase())){W.error(`You cannot assign yourself as ${ee.name} approver.`),a&&a({type:"self-assign",email:V.email,message:`You cannot assign yourself as ${ee.name} approver.`});return}if((t.approvers||[]).some(Pe=>{var De,le;return Pe.level!==O&&(Pe.userId===V.userId||((De=Pe.email)==null?void 0:De.toLowerCase())===((le=V.email)==null?void 0:le.toLowerCase()))})){W.error("This user is already assigned to another step."),a&&a({type:"error",email:V.email,message:"This user is already assigned to another step."});return}const _e=await ya({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}),Ze=[...t.approvers||[]],Ue=Ze.findIndex(Pe=>Pe.originalStepLevel===O||!Pe.originalStepLevel&&Pe.level===O&&!Pe.isAdditional);if(Ue===-1){const Pe=Js.find(De=>De.level===O);Ze.push({email:V.email,name:V.displayName||[V.firstName,V.lastName].filter(Boolean).join(" "),userId:_e.userId,level:O,tat:(Pe==null?void 0:Pe.defaultTat)||48,tatType:"hours",originalStepLevel:O})}else{const Pe=Ze[Ue];Pe&&(Ze[Ue]={...Pe,email:V.email,name:V.displayName||[V.firstName,V.lastName].filter(Boolean).join(" "),userId:_e.userId,originalStepLevel:Pe.originalStepLevel||O})}s("approvers",Ze),u(O-1),W.success(`Approver for ${(q=Js.find(Pe=>Pe.level===O))==null?void 0:q.name} selected successfully.`)}catch(ee){console.error("Failed to ensure user exists:",ee),W.error("Failed to validate user. Please try again."),a&&a({type:"error",email:V.email,message:"Failed to validate user. Please try again."})}},R=(O,V)=>{const Q=[...t.approvers||[]],q=Q.findIndex(ee=>ee.originalStepLevel===O||!ee.originalStepLevel&&ee.level===O&&!ee.isAdditional);if(q!==-1){const ee=Q[q];ee&&(Q[q]={...ee,tat:V},s("approvers",Q))}},C=(O,V)=>{const Q=[...t.approvers||[]],q=Q.findIndex(ee=>ee.originalStepLevel===O||!ee.originalStepLevel&&ee.level===O&&!ee.isAdditional);if(q!==-1){const ee=Q[q];ee&&(Q[q]={...ee,tatType:V,tat:""},s("approvers",Q))}},G=O=>{if(b(O),M&&M.email.toLowerCase()!==O.toLowerCase()&&P(null),B.current&&clearTimeout(B.current),!O||!O.startsWith("@")||O.length<2){D([]),v(!1);return}v(!0),B.current=setTimeout(async()=>{var V;try{const Q=O.slice(1),ee=((V=(await Na(Q,10)).data)==null?void 0:V.data)||[];D(ee)}catch(Q){console.error("Search failed:",Q),D([])}finally{v(!1)}},300)},U=async O=>{try{await ya({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),P(O),D([]),v(!1)}catch(V){console.error("Failed to ensure user exists:",V),W.error("Failed to verify user. Please try again.")}},$=async()=>{var De,le;const O=f.trim().toLowerCase();if(!O){W.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(O)){W.error("Please enter a valid email address");return}const Q=typeof j=="string"?Number(j):j;if(!Q||Q<=0||isNaN(Q)){W.error("Please enter valid TAT (minimum 1)");return}const q=N==="days"?30:720;if((N==="days"?Q*24:Q)>720){W.error(`TAT cannot exceed ${q} ${N==="days"?"days":"hours"}`);return}const te=Js.find(ye=>ye.name==="Requestor Claim Approval");if(te&&A>=te.level){W.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if(O===(r==null?void 0:r.toLowerCase())){W.error("You cannot add yourself as an additional approver.");return}const ue=t.approvers||[];if(ue.some(ye=>{var ae;return ye.userId&&(M==null?void 0:M.userId)&&ye.userId===M.userId||((ae=ye.email)==null?void 0:ae.toLowerCase())===O})){W.error("This user is already assigned as an approver.");return}const Ze=ue.find(ye=>ye.originalStepLevel===A||!ye.originalStepLevel&&!ye.isAdditional&&ye.level===A),Pe=(Ze?Ze.level:A)+1;if(o){const ae=new Set(ue.map(he=>he.level)).size+1;if(ae>o){const he=[{type:"max_approval_levels",message:`Adding this approver would create ${ae} approval levels, which exceeds the maximum allowed (${o}). Please remove some approvers before adding a new one.`,currentValue:ae,maxValue:o}];c?c(he):W.error(((De=he[0])==null?void 0:De.message)||"Maximum approval levels exceeded");return}}if(!M||M.email.toLowerCase()!==O)try{const ae=((le=(await Na(O,1)).data)==null?void 0:le.data)||[];if(ae.length===0){W.error("User not found in organization directory. Please use @ to search for users.");return}const he=ae[0];await ya({userId:he.userId,email:he.email,displayName:he.displayName,firstName:he.firstName,lastName:he.lastName,department:he.department,phone:he.phone,mobilePhone:he.mobilePhone,designation:he.designation,jobTitle:he.jobTitle,manager:he.manager,employeeId:he.employeeId,employeeNumber:he.employeeNumber,secondEmail:he.secondEmail,location:he.location});const ne={email:he.email,name:he.displayName||[he.firstName,he.lastName].filter(Boolean).join(" "),userId:he.userId,level:Pe,tat:typeof j=="string"?Number(j):j,tatType:N,isAdditional:!0,insertAfterLevel:A,stepName:`Additional Approver - ${he.displayName||he.email}`},ge=ue.map(ke=>ke.level>=Pe?{...ke,level:ke.level+1}:ke);ge.push(ne),ge.sort((ke,Oe)=>ke.level-Oe.level),s("approvers",ge),W.success("Additional approver added and subsequent steps shifted")}catch(ye){console.error("Failed to validate approver:",ye),W.error("Failed to validate user. Please try again.");return}else{const ye={email:M.email,name:M.displayName||[M.firstName,M.lastName].filter(Boolean).join(" "),userId:M.userId,level:Pe,tat:j,tatType:N,isAdditional:!0,insertAfterLevel:A,stepName:`Additional Approver - ${M.displayName||M.email}`},ae=ue.map(he=>he.level>=Pe?{...he,level:he.level+1}:he);ae.push(ye),ae.sort((he,ne)=>he.level-ne.level),s("approvers",ae),W.success("Additional approver added and subsequent steps shifted")}b(""),y(24),S("hours"),w(3),P(null),D([]),g(!1)},F=O=>{const V=[...t.approvers||[]];if(!V.find(te=>te.level===O))return;const ee=V.filter(te=>te.level!==O).map(te=>te.level>O&&!te.isAdditional?{...te,level:te.level-1}:te);ee.sort((te,ue)=>te.level-ue.level),s("approvers",ee),W.success("Additional approver removed and subsequent steps shifted back")},H=()=>[...t.approvers||[]].sort((V,Q)=>V.level-Q.level),K=t.approvers||[],z=H();return e.jsxs(Wt.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(qt,{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(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(Hr,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsxs(we,{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||[],Q=new Set(O.map(q=>q.level)).size;return Q>0?e.jsxs("span",{children:[" (",Q,"/",o,")"]}):null})()]})]})]})}),e.jsxs(Z,{className:"border-2",children:[e.jsxs(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(fs,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx(we,{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(J,{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||[],Q=new Set(O.map(q=>q.level)).size;return Q>0?e.jsxs("span",{children:[" (",Q,"/",o,")"]}):null})()]}),e.jsxs(E,{type:"button",variant:"outline",onClick:()=>g(!0),className:"flex items-center gap-2",children:[e.jsx(ms,{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(Ht,{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(re,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-xs text-blue-700",children:"Creates and submits the request"})]})]})}),(()=>{const O=z.filter(Q=>Q.isAdditional&&Q.insertAfterLevel===0);let V=O.length;return Js.filter(Q=>!Q.isAuto).map((Q,q,ee)=>{const te=K.find(De=>De.originalStepLevel===Q.level||!De.originalStepLevel&&De.level===Q.level&&!De.isAdditional)||{email:"",name:"",level:Q.level,tat:Q.defaultTat,tatType:"hours",originalStepLevel:Q.level},ue=q===ee.length-1,_e=Q.isAuto||Q.approverType==="dealer"||Q.approverType==="initiator",Ze=!Q.isAuto,Ue=z.filter(De=>De.isAdditional&&De.insertAfterLevel===Q.level).sort((De,le)=>De.level-le.level),Pe=V+1;return V++,V+=Ue.length,e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-3 bg-gray-300"})}),q===0&&O.map((De,le)=>{const ye=le+1;return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-3 bg-gray-300"})}),e.jsx("div",{className:"p-3 rounded-lg border-2 border-purple-200 bg-purple-50",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 bg-purple-600",children:e.jsx("span",{className:"text-white font-semibold text-sm",children:ye})}),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(re,{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:()=>F(De.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(yt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:De.name||De.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",De.email]}),e.jsxs("div",{children:["TAT: ",De.tat," ",De.tatType]})]})]})]})})]},`additional-${De.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${te.email&&te.userId?"border-green-200 bg-green-50":_e?"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 ${te.email&&te.userId?"bg-green-600":_e?"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:Q.name}),ue&&e.jsx(re,{variant:"destructive",className:"text-xs",children:"FINAL"}),_e&&e.jsx(re,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:Q.description}),Ze&&(()=>{var ye,ae;const De=!!(te.email&&te.userId),le=!te.email&&!_e;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(se,{htmlFor:`approver-${Q.level}`,className:`text-xs font-bold ${le?"text-blue-900":De?"text-green-900":"text-gray-900"}`,children:["Approver Email ",!_e&&"*",le&&e.jsx("span",{className:"ml-2 text-[10px] font-semibold italic text-blue-600",children:"(Required)"})]}),De&&e.jsxs(re,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Be,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Re,{id:`approver-${Q.level}`,type:"text",placeholder:_e?te.email:"@username or email...",value:te.email||"",onChange:he=>{const ne=he.target.value;_e||_(Q.level,ne)},disabled:_e||Q.isAuto,className:`h-9 border-2 transition-all mt-1 w-full text-sm ${_e?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":De?"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"}`}),!_e&&!Q.isAuto&&(m[Q.level-1]||(((ye=d[Q.level-1])==null?void 0:ye.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:m[Q.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:(ae=d[Q.level-1])==null?void 0:ae.map(he=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>L(Q.level,he),children:[e.jsx("div",{className:"font-medium text-gray-900",children:he.displayName||he.email}),e.jsx("div",{className:"text-xs text-gray-600",children:he.email}),he.department&&e.jsx("div",{className:"text-xs text-gray-500",children:he.department})]},he.userId))})})]}),te.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:te.name})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:`tat-${Q.level}`,className:`text-xs font-bold ${le?"text-blue-900":De?"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(Re,{id:`tat-${Q.level}`,type:"number",placeholder:te.tatType==="days"?"7":"24",min:"1",max:te.tatType==="days"?"30":"720",value:te.tat||"",onChange:he=>R(Q.level,parseInt(he.target.value)||""),disabled:Q.isAuto,className:`h-9 border-2 transition-all flex-1 text-sm ${_e?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":De?"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(He,{value:te.tatType||"hours",onValueChange:he=>C(Q.level,he),disabled:Q.isAuto,children:[e.jsx(We,{className:`w-20 h-9 border-2 transition-all text-sm ${_e?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed":De?"bg-green-50/50 border-green-600 focus:border-green-700 focus:ring-1 focus:ring-green-100 text-gray-900 font-medium":"bg-white border-blue-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`,children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"hours",children:"Hours"}),e.jsx(X,{value:"days",children:"Days"})]})]})]})]})]})})()]})]})}),Ue.map((De,le)=>{const ye=Pe+le+1;return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-3 bg-gray-300"})}),e.jsx("div",{className:"p-3 rounded-lg border-2 border-purple-200 bg-purple-50",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 bg-purple-600",children:e.jsx("span",{className:"text-white font-semibold text-sm",children:ye})}),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:De.stepName||"Additional Approver"}),e.jsx(re,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),De.email&&De.userId&&e.jsxs(re,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Be,{className:"w-3 h-3 mr-1"}),"Verified"]}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>F(De.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(yt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:De.name||De.email||"No approver assigned"}),De.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",De.email]}),De.tat&&e.jsxs("div",{children:["TAT: ",De.tat," ",De.tatType]})]})]})]})})]},`additional-${De.level}`)})]},Q.level)})})()]})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(ce,{children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(J,{children:e.jsx("div",{className:"space-y-3",children:z.map(O=>{const V=O.originalStepLevel?Js.find(te=>te.level===O.originalStepLevel):Js.find(te=>te.level===O.level&&!O.isAdditional);if(V!=null&&V.isAuto)return null;const Q=Number(O.tat||0),ee=(O.tatType||"hours")==="days"?Q*24:Q;if(!Q)return null;if(O.isAdditional){const te=Js.find(ue=>ue.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 "${(te==null?void 0:te.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[ee," 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:(V==null?void 0:V.name)||"Unknown"}),e.jsxs("span",{className:"text-sm text-gray-600",children:[ee," hours"]})]},O.level)})})})]})]}),e.jsx(xt,{open:h,onOpenChange:g,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ms,{className:"w-5 h-5 text-blue-600"}),"Add Additional Approver"]}),e.jsx(_t,{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(se,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(He,{value:A.toString(),onValueChange:O=>w(Number(O)),children:[e.jsx(We,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select step"})}),e.jsx(Ye,{children:Js.filter(O=>{if(O.isAuto)return!1;const V=Js.find(Q=>Q.name==="Requestor Claim Approval");return!(V&&O.level>=V.level)}).map(O=>e.jsx(X,{value:O.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fs,{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||[],Q=new Set(O.map(q=>q.level)).size;return Q>0?e.jsxs("span",{children:[" (",Q,"/",o,")"]}):null})()]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{type:"number",min:"1",max:N==="days"?"30":"720",value:j,onChange:O=>{const V=O.target.value;if(V==="")y("");else{const Q=Number(V);!isNaN(Q)&&Q>=0&&y(Q)}},onBlur:O=>{const V=O.target.value;(!V||V===""||Number(V)<=0)&&y(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(He,{value:N,onValueChange:O=>S(O),children:[e.jsx(We,{className:"w-24 h-11 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"hours",children:"Hours"}),e.jsx(X,{value:"days",children:"Days"})]})]})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum time for this approver to respond (1-",N==="days"?"30 days":"720 hours",")"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(bl,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Re,{type:"text",placeholder:"@username or user@example.com",value:f,onChange:O=>G(O.target.value),className:"pl-10 h-11 border-gray-300",autoFocus:!0}),(T||I.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:T?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):I.length>0?e.jsx("ul",{className:"divide-y",children:I.map(O=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>U(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(Dt,{children:[e.jsx(E,{type:"button",variant:"outline",onClick:()=>{g(!1),b(""),y(24),S("hours"),w(3),P(null),D([])},className:"flex-1",children:"Cancel"}),e.jsxs(E,{type:"button",onClick:$,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!f.trim()||!j,children:[e.jsx(ms,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const jo=[{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"}],yo=["Claim Details","Approver Selection","Review & Submit"];function W4({onBack:t,onSubmit:s}){const{user:a}=us(),[r,n]=x.useState(1),[i,l]=x.useState(!1),[o,c]=x.useState([]),[d,m]=x.useState(!1),[p,u]=x.useState(""),h=x.useRef(null),[g,f]=x.useState(!1),b=x.useRef(null),[j,y]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[N,S]=x.useState({open:!1,violations:[]}),[A,w]=x.useState([]),[I,D]=x.useState(!0);x.useEffect(()=>{(async()=>{try{D(!0);const F=await e5();w(F)}catch(F){console.error("Failed to load activity types:",F),W.error("Failed to load activity types. Please refresh the page.")}finally{D(!1)}})()},[]),x.useEffect(()=>{(async()=>{var F;try{const H=await ua("SYSTEM_SETTINGS"),K=await ua("WORKFLOW_SHARING"),z=[...H,...K],O={};z.forEach(V=>{O[V.configKey]=V.configValue}),y({maxApprovalLevels:parseInt(O.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(O.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((F=O.ALLOW_ADD_SPECTATOR)==null?void 0:F.toLowerCase())==="true",maxSpectators:parseInt(O.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(H){console.error("Failed to load system policy:",H)}})()},[]),x.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const[T,v]=x.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",dealerItemGroup:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),M=yo.length,P=$=>{if(u($),h.current&&clearTimeout(h.current),!$||$.trim().length<2){c([]),m(!1);return}m(!0),h.current=setTimeout(async()=>{try{const F=await H4($);if(F){const H={dealerId:F.dealer||F.dealer_code||$,dealerCode:F.dealer||F.dealer_code||$,dealerName:F["dealer name"]||F.dealer_name||"Unknown Dealer",displayName:F["dealer name"]||F.dealer_name||"Unknown Dealer",email:F["dealer email"]||"",phone:F["dealer phone"]||"",city:F["re city"]||F.city||"",state:F["re state code"]||F.state||"",isLoggedIn:!0,parentCode:F.parentcode||null,itemGroup:F["item group"]||null};c([H])}else c([])}catch(F){console.error("Error searching external dealer:",F),c([])}finally{m(!1)}},300)},B=($,F)=>{v(H=>{const K={...H,[$]:F};if($==="periodStartDate")F&&K.periodEndDate&&F>K.periodEndDate&&(K.periodEndDate=void 0,W.error("End date must be on or after the start date. End date has been cleared."));else if($==="periodEndDate"&&F&&K.periodStartDate&&F<K.periodStartDate)return W.error("End date must be on or after the start date."),H;if($==="activityType"&&K.dealerCode){const z=A.find(O=>O.title===F);if(z)if(z.creditPostingOn){const O=z.creditPostingOn.toLowerCase(),V=(K.dealerItemGroup||"").toLowerCase();if(V){let Q=!1;if(((O==="vehicle"||O==="vehicles")&&(V==="vehicle"||V==="vehicles")||O==="spares"&&V==="spares"||O==="gma"&&V==="gma"||O==="apparel"&&V==="apparel"||O===V)&&(Q=!0),!Q)return W.error("incorrect Delercode for selected service group",{description:`Activity requires ${z.creditPostingOn}, but already selected dealer is ${K.dealerItemGroup}`,duration:6e3}),H}}else console.warn(`[ClaimWizard] Activity type "${F}" is missing creditPostingOn configuration.`)}return K})},k=$=>{v(F=>({...F,...$}))},_=()=>{switch(r){case 1:return T.activityName&&T.activityType&&T.dealerCode&&T.dealerName&&T.activityDate&&T.location&&T.requestDescription;case 2:const F=(T.approvers||[]).find(H=>H.originalStepLevel===3||!H.originalStepLevel&&H.level===3&&!H.isAdditional);return(F==null?void 0:F.email)&&(F==null?void 0:F.userId)&&(F==null?void 0:F.tat);case 3:return!0;default:return!1}},L=()=>{if(r<M){if(!_()){if(r===2){const F=(T.approvers||[]).find(K=>K.originalStepLevel===3||!K.originalStepLevel&&K.level===3&&!K.isAdditional),H=[];(!(F!=null&&F.email)||!(F!=null&&F.userId)||!(F!=null&&F.tat))&&H.push("Department Lead Approval"),H.length>0?W.error(`Please add missing approvers: ${H.join(", ")}`):W.error("Please complete all required approver selections (email, user verification, and TAT) before proceeding.")}else W.error("Please complete all required fields before proceeding.");return}n(r+1)}},R=()=>{r>1&&n(r-1)},C=async $=>{l(!0);try{const F=await z4($.dealerCode);if(!F.isLoggedIn){W.error(`Dealer "${F.dealerName||F.displayName}" (${F.dealerCode}) is not mapped to the system.`,{duration:5e3}),u(""),c([]),B("dealerCode",""),B("dealerName",""),B("dealerEmail",""),B("dealerPhone",""),B("dealerAddress",""),l(!1);return}if(T.activityType){const H=A.find(K=>K.title===T.activityType);if(H&&H.creditPostingOn){const K=H.creditPostingOn.toLowerCase(),z=(F.itemGroup||"").toLowerCase();let O=!1;if((K==="vehicle"&&z==="vehicle"||K==="spares"&&z==="spares"||K==="gma"&&z==="gma"||K==="apparel"&&z==="apparel"||K===z)&&(O=!0),!O){W.error("incorrect Delercode for selected service group",{description:`Activity requires ${H.creditPostingOn}, but dealer is ${F.itemGroup||"N/A"}`,duration:6e3}),u(""),c([]),l(!1);return}}}k({dealerCode:F.dealerCode,dealerName:F.dealerName||F.displayName,dealerEmail:F.email||"",dealerPhone:F.phone||"",dealerAddress:"",dealerItemGroup:F.itemGroup||""}),u(F.dealerName||F.displayName),c([]),W.success(`Dealer "${F.dealerName||F.displayName}" verified and mapped to the System`)}catch{W.error("Dealer is not mapped to the system",{duration:5e3}),u(""),c([]),B("dealerCode",""),B("dealerName",""),B("dealerEmail",""),B("dealerPhone",""),B("dealerAddress","")}finally{l(!1)}},G=()=>{if(g)return;const F=[...T.approvers||[]].sort((V,Q)=>V.level-Q.level),H=new Map,K=[];if(F.forEach(V=>{H.has(V.level)?K.push(V.level):H.set(V.level,V)}),K.length>0){W.error(`Duplicate approver levels detected: ${K.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",K,F);return}const z=F.map(V=>{const Q={email:V.email,name:V.name,userId:V.userId,level:V.level,tat:V.tat,tatType:V.tatType};return V.isAdditional&&V.stepName&&(Q.stepName=V.stepName,Q.isAdditional=!0),V.originalStepLevel&&(Q.originalStepLevel=V.originalStepLevel),Q}),O={...T,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:z};if(f(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{f(!1),b.current=null},3e4),s)try{s(O)}catch(V){b.current&&(clearTimeout(b.current),b.current=null),f(!1),console.error("Error submitting claim:",V)}else b.current&&(clearTimeout(b.current),b.current=null),f(!1)},U=()=>{switch(r){case 1:return e.jsxs(Wt.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(Mt,{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(se,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(Re,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:T.activityName,onChange:$=>B("activityName",$.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(He,{value:T.activityType,onValueChange:$=>B("activityType",$),disabled:I,children:[e.jsx(We,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(Ge,{placeholder:I?"Loading activity types...":"Select activity type"})}),e.jsx(Ye,{className:"max-h-80",children:A.length>0?A.map($=>e.jsx(X,{value:$.title,className:"focus:bg-blue-600 focus:text-white group",children:e.jsxs("div",{className:"flex flex-col py-0.5",children:[e.jsx("span",{className:"font-medium text-[13px] leading-[1.1] text-gray-900 group-focus:text-white",children:$.title}),e.jsxs("div",{className:"flex items-center gap-1 text-[9px] text-gray-500 group-focus:text-blue-100 uppercase font-bold tracking-wider leading-none mt-0.5",children:[$.creditPostingOn&&e.jsx("span",{children:$.creditPostingOn}),$.creditPostingOn&&$.taxationType&&e.jsx("span",{className:"opacity-40 select-none",children:"•"}),$.taxationType&&e.jsx("span",{children:$.taxationType})]})]})},$.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(se,{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(Re,{placeholder:"Type dealer code, name, or email to search...",value:T.dealerCode?`${T.dealerName} (${T.dealerCode})`:p,onChange:$=>{T.dealerCode?(B("dealerCode",""),B("dealerName",""),B("dealerEmail",""),B("dealerPhone",""),B("dealerAddress",""),u($.target.value)):P($.target.value)},onFocus:()=>{p&&p.length>=2&&P(p)},className:"h-12 border-2 border-gray-300 focus:border-blue-500",disabled:i}),T.dealerCode&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsxs(re,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Be,{className:"w-3 h-3 mr-1"}),"Verified"]})}),(d||o.length>0)&&!T.dealerCode&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:d?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:o.map($=>e.jsx("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>C($),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:$.dealerName||$.displayName}),e.jsxs("div",{className:"text-[10px] text-gray-600 mt-0.5 font-medium flex items-center gap-1.5",children:[e.jsx("span",{className:"font-mono",children:$.dealerCode}),$.email&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-40",children:"•"}),e.jsx("span",{children:$.email})]})]}),e.jsxs("div",{className:"text-[10px] text-gray-500 mt-0.5",children:[$.city,", ",$.state]}),$.itemGroup&&e.jsx("div",{className:"text-[9px] text-blue-600 font-bold uppercase tracking-wider mt-0.5",children:$.itemGroup})]}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:$.isLoggedIn?e.jsx(Be,{className:"w-4 h-4 text-green-600"}):e.jsx(St,{className:"w-4 h-4 text-red-500"})})]})},$.dealerId))})})]})}),T.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:T.dealerName})," (",T.dealerCode,")"]}),T.dealerEmail&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Email: ",T.dealerEmail]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(aa,{children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(ft,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:T.activityDate?st(T.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(na,{className:"w-auto p-0",align:"start",children:e.jsx(Oi,{mode:"single",selected:T.activityDate,onSelect:$=>B("activityDate",$),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(Re,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:T.location,onChange:$=>B("location",$.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(se,{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(hi,{value:T.requestDescription||"",onChange:$=>B("requestDescription",$),placeholder:"Provide comprehensive details about your claim requirement including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(se,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(re,{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(se,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(aa,{children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(ft,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:T.periodStartDate?st(T.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(na,{className:"w-auto p-0",align:"start",children:e.jsx(Oi,{mode:"single",selected:T.periodStartDate,onSelect:$=>B("periodStartDate",$),initialFocus:!0,toDate:T.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(aa,{children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",disabled:!T.periodStartDate,children:[e.jsx(ft,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:T.periodEndDate?st(T.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(na,{className:"w-auto p-0",align:"start",children:e.jsx(Oi,{mode:"single",selected:T.periodEndDate,onSelect:$=>B("periodEndDate",$),initialFocus:!0,fromDate:T.periodStartDate||void 0})})]}),!T.periodStartDate&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Please select start date first"})]})]}),(T.periodStartDate||T.periodEndDate)&&e.jsx("div",{className:"mt-2",children:T.periodStartDate&&T.periodEndDate?e.jsxs("p",{className:"text-xs text-gray-600",children:["Period: ",st(T.periodStartDate,"d MMM yyyy")," - ",st(T.periodEndDate,"d MMM yyyy")]}):e.jsx("p",{className:"text-xs text-gray-500",children:T.periodStartDate?"Please select end date for the period":"Please select start date first"})})]})]})]});case 2:return e.jsx(G4,{formData:T,updateFormData:B,currentUserEmail:(a==null?void 0:a.email)||"",currentUserId:(a==null?void 0:a.userId)||"",currentUserName:(a==null?void 0:a.displayName)||(a==null?void 0:a.name)||(a!=null&&a.firstName&&(a!=null&&a.lastName)?`${a.firstName} ${a.lastName}`.trim():(a==null?void 0:a.email)||"User"),maxApprovalLevels:j.maxApprovalLevels,onPolicyViolation:$=>S({open:!0,violations:$})});case 3:return e.jsxs(Wt.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(Be,{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(ce,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(J,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:T.activityName})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(re,{variant:"secondary",className:"mt-1",children:T.activityType})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(ce,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(jl,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(J,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(se,{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:T.dealerCode})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:T.dealerName})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:T.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:T.dealerPhone})]}),T.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:T.dealerAddress})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(ce,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-5 h-5 text-purple-600"}),"Selected Approvers"]})}),e.jsx(J,{className:"pt-6 space-y-4",children:e.jsx("div",{className:"space-y-3",children:[...T.approvers||[]].filter(F=>{var H,K;return!((H=F.email)!=null&&H.includes("system@"))&&!((K=F.email)!=null&&K.includes("finance@"))}).sort((F,H)=>F.level-H.level).map(F=>{const H=Number(F.tat||0),z=(F.tatType||"hours")==="days"?H*24:H;let O="Unknown",V="";if(F.isAdditional){O=F.stepName||"Additional Approver";const Q=jo.find(q=>q.level===F.insertAfterLevel);V=F.stepName||`Additional Approver (after "${(Q==null?void 0:Q.name)||"Unknown"}")`}else{const Q=F.originalStepLevel?jo.find(q=>q.level===F.originalStepLevel):jo.find(q=>q.level===F.level&&!q.isAuto);O=(Q==null?void 0:Q.name)||"Unknown",V=O}return e.jsx("div",{className:`p-3 rounded-lg border ${F.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(se,{className:"text-xs text-gray-600 uppercase tracking-wider",children:V}),F.isAdditional&&e.jsx(re,{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:F.name||F.email||"Not selected"}),F.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:F.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[z," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${F.level}-${F.email}`)})})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(ce,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(J,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:T.activityDate?st(T.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(se,{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(yc,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:T.location})]})]}),T.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{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:T.estimatedBudget})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(ce,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(J,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(se,{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:T.requestDescription||"",className:"text-sm"})})]})})]}),(T.periodStartDate||T.periodEndDate)&&e.jsxs(Z,{className:"border-2",children:[e.jsx(ce,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(J,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:T.periodStartDate?st(T.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:T.periodEndDate?st(T.periodEndDate,"PPP"):"Not specified"})]})]})})]}),e.jsx("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-6",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Hr,{className:"w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-blue-900 mb-1",children:"Ready to Submit"}),e.jsx("p",{className:"text-sm text-blue-800",children:"Please review all the information above. Once submitted, your claim request will enter the approval workflow."})]})]})})]})]});default:return null}};return e.jsxs("div",{className:"w-full bg-gradient-to-br from-gray-50 to-gray-100 py-4 sm:py-6 lg:py-8 px-3 sm:px-4 lg:px-6 overflow-y-auto",children:[e.jsxs("div",{className:"max-w-6xl mx-auto pb-8",children:[e.jsxs("div",{className:"mb-6 sm:mb-8",children:[e.jsxs(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(re,{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 ",M,": ",e.jsx("span",{className:"hidden sm:inline",children:yo[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(ia,{value:r/M*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:yo.map(($,F)=>e.jsx("span",{className:`text-xs sm:text-sm ${F+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:F+1},F))})]})]}),e.jsx(Z,{className:"mb-6 sm:mb-8",children:e.jsx(J,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(Rl,{mode:"wait",children:U()})})}),e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between gap-3 sm:gap-0 pb-4 sm:pb-0",children:[e.jsxs(E,{variant:"outline",onClick:R,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<M?e.jsxs(E,{onClick:L,className:`gap-2 w-full sm:w-auto order-1 sm:order-2 ${_()?"":"opacity-50 cursor-pointer hover:opacity-60"}`,children:["Next",e.jsx(js,{className:"w-4 h-4"})]}):e.jsx(E,{onClick:G,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(ze,{className:"w-4 h-4 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx($a,{className:"w-4 h-4"}),"Submit Claim Request"]})})]})]}),e.jsx(ji,{open:N.open,onClose:()=>S({open:!1,violations:[]}),violations:N.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}const{DocumentsTab:Y4,ActivityTab:Q4,WorkNotesTab:K4,SummaryTab:X4,RequestDetailHeader:Z4,QuickActionsSidebar:J4,RequestDetailModals:q4}=mf;let e6=class extends x.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("Dealer Claim RequestDetail Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(ss,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(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 t6({requestId:t,onBack:s,dynamicRequests:a=[]}){var Qt,As,la,wr,Cr,Sa,sr;const n=Va().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=x.useState(l),[d,m]=x.useState(!1),[p,u]=x.useState(null),[h,g]=x.useState(null),[f,b]=x.useState(!1),[j,y]=x.useState(0),[N,S]=x.useState(!1),[A,w]=x.useState(!1),[I,D]=x.useState(!1),[T,v]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[M,P]=x.useState({open:!1,violations:[]}),{user:B}=us(),{request:k,apiRequest:_,loading:L,refreshing:R,refreshDetails:C,currentApprovalLevel:G,isSpectator:U,isInitiator:$,existingParticipants:F,accessDenied:H}=Nd(n,a,B),K=(B==null?void 0:B.userId)||"",z=(Qt=B==null?void 0:B.email)==null?void 0:Qt.toLowerCase(),O=((k==null?void 0:k.approvalFlow)||[]).some(Rt=>{var xs;return Rt.role==="Department Lead Approval"&&((xs=Rt.approverEmail)==null?void 0:xs.toLowerCase())===z}),V=(B==null?void 0:B.jobTitle)==="Dealer"||(B==null?void 0:B.designation)==="Dealer",q=((k==null?void 0:k.workflowType)==="CLAIM_MANAGEMENT"||(_==null?void 0:_.workflowType)==="CLAIM_MANAGEMENT"||(k==null?void 0:k.templateType)==="claim-management")&&!V&&($||O),{mergedMessages:ee,unreadWorkNotes:te,workNoteAttachments:ue,setWorkNoteAttachments:_e}=Z0(n,_,o,B),{uploadingDocument:Ze,triggerFileInput:Ue,previewDocument:Pe,setPreviewDocument:De,documentPolicy:le,documentError:ye,setDocumentError:ae}=J0(_,C),[he,ne]=x.useState(null),ge=he||G,{showApproveModal:ke,setShowApproveModal:Oe,showRejectModal:je,setShowRejectModal:ie,showAddApproverModal:Se,setShowAddApproverModal:qe,showAddSpectatorModal:rt,setShowAddSpectatorModal:gt,showSkipApproverModal:It,setShowSkipApproverModal:oe,showActionStatusModal:Me,setShowActionStatusModal:me,skipApproverData:Xe,setSkipApproverData:Qe,actionStatus:nt,setActionStatus:Ke,handleApproveConfirm:lt,handleRejectConfirm:et,handleAddApprover:ut,handleSkipApprover:Hs,handleAddSpectator:is}=ef(n,ge,C),vt=async Rt=>{await lt(Rt),ne(null)},pt=async Rt=>{await et(Rt),ne(null)},Pt=((k==null?void 0:k.status)||(_==null?void 0:_.status)||"").toLowerCase(),Ss=(Pt==="approved"||Pt==="rejected")&&$,{conclusionRemark:as,setConclusionRemark:za,conclusionLoading:Ha,conclusionSubmitting:br,aiGenerated:wa,handleGenerateConclusion:Lt,handleFinalizeConclusion:Ca,generationAttempts:Us,generationFailed:Qr,maxAttemptsReached:Kr}=q0(k,n,$,C,s,Ke,me);x.useEffect(()=>{(async()=>{var xs;try{const Xs=await ua("SYSTEM_SETTINGS"),xa=await ua("WORKFLOW_SHARING"),Zr=[...Xs,...xa],Aa={};Zr.forEach(ar=>{Aa[ar.configKey]=ar.configValue}),v({maxApprovalLevels:parseInt(Aa.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Aa.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((xs=Aa.ALLOW_ADD_SPECTATOR)==null?void 0:xs.toLowerCase())==="true",maxSpectators:parseInt(Aa.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Xs){console.error("Failed to load system policy:",Xs)}})()},[]),x.useEffect(()=>{const xs=new URLSearchParams(window.location.search).get("tab");xs&&c(xs)},[n]);const jr=()=>{C()},Xr=()=>{S(!0)},Ja=()=>{w(!0)},yr=async()=>{await C()},qa=()=>{D(!0)},vr=async()=>{await C()},Nr=async()=>{await C()},er=async()=>{if(!(_!=null&&_.requestId)){W.error("Request ID not found");return}if(!p){W.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Pa=(k==null?void 0:k.status)==="closed";x.useEffect(()=>{(async()=>{if(!Pa||!(_!=null&&_.requestId)){g(null),u(null);return}try{b(!0);const xs=await lf(_.requestId);if(xs!=null&&xs.summaryId){u(xs.summaryId);try{const Xs=await Cd(xs.summaryId);g(Xs)}catch(Xs){console.error("Failed to fetch summary details:",Xs),g(null),u(null)}}else g(null),u(null)}catch{g(null),u(null)}finally{b(!1)}})()},[Pa,_==null?void 0:_.requestId]),x.useEffect(()=>{if(!K||!(_!=null&&_.requestId))return;const Rt=Vr();if(!Rt)return;Tc(Rt,K);const xs=Xs=>{var ar,kn,Dn,Rn;const xa=Xs==null?void 0:Xs.notification;if(!xa)return;const Zr=xa.requestId||xa.request_id,Aa=((ar=xa.metadata)==null?void 0:ar.requestNumber)||((kn=xa.metadata)==null?void 0:kn.request_number);Zr!==_.requestId&&Aa!==n&&Aa!==_.requestNumber||((Dn=xa.metadata)!=null&&Dn.creditNoteNumber||(Rn=xa.metadata)!=null&&Rn.credit_note_number)&&C()};return Rt.on("notification:new",xs),()=>{Rt.off("notification:new",xs)}},[K,_==null?void 0:_.requestId,n,C]);const tr=((k==null?void 0:k.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 L&&!k&&!_?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(Et,{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..."})]})}):H!=null&&H.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(lp,{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:H.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"})]})]})}):k?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"dealer-claim-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(Z4,{request:k,refreshing:R,onBack:s||(()=>window.history.back()),onRefresh:jr,onShareSummary:er,isInitiator:$,slaData:((As=k==null?void 0:k.summary)==null?void 0:As.sla)||(k==null?void 0:k.sla)||null,isPaused:((la=k==null?void 0:k.pauseInfo)==null?void 0:la.isPaused)||!1}),e.jsxs(yi,{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(vi,{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($t,{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(op,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Pa&&h&&e.jsxs($t,{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(vc,{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($t,{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(Qs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),q&&e.jsxs($t,{value:"io",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-io",children:[e.jsx(Da,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"IO"})]}),e.jsxs($t,{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(Fe,{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($t,{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(Bt,{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($t,{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(Ys,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),te>0&&e.jsx(re,{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-red-500 text-white text-[10px] flex items-center justify-center p-0","data-testid":"worknotes-unread-badge",children:te>9?"9+":te})]})]})}),e.jsxs("div",{className:o==="worknotes"?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:o==="worknotes"?"":"lg:col-span-2",children:[e.jsx(Ut,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(Pk,{request:k,apiRequest:_,currentUserId:K,isInitiator:$,needsClosure:Ss,conclusionRemark:as,setConclusionRemark:za,conclusionLoading:Ha,conclusionSubmitting:br,aiGenerated:wa,handleGenerateConclusion:Lt,handleFinalizeConclusion:Ca,generationAttempts:Us,generationFailed:Qr,maxAttemptsReached:Kr})}),Pa&&e.jsx(Ut,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(X4,{summary:h,loading:f,onShare:er,isInitiator:$})}),e.jsx(Ut,{value:"workflow",className:"mt-0",children:e.jsx(B4,{request:k,user:B,isInitiator:$,isSpectator:U,onSkipApprover:Rt=>{if(!Rt.levelId){alert("Level ID not available");return}Qe(Rt),oe(!0)},onRefresh:C,documentPolicy:le})}),q&&e.jsx(Ut,{value:"io",className:"mt-0",children:e.jsx(V4,{request:k,apiRequest:_,onRefresh:C,isSpectator:U})}),e.jsx(Ut,{value:"documents",className:"mt-0",children:e.jsx(Y4,{request:k,workNoteAttachments:ue,uploadingDocument:Ze,documentPolicy:le,triggerFileInput:Ue,setPreviewDocument:De,downloadDocument:Ms,isSpectator:U})}),e.jsx(Ut,{value:"activity",className:"mt-0",children:e.jsx(Q4,{request:k})}),e.jsx(Ut,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(K4,{requestId:n,requestTitle:k.title,mergedMessages:ee,setWorkNoteAttachments:_e,isInitiator:$,isSpectator:U,currentLevels:tr,onAddApprover:ut,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Rt=>P({open:!0,violations:Rt})})})]}),o!=="worknotes"&&e.jsx(J4,{request:k,isInitiator:$,isSpectator:U,currentApprovalLevel:G,onAddApprover:()=>qe(!0),onAddSpectator:()=>gt(!0),onApprove:()=>Oe(!0),onReject:()=>ie(!0),onPause:Xr,onResume:Ja,onRetrigger:qa,summaryId:p,refreshTrigger:j,pausedByUserId:(Cr=(wr=k==null?void 0:k.pauseInfo)==null?void 0:wr.pausedBy)==null?void 0:Cr.userId,currentUserId:K,apiRequest:_,hideApproveReject:V})]})]})]})}),d&&p&&e.jsx(uf,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(k==null?void 0:k.title)||"N/A",onSuccess:()=>{C(),y(Rt=>Rt+1)}}),N&&(_==null?void 0:_.requestId)&&e.jsx(xf,{isOpen:N,onClose:()=>S(!1),requestId:_.requestId,levelId:(G==null?void 0:G.levelId)||null,onSuccess:vr}),A&&(_==null?void 0:_.requestId)&&e.jsx(hf,{isOpen:A,onClose:()=>w(!1),requestId:_.requestId,onSuccess:yr}),I&&(_==null?void 0:_.requestId)&&e.jsx(pf,{isOpen:I,onClose:()=>D(!1),requestId:_.requestId,approverName:(sr=(Sa=k==null?void 0:k.pauseInfo)==null?void 0:Sa.pausedBy)==null?void 0:sr.name,onSuccess:Nr}),e.jsx(q4,{showApproveModal:ke,showRejectModal:je,showAddApproverModal:Se,showAddSpectatorModal:rt,showSkipApproverModal:It,showActionStatusModal:Me,previewDocument:Pe,documentError:ye,request:k,skipApproverData:Xe,actionStatus:nt,existingParticipants:F,currentLevels:tr,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Rt=>P({open:!0,violations:Rt}),setShowApproveModal:Oe,setShowRejectModal:ie,setShowAddApproverModal:qe,setShowAddSpectatorModal:gt,setShowSkipApproverModal:oe,setShowActionStatusModal:me,setPreviewDocument:De,setDocumentError:ae,setSkipApproverData:Qe,setActionStatus:Ke,handleApproveConfirm:vt,handleRejectConfirm:pt,handleAddApprover:ut,handleAddSpectator:is,handleSkipApprover:Hs,downloadDocument:Ms,documentPolicy:le}),e.jsx(ji,{open:M.open,onClose:()=>P({open:!1,violations:[]}),violations:M.violations,policyDetails:{maxApprovalLevels:T.maxApprovalLevels,maxParticipants:T.maxParticipants,allowSpectators:T.allowSpectators,maxSpectators:T.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(Fe,{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 s6(t){return e.jsx(e6,{children:e.jsx(t6,{...t})})}function a6({onNavigate:t,onNewRequest:s}){const[a,r]=x.useState(!0),[n,i]=x.useState(!1),[l,o]=x.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]=x.useState([]),[m,p]=x.useState("all"),[u,h]=x.useState(),[g,f]=x.useState(),b=async(P=!1)=>{try{P?i(!0):r(!0);const B=await _4(m||"all",u,g);o(B.kpis||{totalClaims:0,totalValue:0,approved:0,rejected:0,pending:0,credited:0,pendingCredit:0,approvedValue:0,rejectedValue:0,pendingValue:0,creditedValue:0,pendingCreditValue:0}),d(B.categoryData||[])}catch(B){console.error("[DealerDashboard] Error fetching data:",B),W.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)}};x.useEffect(()=>{b()},[]);const j=(P,B=!1)=>{if(P==null||isNaN(P))return"₹0";const k=typeof P=="string"?parseFloat(P):Number(P);return k<=0?"₹0":B||k<1e4?`₹${Math.round(k).toLocaleString("en-IN")}`:k>=1e5?`₹${(k/1e5).toFixed(1)}L`:k>=1e3?`₹${(k/1e3).toFixed(1)}K`:`₹${Math.round(k).toLocaleString("en-IN")}`},y=P=>P.toLocaleString("en-IN"),N=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),S=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),A=x.useMemo(()=>{const P=c.reduce((B,k)=>B+k.raised,0);return P===0?[]:c.map(B=>({name:B.activityType.length>20?B.activityType.substring(0,20)+"...":B.activityType,value:B.raised,fullName:B.activityType,percentage:(B.raised/P*100).toFixed(0)}))},[c]),w=x.useMemo(()=>c.map(P=>({name:P.activityType.length>15?P.activityType.substring(0,15)+"...":P.activityType,fullName:P.activityType,Raised:P.raised,Approved:P.approved,Rejected:P.rejected,Pending:P.pending})),[c]),I=x.useMemo(()=>c.map(P=>({name:P.activityType.length>15?P.activityType.substring(0,15)+"...":P.activityType,fullName:P.activityType,Raised:P.raisedValue,Approved:P.approvedValue,Credited:P.creditedValue})),[c]),D=["#166534","#15803d","#16a34a","#22c55e","#4ade80","#86efac","#bbf7d0"],T=x.useMemo(()=>c.length===0?null:c.reduce((P,B)=>B.approvalRate>((P==null?void 0:P.approvalRate)||0)?B:P),[c]),v=x.useMemo(()=>c.length===0?null:c.reduce((P,B)=>B.raisedValue>((P==null?void 0:P.raisedValue)||0)?B:P),[c]);return a?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Et,{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(J,{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(fs,{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(Et,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh"]})})]})})})]}),e.jsx(Z,{className:"shadow-lg",children:e.jsxs(J,{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(_o,{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(Et,{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(J,{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(fs,{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(it,{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(Fe,{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(qi,{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(ce,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Raised Claims"}),e.jsx("div",{className:"p-2 rounded-lg bg-blue-50",children:e.jsx(Fe,{className:"h-4 w-4 text-blue-600"})})]})}),e.jsxs(J,{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(ce,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Approved"}),e.jsx("div",{className:"p-2 rounded-lg bg-green-50",children:e.jsx(Be,{className:"h-4 w-4 text-green-600"})})]})}),e.jsxs(J,{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(Qs,{className:"h-3 w-3 text-green-600"}),e.jsxs("p",{className:"text-xs text-green-600",children:[N(),"% 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(ce,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{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(J,{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(_j,{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(ce,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Pending"}),e.jsx("div",{className:"p-2 rounded-lg bg-orange-50",children:e.jsx(it,{className:"h-4 w-4 text-orange-600"})})]})}),e.jsxs(J,{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(ce,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Credited"}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-50",children:e.jsx(Mj,{className:"h-4 w-4 text-emerald-600"})})]})}),e.jsxs(J,{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(Qs,{className:"h-3 w-3 text-emerald-600"}),e.jsxs("p",{className:"text-xs text-emerald-600",children:[S(),"% 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(ce,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Pending Credit"}),e.jsx("div",{className:"p-2 rounded-lg bg-amber-50",children:e.jsx(ss,{className:"h-4 w-4 text-amber-600"})})]})}),e.jsxs(J,{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(ce,{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(_o,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(de,{children:"Claims Distribution by Activity Type"}),e.jsx(we,{children:"Total claims raised across activity types"})]})]})}),e.jsxs(J,{children:[e.jsx(dn,{width:"100%",height:300,children:e.jsxs(zh,{children:[e.jsx(Hh,{data:A,cx:"50%",cy:"50%",labelLine:!1,label:({name:P,percentage:B})=>`${P}: ${B}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:A.map((P,B)=>e.jsx(Gh,{fill:D[B%D.length]},`cell-${B}`))}),e.jsx(mn,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:A.slice(0,3).map((P,B)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-gray-50",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:D[B%D.length]}}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600",children:P.name}),e.jsx("p",{className:"text-sm text-gray-900",children:y(P.value)})]})]},B))})]})]}),e.jsxs(Z,{className:"shadow-lg",children:[e.jsx(ce,{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(qi,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{children:"Claims Status by Activity Type"}),e.jsx(we,{children:"Count comparison across workflow stages"})]})]})}),e.jsx(J,{children:e.jsx(dn,{width:"100%",height:300,children:e.jsxs(Io,{data:w,children:[e.jsx(Yi,{strokeDasharray:"3 3"}),e.jsx(Qi,{dataKey:"name"}),e.jsx(Ki,{}),e.jsx(mn,{}),e.jsx(Xi,{}),e.jsx(Ea,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(Ea,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(Ea,{dataKey:"Rejected",fill:"#ef4444"}),e.jsx(Ea,{dataKey:"Pending",fill:"#f59e0b"})]})})})]})]}),e.jsxs(Z,{className:"shadow-lg",children:[e.jsx(ce,{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(Bt,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(de,{children:"Detailed Activity Type Breakdown"}),e.jsx(we,{children:"In-depth analysis of claims by type and status"})]})]})}),e.jsx(J,{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(dn,{width:"100%",height:350,children:e.jsxs(Io,{data:I,children:[e.jsx(Yi,{strokeDasharray:"3 3"}),e.jsx(Qi,{dataKey:"name"}),e.jsx(Ki,{tickFormatter:P=>j(P)}),e.jsx(mn,{formatter:P=>j(P),labelFormatter:P=>P}),e.jsx(Xi,{}),e.jsx(Ea,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(Ea,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(Ea,{dataKey:"Credited",fill:"#10b981"})]})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-6",children:c.slice(0,3).map((P,B)=>e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow",children:[e.jsx(ce,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-base",children:P.activityType}),e.jsxs(re,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[P.approvalRate.toFixed(1),"% approved"]})]})}),e.jsxs(J,{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(P.raised)," (",j(P.raisedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Approved:"}),e.jsxs("span",{className:"text-green-600",children:[y(P.approved)," (",j(P.approvedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Rejected:"}),e.jsxs("span",{className:"text-red-600",children:[y(P.rejected)," (",j(P.rejectedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Pending:"}),e.jsxs("span",{className:"text-orange-600",children:[y(P.pending)," (",j(P.pendingValue),")"]})]}),e.jsx("div",{className:"h-px bg-gray-200 my-2"}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Credited:"}),e.jsxs("span",{className:"text-emerald-600",children:[y(P.credited)," (",j(P.creditedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Pending Credit:"}),e.jsxs("span",{className:"text-amber-600",children:[y(P.pendingCredit)," (",j(P.pendingCreditValue),")"]})]})]}),e.jsxs("div",{className:"pt-2",children:[e.jsxs("div",{className:"flex justify-between text-xs text-gray-600 mb-1",children:[e.jsx("span",{children:"Credit Rate"}),e.jsxs("span",{children:[P.creditRate.toFixed(1),"%"]})]}),e.jsx(ia,{value:P.creditRate,className:"h-2"})]})]})]},B))})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(Z,{className:"border-t-4 border-t-green-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(J,{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(ts,{className:"h-6 w-6 text-green-600"})}),e.jsx(Qs,{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:(T==null?void 0:T.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-green-600",children:[(T==null?void 0:T.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(J,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Da,{className:"h-6 w-6 text-blue-600"})}),e.jsx(Bt,{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(J,{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(hl,{className:"h-6 w-6 text-emerald-600"})}),e.jsx(Be,{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:[S(),"%"]}),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(J,{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(tp,{className:"h-6 w-6 text-amber-600"})}),e.jsx(ss,{className:"h-5 w-5 text-amber-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Pending Action"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:y(l.pendingCredit)}),e.jsxs("p",{className:"text-sm text-amber-600",children:[j(l.pendingCreditValue)," awaiting credit"]})]})})]})]})}function r6({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(ce,{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(Ua,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(we,{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(yt,{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(J,{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(Zt,{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(Re,{placeholder:"Search requests, IDs...",value:t,onChange:d=>r(d.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:s,onValueChange:d=>n(d),children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"due",children:"Due Date"}),e.jsx(X,{value:"created",children:"Date Created"}),e.jsx(X,{value:"priority",children:"Priority"}),e.jsx(X,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(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(yl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(vl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function n6({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(ce,{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(Ua,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(we,{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(yt,{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(J,{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(Zt,{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(Re,{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(He,{value:s,onValueChange:i,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200","data-testid":"dealer-closed-requests-status-filter",children:e.jsx(Ge,{placeholder:"Closure Type"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Closures"}),e.jsx(X,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(X,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(He,{value:a,onValueChange:p=>l(p),children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200","data-testid":"dealer-closed-requests-sort-by",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"due",children:"Due Date"}),e.jsx(X,{value:"created",children:"Date Created"}),e.jsx(X,{value:"priority",children:"Priority"})]})]}),e.jsx(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(yl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(vl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function i6({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:u,onInitiatorChange:h,onApproverChange:g,onApproverTypeChange:f,onDateRangeChange:b,onCustomStartDateChange:j,onCustomEndDateChange:y,onShowCustomDatePickerChange:N,onApplyCustomDate:S,onClearFilters:A,hasActiveFilters:w,...I}){return e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"dealer-user-all-requests-filters",children:e.jsx(J,{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(Ua,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),w&&e.jsx(re,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),w&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:A,className:"gap-2",children:[e.jsx(Et,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Jt,{}),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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Re,{placeholder:"Search requests...",value:t,onChange:D=>p(D.target.value),className:"pl-10 h-10","data-testid":"dealer-search-input"})]}),e.jsxs(He,{value:s,onValueChange:u,children:[e.jsx(We,{className:"h-10","data-testid":"dealer-status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Status"}),e.jsx(X,{value:"pending",children:"Pending"}),e.jsx(X,{value:"paused",children:"Paused"}),e.jsx(X,{value:"approved",children:"Approved"}),e.jsx(X,{value:"rejected",children:"Rejected"}),e.jsx(X,{value:"closed",children:"Closed"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(se,{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(yt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{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(se,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r!=="all"&&f&&e.jsxs(He,{value:n,onValueChange:D=>f(D),children:[e.jsx(We,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"current",children:"Current Only"}),e.jsx(X,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:m.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:m.selectedUser.displayName||m.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:m.handleClear,children:e.jsx(yt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{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(ft,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:i,onValueChange:D=>b(D),children:[e.jsx(We,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),i==="custom"&&e.jsxs(aa,{open:c,onOpenChange:N,children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ft,{className:"w-4 h-4"}),l&&o?`${st(l,"MMM d, yyyy")} - ${st(o,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(na,{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(se,{htmlFor:"start-date",children:"Start Date"}),e.jsx(ta,{value:l||null,onChange:D=>{const T=D?new Date(D):void 0;T?(j==null||j(T),o&&T>o&&(y==null||y(T))):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(se,{htmlFor:"end-date",children:"End Date"}),e.jsx(ta,{value:o||null,onChange:D=>{const T=D?new Date(D):void 0;T?(y==null||y(T),l&&T<l&&(j==null||j(T))):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:S,disabled:!l||!o,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>{N==null||N(!1),j==null||j(void 0),y==null||y(void 0),b("month")},children:"Cancel"})]})]})})]})]})]})})})}function l6(t){switch(t){case"DEALER_CLAIM":return s6;case"CUSTOM":default:return Sk}}function o6(t){switch(t){case"DEALER":return r6;case"STANDARD":default:return kk}}function c6(t){switch(t){case"DEALER":return n6;case"STANDARD":default:return Fk}}function d6(t){switch(t){case"DEALER":return i6;case"STANDARD":default:return Ik}}const m6=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ia,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:ts,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ts,iconColor:"text-gray-600"}}},u6=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:it,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Je,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:Be,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Je,iconColor:"text-gray-600",label:t}}};function x6({onViewRequest:t}){const[s,a]=x.useState([]),[r,n]=x.useState(!1),[i,l]=x.useState(!1),[o,c]=x.useState(1),[d,m]=x.useState(0),[p]=x.useState(10),u=x.useRef(null),h=_1(),g=x.useMemo(()=>{try{const T=tt.getUserData();return Bc(T)}catch(T){return console.error("[OpenRequests] Error getting user filter type:",T),"STANDARD"}},[]),f=x.useMemo(()=>o6(g),[g]),b=g==="DEALER",j=T=>{const v={search:h.searchTerm||void 0,status:T&&!b&&h.statusFilter!=="all"?h.statusFilter:void 0,priority:!b&&h.priorityFilter!=="all"?h.priorityFilter:void 0,templateType:h.templateTypeFilter!=="all"?h.templateTypeFilter:void 0,sortBy:h.sortBy,sortOrder:h.sortOrder};return v.templateType==="FORM_16"&&(h.form16FinancialYear&&(v.financialYear=h.form16FinancialYear),h.form16Quarter&&(v.quarter=h.form16Quarter)),v},y=x.useCallback(async(T=1,v)=>{try{T===1&&(n(!0),a([]));const M=await Ks.listOpenForMe({page:T,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}),P=Array.isArray(M==null?void 0:M.data)?M.data:[],B=M==null?void 0:M.pagination;B&&(h.setCurrentPage(B.page||1),c(B.totalPages||1),m(B.total||0));const k=P.map(_=>{var R,C,G,U;const L=_.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:((R=_.initiator)==null?void 0:R.displayName)||((C=_.initiator)==null?void 0:C.email)||"—",avatar:(((G=_.initiator)==null?void 0:G.displayName)||((U=_.initiator)==null?void 0:U.email)||"NA").split(" ").map($=>$[0]).join("").slice(0,2).toUpperCase()},currentApprover:_.currentApprover?{name:_.currentApprover.name||_.currentApprover.email||"—",avatar:(_.currentApprover.name||_.currentApprover.email||"CA").split(" ").map($=>$[0]).join("").slice(0,2).toUpperCase(),sla:_.currentApprover.sla}:void 0,createdAt:L||"—",approvalStep:_.currentLevel?`Step ${_.currentLevel} of ${_.totalLevels||"?"}`:void 0,department:_.department,currentLevelSLA:_.currentLevelSLA,templateType:_.templateType||_.template_type,form16Submission:_.form16Submission??null}});a(k)}finally{n(!1),l(!1)}},[p,h]);u.current=y;const N=x.useCallback(()=>{l(!0),y(h.currentPage,j(!0))},[h.currentPage,y]),S=x.useCallback(T=>{T>=1&&T<=o&&(h.setCurrentPage(T),y(T,j(!0)))},[o,h,y]),A=()=>{const T=[];let M=Math.max(1,h.currentPage-Math.floor(2.5)),P=Math.min(o,M+5-1);P-M<4&&(M=Math.max(1,P-5+1));for(let B=M;B<=P;B++)T.push(B);return T},w=x.useRef(!1);x.useEffect(()=>{if(!w.current){w.current=!0;const T=h.currentPage||1;y(T,j(!0))}},[]);const I=x.useRef({searchTerm:h.searchTerm,statusFilter:h.statusFilter,priorityFilter:h.priorityFilter,templateTypeFilter:h.templateTypeFilter,sortBy:h.sortBy,sortOrder:h.sortOrder,isDealer:b});x.useEffect(()=>{if(!w.current)return;const T=I.current;if(!(T.searchTerm!==h.searchTerm||T.statusFilter!==h.statusFilter||T.priorityFilter!==h.priorityFilter||T.templateTypeFilter!==h.templateTypeFilter||T.sortBy!==h.sortBy||T.sortOrder!==h.sortOrder||T.isDealer!==b))return;const M=setTimeout(()=>{h.setCurrentPage(1),y(1,j(!0)),I.current={searchTerm:h.searchTerm,statusFilter:h.statusFilter,priorityFilter:h.priorityFilter,templateTypeFilter:h.templateTypeFilter,sortBy:h.sortBy,sortOrder:h.sortOrder,isDealer:b}},h.searchTerm?500:0);return()=>clearTimeout(M)},[h.searchTerm,h.statusFilter,h.priorityFilter,h.templateTypeFilter,h.form16FinancialYear,h.form16Quarter,h.sortBy,h.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(Fe,{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(re,{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:N,disabled:i,children:[e.jsx(Et,{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:h.searchTerm,statusFilter:h.statusFilter,priorityFilter:h.priorityFilter,templateTypeFilter:h.templateTypeFilter,form16FinancialYear:h.form16FinancialYear,form16Quarter:h.form16Quarter,sortBy:h.sortBy,sortOrder:h.sortOrder,onSearchChange:h.setSearchTerm,onStatusFilterChange:h.setStatusFilter,onPriorityFilterChange:h.setPriorityFilter,onTemplateTypeFilterChange:h.setTemplateTypeFilter,onForm16FinancialYearChange:h.setForm16FinancialYear,onForm16QuarterChange:h.setForm16Quarter,onSortByChange:h.setSortBy,onSortOrderChange:h.setSortOrder,onClearFilters:h.clearFilters,activeFiltersCount:h.activeFiltersCount}),e.jsx("div",{className:"space-y-3",children:D.map(T=>{const v=m6(T.priority),M=(T.templateType||T.template_type||"").toString().toUpperCase()==="FORM_16",P=T.form16Submission,B=P==null?void 0:P.displayStatus,k=B&&/balance mismatch|failed/i.test(String(B)),_=M&&B?{color:k?"bg-red-100 text-red-800 border-red-200":B==="Completed"?"bg-green-100 text-green-800 border-green-200":"bg-gray-100 text-gray-700 border-gray-200",icon:Je,label:B}:u6(T.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(T.id,T.title),children:e.jsx(J,{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:T.displayId||T.id}),e.jsxs(re,{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||T.status]}),T.department&&e.jsx(re,{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(re,{variant:"outline",className:`${v.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:T.priority}),(()=>{const L=(T==null?void 0:T.templateType)||(T==null?void 0:T.template_type)||"",R=(L==null?void 0:L.toUpperCase())||"";let C="Non-Templatized",G="bg-purple-100 !text-purple-600 border-purple-200";return R==="DEALER CLAIM"?(C="Dealer Claim",G="bg-blue-100 !text-blue-700 border-blue-200"):R==="FORM_16"?(C="Form 16",G="bg-emerald-100 !text-emerald-700 border-emerald-200"):R==="TEMPLATE"&&(C="Template"),e.jsx(re,{variant:"outline",className:`${G} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:C})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:T.title}),(T.templateType||"").toString().toUpperCase()==="FORM_16"&&T.form16Submission&&e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-600 mt-1",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||"—"]})]}),T.currentLevelSLA&&(()=>{var U;const L=!!(T.isPaused||(U=T.pauseInfo)!=null&&U.isPaused||T.status==="paused"),R=T.currentLevelSLA.percentageUsed||0,G=L?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:R>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:R>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:R>=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 ${G.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:[L?e.jsx(or,{className:`w-3.5 h-3.5 ${G.icon}`}):e.jsx(it,{className:`w-3.5 h-3.5 ${G.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",R,"% ",L&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:T.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${G.text}`,children:[T.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(ia,{value:R,className:"h-1.5",indicatorClassName:G.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(cs,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ds,{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.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(cs,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(ds,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:T.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:T.currentApprover.name})]}),T.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Je,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:T.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ft,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",T.createdAt!=="—"?Fa(T.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(js,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},T.id)})}),D.length===0&&e.jsx(Z,{className:"shadow-lg border-0",children:e.jsxs(J,{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(Fe,{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:h.searchTerm||h.activeFiltersCount>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),h.activeFiltersCount>0&&e.jsx(E,{variant:"outline",className:"mt-4",onClick:h.clearFilters,children:"Clear all filters"})]})}),o>1&&!r&&e.jsx(Z,{className:"shadow-md",children:e.jsx(J,{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 ",(h.currentPage-1)*p+1," to ",Math.min(h.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:()=>S(h.currentPage-1),disabled:h.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(js,{className:"h-4 w-4 rotate-180"})}),h.currentPage>3&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>S(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),A().map(T=>e.jsx(E,{variant:T===h.currentPage?"default":"outline",size:"sm",onClick:()=>S(T),className:`h-8 w-8 p-0 ${T===h.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:T},T)),h.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:()=>S(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>S(h.currentPage+1),disabled:h.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(js,{className:"h-4 w-4"})})]})]})})})]})}function h6({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(Fe,{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(re,{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(Et,{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 p6(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ia,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:ts,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ts,iconColor:"text-gray-600"}}}function g6(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:Be,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:Je,iconColor:"text-gray-600",label:t,description:""}}}function f6({request:t,onViewRequest:s}){var l;const a=p6(t.priority),r=g6(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(J,{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(re,{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(re,{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(re,{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(re,{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(cs,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ds,{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(Be,{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(ft,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?Fa(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Be,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",Fa(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(js,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function b6({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(f6,{request:r,onViewRequest:a},r.id))})}function j6({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(Z,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(J,{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(Fe,{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 y6(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 v6({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=y6(a,r);return e.jsx(Z,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(J,{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(js,{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(js,{className:"h-4 w-4"})})]})]})})})}function N6(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 w6(t){return t.map(N6)}function C6({itemsPerPage:t=10}={}){const[s,a]=x.useState([]),[r,n]=x.useState(!1),[i,l]=x.useState(!1),[o,c]=x.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=x.useCallback(async(p=1,u)=>{try{p===1&&(n(!0),a([]));const h=await Ks.listClosedByMe({page:p,limit:t,search:u==null?void 0:u.search,status:u!=null&&u.status&&u.status!=="all"?u.status:void 0,priority:u==null?void 0:u.priority,templateType:u==null?void 0:u.templateType,financialYear:u==null?void 0:u.financialYear,quarter:u==null?void 0:u.quarter,sortBy:u==null?void 0:u.sortBy,sortOrder:u==null?void 0:u.sortOrder}),g=Array.isArray(h==null?void 0:h.data)?h.data:[],f=w6(g);a(f);const b=h==null?void 0:h.pagination;b&&c({currentPage:b.page||1,totalPages:b.totalPages||1,totalRecords:b.total||0,itemsPerPage:t})}catch(h){console.error("[ClosedRequests] Error fetching requests:",h),a([])}finally{n(!1),l(!1)}},[t]),m=x.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 S6={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},Df=yn({name:"closedRequests",initialState:S6,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:A6,setStatusFilter:T6,setPriorityFilter:k6,setTemplateTypeFilter:D6,setForm16FinancialYear:R6,setForm16Quarter:F6,setSortBy:I6,setSortOrder:P6,setCurrentPage:E6,clearFilters:_6}=Df.actions;function M6({onFiltersChange:t,debounceMs:s=500}={}){const a=di(),r=x.useRef(null),n=x.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,form16FinancialYear:d,form16Quarter:m,sortBy:p,sortOrder:u,currentPage:h}=Nn(v=>v.closedRequests),g=x.useCallback(v=>a(A6(v)),[a]),f=x.useCallback(v=>a(T6(v)),[a]),b=x.useCallback(v=>a(k6(v)),[a]),j=x.useCallback(v=>a(D6(v)),[a]),y=x.useCallback(v=>a(R6(v)),[a]),N=x.useCallback(v=>a(F6(v)),[a]),S=x.useCallback(v=>a(I6(v)),[a]),A=x.useCallback(v=>a(P6(v)),[a]),w=x.useCallback(v=>a(E6(v)),[a]),I=x.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:u}),[i,l,o,c,d,m,p,u]);x.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const v=setTimeout(()=>{t&&t(I())},i?s:0);return r.current=v,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,p,u,t,I,s]);const D=x.useCallback(()=>{a(_6())},[a]),T=[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:u,currentPage:h,setSearchTerm:g,setPriorityFilter:b,setStatusFilter:f,setTemplateTypeFilter:j,setForm16FinancialYear:y,setForm16Quarter:N,setSortBy:S,setSortOrder:A,setCurrentPage:w,clearFilters:D,activeFiltersCount:T,getFilters:I}}function L6({onViewRequest:t}){const s=C6({itemsPerPage:10}),a=x.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=M6(),n=x.useMemo(()=>{try{const u=tt.getUserData();return Bc(u)}catch(u){return console.error("[ClosedRequests] Error getting user filter type:",u),"STANDARD"}},[]),i=x.useMemo(()=>c6(n),[n]),l=n==="DEALER",o=x.useCallback(()=>{const u=r.getFilters();return{search:u.search||void 0,status:u.status!=="all"?u.status:void 0,priority:!l&&u.priority?u.priority:void 0,templateType:u.templateType,financialYear:u.financialYear,quarter:u.quarter,sortBy:u.sortBy,sortOrder:u.sortOrder}},[r,l]),c=x.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=x.useRef(!1);x.useEffect(()=>{const u=r.currentPage||1;a.current(u,o()),d.current=!0},[l]),x.useEffect(()=>{if(!d.current)return;const u=c.current;if(!(u.searchTerm!==r.searchTerm||u.statusFilter!==r.statusFilter||u.priorityFilter!==r.priorityFilter||u.templateTypeFilter!==r.templateTypeFilter||u.form16FinancialYear!==r.form16FinancialYear||u.form16Quarter!==r.form16Quarter||u.sortBy!==r.sortBy||u.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!==u.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=x.useCallback(u=>{u>=1&&u<=s.pagination.totalPages&&(r.setCurrentPage(u),s.fetchRequests(u,o()))},[s,r,o]),p=x.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(h6,{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(b6,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(j6,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(v6,{pagination:s.pagination,onPageChange:m})]})}function O6(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 $6(t){return O6(t)?"DEALER_CLAIM":"CUSTOM"}function U6(t,s){return`/request/${t}`}class B6 extends x.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("RequestDetail Router Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(ss,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(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 V6({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=Va().requestId||t||"",{user:i}=us(),{apiRequest:l,loading:o}=Nd(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(Et,{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=$6(l),d=l6(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function z6(t){return e.jsx(B6,{children:e.jsx(V6,{...t})})}function H6({onViewSummary:t}){const s=Cs(),[a,r]=x.useState([]),[n,i]=x.useState(!0),[l,o]=x.useState(""),[c,d]=x.useState(1),[m,p]=x.useState(1),[u,h]=x.useState(0),g=10,f=x.useCallback(async(N=1)=>{try{i(!0);const S=await rk({page:N,limit:g});r(S.data||[]),p(S.pagination.totalPages||1),h(S.pagination.total||0),d(S.pagination.page||1)}catch(S){console.error("Failed to fetch shared summaries:",S),W.error("Failed to load shared summaries")}finally{i(!1)}},[]);x.useEffect(()=>{f(1)},[f]);const b=async N=>{try{await nf(N),r(S=>S.map(A=>A.sharedSummaryId===N?{...A,isRead:!0,viewedAt:new Date().toISOString()}:A)),t?t(N):s(`/shared-summaries/${N}`)}catch(S){console.error("Failed to mark as viewed:",S),t?t(N):s(`/shared-summaries/${N}`)}},j=N=>{N>=1&&N<=m&&f(N)},y=a.filter(N=>{var A,w,I,D;if(!l)return!0;const S=l.toLowerCase();return((A=N.title)==null?void 0:A.toLowerCase().includes(S))||((w=N.requestNumber)==null?void 0:w.toLowerCase().includes(S))||((I=N.initiatorName)==null?void 0:I.toLowerCase().includes(S))||((D=N.sharedByName)==null?void 0:D.toLowerCase().includes(S))});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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Re,{placeholder:"Search by title, request number, or user...",value:l,onChange:N=>o(N.target.value),className:"pl-10 text-sm sm:text-base"})]})}),n&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ze,{className:"h-8 w-8 animate-spin text-blue-600"})}),!n&&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(Fe,{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(N=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${N.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>b(N.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:[N.isRead?e.jsx(Lj,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(Nt,{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:N.title}),!N.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:N.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(Ht,{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:N.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Ht,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared by: ",e.jsx("span",{className:"font-medium",children:N.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(ft,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",st(new Date(N.sharedAt),"MMM dd, yyyy HH:mm")]})]}),N.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Nt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",st(new Date(N.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(E,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:S=>{S.stopPropagation(),b(N.sharedSummaryId)},children:"View"})]})})},N.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,u)," of ",u," 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 G6(){const{sharedSummaryId:t}=Va(),s=Cs(),[a,r]=x.useState(null),[n,i]=x.useState(!0);x.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,p;try{i(!0);try{await nf(t)}catch(h){console.warn("Failed to mark as viewed:",h)}const u=await Cd(t);r(u)}catch(u){console.error("Failed to fetch summary details:",u),W.error(((p=(m=u==null?void 0:u.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(Be,{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(it,{className:"h-4 w-4 text-orange-600"}):e.jsx(Fe,{className:"h-4 w-4 text-gray-600"})},o=d=>{const m=d.toLowerCase();return m==="approved"?"bg-green-100 text-green-700 border-green-300":m==="rejected"?"bg-red-100 text-red-700 border-red-300":m==="pending"||m==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},c=(d,m)=>d&&d.trim()&&d.trim().toUpperCase()!=="N/A"?d:m&&m.trim()&&m.trim().toUpperCase()!=="N/A"?m:"N/A";return n?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ze,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):a?e.jsx("div",{className:"min-h-screen bg-gray-50 p-4 sm:p-6",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs(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(re,{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:st(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:st(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(re,{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(Fe,{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 W6(){const{requestId:t}=Va(),s=Cs(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(zt,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(rf,{requestId:t||""})})})}function Rf({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(re,{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 ca({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(J,{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 Y6({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(ca,{label:"Total",value:t.total,icon:Fe,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(ca,{label:"Pending",value:t.pending,icon:it,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(ca,{label:"Paused",value:t.paused,icon:mr,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(ca,{label:"Approved",value:t.approved,icon:Be,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(ca,{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(ca,{label:"Draft",value:t.draft,icon:Nl,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(ca,{label:"Closed",value:t.closed,icon:wl,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 Q6({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(J,{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(Zt,{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(Re,{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(He,{value:s,onValueChange:i,children:[e.jsx(We,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"Status"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Status"}),e.jsx(X,{value:"draft",children:"Draft"}),e.jsx(X,{value:"pending",children:"Pending"}),e.jsx(X,{value:"paused",children:"Paused"}),e.jsx(X,{value:"approved",children:"Approved"}),e.jsx(X,{value:"rejected",children:"Rejected"}),e.jsx(X,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:l,children:[e.jsx(We,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"Priority"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Priority"}),e.jsx(X,{value:"express",children:"Express"}),e.jsx(X,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:o,children:[e.jsx(We,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"Template Type"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Templates"}),e.jsx(X,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(X,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]})]})]})})})}function K6(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ia,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:ts,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ts,iconColor:"text-gray-600"}}}function X6(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Be,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:it,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Be,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Nl,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Je,iconColor:"text-gray-600"}}}const Z6=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 J6({request:t,index:s,onViewRequest:a}){var o;const r=X6(t.status),n=K6(t.priority),i=r.icon,l=n.icon;return e.jsx(Wt.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(J,{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(re,{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(re,{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(mr,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(re,{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(re,{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:Z6(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:"})," ",Fa(t.submittedDate)]})]})]}),e.jsx(js,{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(Qs,{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(Ht,{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(Qs,{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(it,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",Fa(t.submittedDate)]})]})]})]})})})})}function q6({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(J,{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(J,{className:"p-12 text-center",children:[e.jsx(Fe,{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(J6,{request:l,index:o,onViewRequest:i},l.id))})}function eD(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 Ff(t){return Array.isArray(t)?t.map(eD):[]}function tD({itemsPerPage:t=10}={}){const[s,a]=x.useState([]),[r,n]=x.useState(!1),[i,l]=x.useState(!1),[o,c]=x.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=x.useCallback(async(m=1,p)=>{try{m===1&&(n(!0),a([]));const u=await Ks.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}),h=Array.isArray(u==null?void 0:u.data)?u.data:[],g=Ff(h);a(g),l(!0);const f=u==null?void 0:u.pagination;f&&c({currentPage:f.page||1,totalPages:f.totalPages||1,totalRecords:f.total||0,itemsPerPage:t})}catch(u){console.error("[MyRequests] Error fetching requests:",u),a([]),l(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:o,fetchMyRequests:d}}const sD={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},If=yn({name:"myRequests",initialState:sD,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:aD,setStatusFilter:rD,setPriorityFilter:nD,setTemplateTypeFilter:iD,setCurrentPage:lD,clearFilters:oD}=If.actions;function cD({onFiltersChange:t,debounceMs:s=500}={}){const a=di(),r=x.useRef(null),n=x.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d}=Nn(j=>j.myRequests),m=x.useCallback(j=>a(aD(j)),[a]),p=x.useCallback(j=>a(rD(j)),[a]),u=x.useCallback(j=>a(nD(j)),[a]),h=x.useCallback(j=>a(iD(j)),[a]),g=x.useCallback(j=>a(lD(j)),[a]),f=x.useCallback(()=>({search:i,status:l,priority:o,templateType:c}),[i,l,o,c]);x.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=x.useCallback(()=>{a(oD())},[a]);return{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d,setSearchTerm:m,setStatusFilter:p,setPriorityFilter:u,setTemplateTypeFilter:h,setCurrentPage:g,getFilters:f,resetFilters:b}}function dD({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=us(),r=tD({itemsPerPage:10}),n=x.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=cD(),l=x.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}),o=x.useRef(!1);x.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},[]),x.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 N=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(N)},[i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter]);const[c,d]=x.useState(null),[m,p]=x.useState(!1),u=x.useCallback(async()=>{if(a!=null&&a.userId)try{p(!0);const j=await Ot.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]);x.useEffect(()=>{const j=setTimeout(()=>{u()},i.searchTerm?500:0);return()=>clearTimeout(j)},[i.searchTerm,i.priorityFilter,i.templateTypeFilter,u]);const h=Ff(s),g=r.hasFetchedFromApi?r.requests:h,f=x.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=x.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(Rf,{icon:Fe,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(Y6,{stats:f,onStatusFilter:j=>{i.setStatusFilter(j)}}),e.jsx(Q6,{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(q6,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(Wr,{currentPage:i.currentPage||r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:b,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function Pf({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(Rf,{icon:Fe,title:i(),description:l(),testId:"requests-header"}),e.jsx(re,{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(Et,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function Ef({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(ca,{label:"Total",value:t.total,icon:Fe,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(ca,{label:"Pending",value:t.pending,icon:it,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(ca,{label:"Paused",value:t.paused,icon:mr,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(ca,{label:"Approved",value:t.approved,icon:Be,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(ca,{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(ca,{label:"Closed",value:t.closed,icon:wl,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 mD=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ia,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:ts,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ts,iconColor:"text-gray-600"}}},fh=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Be,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:it,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"closed",icon:Be,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"draft",icon:Nl,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:Je,iconColor:"text-gray-600"}}},uD=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 xD(t){return t==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function hD({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:fh(t.status).icon,label:i}:fh(t.status),c=mD(t.priority),d=o.icon,m=c.icon;return e.jsx(Wt.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(J,{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(re,{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(re,{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(mr,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(re,{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 u=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",h=(u==null?void 0:u.toUpperCase())||"";let g="Non-Templatized",f="bg-purple-100 !text-purple-600 border-purple-200";return h==="DEALER CLAIM"?(g="Dealer Claim",f="bg-blue-100 !text-blue-700 border-blue-200"):h==="FORM_16"?(g="Form 16",f="bg-emerald-100 !text-emerald-700 border-emerald-200"):h==="TEMPLATE"&&(g="Template"),e.jsx(re,{variant:"outline",className:`${f} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:g})})(),t.department&&e.jsx(re,{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:uD(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:"})," ",Fa(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?xD(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(js,{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(Qs,{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(Ht,{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(Qs,{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(it,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",Fa(t.submittedDate)]})]})]})]})})})})}function _f({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(Z,{"data-testid":"loading-state",children:e.jsx(J,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(Z,{"data-testid":"empty-state",children:e.jsxs(J,{className:"p-12 text-center",children:[e.jsx(Fe,{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(hD,{request:n,index:i,onViewRequest:r},n.id))})}const pD={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},Mf=yn({name:"requests",initialState:pD,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:gD,setStatusFilter:fD,setPriorityFilter:bD,setTemplateTypeFilter:jD,setRequestTypeFilter:yD,setForm16FinancialYear:vD,setForm16Quarter:ND,setSlaComplianceFilter:wD,setDepartmentFilter:CD,setInitiatorFilter:SD,setApproverFilter:AD,setApproverFilterType:TD,setDateRange:bh,setCustomStartDate:vo,setCustomEndDate:No,setShowCustomDatePicker:Ri,setCurrentPage:kD,clearFilters:DD}=Mf.actions;function Lf(){const t=di(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,requestTypeFilter:i,form16FinancialYear:l,form16Quarter:o,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:m,approverFilter:p,approverFilterType:u,dateRange:h,customStartDate:g,customEndDate:f,showCustomDatePicker:b,currentPage:j}=Nn(z=>z.requests),y=x.useCallback(z=>t(gD(z)),[t]),N=x.useCallback(z=>t(fD(z)),[t]),S=x.useCallback(z=>t(bD(z)),[t]),A=x.useCallback(z=>t(jD(z)),[t]),w=x.useCallback(z=>t(yD(z)),[t]),I=x.useCallback(z=>t(vD(z)),[t]),D=x.useCallback(z=>t(ND(z)),[t]),T=x.useCallback(z=>t(wD(z)),[t]),v=x.useCallback(z=>t(CD(z)),[t]),M=x.useCallback(z=>t(SD(z)),[t]),P=x.useCallback(z=>t(AD(z)),[t]),B=x.useCallback(z=>t(TD(z)),[t]),k=x.useCallback(z=>t(bh(z)),[t]),_=x.useCallback(z=>t(vo(z)),[t]),L=x.useCallback(z=>t(No(z)),[t]),R=x.useCallback(z=>t(Ri(z)),[t]),C=x.useCallback(z=>t(kD(z)),[t]),G=x.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"?u:void 0,dateRange:h,startDate:g,endDate:f},[s,a,r,n,l,o,c,d,m,p,u,h,g,f]),U=x.useCallback(()=>{t(DD())},[t]),$=x.useCallback(z=>{const O=z;t(bh(O)),O!=="custom"?(t(vo(void 0)),t(No(void 0)),t(Ri(!1))):t(Ri(!0))},[t]),F=x.useCallback(()=>{g&&f&&(g>f&&(t(vo(f)),t(No(g))),t(Ri(!1)))},[g,f,t]),H=n==="FORM_16";return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,requestTypeFilter:i,form16FinancialYear:l,form16Quarter:o,isForm16:H,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:m,approverFilter:p,approverFilterType:u,dateRange:h,customStartDate:g,customEndDate:f,showCustomDatePicker:b,currentPage:j,hasActiveFilters:H?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"||h!=="all"||g||f),setSearchTerm:y,setStatusFilter:N,setPriorityFilter:S,setTemplateTypeFilter:A,setRequestTypeFilter:w,setForm16FinancialYear:I,setForm16Quarter:D,setSlaComplianceFilter:T,setDepartmentFilter:v,setInitiatorFilter:M,setApproverFilter:P,setApproverFilterType:B,setDateRange:k,setCustomStartDate:_,setCustomEndDate:L,setShowCustomDatePicker:R,setCurrentPage:C,getFilters:G,clearFilters:U,handleDateRangeChange:$,handleApplyCustomDate:F}}function ll({filterValue:t,onFilterChange:s,source:a="default"}){const[r,n]=x.useState(""),[i,l]=x.useState([]),[o,c]=x.useState(!1),[d,m]=x.useState(null),[p,u]=x.useState(!1),h=x.useRef(null);x.useEffect(()=>{async function j(){if(t!=="all"&&!d)try{const y=await da.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]),x.useEffect(()=>()=>{h.current&&clearTimeout(h.current)},[]);const g=x.useCallback(j=>{if(n(j),h.current&&clearTimeout(h.current),!j||j.trim().length<2){l([]),c(!1);return}h.current=setTimeout(async()=>{var y;u(!0);try{const S=((y=(await da.searchUsers(j.trim(),10,a)).data)==null?void 0:y.data)||[];l(S),c(S.length>0)}catch(N){console.error("Search API failed:",N),l([]),c(!1)}finally{u(!1)}},400)},[a]),f=x.useCallback(j=>{m(j),s(j.userId),n(j.displayName||j.email),c(!1),l([])},[s]),b=x.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 RD(t){var d,m,p,u,h,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((N,S)=>{const A=N.levelNumber||N.level_number||0;return(S.levelNumber||S.level_number||0)-A})[0];y&&(n=y.approverName||((u=y.approver)==null?void 0:u.name)||((h=y.approver)==null?void 0:h.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 Of(t){return Array.isArray(t)?t.map(RD):[]}function FD(t,s,a,r,n,i){if(t.length>0){const l=t.length,o=t.filter(h=>{const g=(h.status||"").toString().toUpperCase();return g==="PENDING"||g==="IN_PROGRESS"}).length,c=t.filter(h=>(h.status||"").toString().toUpperCase()==="APPROVED").length,d=t.filter(h=>(h.status||"").toString().toUpperCase()==="REJECTED").length,m=t.filter(h=>(h.status||"").toString().toUpperCase()==="DRAFT").length,p=t.filter(h=>(h.status||"").toString().toUpperCase()==="CLOSED").length,u=t.filter(h=>(h.status||"").toString().toUpperCase()==="PAUSED").length;return{total:l,pending:o,paused:u,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 $f={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(cl,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})($f);var ID=$f.exports;const Uf=dl(ID);var Bf={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(cl,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(Bf);var PD=Bf.exports;const Vf=dl(PD);rs.extend(Vf);rs.extend(Uf);function ED(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(u=>{const h=(u.status||"").toString().toUpperCase();return h==="IN_PROGRESS"||h==="PENDING"}))==null?void 0:d.approverId)||((p=(m=n.approvals)==null?void 0:m.find(u=>{const h=(u.status||"").toString().toUpperCase();return h==="IN_PROGRESS"||h==="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,u,h,g,f,b,j,y,N;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const S=(r.status||"").toString().toUpperCase();if(!(S==="APPROVED"||S==="REJECTED"||S==="CLOSED"))return!1;const w=((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)||((h=(u=r.summary)==null?void 0:u.sla)==null?void 0:h.status);return w?w!=="breached"&&w.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)||((N=(y=r.summary)==null?void 0:y.sla)==null?void 0:N.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=rs(s.startDate).startOf("day").toDate(),n=rs(s.endDate).endOf("day").toDate();else{const i=rs();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=rs(m).startOf("day").toDate(),u=rs(r).startOf("day").toDate(),h=rs(n).endOf("day").toDate();return p>=u&&p<=h}const o=rs(l).startOf("day").toDate(),c=rs(r).startOf("day").toDate(),d=rs(n).endOf("day").toDate();return o>=c&&o<=d}))}return a}rs.extend(Uf);rs.extend(Vf);function _D(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return st(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function zf(t,s){const a=ED(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var y,N,S,A,w;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),p=((y=c.initiator)==null?void 0:y.displayName)||((N=c.initiator)==null?void 0:N.email)||c.initiatorName||"N/A",u=c.department||((S=c.initiator)==null?void 0:S.department)||"N/A",h=((A=c.currentApprover)==null?void 0:A.displayName)||((w=c.currentApprover)==null?void 0:w.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",f=_D(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,'""')}"`,`"${u.replace(/"/g,'""')}"`,`"${h.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 MD({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 Ks.listWorkflows({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const p=m.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),u=(d==null?void 0:d.pagination)||{page:t,limit:s,total:p.length,totalPages:1};return{data:p,allData:[],filteredData:p,pagination:{page:u.page,limit:u.limit||s,total:u.total||p.length,totalPages:u.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 Ks.listParticipantRequests({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const p=m.filter(h=>(h.status||"").toString().toUpperCase()!=="DRAFT"),u=(d==null?void 0:d.pagination)||{page:t,limit:s,total:p.length,totalPages:1};return{data:p,allData:[],filteredData:p,pagination:u}}}async function LD(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const l=t?await Ks.listWorkflows({page:r,limit:100}):await Ks.listParticipantRequests({page:r,limit:100});let o=[];if(Array.isArray(l==null?void 0:l.data)?o=l.data:Array.isArray(l)&&(o=l),o.length>0){const c=o.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");a.push(...c),r++,l!=null&&l.pagination?n=r<=l.pagination.totalPages:n=o.length===100}else n=!1}return a}function OD({onViewRequest:t}){const{user:s}=us(),a=Nn(U=>U.dashboard.viewAsUser),r=x.useMemo(()=>Sl(s),[s]),n=x.useMemo(()=>r&&!a,[r,a]),i=Lf(),[l,o]=x.useState([]),[c,d]=x.useState(!1),[m,p]=x.useState(!1),[u,h]=x.useState(null),[g,f]=x.useState([]),[b,j]=x.useState(!1),[y,N]=x.useState(1),[S,A]=x.useState(0),[w]=x.useState(10),I=ll({filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter,source:"local"}),D=ll({filterValue:i.approverFilter,onFilterChange:i.setApproverFilter,source:"local"}),T=x.useCallback(async(U,$,F,H)=>{try{const K=H==null?void 0:H.slaCompliance;if(K&&K!=="all"&&K!=="breached"&&K!=="compliant"){const O={};H!=null&&H.search&&(O.search=H.search),H!=null&&H.priority&&H.priority!=="all"&&(O.priority=H.priority),H!=null&&H.department&&H.department!=="all"&&(O.department=H.department),H!=null&&H.initiator&&H.initiator!=="all"&&(O.initiator=H.initiator),H!=null&&H.approver&&H.approver!=="all"&&(O.approver=H.approver,O.approverType=H.approverType||"current"),O.slaCompliance=K,U&&(O.dateRange=U),$&&(O.startDate=$.toISOString()),F&&(O.endDate=F.toISOString());const V=n?await Ks.listWorkflows({page:1,limit:1e3,...O}):await Ks.listParticipantRequests({page:1,limit:1e3,...O}),Q=Array.isArray(V==null?void 0:V.data)?V.data:[],q=Q.length,ee=Q.filter(Ze=>{const Ue=(Ze.status||"").toString().toUpperCase();return Ue==="PENDING"||Ue==="IN_PROGRESS"}).length,te=Q.filter(Ze=>(Ze.status||"").toString().toUpperCase()==="APPROVED").length,ue=Q.filter(Ze=>(Ze.status||"").toString().toUpperCase()==="REJECTED").length,_e=Q.filter(Ze=>(Ze.status||"").toString().toUpperCase()==="CLOSED").length;h({total:q,pending:ee,paused:0,approved:te,rejected:ue,draft:0,closed:_e})}else{const O=await Ot.getRequestStats(U,$?$.toISOString():void 0,F?F.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,!n);h({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(K){console.error("Failed to fetch backend stats:",K)}finally{}},[n]),v=x.useCallback(async()=>{try{j(!0);const U=await Ot.getDepartments();f(U)}catch{}finally{j(!1)}},[]),M=x.useRef(i),P=x.useRef(T);x.useEffect(()=>{M.current=i,P.current=T},[i,T]),x.useEffect(()=>{const U=new URLSearchParams(window.location.search),$=U.get("approver"),F=U.get("approverType"),H=U.get("slaCompliance"),K=U.get("dateRange"),z=U.get("startDate"),O=U.get("endDate");$&&i.setApproverFilter($),(F==="current"||F==="any")&&i.setApproverFilterType(F),H&&i.setSlaComplianceFilter(H),K&&i.setDateRange(K),z&&i.setCustomStartDate(new Date(z)),O&&i.setCustomEndDate(new Date(O))},[]);const B=x.useCallback(async(U=1)=>{try{U===1&&(d(!0),o([]));const $=M.current.getFilters(),F=await MD({page:U,itemsPerPage:w,filters:$,isOrgLevel:n});o(F.data),i.setCurrentPage(F.pagination.page),N(F.pagination.totalPages),A(F.pagination.total)}catch{o([])}finally{d(!1)}},[w,n]),k=x.useCallback(async()=>{try{p(!0);const U=await LD(n);await zf(U,i.getFilters())}catch(U){console.error("Failed to export requests:",U),alert("Failed to export requests. Please try again.")}finally{p(!1)}},[n,i]);x.useEffect(()=>{v()},[v]),x.useEffect(()=>{const U=setTimeout(()=>{const $={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},F=i.dateRange||"all";P.current(F,i.customStartDate,i.customEndDate,$)},i.searchTerm?500:0);return()=>clearTimeout(U)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.templateTypeFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const _=x.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}),L=x.useRef(!1);x.useEffect(()=>{const U=i.currentPage||1;B(U),L.current=!0},[]),x.useEffect(()=>{if(!L.current)return;const U=_.current;if(!(U.searchTerm!==i.searchTerm||U.statusFilter!==i.statusFilter||U.priorityFilter!==i.priorityFilter||U.templateTypeFilter!==i.templateTypeFilter||U.form16FinancialYear!==i.form16FinancialYear||U.form16Quarter!==i.form16Quarter||U.slaComplianceFilter!==i.slaComplianceFilter||U.departmentFilter!==i.departmentFilter||U.initiatorFilter!==i.initiatorFilter||U.approverFilter!==i.approverFilter||U.approverFilterType!==i.approverFilterType||U.dateRange!==i.dateRange||U.customStartDate!==i.customStartDate||U.customEndDate!==i.customEndDate||U.isOrgLevel!==n))return;const F=setTimeout(()=>{i.setCurrentPage(1),B(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!==U.searchTerm?500:0);return()=>clearTimeout(F)},[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 R=x.useCallback(U=>{U>=1&&U<=y&&(i.setCurrentPage(U),B(U))},[y,B,i]),C=x.useMemo(()=>Of(l),[l]),G=x.useMemo(()=>u?{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}:FD([],n,u,!1,S,C),[n,u,S,C]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(Pf,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:k}),e.jsx(Ef,{stats:G,onStatusFilter:U=>{i.setStatusFilter(U)}}),e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(J,{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(Ua,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(re,{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(Et,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Jt,{}),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(se,{className:"text-sm font-medium text-gray-700",children:"All Templates"}),e.jsxs(He,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(We,{className:"h-10 w-[180px]","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Templates"}),e.jsx(X,{value:"CUSTOM",children:"Custom"}),e.jsx(X,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(X,{value:"FORM_16",children:"Form 16"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(se,{className:"text-sm font-medium text-gray-700",children:"Financial Year"}),e.jsxs(He,{value:i.form16FinancialYear,onValueChange:i.setForm16FinancialYear,children:[e.jsx(We,{className:"h-10 w-[140px]","data-testid":"form16-financial-year-filter",children:e.jsx(Ge,{placeholder:"Financial Year"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Years"}),e.jsx(X,{value:"2024-25",children:"2024-25"}),e.jsx(X,{value:"2023-24",children:"2023-24"}),e.jsx(X,{value:"2022-23",children:"2022-23"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(se,{className:"text-sm font-medium text-gray-700",children:"Quarter"}),e.jsxs(He,{value:i.form16Quarter,onValueChange:i.setForm16Quarter,children:[e.jsx(We,{className:"h-10 w-[130px]","data-testid":"form16-quarter-filter",children:e.jsx(Ge,{placeholder:"Quarter"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Quarters"}),e.jsx(X,{value:"Q1",children:"Q1"}),e.jsx(X,{value:"Q2",children:"Q2"}),e.jsx(X,{value:"Q3",children:"Q3"}),e.jsx(X,{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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Re,{placeholder:"Search requests...",value:i.searchTerm,onChange:U=>i.setSearchTerm(U.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(We,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Status"}),e.jsx(X,{value:"pending",children:"Pending"}),e.jsx(X,{value:"paused",children:"Paused"}),e.jsx(X,{value:"approved",children:"Approved"}),e.jsx(X,{value:"rejected",children:"Rejected"}),e.jsx(X,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(We,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"All Priority"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Priority"}),e.jsx(X,{value:"express",children:"Express"}),e.jsx(X,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(We,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Templates"}),e.jsx(X,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(X,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(X,{value:"FORM_16",children:"Form 16"})]})]}),e.jsxs(He,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:b||g.length===0,children:[e.jsx(We,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ge,{placeholder:b?"Loading...":"All Departments"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Departments"}),g.map(U=>e.jsx(X,{value:U,children:U},U))]})]}),e.jsxs(He,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(We,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"All SLA Status"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All SLA Status"}),e.jsx(X,{value:"compliant",children:"Compliant"}),e.jsx(X,{value:"on-track",children:"On Track"}),e.jsx(X,{value:"approaching",children:"Approaching"}),e.jsx(X,{value:"critical",children:"Critical"}),e.jsx(X,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(se,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:I.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:I.selectedUser.displayName||I.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:I.handleClear,children:e.jsx(yt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{placeholder:"Search initiator...",value:I.searchQuery,onChange:U=>I.handleSearch(U.target.value),onFocus:()=>{I.searchResults.length>0&&I.setShowResults(!0)},onBlur:()=>setTimeout(()=>I.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),I.showResults&&I.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:I.searchResults.map(U=>e.jsx("button",{type:"button",onClick:()=>I.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(se,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(He,{value:i.approverFilterType,onValueChange:U=>i.setApproverFilterType(U),children:[e.jsx(We,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"current",children:"Current Only"}),e.jsx(X,{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(yt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{placeholder:"Search approver...",value:D.searchQuery,onChange:U=>D.handleSearch(U.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(U=>e.jsx("button",{type:"button",onClick:()=>D.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(ft,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(We,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(aa,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ft,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${st(i.customStartDate,"MMM d, yyyy")} - ${st(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(na,{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(se,{htmlFor:"start-date",children:"Start Date"}),e.jsx(ta,{value:i.customStartDate||null,onChange:U=>{const $=U?new Date(U):void 0;$?(i.setCustomStartDate($),i.customEndDate&&$>i.customEndDate&&i.setCustomEndDate($)):i.setCustomStartDate(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"end-date",children:"End Date"}),e.jsx(ta,{value:i.customEndDate||null,onChange:U=>{const $=U?new Date(U):void 0;$?(i.setCustomEndDate($),i.customStartDate&&$<i.customStartDate&&i.setCustomStartDate($)):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(_f,{requests:C,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(Wr,{currentPage:i.currentPage||1,totalPages:y,totalRecords:S,itemsPerPage:w,onPageChange:R,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function $D({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 Ks.listParticipantRequests({page:t,limit:s,...r});let i=[];Array.isArray(n==null?void 0:n.data)?i=n.data:Array.isArray(n)&&(i=n);const l=i.filter(c=>(c.status||"").toString().toUpperCase()!=="DRAFT"),o=(n==null?void 0:n.pagination)||{page:t,limit:s,total:l.length,totalPages:1};return{data:l,allData:[],filteredData:l,pagination:{page:o.page,limit:o.limit||s,total:o.total||l.length,totalPages:o.totalPages||1}}}const jh=100;async function UD(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 Ks.listParticipantRequests({page:r,limit:jh,...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===jh}}return s}function BD({onViewRequest:t}){const s=Lf(),a=x.useMemo(()=>{try{const K=tt.getUserData();return Bc(K)}catch(K){return console.error("[UserAllRequests] Error getting user filter type:",K),"STANDARD"}},[]),r=x.useMemo(()=>d6(a),[a]),n=a==="DEALER",i=x.useCallback(()=>{const K=s.getFilters();if(!n)return K;const z=s.requestTypeFilter;if(z==="form_16")return{templateType:"FORM_16",financialYear:s.form16FinancialYear!=="all"?s.form16FinancialYear:void 0,quarter:s.form16Quarter!=="all"?s.form16Quarter:void 0};if(z==="claim_management")return{templateType:"DEALER CLAIM",search:K.search,status:K.status!=="all"?K.status:void 0,dateRange:K.dateRange,startDate:K.startDate,endDate:K.endDate,initiator:K.initiator,approver:K.approver,approverType:K.approverType};const{priority:O,templateType:V,department:Q,slaCompliance:q,...ee}=K;return ee},[s,n]),l=x.useCallback(()=>{if(n){const K=s.requestTypeFilter;return K==="form_16"?s.form16FinancialYear!=="all"||s.form16Quarter!=="all":K==="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]=x.useState([]),[d,m]=x.useState(!1),[p,u]=x.useState(!1),[h,g]=x.useState(null),[f,b]=x.useState([]),[j,y]=x.useState(!1),[N,S]=x.useState(!1),[A,w]=x.useState(1),[I,D]=x.useState(0),[T]=x.useState(10),v=ll({filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter,source:"local"}),M=ll({filterValue:s.approverFilter,onFilterChange:s.setApproverFilter,source:"local"}),P=x.useCallback(async(K,z,O,V)=>{try{const Q=await Ot.getRequestStats(K,z?z.toISOString():void 0,O?O.toISOString():void 0,void 0,V==null?void 0:V.priority,V==null?void 0:V.templateType,V==null?void 0:V.department,V==null?void 0:V.initiator,V==null?void 0:V.approver,V==null?void 0:V.approverType,V==null?void 0:V.search,V==null?void 0:V.slaCompliance,!0);g({total:Q.totalRequests||0,pending:Q.openRequests||0,paused:Q.pausedRequests||0,approved:Q.approvedRequests||0,rejected:Q.rejectedRequests||0,draft:Q.draftRequests||0,closed:Q.closedRequests||0})}catch(Q){console.error("Failed to fetch backend stats:",Q)}},[]),B=x.useCallback(async()=>{try{y(!0);const K=await Ot.getDepartments();b(K)}catch{}finally{y(!1)}},[]);x.useEffect(()=>{a==="STANDARD"&&Fc().then(K=>S(!!(K.canViewForm16Submission||K.canView26AS))).catch(()=>S(!1))},[a]);const k=x.useRef(s),_=x.useRef(P),L=x.useRef(i);x.useEffect(()=>{k.current=s,_.current=P,L.current=i},[s,P,i]);const R=x.useCallback(async(K=1)=>{try{K===1&&(m(!0),c([]));const z=L.current(),O=await $D({page:K,itemsPerPage:T,filters:z});c(O.data),s.setCurrentPage(O.pagination.page),w(O.pagination.totalPages),D(O.pagination.total)}catch{c([])}finally{m(!1)}},[T,s]),C=x.useCallback(async()=>{try{u(!0);const K=i(),z=await UD(K);await zf(z,K)}catch(K){console.error("Failed to export requests:",K),alert("Failed to export requests. Please try again.")}finally{u(!1)}},[i]);x.useEffect(()=>{B()},[B]),x.useEffect(()=>{const K=setTimeout(()=>{const z={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"&&(z.priority=s.priorityFilter),s.templateTypeFilter!=="all"&&(z.templateType=s.templateTypeFilter),s.departmentFilter!=="all"&&(z.department=s.departmentFilter),s.slaComplianceFilter!=="all"&&(z.slaCompliance=s.slaComplianceFilter));const O=s.dateRange==="all"?"all":s.dateRange||"month";_.current(O,s.customStartDate,s.customEndDate,z)},s.searchTerm?500:0);return()=>clearTimeout(K)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter,n]);const G=x.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}),U=x.useRef(!1);x.useEffect(()=>{const K=s.currentPage||1;R(K),U.current=!0},[]),x.useEffect(()=>{if(!U.current)return;const K=G.current;if(!(K.searchTerm!==s.searchTerm||K.statusFilter!==s.statusFilter||K.priorityFilter!==s.priorityFilter||K.templateTypeFilter!==s.templateTypeFilter||K.slaComplianceFilter!==s.slaComplianceFilter||K.departmentFilter!==s.departmentFilter||K.initiatorFilter!==s.initiatorFilter||K.approverFilter!==s.approverFilter||K.approverFilterType!==s.approverFilterType||K.dateRange!==s.dateRange||K.customStartDate!==s.customStartDate||K.customEndDate!==s.customEndDate))return;const O=setTimeout(()=>{s.setCurrentPage(1),R(1),G.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!==K.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 $=x.useCallback(K=>{K>=1&&K<=A&&(s.setCurrentPage(K),R(K))},[A,R,s]),F=x.useMemo(()=>Of(o),[o]),H=x.useMemo(()=>{if(h)return{total:h.total||0,pending:h.pending||0,paused:h.paused||0,approved:h.approved||0,rejected:h.rejected||0,draft:h.draft||0,closed:h.closed||0};const K=F.filter(q=>{const ee=(q.status||"").toString().toLowerCase();return ee==="pending"||ee==="in-progress"}).length,z=F.filter(q=>(q.status||"").toString().toLowerCase()==="paused").length,O=F.filter(q=>(q.status||"").toString().toLowerCase()==="approved").length,V=F.filter(q=>(q.status||"").toString().toLowerCase()==="rejected").length,Q=F.filter(q=>(q.status||"").toString().toLowerCase()==="closed").length;return{total:I>0?I:F.length,pending:K,paused:z,approved:O,rejected:V,draft:0,closed:Q}},[h,I,F]);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(Pf,{isOrgLevel:!1,isAdmin:!1,loading:d,exporting:p,onExport:C}),e.jsx(Ef,{stats:H,onStatusFilter:K=>{s.setStatusFilter(K)}}),e.jsx(r,{requestTypeFilter:s.requestTypeFilter,onRequestTypeChange:K=>s.setRequestTypeFilter(K),showForm16Filter:N,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:M,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(_f,{requests:F,loading:d,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(Wr,{currentPage:s.currentPage||1,totalPages:A,totalRecords:I,itemsPerPage:T,onPageChange:$,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function VD(){const t=Cs();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(J,{className:"p-8 text-center",children:[e.jsx(Je,{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 zD({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(qt,{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(Et,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function HD({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(ce,{className:"pb-3",children:e.jsx(de,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(J,{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(ts,{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(ia,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(Z,{children:[e.jsx(ce,{className:"pb-3",children:e.jsx(de,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(J,{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(Be,{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(ce,{className:"pb-3",children:e.jsx(de,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(J,{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(Nc,{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(ce,{className:"pb-3",children:e.jsx(de,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(J,{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(it,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function GD({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(Z,{"data-testid":"approver-actions-stats",children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Approver's Actions"}),e.jsxs(we,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?p1(a,r,n,""):"(all time)"]})]}),e.jsxs(J,{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(qt,{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(Be,{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(it,{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(wl,{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(Fe,{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(ts,{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(Oj,{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(Je,{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(qi,{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 WD({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:u,onSlaComplianceChange:h,onDateRangeChange:g,onShowCustomDatePickerChange:f,onTempStartDateChange:b,onTempEndDateChange:j,onApplyCustomDate:y,onClearFilters:N}){return e.jsxs(Z,{"data-testid":"approver-performance-filters",children:[e.jsx(ce,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{children:"Filters"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:N,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(J,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Re,{placeholder:"Search requests...",value:t,onChange:S=>m(S.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:p,children:[e.jsx(We,{"data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"Status"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Status"}),e.jsx(X,{value:"pending",children:"Pending"}),e.jsx(X,{value:"approved",children:"Approved"}),e.jsx(X,{value:"rejected",children:"Rejected"}),e.jsx(X,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:u,children:[e.jsx(We,{"data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"Priority"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Priority"}),e.jsx(X,{value:"express",children:"Express"}),e.jsx(X,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:h,children:[e.jsx(We,{"data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"SLA Compliance"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All SLA"}),e.jsx(X,{value:"compliant",children:"Compliant"}),e.jsx(X,{value:"on-track",children:"On Track"}),e.jsx(X,{value:"approaching",children:"Approaching"}),e.jsx(X,{value:"critical",children:"Critical"}),e.jsx(X,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:n,onValueChange:g,children:[e.jsx(We,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Time"}),e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"last7days",children:"Last 7 Days"}),e.jsx(X,{value:"last30days",children:"Last 30 Days"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(aa,{open:o,onOpenChange:f,children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(ft,{className:"w-4 h-4"}),c&&d?`${st(c,"MMM d")} - ${st(d,"MMM d")}`:"Select dates"]})}),e.jsx(na,{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(se,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Re,{id:"start-date",type:"date",value:c?st(c,"yyyy-MM-dd"):"",onChange:S=>{const A=S.target.value?new Date(S.target.value):void 0;A?(b(A),d&&A>d&&j(A)):b(void 0)},max:st(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Re,{id:"end-date",type:"date",value:d?st(d,"yyyy-MM-dd"):"",onChange:S=>{const A=S.target.value?new Date(S.target.value):void 0;A?(j(A),c&&A<c&&b(A)):j(void 0)},min:c?st(c,"yyyy-MM-dd"):void 0,max:st(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 YD=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Qs,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:ts,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ts,iconColor:"text-gray-600"}}},QD=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Be,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:it,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:it,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Be,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Fe,iconColor:"text-gray-600"}}},KD=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 XD(t){if(!t)return"N/A";try{return st(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function ZD(t){if(!t)return"N/A";try{return st(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function ol(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=U6(s);n(l)}function JD({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const c=Cs();return e.jsxs(Z,{"data-testid":"approver-performance-request-list",children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Request Details"}),e.jsxs(we,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(J,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(Et,{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(Fe,{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=YD(d.priority),p=QD(d.status),u=KD(d.slaStatus||""),h=m.icon,g=p.icon;return e.jsx(Z,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{ol({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(J,{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(re,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(h,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(re,{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(re,{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(Be,{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(it,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(re,{className:u.color,"data-testid":"sla-status-badge",children:u.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(Ht,{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(it,{className:"w-3 h-3"}),"Submitted: ",XD(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(Be,{className:"w-3 h-3"}),"Action: ",ZD(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(ts,{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(Nc,{className:"w-3 h-3"}),Xt(d.levelElapsedHours)," / ",Xt(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:f=>{f.stopPropagation(),ol({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(js,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(Wr,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function qD(){const[t]=xp(),[s,a]=x.useState(""),[r,n]=x.useState(t.get("status")||"all"),[i,l]=x.useState(t.get("priority")||"all"),[o,c]=x.useState(t.get("slaCompliance")||"all"),[d,m]=x.useState(t.get("dateRange")||"all"),[p,u]=x.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[h,g]=x.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[f,b]=x.useState(!1),[j,y]=x.useState(void 0),[N,S]=x.useState(void 0),A=x.useCallback(()=>{a(""),n("all"),l("all"),c("all"),m("all"),u(void 0),g(void 0),y(void 0),S(void 0),b(!1)},[]),w=x.useCallback(D=>{const T=D;m(T),T!=="custom"?(u(void 0),g(void 0),y(void 0),S(void 0),b(!1)):(y(p),S(h),b(!0))},[p,h]),I=x.useCallback(()=>{if(j&&N){if(j>N){const D=j;u(N),g(D),y(N),S(D)}else u(j),g(N);b(!1)}},[j,N]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:d,customStartDate:p,customEndDate:h,showCustomDatePicker:f,tempCustomStartDate:j,tempCustomEndDate:N,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:u,setCustomEndDate:g,setShowCustomDatePicker:b,setTempCustomStartDate:y,setTempCustomEndDate:S,clearFilters:A,handleDateRangeChange:w,handleApplyCustomDate:I}}function eR({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:l,searchTerm:o,itemsPerPage:c}){const[d,m]=x.useState([]),[p,u]=x.useState(null),[h,g]=x.useState([]),[f,b]=x.useState(!0),[j,y]=x.useState(!1),[N,S]=x.useState(1),[A,w]=x.useState(1),[I,D]=x.useState(0),T=x.useRef(!0),v=x.useCallback(async()=>{if(t)try{const k=s==="all"?void 0:s,_=await Ot.getSingleApproverStats(t,k,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);u(_)}catch(k){console.error("[ApproverPerformance] Failed to fetch approver stats:",k),u(null)}},[t,s,a,r,i,l]),M=x.useCallback(async(k=1)=>{if(!t){b(!1);return}try{b(!0);const _=await Ot.getRequestsByApprover(t,k,c,s==="all"?void 0:s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,l!=="all"?l:void 0,o||void 0);m(_.requests),D(_.pagination.totalRecords),w(_.pagination.totalPages),S(_.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]);x.useEffect(()=>{T.current&&(T.current=!1,v(),M(1))},[]),x.useEffect(()=>{T.current||v()},[s,a,r,i,l]),x.useEffect(()=>{T.current||M(1)},[s,a,r,n,i,l,o]);const P=x.useCallback(()=>{y(!0),v(),M(1)},[v,M]),B=x.useCallback(k=>{M(k)},[M]);return{requests:d,approverStats:p,allFilteredRequests:h,loading:f,refreshing:j,currentPage:N,totalPages:A,totalRecords:I,handleRefresh:P,handlePageChange:B}}const yh=10;function tR(){const[t]=xp(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=qD(),n=eR({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:yh});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(zD,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(HD,{approverStats:n.approverStats}),n.approverStats&&e.jsx(GD,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(WD,{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(JD,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:yh,onPageChange:n.handlePageChange})]}):e.jsx(VD,{})}function sR(){const{user:t}=us(),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(J,{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(cs,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Tl,{src:(t==null?void 0:t.picture)||""}),e.jsx(ds,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),Dr(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(fs,{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:[Dr(t)&&e.jsxs(re,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(fs,{className:"w-3 h-3 mr-1"}),"Administrator"]}),In(t)&&e.jsxs(re,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(qt,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(re,{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(ce,{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(Ht,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(we,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(J,{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(va,{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(Ht,{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(Ht,{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(Ht,{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(oi,{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(ce,{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(xu,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(we,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(J,{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(Ht,{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(fc,{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(xu,{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(fs,{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(re,{variant:Dr(t)||In(t)?"default":"secondary",className:Dr(t)?"bg-yellow-400 text-slate-900":In(t)?"bg-blue-400 text-slate-900":"",children:Dr(t)?"Administrator":In(t)?"Management":"User"}),(Dr(t)||In(t))&&e.jsx(Be,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ce,{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(ft,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(we,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(J,{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(Be,{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(re,{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 Fi="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",aR="https://reflow-uat.royalenfield.com";function wo(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 rR(){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 nR(t){if(Fi.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:wo(Fi)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:wo(Fi)})}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:wo(Fi)})}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(`${aR}/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 iR(){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 rR()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await nR(s)}catch(a){throw a}}function dc({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const l=x.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(Yb,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:Le("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(Qb,{"data-slot":"slider-track",className:Le("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(Kb,{"data-slot":"slider-range",className:Le("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,c)=>e.jsx(Xb,{"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 lR({onConfigUpdate:t}){const[s,a]=x.useState([]),[r,n]=x.useState(!0),[i,l]=x.useState(null),[o,c]=x.useState(null),[d,m]=x.useState({}),[p,u]=x.useState(null);x.useEffect(()=>{h()},[]);const h=async()=>{var v,M;try{n(!0),c(null);const P=await El();a(P)}catch(P){c(((M=(v=P.response)==null?void 0:v.data)==null?void 0:M.error)||"Failed to load configurations")}finally{n(!1)}},g=async v=>{var M,P;try{l(v.configKey),c(null);const B=d[v.configKey]??v.configValue;if(v.validationRules){const k=parseFloat(B);if(v.valueType==="NUMBER"){if(v.validationRules.min!==void 0&&k<v.validationRules.min)throw new Error(`Value must be at least ${v.validationRules.min}`);if(v.validationRules.max!==void 0&&k>v.validationRules.max)throw new Error(`Value must be at most ${v.validationRules.max}`)}}await Gs(v.configKey,B),a(k=>k.map(_=>_.configKey===v.configKey?{..._,configValue:B}:_)),m(k=>{const _={...k};return delete _[v.configKey],_}),u(`${v.displayName} updated successfully`),setTimeout(()=>u(null),3e3),t&&t()}catch(B){c(B.message||((P=(M=B.response)==null?void 0:M.data)==null?void 0:P.error)||"Failed to save configuration")}finally{l(null)}},f=async v=>{var M,P;if(confirm(`Reset "${v.displayName}" to default value?`))try{l(v.configKey),c(null),await YT(v.configKey),a(B=>B.map(k=>k.configKey===v.configKey?{...k,configValue:k.defaultValue||""}:k)),m(B=>{const k={...B};return delete k[v.configKey],k}),u(`${v.displayName} reset to default`),setTimeout(()=>u(null),3e3)}catch(B){c(((P=(M=B.response)==null?void 0:M.data)==null?void 0:P.error)||"Failed to reset configuration")}finally{l(null)}},b=(v,M)=>{m(P=>({...P,[v]:M}))},j=v=>d[v.configKey]??v.configValue,y=v=>d[v.configKey]!==void 0&&d[v.configKey]!==v.configValue,N=v=>{var B,k,_,L;const M=j(v),P=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(Je,{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 ${M==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${M==="true"?"text-green-700":"text-slate-600"}`,children:M==="true"?"Enabled":"Disabled"})]}),e.jsx(os,{checked:M==="true",onCheckedChange:U=>b(v.configKey,U?"true":"false"),disabled:P})]});case"slider":const R=parseInt(M)||0,C=((B=v.validationRules)==null?void 0:B.min)||0,G=((k=v.validationRules)==null?void 0:k.max)||100;return e.jsxs("div",{className:"space-y-3 p-3 bg-slate-50 border border-slate-200 rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-lg font-semibold text-slate-900",children:[R,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",C,"-",G]})]}),e.jsx(dc,{value:[R],min:C,max:G,step:1,onValueChange:([U])=>{U!==void 0&&b(v.configKey,U.toString())},disabled:P,className:"w-full"})]});case"number":return e.jsx(Re,{type:"number",value:M,onChange:U=>b(v.configKey,U.target.value),disabled:P,min:(_=v.validationRules)==null?void 0:_.min,max:(L=v.validationRules)==null?void 0:L.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(Re,{type:"text",value:M,onChange:U=>b(v.configKey,U.target.value),disabled:P,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},S=v=>{switch(v){case"TAT_SETTINGS":return e.jsx(it,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Fe,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(_s,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(pl,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(bn,{className:"w-5 h-5"});default:return e.jsx(dr,{className:"w-5 h-5"})}},A=["DASHBOARD_LAYOUT"],w=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],I=s.filter(v=>!A.includes(v.configCategory)&&!w.includes(v.configKey)),D=I.reduce((v,M)=>(v[M.configCategory]||(v[M.configCategory]=[]),v[M.configCategory].push(M),v),{});if(Object.keys(D).forEach(v=>{const M=D[v];M&&M.sort((P,B)=>P.sortOrder-B.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ze,{className:"w-8 h-8 animate-spin text-gray-400"})});if(I.length===0)return e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(J,{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(dr,{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 T=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(Be,{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(Je,{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(yi,{defaultValue:T[0],className:"w-full",children:[e.jsx(vi,{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:T.map(v=>e.jsx($t,{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))}),T.map(v=>{var M,P,B;return e.jsx(Ut,{value:v,className:"space-y-4 mt-6",children:e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ce,{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:S(v)})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-slate-900",children:v.replace(/_/g," ")}),e.jsxs(we,{className:"text-sm",children:[((M=D[v])==null?void 0:M.length)||0," setting",(((P=D[v])==null?void 0:P.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(J,{className:"space-y-6",children:(B=D[v])==null?void 0:B.map(k=>e.jsxs("div",{className:"space-y-3 pb-6 border-b border-slate-100 last:border-b-0 last:pb-0 hover:bg-slate-50/50 -mx-6 px-6 py-4 rounded-md transition-colors",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[e.jsx(se,{className:"text-sm font-semibold text-slate-900",children:k.displayName}),y(k)&&e.jsx(re,{variant:"outline",className:"text-xs bg-gradient-to-r from-yellow-50 to-amber-50 text-yellow-800 border-yellow-400 font-medium shadow-sm",children:"Modified"}),k.requiresRestart&&e.jsx(re,{variant:"outline",className:"text-xs bg-gradient-to-r from-orange-50 to-red-50 text-orange-800 border-orange-400 font-medium shadow-sm",children:"Requires Restart"})]}),k.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:k.description}),k.defaultValue&&e.jsxs("p",{className:"text-xs text-slate-500 mt-2",children:["Default: ",e.jsx("code",{className:"px-2 py-0.5 bg-slate-100 text-slate-700 rounded-sm font-mono text-xs border border-slate-200",children:k.defaultValue})]})]})}),N(k),k.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(E,{size:"sm",onClick:()=>g(k),disabled:!y(k)||i===k.configKey,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm disabled:opacity-50 disabled:cursor-not-allowed",children:i===k.configKey?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ba,{className:"w-4 h-4"}),"Save Changes"]})}),k.defaultValue&&e.jsxs(E,{size:"sm",variant:"outline",onClick:()=>f(k),disabled:i===k.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(rp,{className:"w-4 h-4"}),"Reset to Default"]})]})]},k.configKey))})]})},v)})]})]})}function oR(){const[t,s]=x.useState([]),[a,r]=x.useState(!0),[n,i]=x.useState(new Date().getFullYear()),[l,o]=x.useState(!1),[c,d]=x.useState(null),[m,p]=x.useState(null),[u,h]=x.useState(null),[g,f]=x.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});x.useEffect(()=>{b()},[n]);const b=async()=>{var v,M;try{r(!0),p(null);const P=await XT(n);s(P)}catch(P){p(((M=(v=P.response)==null?void 0:v.data)==null?void 0:M.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)},N=()=>{if(c)return;const v=new Date;return v.setDate(v.getDate()+1),v.toISOString().split("T")[0]},S=async()=>{var v,M;try{if(p(null),!g.holidayDate||!g.holidayName){p("Holiday date and name are required");return}c?(await JT(c.holidayId,g),W.success("Holiday updated successfully")):(await ZT(g),W.success("Holiday created successfully")),await b(),o(!1),setTimeout(()=>h(null),3e3)}catch(P){p(((M=(v=P.response)==null?void 0:v.data)==null?void 0:M.error)||"Failed to save holiday")}},A=async v=>{var M,P;if(confirm(`Delete "${v.holidayName}"?`))try{p(null),await qT(v.holidayId),W.success("Holiday deleted successfully"),await b()}catch(B){const k=((P=(M=B.response)==null?void 0:M.data)==null?void 0:P.error)||"Failed to delete holiday";p(k),W.error(k)}},w=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"}},I=Array.from({length:5},(v,M)=>new Date().getFullYear()-1+M),D=t.reduce((v,M)=>{const P=new Date(M.holidayDate).toLocaleString("default",{month:"long"});return v[P]||(v[P]=[]),v[P].push(M),v},{}),T=Object.keys(D).sort((v,M)=>{const P=new Date(Date.parse(v+" 1, 2000")).getMonth(),B=new Date(Date.parse(M+" 1, 2000")).getMonth();return P-B});return e.jsxs("div",{className:"space-y-6",children:[u&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(Be,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:u})]}),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(Je,{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(ce,{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(ft,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(we,{className:"text-sm",children:"Manage organization holidays for TAT calculations"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 w-full sm:w-auto",children:[e.jsxs(He,{value:n.toString(),onValueChange:v=>i(parseInt(v)),children:[e.jsx(We,{className:"w-24 sm:w-32 border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm",children:e.jsx(Ge,{})}),e.jsx(Ye,{className:"rounded-md",children:I.map(v=>e.jsx(X,{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(ms,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Add Holiday"}),e.jsx("span",{className:"xs:hidden",children:"Add"})]})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ze,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(J,{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(ft,{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(ms,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:T.map(v=>{var M,P,B;return e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ce,{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(de,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[v," ",n]}),e.jsxs(we,{className:"text-xs sm:text-sm",children:[((M=D[v])==null?void 0:M.length)||0," holiday",(((P=D[v])==null?void 0:P.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(ft,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(J,{className:"space-y-3 pt-4",children:(B=D[v])==null?void 0:B.map(k=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 hover:border-slate-300 transition-all shadow-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-900 text-sm sm:text-base truncate",children:k.holidayName}),e.jsx(re,{variant:"outline",className:`${w(k.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:k.holidayType}),k.isRecurring&&e.jsx(re,{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:ug(k.holidayDate)}),k.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:k.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>y(k),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(qn,{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:()=>A(k),className:"gap-1.5 text-red-600 hover:text-red-700 hover:bg-red-50 border border-transparent hover:border-red-200 text-xs sm:text-sm",children:[e.jsx(Gr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},k.holidayId))})]},v)})}),e.jsx(xt,{open:l,onOpenChange:o,children:e.jsxs(dt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(ht,{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(ft,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(_t,{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(se,{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(Re,{id:"date",type:"date",value:g.holidayDate,onChange:v=>f({...g,holidayDate:v.target.value}),min:N(),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(se,{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(Re,{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(se,{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(Re,{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(se,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(He,{value:g.holidayType,onValueChange:v=>f({...g,holidayType:v}),children:[e.jsx(We,{id:"type",className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Ye,{className:"rounded-lg",children:[e.jsx(X,{value:"NATIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-red-500"}),e.jsx("span",{children:"National"})]})}),e.jsx(X,{value:"REGIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-500"}),e.jsx("span",{children:"Regional"})]})}),e.jsx(X,{value:"ORGANIZATIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-purple-500"}),e.jsx("span",{children:"Organizational"})]})}),e.jsx(X,{value:"OPTIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-500"}),e.jsx("span",{children:"Optional"})]})})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select the category of this holiday"})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gradient-to-br from-slate-50 to-slate-100/50 border-2 border-slate-200 rounded-lg hover:border-slate-300 hover:bg-slate-100 transition-all cursor-pointer group",onClick:()=>f({...g,isRecurring:!g.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:g.isRecurring,onChange: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(se,{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(Dt,{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:S,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(ft,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function cR(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function dR(){const[t,s]=x.useState(""),[a,r]=x.useState([]),[n,i]=x.useState(!1),[l,o]=x.useState(null),[c,d]=x.useState("USER"),[m,p]=x.useState(!1),[u,h]=x.useState(null),[g,f]=x.useState([]),[b,j]=x.useState(!1),[y,N]=x.useState({admins:0,management:0,users:0}),[S,A]=x.useState("ELEVATED"),[w,I]=x.useState(1),[D,T]=x.useState(1),[v,M]=x.useState(0),P=10,B=x.useRef(null),k=x.useRef(null),_=x.useCallback(cR(async O=>{var V,Q,q;if(!O||!O.startsWith("@")||O.length<2){r([]),i(!1);return}i(!0);try{const ee=O.slice(1),ue=((V=(await da.searchUsers(ee,20)).data)==null?void 0:V.data)||[];r(ue)}catch(ee){console.error("Search failed:",ee),h({type:"error",text:((q=(Q=ee.response)==null?void 0:Q.data)==null?void 0:q.message)||"Failed to search users"})}finally{i(!1)}},300),[]),L=O=>{const V=O.target.value;s(V),_(V)},R=async O=>{o(O),s(O.email),r([]);const V=g.find(Q=>Q.email.toLowerCase()===O.email.toLowerCase()||Q.userId===O.userId);if(V&&V.role)d(V.role);else try{const q=(await da.getAllUsers()).find(ee=>ee.email&&ee.email.toLowerCase()===O.email.toLowerCase()||ee.userId&&ee.userId===O.userId);q&&q.role?d(q.role):d("USER")}catch(Q){console.error("Failed to check user role:",Q),d("USER")}},C=async()=>{var O,V;if(!l||!c){h({type:"error",text:"Please select a user and role"});return}p(!0),h(null);try{await da.assignRole(l.email,c),h({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await G(),await U()}catch(Q){console.error("Role assignment failed:",Q),h({type:"error",text:((V=(O=Q.response)==null?void 0:O.data)==null?void 0:V.error)||"Failed to assign role"})}finally{p(!1)}},G=async(O=w)=>{var V,Q,q,ee,te,ue;j(!0);try{const _e=await da.getUsersByRole(S,O,P),Ze=((Q=(V=_e.data)==null?void 0:V.data)==null?void 0:Q.users)||[],Ue=(ee=(q=_e.data)==null?void 0:q.data)==null?void 0:ee.pagination,Pe=(ue=(te=_e.data)==null?void 0:te.data)==null?void 0:ue.summary;f(Ze),Ue&&(I(Ue.currentPage),T(Ue.totalPages),M(Ue.totalUsers)),Pe&&N({admins:Pe.ADMIN||0,management:Pe.MANAGEMENT||0,users:Pe.USER||0})}catch(_e){console.error("Failed to fetch users:",_e)}finally{j(!1)}},U=async()=>{var O,V,Q,q,ee,te;try{const ue=await da.getRoleStatistics(),_e=((V=(O=ue.data)==null?void 0:O.data)==null?void 0:V.statistics)||((Q=ue.data)==null?void 0:Q.statistics)||[];N({admins:parseInt(((q=_e.find(Ze=>Ze.role==="ADMIN"))==null?void 0:q.count)||"0"),management:parseInt(((ee=_e.find(Ze=>Ze.role==="MANAGEMENT"))==null?void 0:ee.count)||"0"),users:parseInt(((te=_e.find(Ze=>Ze.role==="USER"))==null?void 0:te.count)||"0")})}catch(ue){console.error("Failed to fetch statistics:",ue)}};x.useEffect(()=>{G(1),U()},[S]);const $=O=>{A(O),I(1)},F=O=>{G(O)},H=O=>{A(O),I(1),requestAnimationFrame(()=>{const V=k.current;V&&V.scrollIntoView({behavior:"smooth",block:"start"})})};x.useEffect(()=>{const O=V=>{B.current&&!B.current.contains(V.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",O),()=>{document.removeEventListener("mousedown",O)}},[a]);const K=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"}},z=O=>{switch(O){case"ADMIN":return e.jsx(sn,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(qt,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(Ht,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ce,{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($j,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(J,{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 ${S==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>H("ADMIN"),children:e.jsx(J,{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:S==="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(sn,{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 ${S==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>H("MANAGEMENT"),children:e.jsx(J,{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:S==="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(qt,{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 ${S==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>H("USER"),children:e.jsx(J,{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:S==="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(Ht,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(Jt,{}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"Assign User Role"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Search for a user in Okta and assign them a role"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",ref:B,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(Re,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:L,className:"pl-10 pr-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"user-search-input"}),n&&e.jsx(ze,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Start with @ to search users (e.g., @john)"}),a.length>0&&e.jsxs("div",{className:"border border-purple-200 rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-purple-50 px-4 py-2 border-b border-purple-100",children:e.jsxs("p",{className:"text-xs font-semibold text-purple-700",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-2",children:a.map(O=>e.jsxs("button",{onClick:()=>R(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(He,{value:c,onValueChange:O=>d(O),children:[e.jsx(We,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Ge,{placeholder:"Select role"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(X,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(X,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(E,{onClick:C,disabled:!l||m,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"assign-role-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(fs,{className:"w-4 h-4 mr-2"}),"Assign Role"]})}),u&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${u.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:[u.type==="success"?e.jsx(Be,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Je,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${u.type==="success"?"text-green-800":"text-red-800"}`,children:u.text})]})})]})]}),e.jsx(Jt,{}),e.jsxs("div",{ref:k,children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"User Management"}),e.jsxs("p",{className:"text-sm text-gray-600",children:["View and manage user roles (",v," ",S!=="ALL"&&S!=="ELEVATED"?S.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(He,{value:S,onValueChange:$,children:[e.jsx(We,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Ge,{placeholder:"Filter by role"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fs,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",y.admins+y.management,")"]})]})}),e.jsx(X,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",y.admins,")"]})]})}),e.jsx(X,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",y.management,")"]})]})}),e.jsx(X,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",y.users,")"]})]})}),e.jsx(X,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{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(ze,{className:"w-6 h-6 animate-spin text-purple-500 mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading users..."})]}):g.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(qt,{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:S==="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 ${K(O.role)} flex items-center justify-center shadow-sm`,children:z(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(re,{className:`${K(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 ",(w-1)*P+1," to ",Math.min(w*P,v)," of ",v," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>F(w-1),disabled:w===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,V)=>{let Q;return D<=5||w<=3?Q=V+1:w>=D-2?Q=D-4+V:Q=w-2+V,e.jsx(E,{variant:w===Q?"default":"outline",size:"sm",onClick:()=>F(Q),className:`w-9 h-9 p-0 ${w===Q?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${Q}-button`,children:Q},Q)})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>F(w+1),disabled:w===D,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function mR(){const[t,s]=x.useState([]),[a,r]=x.useState(!0),[n,i]=x.useState(!1),[l,o]=x.useState(null),[c,d]=x.useState(null),[m,p]=x.useState(null),[u,h]=x.useState({title:"",itemCode:"",taxationType:"",sapRefNo:"",creditPostingOn:""});x.useEffect(()=>{g()},[]);const g=async()=>{var A,w;try{r(!0),d(null);const I=await t5(!1);s(I)}catch(I){const D=((w=(A=I.response)==null?void 0:A.data)==null?void 0:w.error)||"Failed to load activity types";d(D),W.error(D)}finally{r(!1)}},f=()=>{h({title:"",itemCode:"",taxationType:"",sapRefNo:"",creditPostingOn:""}),o(null),i(!0)},b=A=>{h({title:A.title,itemCode:A.itemCode||"",taxationType:A.taxationType||"",sapRefNo:A.sapRefNo||"",creditPostingOn:A.creditPostingOn||""}),o(A),i(!0)},j=async()=>{var A,w;try{if(d(null),!u.title.trim()||!u.taxationType.trim()||!u.sapRefNo.trim()||!u.creditPostingOn.trim()){d("Title, Taxation Type, Credit Posting On, and Claim Document Type (SAP Ref) are required"),W.error("Please fill in all mandatory fields");return}const I={title:u.title.trim(),itemCode:u.itemCode.trim()||null,taxationType:u.taxationType.trim(),sapRefNo:u.sapRefNo.trim(),creditPostingOn:u.creditPostingOn.trim()};l?(await a5(l.activityTypeId,I),W.success("Activity type updated successfully")):(await s5(I),W.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>p(null),3e3)}catch(I){const D=((w=(A=I.response)==null?void 0:A.data)==null?void 0:w.error)||"Failed to save activity type";d(D),W.error(D)}},y=async A=>{var w,I;if(confirm(`Delete "${A.title}"? This will deactivate the activity type.`))try{d(null),await r5(A.activityTypeId),W.success("Activity type deleted successfully"),await g()}catch(D){const T=((I=(w=D.response)==null?void 0:w.data)==null?void 0:I.error)||"Failed to delete activity type";d(T),W.error(T)}},N=t.filter(A=>A.isActive!==!1&&A.isActive!==void 0),S=t.filter(A=>A.isActive===!1);return e.jsxs("div",{className:"space-y-6",children:[m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(Be,{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(Je,{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(ce,{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(Fe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Activity Types"}),e.jsx(we,{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(ms,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Add Activity Type"}),e.jsx("span",{className:"xs:hidden",children:"Add"})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ze,{className:"w-8 h-8 animate-spin text-gray-400"})}):N.length===0?e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(J,{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(Fe,{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(ms,{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(ce,{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(de,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Active Activity Types"}),e.jsxs(we,{className:"text-xs sm:text-sm",children:[N.length," active type",N.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-green-50 rounded-md",children:e.jsx(Be,{className:"w-4 h-4 text-green-600"})})]})}),e.jsx(J,{className:"space-y-3 pt-4",children:N.map(A=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 hover:border-slate-300 transition-all shadow-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-900 text-sm sm:text-base",children:A.title}),e.jsx(re,{variant:"outline",className:"bg-gradient-to-r from-green-50 to-emerald-50 text-green-800 border-green-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Active"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs sm:text-sm text-slate-600",children:[A.itemCode&&e.jsxs("span",{className:"font-medium",children:["Item Code: ",e.jsx("span",{className:"text-slate-900",children:A.itemCode})]}),A.taxationType&&e.jsxs("span",{className:"font-medium",children:["Taxation: ",e.jsx("span",{className:"text-slate-900",children:A.taxationType})]}),A.sapRefNo&&e.jsxs("span",{className:"font-medium",children:["SAP Ref: ",e.jsx("span",{className:"text-slate-900",children:A.sapRefNo})]}),A.creditPostingOn&&e.jsxs("span",{className:"font-medium",children:["Credit Posting On: ",e.jsx(re,{variant:"secondary",className:"ml-1 bg-slate-200 text-slate-800",children:A.creditPostingOn})]}),!A.itemCode&&!A.taxationType&&!A.sapRefNo&&!A.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(A),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(qn,{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(A),className:"gap-1.5 text-red-600 hover:text-red-700 hover:bg-red-50 border border-transparent hover:border-red-200 text-xs sm:text-sm",children:[e.jsx(Gr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},A.activityTypeId))})]}),S.length>0&&e.jsxs(Z,{className:"shadow-lg border-0 rounded-md border-amber-200",children:[e.jsx(ce,{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(de,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Inactive Activity Types"}),e.jsxs(we,{className:"text-xs sm:text-sm",children:[S.length," inactive type",S.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-amber-50 rounded-md",children:e.jsx(Je,{className:"w-4 h-4 text-amber-600"})})]})}),e.jsx(J,{className:"space-y-3 pt-4",children:S.map(A=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-amber-50/50 border border-amber-200 rounded-md hover:bg-amber-50 hover:border-amber-300 transition-all shadow-sm",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-700 text-sm sm:text-base line-through",children:A.title}),e.jsx(re,{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(A),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(qn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]})})]},A.activityTypeId))})]})]}),e.jsx(xt,{open:n,onOpenChange:i,children:e.jsxs(dt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(ht,{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(Fe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl font-semibold text-slate-900",children:l?"Edit Activity Type":"Add New Activity Type"}),e.jsx(_t,{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(se,{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(Re,{id:"title",placeholder:"e.g., Riders Mania Claims, Legal Claims Reimbursement",value:u.title,onChange:A=>h({...u,title:A.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the activity type title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{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(Re,{id:"itemCode",placeholder:"e.g., 1, 2, 3",value:u.itemCode,onChange:A=>h({...u,itemCode:A.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional item code for the activity type"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{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(He,{value:u.taxationType,onValueChange:A=>h({...u,taxationType:A}),children:[e.jsx(We,{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(Ge,{placeholder:"Select Taxation Type"})}),e.jsxs(Ye,{className:"rounded-lg",children:[e.jsx(X,{value:"GST",className:"p-3",children:"GST"}),e.jsx(X,{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(se,{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(Re,{id:"sapRefNo",placeholder:"e.g., ZCNS, ZRE",value:u.sapRefNo,onChange:A=>h({...u,sapRefNo:A.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Required SAP reference number for CSV generation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{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(He,{value:u.creditPostingOn,onValueChange:A=>h({...u,creditPostingOn:A}),children:[e.jsx(We,{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(Ge,{placeholder:"Select Credit Posting Group"})}),e.jsxs(Ye,{className:"rounded-lg",children:[e.jsx(X,{value:"Vehicles",className:"p-3",children:"Vehicles"}),e.jsx(X,{value:"Spares",className:"p-3",children:"Spares"}),e.jsx(X,{value:"GMA",className:"p-3",children:"GMA"}),e.jsx(X,{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(Dt,{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:!u.title.trim()||!u.taxationType||!u.sapRefNo.trim()||!u.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(Fe,{className:"w-4 h-4 mr-2"}),l?"Update Activity Type":"Add Activity Type"]})]})]})})]})}function Ls({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:Le("w-full caption-bottom text-sm",t),...s})})}function Os({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:Le("[&_tr]:border-b",t),...s})}function $s({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:Le("[&_tr:last-child]:border-0",t),...s})}function at({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:Le("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function Ae({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:Le("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 be({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:Le("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function uR(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function vh({emails:t,onAdd:s,onRemove:a,placeholder:r}){const[n,i]=x.useState(""),l=()=>{const o=n.trim().toLowerCase();if(o){if(!uR(o)){W.error("Please enter a valid email address");return}if(t.includes(o)){W.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(Re,{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(ms,{className:"w-4 h-4"}),"Add"]})]}),t.length>0?e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{children:[e.jsx(Ae,{children:"Email"}),e.jsx(Ae,{className:"w-[80px] text-right",children:"Actions"})]})}),e.jsx($s,{children:t.map(o=>e.jsxs(at,{children:[e.jsx(be,{className:"font-medium",children:o}),e.jsx(be,{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(Gr,{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. Access remains restricted (ADMIN always has full access by default)."})]})}function Nh(t,s){return{enabled:t,template:s}}const Co=()=>({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 xR(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState([]),[l,o]=x.useState([]),[c,d]=x.useState(!0),[m,p]=x.useState(7),[u,h]=x.useState(Co()),[g,f]=x.useState(!0),[b,j]=x.useState(0),[y,N]=x.useState(Nh(!0,"Form 16 submitted successfully. Credit note: [CreditNoteRef].")),[S,A]=x.useState(Nh(!0,"Form 16 submission was unsuccessful. Issue: [Issue]. Please review.")),[w,I]=x.useState(!0),[D,T]=x.useState(0),[v,M]=x.useState(7),[P,B]=x.useState(0),[k,_]=x.useState(24),[L,R]=x.useState("09:00"),[C,G]=x.useState("Dear [Name], please submit Form 16A for the pending period. Due: [DueDate]."),[U,$]=x.useState(!0),[F,H]=x.useState(0),[K,z]=x.useState(12),[O,V]=x.useState("10:00"),[Q,q]=x.useState("Reminder: Dear [Name], your Form 16A submission is pending for request [Request ID]. Please complete it.");x.useEffect(()=>{let te=!0;return QT().then(ue=>{if(te){if(i(ue.submissionViewerEmails??[]),o(ue.twentySixAsViewerEmails??[]),d(ue.reminderEnabled??!0),p(typeof ue.reminderDays=="number"?ue.reminderDays:7),ue.notification26AsDataAdded){const _e=ue.notification26AsDataAdded;h({enabled:_e.enabled??!0,templateRe:_e.templateRe??_e.template??Co().templateRe,templateDealers:_e.templateDealers??Co().templateDealers})}f(ue.reminder26AsUploadEnabled??!0),j(typeof ue.reminder26AsUploadAfterQuarterEndDays=="number"?ue.reminder26AsUploadAfterQuarterEndDays:0),ue.notificationForm16SuccessCreditNote&&N(ue.notificationForm16SuccessCreditNote),ue.notificationForm16Unsuccessful&&A(ue.notificationForm16Unsuccessful),I(ue.alertSubmitForm16Enabled??!0),T(typeof ue.alertSubmitForm16AfterQuarterEndDays=="number"?ue.alertSubmitForm16AfterQuarterEndDays:0),M(typeof ue.alertSubmitForm16EveryDays=="number"?ue.alertSubmitForm16EveryDays:7),B(ue.alertSubmitForm16FrequencyDays??0),_(ue.alertSubmitForm16FrequencyHours??24),R(ue.alertSubmitForm16RunAtTime!==void 0&&ue.alertSubmitForm16RunAtTime!==null?ue.alertSubmitForm16RunAtTime:"09:00"),G(ue.alertSubmitForm16Template??"Dear [Name], please submit Form 16A for the pending period. Due: [DueDate]."),$(ue.reminderNotificationEnabled??!0),H(ue.reminderFrequencyDays??0),z(ue.reminderFrequencyHours??12),V(ue.reminderRunAtTime!==void 0&&ue.reminderRunAtTime!==null?ue.reminderRunAtTime:"10:00"),q(ue.reminderNotificationTemplate??"Reminder: Dear [Name], your Form 16A submission is pending for request [Request ID]. Please complete it.")}}).catch(()=>{te&&W.error("Failed to load Form 16 configuration")}).finally(()=>{te&&s(!1)}),()=>{te=!1}},[]);const ee=async()=>{r(!0);try{await KT({submissionViewerEmails:n,twentySixAsViewerEmails:l,reminderEnabled:c,reminderDays:Math.max(1,Math.min(365,m))||7,notification26AsDataAdded:u,reminder26AsUploadEnabled:g,reminder26AsUploadAfterQuarterEndDays:Math.max(0,Math.min(365,b)),notificationForm16SuccessCreditNote:y,notificationForm16Unsuccessful:S,alertSubmitForm16Enabled:w,alertSubmitForm16AfterQuarterEndDays:Math.max(0,Math.min(365,D)),alertSubmitForm16EveryDays:Math.max(1,Math.min(365,v)),alertSubmitForm16FrequencyDays:Math.max(0,Math.min(365,P)),alertSubmitForm16FrequencyHours:Math.max(0,Math.min(168,k)),alertSubmitForm16RunAtTime:L??"",alertSubmitForm16Template:C,reminderNotificationEnabled:U,reminderFrequencyDays:Math.max(0,Math.min(365,F)),reminderFrequencyHours:Math.max(0,Math.min(168,K)),reminderRunAtTime:O??"",reminderNotificationTemplate:Q}),W.success("Form 16 configuration saved")}catch{W.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(ze,{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:[[u==null?void 0:u.enabled,y==null?void 0:y.enabled,S==null?void 0:S.enabled,w,U].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(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(hu,{className:"w-5 h-5 text-re-green"}),"Quarter calendar (how reminders/alerts work)"]}),e.jsx(we,{children:"Form 16 schedules are quarter-based. Reminders/alerts are intended to be sent after the quarter end date (quarter end + N days) if required data is missing."})]}),e.jsx(J,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"font-medium",children:"Q1"}),e.jsx("p",{className:"text-muted-foreground",children:"1 Apr – 30 Jun"})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"font-medium",children:"Q2"}),e.jsx("p",{className:"text-muted-foreground",children:"1 Jul – 30 Sep"})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"font-medium",children:"Q3"}),e.jsx("p",{className:"text-muted-foreground",children:"1 Oct – 31 Dec"})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"font-medium",children:"Q4"}),e.jsx("p",{className:"text-muted-foreground",children:"1 Jan – 31 Mar"})]})]})})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"w-5 h-5"}),"Submission data – who can see"]}),e.jsxs(we,{children:["Users with these email addresses can see Form 16 submission data. Use the ",e.jsx("strong",{children:"exact login email"})," of each user (the same email they use to sign in). ADMIN has full access by default; users not listed here do not get submission-data access unless listed in 26AS viewers."]})]}),e.jsx(J,{children:e.jsx(vh,{emails:n,onAdd:te=>i(ue=>[...ue,te].sort()),onRemove:te=>i(ue=>ue.filter(_e=>_e!==te)),placeholder:"e.g., user@royalenfield.com"})})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(hu,{className:"w-5 h-5"}),"26AS page and button – who can see"]}),e.jsxs(we,{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. ADMIN has full access by default; users not listed here cannot access 26AS."]})]}),e.jsx(J,{children:e.jsx(vh,{emails:l,onAdd:te=>o(ue=>[...ue,te].sort()),onRemove:te=>o(ue=>ue.filter(_e=>_e!==te)),placeholder:"e.g., user@royalenfield.com"})})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"w-5 h-5"}),"Reminder schedule (for dealers)"]}),e.jsx(we,{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(J,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{htmlFor:"reminder-enabled",children:"Enable reminders to dealers"}),e.jsx(os,{id:"reminder-enabled",checked:c,onCheckedChange:d})]}),e.jsxs("div",{className:"space-y-2 max-w-xs",children:[e.jsx(se,{htmlFor:"reminder-days",children:"Remind dealers every (days)"}),e.jsx(Re,{id:"reminder-days",type:"number",min:1,max:365,value:m,onChange:te=>p(parseInt(te.target.value,10)||7)})]})]})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Email and in-app notifications"}),e.jsx(we,{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(J,{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-2",children:[e.jsx("p",{className:"font-medium",children:"Reminder – upload 26AS (RE)"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Sent to:"})," RE users listed in ",e.jsx("span",{className:"font-medium text-foreground",children:"26AS viewers (RE)"}),"."," ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," Quarter end + N days if 26AS is missing for the most recently ended quarter."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{htmlFor:"re-26as-after-days",className:"text-sm whitespace-nowrap",children:"Start after (days):"}),e.jsx(Re,{id:"re-26as-after-days",type:"number",min:0,max:365,value:b,onChange:te=>j(parseInt(te.target.value||"0",10)||0),className:"w-24"})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Stops automatically once 26AS is uploaded for that quarter."})]})]}),e.jsx(os,{checked:g,onCheckedChange:f})]}),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(os,{checked:u.enabled,onCheckedChange:te=>h(ue=>({...ue,enabled:te}))})]}),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-2",children:[e.jsx("p",{className:"font-medium",children:"Reminder – submit Form 16A (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 not submitted Form 16A for the most recently ended quarter."," ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," Quarter end + N days, then repeat every X days (until submitted)."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{htmlFor:"dealer-submit-after-days",className:"text-sm whitespace-nowrap",children:"Start after (days):"}),e.jsx(Re,{id:"dealer-submit-after-days",type:"number",min:0,max:365,value:D,onChange:te=>T(parseInt(te.target.value||"0",10)||0),className:"w-24"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{htmlFor:"dealer-submit-every-days",className:"text-sm whitespace-nowrap",children:"Repeat every (days):"}),e.jsx(Re,{id:"dealer-submit-every-days",type:"number",min:1,max:365,value:v,onChange:te=>M(parseInt(te.target.value||"7",10)||7),className:"w-24"})]})]})]}),e.jsx(os,{checked:w,onCheckedChange:I})]}),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(os,{checked:y.enabled,onCheckedChange:te=>N(ue=>({...ue,enabled:te}))})]}),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(os,{checked:S.enabled,onCheckedChange:te=>A(ue=>({...ue,enabled:te}))})]}),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(se,{htmlFor:"reminder-run-at",className:"text-sm whitespace-nowrap",children:"Run daily at (optional):"}),e.jsx(Re,{id:"reminder-run-at",type:"time",value:O,onChange:te=>V(te.target.value),className:"w-28"}),O?e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>V(""),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(se,{htmlFor:"reminder-freq-days",className:"text-sm whitespace-nowrap",children:"Frequency (days):"}),e.jsx(Re,{id:"reminder-freq-days",type:"number",min:0,max:365,value:F,onChange:te=>H(Math.max(0,parseInt(te.target.value,10)||0)),className:"w-20"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{htmlFor:"reminder-freq-hours",className:"text-sm whitespace-nowrap",children:"Hours:"}),e.jsx(Re,{id:"reminder-freq-hours",type:"number",min:0,max:168,value:K,onChange:te=>z(Math.max(0,parseInt(te.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(os,{checked:U,onCheckedChange:$})]})]})})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(E,{onClick:ee,disabled:a,className:"bg-re-green hover:bg-re-green/90 gap-2",children:[a?e.jsx(ze,{className:"w-4 h-4 animate-spin"}):e.jsx(Ba,{className:"w-4 h-4"}),"Save Form 16 configuration"]})})]})}function hR(){const[t,s]=x.useState([]),[a,r]=x.useState(!0),[n,i]=x.useState(!1),[l,o]=x.useState(null),[c,d]=x.useState(null),[m,p]=x.useState(1),[u,h]=x.useState(1),[g,f]=x.useState(0),[b]=x.useState(10),[j,y]=x.useState(""),[N,S]=x.useState(""),[A,w]=x.useState({code:"",type:"HSN",gstRate:"",description:"",isActive:!0});x.useEffect(()=>{const B=setTimeout(()=>{S(j),p(1)},500);return()=>clearTimeout(B)},[j]),x.useEffect(()=>{I()},[m,N]);const I=async()=>{var B,k;try{r(!0),d(null);const _=await Cf(!1,m,b,N);s(_.codes),h(_.pagination.totalPages),f(_.pagination.totalRecords)}catch(_){const L=((k=(B=_.response)==null?void 0:B.data)==null?void 0:k.error)||"Failed to load HSN/SAC codes";d(L),W.error(L)}finally{r(!1)}},D=()=>{w({code:"",type:"HSN",gstRate:"",description:"",isActive:!0}),o(null),i(!0)},T=B=>{var k;w({code:B.code,type:B.type,gstRate:((k=B.gstRate)==null?void 0:k.toString())||"",description:B.description||"",isActive:B.isActive}),o(B),i(!0)},v=async()=>{var B,k;try{if(d(null),!A.code.trim()||!A.type){d("Code and Type are required"),W.error("Please fill in required fields");return}const{isValid:_,message:L}=ba(A.code,A.type==="SAC");if(!_){d(L),W.error(L);return}const R={code:A.code.trim(),type:A.type,gstRate:A.gstRate?parseFloat(A.gstRate):void 0,description:A.description.trim()||void 0,isActive:A.isActive};l?(await x4(l.id,R),W.success(`${A.type} code updated successfully`)):(await u4(R),W.success(`${A.type} code created successfully`)),await I(),i(!1)}catch(_){const L=((k=(B=_.response)==null?void 0:B.data)==null?void 0:k.error)||"Failed to save code";d(L),W.error(L)}},M=async B=>{var k,_;if(confirm(`Delete ${B.type} code "${B.code}"?`))try{d(null),await h4(B.id),W.success("Code deleted successfully"),await I()}catch(L){const R=((_=(k=L.response)==null?void 0:k.data)==null?void 0:_.error)||"Failed to delete code";d(R),W.error(R)}},P=async B=>{try{await p4(B),await I(),W.success("Status updated successfully")}catch{W.error("Failed to toggle status")}};return e.jsxs("div",{className:"space-y-6",children:[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(Je,{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(ce,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between 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(Mo,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"HSN/SAC Codes"}),e.jsxs(we,{className:"text-xs sm:text-sm",children:["Manage HSN/SAC codes and associated GST rates (",g," total)"]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-3 w-full lg:w-auto",children:[e.jsxs("div",{className:"relative flex-1 sm:w-64",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(Re,{placeholder:"Search code or description...",value:j,onChange:B=>y(B.target.value),className:"pl-9 bg-slate-50 border-slate-200 focus:bg-white transition-all text-sm"})]}),e.jsxs(E,{onClick:D,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm whitespace-nowrap",children:[e.jsx(ms,{className:"w-4 h-4"}),e.jsx("span",{children:"Add New Code"})]})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ze,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(J,{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:N?e.jsx(Uj,{className:"w-10 h-10 text-slate-400"}):e.jsx(Mo,{className:"w-10 h-10 text-slate-400"})}),e.jsx("p",{className:"text-slate-700 font-medium text-lg",children:N?`No results for "${N}"`:"No HSN/SAC codes found"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:N?"Try a different search term":"Add codes to use in dealer claims"}),N?e.jsx(E,{onClick:()=>y(""),variant:"outline",children:"Clear Search"}):e.jsxs(E,{onClick:D,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50",children:[e.jsx(ms,{className:"w-4 h-4"}),"Add First Code"]})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.map(B=>e.jsx(pR,{code:B,onEdit:()=>T(B),onDelete:()=>M(B),onToggle:()=>P(B.id)},B.id))}),u>1&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-4 pt-4 border-t border-slate-100",children:[e.jsxs("p",{className:"text-sm text-slate-500 order-2 sm:order-1",children:["Showing ",e.jsx("span",{className:"font-medium",children:(m-1)*b+1})," to"," ",e.jsx("span",{className:"font-medium",children:Math.min(m*b,g)})," ","of ",e.jsx("span",{className:"font-medium",children:g})," results"]}),e.jsxs("div",{className:"flex items-center gap-2 order-1 sm:order-2",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>p(B=>Math.max(1,B-1)),disabled:m===1,className:"gap-1 h-9",children:[e.jsx(pn,{className:"w-4 h-4"}),e.jsx("span",{children:"Previous"})]}),e.jsx("div",{className:"flex items-center gap-1",children:[...Array(u)].map((B,k)=>{const _=k+1;return u<=7||_===1||_===u||_>=m-1&&_<=m+1?e.jsx(E,{variant:m===_?"default":"outline",size:"sm",onClick:()=>p(_),className:`w-9 h-9 p-0 ${m===_?"bg-slate-800":"text-slate-600"}`,children:_},_):_===m-2&&_>1||_===m+2&&_<u?e.jsx("span",{className:"px-1 text-slate-400",children:"..."},_):null})}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>p(B=>Math.min(u,B+1)),disabled:m===u,className:"gap-1 h-9",children:[e.jsx("span",{children:"Next"}),e.jsx(Ka,{className:"w-4 h-4"})]})]})]})]}),e.jsx(xt,{open:n,onOpenChange:i,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsxs(ht,{children:[e.jsx(mt,{children:l?"Edit Code":"Add New HSN/SAC Code"}),e.jsx(_t,{children:"Enter the details for recovery or claim code"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"type",children:["Type ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs(He,{value:A.type,onValueChange:B=>w({...A,type:B}),children:[e.jsx(We,{children:e.jsx(Ge,{placeholder:"Select type"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"HSN",children:"HSN"}),e.jsx(X,{value:"SAC",children:"SAC"})]})]})]}),e.jsxs("div",{className:"space-y-2 relative pb-5",children:[e.jsxs(se,{htmlFor:"code",children:["Code ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Re,{id:"code",placeholder:"e.g., 998311",value:A.code,onChange:B=>w({...A,code:B.target.value}),className:ba(A.code,A.type==="SAC").isValid?"":"border-red-500"}),!ba(A.code,A.type==="SAC").isValid&&A.code&&e.jsx("p",{className:"text-[10px] text-red-500 absolute left-0 bottom-0 leading-tight",children:ba(A.code,A.type==="SAC").message})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Re,{id:"description",placeholder:"Brief description of the code",value:A.description,onChange:B=>w({...A,description:B.target.value})})]})]}),e.jsxs(Dt,{children:[e.jsx(E,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(E,{onClick:v,className:"bg-re-green hover:bg-re-green/90 text-white",children:l?"Update Code":"Create Code"})]})]})})]})}function pR({code:t,onEdit:s,onDelete:a,onToggle:r}){return e.jsxs("div",{className:`p-4 rounded-lg border flex flex-col justify-between gap-4 transition-all hover:shadow-md ${t.isActive?"bg-white border-slate-200":"bg-slate-50/50 border-slate-100 grayscale-[0.5]"}`,children:[e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-md ${t.type==="HSN"?"bg-blue-50 text-blue-600":"bg-purple-50 text-purple-600"}`,children:e.jsx(Bj,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:t.type}),e.jsx("h4",{className:"font-bold text-slate-900",children:t.code})]}),t.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-1",children:t.description})]})]}),e.jsx("div",{className:"flex items-center gap-1"})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-slate-50 pt-3 mt-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-slate-400 hover:text-blue-600 hover:bg-blue-50",onClick:s,children:e.jsx(qn,{className:"w-4 h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-slate-400 hover:text-red-600 hover:bg-red-50",onClick:a,children:e.jsx(Gr,{className:"w-4 h-4"})})]}),e.jsx(E,{variant:"ghost",size:"sm",className:`text-[10px] font-bold uppercase tracking-widest ${t.isActive?"text-amber-600":"text-green-600"}`,onClick:r,children:t.isActive?"Deactivate":"Activate"})]})]})}function gR({open:t,onClose:s,success:a,message:r}){return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(_t,{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(Be,{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(Dt,{children:e.jsx(E,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const fR=async()=>(await ve.get("/user/preferences/notifications")).data.data,bR=async t=>(await ve.put("/user/preferences/notifications",t)).data.data;function jR({open:t,onClose:s}){const[a,r]=x.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=x.useState(!0),[l,o]=x.useState(null),[c,d]=x.useState(null),[m,p]=x.useState(null);x.useEffect(()=>{t&&u()},[t]);const u=async()=>{var g,f;try{i(!0),p(null);const b=await fR();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)}},h=async(g,f)=>{var b,j;try{o(g),p(null),d(null);const y={[g]:f},N=await bR(y);r(N),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"),u()}finally{o(null)}};return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(ht,{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(dr,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(mt,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(_t,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(Jt,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(ze,{className:"w-8 h-8 animate-spin text-gray-400"})}):e.jsxs("div",{className:"space-y-6",children:[c&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-50 border border-green-200 rounded-md animate-in fade-in slide-in-from-top-2",children:[e.jsx(Be,{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(Je,{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(va,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Receive important updates and alerts via email"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="emailNotificationsEnabled"&&e.jsx(ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(os,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:g=>h("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(se,{htmlFor:"push-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Push Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Get instant browser notifications for real-time updates"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="pushNotificationsEnabled"&&e.jsx(ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(os,{id:"push-notifications-modal",checked:a.pushNotificationsEnabled,onCheckedChange:g=>h("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(Ys,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"inapp-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"View notifications in the notification center"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="inAppNotificationsEnabled"&&e.jsx(ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(os,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>h("inAppNotificationsEnabled",g),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx(Jt,{}),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 yR(){const t=Cs(),{user:s}=us(),a=Dr(s),[r,n]=x.useState(!1),[i,l]=x.useState(!1),[o,c]=x.useState(),[d,m]=x.useState(!1),[p,u]=x.useState(!1),[h,g]=x.useState(!1),[f,b]=x.useState(!0),[j,y]=x.useState(!1),[N,S]=x.useState(!1),[A,w]=x.useState(!1);x.useEffect(()=>{I()},[]);const I=async()=>{try{b(!0);const T=await Lv();g(T.length>0)}catch(T){console.error("Failed to check subscription status:",T),g(!1)}finally{b(!1)}},D=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 T=Notification.permission;if(T==="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(T==="default"&&(T=await Notification.requestPermission(),T==="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(T!=="granted"){l(!1),c("Notification permission is required to enable push notifications. Please grant permission and try again."),n(!0),m(!1);return}await iR(),l(!0),c("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),n(!0),await I()}catch(T){console.error("[Settings] Error enabling notifications:",T),l(!1);const v=(T==null?void 0:T.message)||"Unknown error occurred";c(v.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":v.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":v.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${v}`),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(J,{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(dr,{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(yi,{defaultValue:"user",className:"w-full",children:[e.jsxs(vi,{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($t,{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(dr,{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($t,{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(fs,{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($t,{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(dp,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs($t,{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(ft,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Holidays"}),e.jsx("span",{className:"sm:hidden",children:"Holidays"})]}),e.jsxs($t,{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(Fe,{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(Ut,{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(ce,{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(de,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(J,{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..."})}):h?e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-md",children:e.jsx("p",{className:"text-xs text-green-800 font-medium",children:"✓ This browser is already registered for push notifications."})}):e.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-md",children:e.jsx("p",{className:"text-xs text-blue-800",children:"Click below to register this browser for receiving push notifications. This needs to be done once per browser/device."})}),e.jsxs(E,{onClick:D,disabled:d||h,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(_s,{className:`w-4 h-4 mr-2 ${d?"animate-pulse":""}`}),d?"Registering...":h?"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(ce,{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(or,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(J,{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(or,{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(ce,{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(pu,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(J,{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(ce,{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(fs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(J,{children:e.jsxs(E,{onClick:()=>u(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(fs,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(Ut,{value:"roles",className:"mt-0",children:e.jsx(dR,{})}),e.jsx(Ut,{value:"system",className:"mt-0",children:e.jsx(lR,{})}),e.jsx(Ut,{value:"holidays",className:"mt-0",children:e.jsx(oR,{})}),e.jsx(Ut,{value:"templates",className:"mt-0",children:N?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ce,{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:()=>S(!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(Fe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Form 16 Administration"}),e.jsx(we,{className:"text-sm",children:"Configure Form 16 access, who can view submission data and 26AS, and notification settings"})]})]})})})}),e.jsx(xR,{})]}):j?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ce,{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(Fe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Dealer Claim Activity Settings"}),e.jsx(we,{className:"text-sm",children:"Manage activity types for dealer claim workflows"})]})]})})})}),e.jsx(mR,{})]}):A?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ce,{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:()=>w(!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(Fe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"HSN/SAC Code Configuration"}),e.jsx(we,{className:"text-sm",children:"Manage HSN/SAC codes and associated GST rates"})]})]})})})}),e.jsx(hR,{})]}):e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ce,{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(Fe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Template Settings"}),e.jsx(we,{className:"text-sm",children:"Manage templates and activity types for workflows"})]})]})}),e.jsx(J,{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(J,{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(Fe,{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:()=>S(!0),children:e.jsx(J,{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(Fe,{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(Z,{className:"shadow-md hover:shadow-lg transition-all duration-300 border border-slate-200 rounded-lg cursor-pointer group",onClick:()=>w(!0),children:e.jsx(J,{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-re-green to-teal-600 rounded-lg shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Fe,{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-re-green transition-colors",children:"HSN/SAC Code Configuration"}),e.jsx("p",{className:"text-sm text-slate-600 mt-1",children:"Manage HSN/SAC codes for recoveries and claims"})]})]}),e.jsx("div",{className:"text-slate-400 group-hover:text-re-green 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(ce,{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(de,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(J,{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..."})}):h?e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-md",children:e.jsx("p",{className:"text-xs text-green-800 font-medium",children:"✓ This browser is already registered for push notifications."})}):e.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-md",children:e.jsx("p",{className:"text-xs text-blue-800",children:"Click below to register this browser for receiving push notifications. This needs to be done once per browser/device."})}),e.jsxs(E,{onClick:D,disabled:d||h,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(_s,{className:`w-4 h-4 mr-2 ${d?"animate-pulse":""}`}),d?"Registering...":h?"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(ce,{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(or,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(J,{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(or,{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(ce,{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(pu,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(J,{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(ce,{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(fs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(J,{children:e.jsxs(E,{onClick:()=>u(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(fs,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(gR,{open:r,onClose:()=>n(!1),success:i,message:o}),e.jsx(jR,{open:p,onClose:()=>u(!1)})]})}const vR=kc("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 NR({className:t,variant:s,...a}){return e.jsx("div",{"data-slot":"alert",role:"alert",className:Le(vR({variant:s}),t),...a})}function wR({className:t,...s}){return e.jsx("div",{"data-slot":"alert-title",className:Le("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",t),...s})}function CR({className:t,...s}){return e.jsx("div",{"data-slot":"alert-description",className:Le("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",t),...s})}function SR(){const[t,s]=x.useState([]),[a,r]=x.useState(!0),[n,i]=x.useState(!1),[l,o]=x.useState(""),[c,d]=x.useState(""),[m,p]=x.useState(null),[u,h]=x.useState(!1),[g,f]=x.useState(!1),[b,j]=x.useState(null);x.useEffect(()=>{y()},[]);const y=async()=>{try{r(!0);const D=await ve.get("/api-tokens");s(D.data.data.tokens)}catch(D){console.error("Failed to fetch API tokens:",D),W.error("Failed to load API tokens")}finally{r(!1)}},N=async()=>{if(l.trim())try{h(!0);const D={name:l};c&&(D.expiresInDays=Number(c));const T=await ve.post("/api-tokens",D);p(T.data.data.token),W.success("API Token created successfully"),y()}catch(D){console.error("Failed to create token:",D),W.error("Failed to create API token")}finally{h(!1)}},S=D=>{j(D)},A=async()=>{if(b)try{await ve.delete(`/api-tokens/${b.id}`),W.success("Token revoked successfully"),s(t.filter(D=>D.id!==b.id)),j(null)}catch(D){console.error("Failed to revoke token:",D),W.error("Failed to revoke token")}},w=()=>{m&&(navigator.clipboard.writeText(m),f(!0),setTimeout(()=>f(!1),2e3),W.success("Token copied to clipboard"))},I=()=>{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(ms,{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(mp,{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(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{children:[e.jsx(Ae,{children:"Name"}),e.jsx(Ae,{children:"Prefix"}),e.jsx(Ae,{children:"Last Used"}),e.jsx(Ae,{children:"Expires"}),e.jsx(Ae,{className:"text-right",children:"Actions"})]})}),e.jsx($s,{children:t.map(D=>e.jsxs(at,{children:[e.jsx(be,{className:"font-medium",children:D.name}),e.jsxs(be,{className:"font-mono text-xs bg-slate-100 rounded px-2 py-1 w-fit",children:[D.prefix,"..."]}),e.jsx(be,{className:"text-gray-500 text-sm",children:D.lastUsedAt?st(new Date(D.lastUsedAt),"MMM d, yyyy"):"Never"}),e.jsx(be,{className:"text-gray-500 text-sm",children:D.expiresAt?st(new Date(D.expiresAt),"MMM d, yyyy"):"No Expiry"}),e.jsx(be,{className:"text-right",children:e.jsxs(E,{variant:"ghost",size:"sm",onClick:()=>S(D),className:"text-red-600 hover:text-red-700 hover:bg-red-50",children:[e.jsx(Gr,{className:"w-4 h-4"}),e.jsx("span",{className:"sr-only",children:"Revoke"})]})})]},D.id))})]})}),e.jsx(xt,{open:n,onOpenChange:D=>!D&&I(),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsx(mt,{children:"Generate API Token"}),e.jsx(_t,{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(NR,{className:"bg-green-50 border-green-200",children:[e.jsx($a,{className:"h-4 w-4 text-green-600"}),e.jsx(wR,{className:"text-green-800",children:"Token Generated Successfully"}),e.jsx(CR,{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:w,children:g?e.jsx($a,{className:"w-4 h-4 text-green-500"}):e.jsx(Vj,{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(se,{htmlFor:"token-name",children:"Token Name"}),e.jsx(Re,{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(se,{htmlFor:"token-expiry",children:"Expiration (Days)"}),e.jsx(Re,{id:"token-expiry",type:"number",min:"1",placeholder:"Leave empty for no expiry",value:c,onChange:D=>{const T=D.target.value;if(T==="")d("");else{const v=parseInt(T);!isNaN(v)&&v>=1&&d(v)}}})]})]}),e.jsx(Dt,{children:m?e.jsx(E,{onClick:I,children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",onClick:I,children:"Cancel"}),e.jsx(E,{onClick:N,disabled:!l.trim()||u,children:u?"Generating...":"Generate Token"})]})})]})}),e.jsx(Ip,{open:!!b,onOpenChange:D=>!D&&j(null),children:e.jsxs(Rc,{children:[e.jsxs(Ep,{children:[e.jsx(Mp,{children:"Revoke API Token"}),e.jsxs(Lp,{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(_p,{children:[e.jsx($p,{children:"Cancel"}),e.jsx(Op,{onClick:A,className:"bg-red-600 hover:bg-red-700 text-white",children:"Revoke Token"})]})]})})]})}function AR(){const t=Cs();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(ce,{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(or,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{children:"Password"}),e.jsx(we,{children:"Manage your sign-in password"})]})]})}),e.jsx(J,{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(ce,{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(mp,{className:"w-5 h-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(de,{children:"API Tokens"}),e.jsx(we,{children:"Manage personal access tokens for external integrations"})]})]})}),e.jsx(J,{children:e.jsx(SR,{})})]})]})]})}function TR({onNavigate:t}){const[s,a]=x.useState([]),[r,n]=x.useState(!0),[i,l]=x.useState(1),[o,c]=x.useState(1),[d,m]=x.useState(0),[p,u]=x.useState("all"),[h,g]=x.useState(!1),f=20,b=async(T=i,v=p==="unread")=>{var M,P;try{n(T===1);const B=await cr.list({page:T,limit:f,unreadOnly:v}),k=((M=B.data)==null?void 0:M.notifications)||[],_=((P=B.data)==null?void 0:P.pagination)||{},L=_.total||0,R=_.totalPages||1;a(k),m(L),c(R),l(T)}catch(B){console.error("[Notifications] Failed to fetch:",B)}finally{n(!1),g(!1)}};x.useEffect(()=>{l(1),b(1,p==="unread")},[p]);const j=async T=>{var v;try{if(T.isRead||(await cr.markAsRead(T.notificationId),a(M=>M.map(P=>P.notificationId===T.notificationId?{...P,isRead:!0}:P))),T.actionUrl&&t){const M=(v=T.metadata)==null?void 0:v.requestNumber;if(M){let P=`request/${M}`;(T.notificationType==="mention"||T.notificationType==="comment"||T.notificationType==="worknote")&&(P+="?tab=worknotes"),T.notificationType==="document_added"&&(P+="?tab=documents"),t(P)}}}catch(M){console.error("[Notifications] Error handling notification click:",M)}},y=async()=>{try{g(!0),await cr.markAllAsRead(),await b(i,p==="unread")}catch(T){console.error("[Notifications] Error marking all as read:",T),g(!1)}},N=async T=>{try{await cr.delete(T),a(v=>v.filter(M=>M.notificationId!==T)),m(v=>v-1)}catch(v){console.error("[Notifications] Error deleting notification:",v)}},S=()=>{g(!0),b(i,p==="unread")},A=T=>{T<1||T>o||(l(T),b(T,p==="unread"))},w=T=>{const v="w-6 h-6";switch(T){case"mention":case"comment":return e.jsx(Ys,{className:`${v} text-blue-600`});case"worknote":return e.jsx(Fe,{className:`${v} text-purple-600`});case"document_added":return e.jsx(Fe,{className:`${v} text-teal-600`});case"assignment":return e.jsx(fl,{className:`${v} text-indigo-600`});case"approval":return e.jsx(Be,{className:`${v} text-green-600`});case"rejection":return e.jsx(St,{className:`${v} text-red-600`});case"tat_alert":return e.jsx(it,{className:`${v} text-orange-600`});case"tat_breach":return e.jsx(Je,{className:`${v} text-red-600`});case"tat_breach_initiator":return e.jsx(ss,{className:`${v} text-amber-600`});default:return e.jsx(_s,{className:`${v} text-gray-600`})}},I=T=>{switch(T==null?void 0:T.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(T=>!T.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:S,disabled:h,className:"gap-2",children:[e.jsx(Et,{className:`w-4 h-4 ${h?"animate-spin":""}`}),"Refresh"]}),D>0&&e.jsxs(E,{variant:"outline",size:"sm",onClick:y,disabled:h,className:"gap-2",children:[e.jsx(zj,{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:()=>{u("all"),l(1)},children:"All Notifications"}),e.jsxs(E,{variant:p==="unread"?"default":"outline",size:"sm",onClick:()=>{u("unread"),l(1)},children:["Unread",D>0&&e.jsx(re,{className:"ml-2 bg-red-500 text-white",children:D})]})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Recent Activity"}),e.jsx(we,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(J,{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(T=>{var v;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${T.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>j(T),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:w(T.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 ${T.isRead?"font-semibold":"font-bold"} text-gray-900`,children:T.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[T.priority&&T.priority!=="LOW"&&e.jsx(re,{variant:"outline",className:`text-xs ${I(T.priority)}`,children:T.priority}),!T.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:T.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[Wh(new Date(T.createdAt),{addSuffix:!0}),((v=T.metadata)==null?void 0:v.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",T.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:M=>{M.stopPropagation(),N(T.notificationId)},children:e.jsx(Gr,{className:"w-3.5 h-3.5"})})]})]})]})},T.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:()=>A(i-1),disabled:i===1,children:[e.jsx(pn,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,o)},(T,v)=>{let M;return o<=5||i<=3?M=v+1:i>=o-2?M=o-4+v:M=i-2+v,e.jsx(E,{variant:i===M?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>A(M),children:M},M)})}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>A(i+1),disabled:i===o,children:["Next",e.jsx(Ka,{className:"w-4 h-4"})]})]})]})]})}function kR({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(Fe,{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 Td({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:u="date-filter"}){const h=s&&a?`${st(s,"d MMM yyyy")} - ${st(a,"d MMM yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${u}-container`,children:[e.jsx(ft,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:t,onValueChange:l,"data-testid":`${u}-select`,children:[e.jsx(We,{className:"w-[160px]",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"today",children:"Today"}),e.jsx(X,{value:"week",children:"This Week"}),e.jsx(X,{value:"month",children:"This Month"}),e.jsx(X,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(aa,{open:r,onOpenChange:o,children:[e.jsx(ra,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${u}-custom-trigger`,children:[e.jsx(ft,{className:"w-4 h-4"}),h]})}),e.jsx(na,{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(se,{htmlFor:`${u}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(ta,{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:`${u}-start-date`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:`${u}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(ta,{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:`${u}-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":`${u}-apply-button`,children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:p,"data-testid":`${u}-cancel-button`,children:"Cancel"})]})]})})]})]})}function DR(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 Hf(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 Gf(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 RR(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function FR({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:u,onShowCustomDatePickerChange:h,onStartDateChange:g,onEndDateChange:f,onApplyCustomDate:b,onCancelCustomDate:j,onPageChange:y,onExport:N,onViewRequest:S}){return e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(ce,{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(Bt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(we,{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:N,disabled:p,"data-testid":"export-lifecycle-button",children:[e.jsx(Tt,{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(Td,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:u,onShowCustomDatePickerChange:h,onStartDateChange:g,onEndDateChange:f,onApply:b,onCancel:j,testIdPrefix:"lifecycle"})})]}),e.jsxs(J,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(ze,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading lifecycle data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"lifecycle-error",children:[e.jsx(Je,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"lifecycle-empty",children:e.jsx("p",{className:"text-sm",children:"No lifecycle data available"})}):e.jsx("div",{className:"space-y-4",children:t.map(A=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${A.id}`,children:e.jsx("div",{className:"p-4 bg-gradient-to-r from-gray-50 to-white hover:bg-gray-100 cursor-pointer transition-all",onClick:()=>S(A.requestId||A.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("button",{onClick:w=>{w.stopPropagation(),S(A.requestId||A.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${A.id}`,children:A.id}),e.jsx(re,{className:Hf(A.priority),"data-testid":`lifecycle-priority-${A.id}`,children:A.priority}),e.jsx(re,{className:Gf(A.status),"data-testid":`lifecycle-status-${A.id}`,children:A.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:A.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:A.initiator})," on ",A.initDate]}),A.currentStage&&!A.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",A.currentStage]})]})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Current Stage"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:A.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",A.currentLevel,"/",A.totalLevels,")"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Overall TAT"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:A.overallTAT}),A.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[A.breachCount," breach",A.breachCount>1?"es":""]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>S(A.requestId||A.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${A.id}`,children:e.jsx(Ka,{className:"w-4 h-4"})})]})]})})},A.id))}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"lifecycle-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(ze,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(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 IR({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:u,exporting:h,onDateRangeChange:g,onShowCustomDatePickerChange:f,onStartDateChange:b,onEndDateChange:j,onApplyCustomDate:y,onCancelCustomDate:N,onCategoryChange:S,onSeverityChange:A,onClearFilters:w,onPageChange:I,onExport:D,onViewRequest:T}){const v=p!=="all"||u!=="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(ce,{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(cp,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(we,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",onClick:D,disabled:h,"data-testid":"export-activity-button",children:[e.jsx(Tt,{className:"w-4 h-4"}),h?"Exporting...":"Download CSV"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(Td,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:g,onShowCustomDatePickerChange:f,onStartDateChange:b,onEndDateChange:j,onApply:y,onCancel:N,testIdPrefix:"activity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Category:"}),e.jsxs(He,{value:p,onValueChange:S,"data-testid":"activity-category-filter",children:[e.jsx(We,{className:"w-40",children:e.jsx(Ge,{placeholder:"All Categories"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Categories"}),e.jsx(X,{value:"WORKFLOW",children:"Workflow"}),e.jsx(X,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(X,{value:"DOCUMENT",children:"Document"}),e.jsx(X,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(X,{value:"SYSTEM",children:"System"}),e.jsx(X,{value:"OTHER",children:"Other"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Severity:"}),e.jsxs(He,{value:u,onValueChange:A,"data-testid":"activity-severity-filter",children:[e.jsx(We,{className:"w-40",children:e.jsx(Ge,{placeholder:"All Severities"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Severities"}),e.jsx(X,{value:"INFO",children:"Info"}),e.jsx(X,{value:"WARNING",children:"Warning"}),e.jsx(X,{value:"ERROR",children:"Error"}),e.jsx(X,{value:"CRITICAL",children:"Critical"})]})]})]}),v&&e.jsx(E,{variant:"ghost",size:"sm",onClick:w,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(J,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(ze,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading activity data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"activity-error",children:[e.jsx(Je,{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(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{className:"bg-gray-50",children:[e.jsx(Ae,{className:"font-semibold",children:"Timestamp"}),e.jsx(Ae,{className:"font-semibold",children:"User"}),e.jsx(Ae,{className:"font-semibold",children:"Action"}),e.jsx(Ae,{className:"font-semibold",children:"Details"}),e.jsx(Ae,{className:"font-semibold",children:"IP Address"}),e.jsx(Ae,{className:"font-semibold",children:"Request ID"})]})}),e.jsx($s,{children:t.map((M,P)=>e.jsxs(at,{className:"hover:bg-gray-50","data-testid":`activity-row-${P}`,children:[e.jsx(be,{className:"text-xs font-medium",children:M.timestamp}),e.jsx(be,{className:"text-sm",children:M.user}),e.jsx(be,{children:e.jsx(re,{className:DR(M.action),"data-testid":`activity-action-${P}`,children:M.action})}),e.jsx(be,{className:"text-sm text-gray-600",children:M.details}),e.jsx(be,{className:"text-xs font-mono text-gray-500",children:M.ip&&M.ip!=="N/A"?e.jsx("span",{title:M.userAgent||"",children:M.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(be,{children:M.requestId!=="-"&&M.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const B=M.requestId;B&&T(B)},className:"hover:underline","data-testid":`activity-request-link-${P}`,children:e.jsx(re,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:M.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},P))})]}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"activity-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(ze,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>I(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>I(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function PR({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:u,searchQuery:h,exporting:g,onThresholdChange:f,onThresholdBlur:b,onDateRangeChange:j,onShowCustomDatePickerChange:y,onStartDateChange:N,onEndDateChange:S,onApplyCustomDate:A,onCancelCustomDate:w,onSearchChange:I,onPageChange:D,onExport:T,onViewRequest:v}){return e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(ce,{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(Nc,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(we,{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(Re,{type:"number",min:"1",value:i,onChange:M=>f(M.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(re,{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:T,disabled:g,"data-testid":"export-aging-button",children:[e.jsx(Tt,{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(Td,{dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:p,tempCustomEndDate:u,onDateRangeChange:j,onShowCustomDatePickerChange:y,onStartDateChange:N,onEndDateChange:S,onApply:A,onCancel:w,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Re,{placeholder:"Search by Request ID, Title, or Initiator...",value:h,onChange:M=>I(M.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(J,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(ze,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading aging data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"aging-error",children:[e.jsx(Je,{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(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{className:"bg-gray-50",children:[e.jsx(Ae,{className:"font-semibold",children:"Request ID"}),e.jsx(Ae,{className:"font-semibold",children:"Title"}),e.jsx(Ae,{className:"font-semibold",children:"Initiator"}),e.jsx(Ae,{className:"font-semibold",children:"Start Date"}),e.jsx(Ae,{className:"font-semibold",children:"Days Open"}),e.jsx(Ae,{className:"font-semibold",children:"Current Stage"}),e.jsx(Ae,{className:"font-semibold",children:"Assigned To"}),e.jsx(Ae,{className:"font-semibold",children:"Priority"}),e.jsx(Ae,{className:"font-semibold",children:"Status"})]})}),e.jsx($s,{children:t.map(M=>e.jsxs(at,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${M.id}`,children:[e.jsx(be,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>v(M.requestId||M.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${M.id}`,children:M.id})}),e.jsx(be,{className:"text-sm",children:M.title}),e.jsx(be,{className:"text-sm",children:M.initiator}),e.jsx(be,{className:"text-sm text-gray-600",children:M.startDate}),e.jsx(be,{children:e.jsxs(re,{className:`${RR(M.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${M.id}`,children:[M.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(be,{className:"text-sm",children:M.currentStage}),e.jsx(be,{className:"text-sm",children:M.assignedTo&&M.assignedTo!=="N/A"?M.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(be,{children:e.jsx(re,{className:Hf(M.priority),"data-testid":`aging-priority-${M.id}`,children:M.priority})}),e.jsx(be,{children:e.jsx(re,{className:Gf(M.status),"data-testid":`aging-status-${M.id}`,children:M.status})})]},M.id))})]}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"aging-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(ze,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(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 So(t="month"){const[s,a]=x.useState(t),[r,n]=x.useState(void 0),[i,l]=x.useState(void 0),[o,c]=x.useState(!1),[d,m]=x.useState(void 0),[p,u]=x.useState(void 0),h=x.useCallback(S=>{const A=S;a(A),A!=="custom"?(n(void 0),l(void 0),m(void 0),u(void 0),c(!1)):(m(r),u(i),c(!0))},[r,i]),g=x.useCallback(()=>{if(d&&p){if(d>p){const S=d;n(p),l(S),m(p),u(S)}else n(d),l(p);c(!1)}},[d,p]),f=x.useCallback(()=>{c(!1),m(r),u(i),(!r||!i)&&(n(void 0),l(void 0),a("month"))},[r,i]),b=x.useCallback(S=>{S?(m(S),p&&S>p&&u(S)):m(void 0)},[p]),j=x.useCallback(S=>{S?(u(S),d&&S<d&&m(S)):u(void 0)},[d]),y=x.useCallback(()=>r&&i?`${st(r,"MMM d, yyyy")} - ${st(i,"MMM d, yyyy")}`:"Select dates",[r,i]),N=x.useCallback(()=>{a("month"),n(void 0),l(void 0),c(!1),m(void 0),u(void 0)},[]);return{dateRange:s,customStartDate:r,customEndDate:i,showCustomDatePicker:o,tempCustomStartDate:d,tempCustomEndDate:p,setShowCustomDatePicker:c,handleDateRangeChange:h,handleApplyCustomDate:g,handleCancelCustomDate:f,handleStartDateChange:b,handleEndDateChange:j,getDisplayDateRange:y,reset:N}}function ER(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return Xt(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${Xt(r)}`:`${a}d`}function Wf(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 Pr(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 Yf(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 _R=10;function MR({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=x.useState([]),[i,l]=x.useState(!0),[o,c]=x.useState(!1),[d,m]=x.useState(null),[p,u]=x.useState({page:1,totalPages:1,totalRecords:0}),h=x.useRef(!0),g=x.useCallback(async(f=1)=>{const b=f===1&&h.current;try{b?l(!0):c(!0),m(null);const j=await Ot.getLifecycleReport(f,_R,t,s,a),y=j.lifecycleData.map(N=>{const S=ER(N.overallTATHours);return{id:N.requestNumber,requestId:N.requestId,title:N.title,priority:N.priority||"medium",status:N.status,initiator:N.initiatorName||"Unknown",initDate:Wf(N.submissionDate),currentStage:N.currentStageName||`Level ${N.currentLevel}`,overallTAT:S,currentLevel:N.currentLevel,totalLevels:N.totalLevels,breachCount:N.breachCount||0}});n(y),u({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&&(h.current=!1)},[t,s,a]);return x.useEffect(()=>{t==="custom"&&(!s||!a)||g(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:o,error:d,pagination:p,fetchData:g}}const LR=20;function OR({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,l]=x.useState([]),[o,c]=x.useState(!0),[d,m]=x.useState(!1),[p,u]=x.useState(null),[h,g]=x.useState({page:1,totalPages:1,totalRecords:0}),f=x.useRef(!0),b=x.useCallback(async(j=1)=>{const y=j===1&&f.current;try{y?c(!0):m(!0),u(null);const N=await Ot.getActivityLogReport(j,LR,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),S=N.activities.map(A=>{const w=Yf(A.type||"",A.details),I=(A.type||"").toLowerCase()==="login"||A.requestId==="00000000-0000-0000-0000-000000000001"||A.requestId==="SYSTEM_LOGIN",D=I?A.details||"User login":A.requestTitle||A.requestNumber||A.details||"N/A";return{timestamp:A.timestamp?Wf(A.timestamp):"N/A",user:A.userName||"Unknown",action:w,details:D,ip:A.ipAddress||"N/A",userAgent:A.userAgent||null,requestId:I?"System Login":A.requestNumber||A.requestId||"-",userId:A.userId}});l(S),g({page:N.pagination.currentPage,totalPages:N.pagination.totalPages,totalRecords:N.pagination.totalRecords})}catch(N){console.error("Failed to fetch activity data:",N),u((N==null?void 0:N.message)||"Failed to load activity data")}finally{y?c(!1):m(!1)}y&&(f.current=!1)},[r,n,t,s,a]);return x.useEffect(()=>{t==="custom"&&(!s||!a)||b(1)},[r,n,t,s,a]),{activityLog:i,loading:o,loadingPage:d,error:p,pagination:h,fetchData:b}}const $R=20;function UR({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,l]=x.useState([]),[o,c]=x.useState(!0),[d,m]=x.useState(!1),[p,u]=x.useState(null),[h,g]=x.useState({page:1,totalPages:1,totalRecords:0}),f=x.useRef(!0),b=x.useCallback(async(y=1)=>{const N=y===1&&f.current;try{N?c(!0):m(!0),u(null);const S=parseInt(t,10);if(isNaN(S)||S<1){u("Please enter a valid threshold (minimum 1 day)");return}const A=await Ot.getWorkflowAgingReport(S,y,$R,s,a,r),w=A.agingData.map(I=>({id:I.requestNumber||I.requestId,requestId:I.requestId,title:I.title,initiator:I.initiatorName||"Unknown",startDate:I.submissionDate?new Date(I.submissionDate).toLocaleDateString():"N/A",daysOpen:I.daysOpen,currentStage:I.currentStageName||`Level ${I.currentLevel}`,assignedTo:I.currentApproverName||"N/A",priority:I.priority||"medium",status:I.status||"pending"}));l(w),g({page:A.pagination.currentPage,totalPages:A.pagination.totalPages,totalRecords:A.pagination.totalRecords})}catch(S){console.error("Failed to fetch aging data:",S),u((S==null?void 0:S.message)||"Failed to load aging data")}finally{N?c(!1):m(!1)}N&&(f.current=!1)},[t,s,a,r]),j=x.useMemo(()=>i.filter(y=>{var S,A,w;if(!n)return!0;const N=n.toLowerCase();return((S=y.id)==null?void 0:S.toLowerCase().includes(N))||((A=y.title)==null?void 0:A.toLowerCase().includes(N))||((w=y.initiator)==null?void 0:w.toLowerCase().includes(N))}),[i,n]);return x.useEffect(()=>{s==="custom"&&(!a||!r)||b(1)},[t,s,a,r]),{agingWorkflows:j,loading:o,loadingPage:d,error:p,pagination:h,fetchData:b}}function BR(t="7"){const[s,a]=x.useState(t),[r,n]=x.useState(null),i=x.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=x.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 VR(t,s,a){const r=await Ot.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?Pr(i.submissionDate):"N/A",c=i.closureDate?Pr(i.closureDate):"N/A",d=i.overallTATHours||0,m=d>0?(d/8).toFixed(2):"0",p=i.totalLevels||1,u=Math.min(Math.max(1,i.currentLevel||1),p),h=(l==null?void 0:l.approvals)||[];if(h.length===0){const g=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,c,p.toString(),u.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 h.forEach(g=>{const f=g.levelStartTime?Pr(g.levelStartTime):"N/A",b=g.levelEndTime||g.completedAt?Pr(g.levelEndTime||g.completedAt):"N/A",j=g.tatHours||0,y=g.tatDays||(j>0?(j/8).toFixed(2):"0");let N="N/A",S="N/A",A="N/A",w="N/A";if(g.levelStartTime){const D=new Date(g.levelStartTime);if(S=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-D.getTime())/(1e3*60*60)).toFixed(2),j>0){const M=parseFloat(S);A=Math.max(0,j-M).toFixed(2),w=(M/j*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?N=M<=j?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?N=M<=j?"On Track":"At Risk":N="N/A"}}const I=[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(),N,S,A,w];n.push(I.join(","))})}catch(l){console.error(`Failed to fetch details for request ${i.requestNumber}:`,l);const o=i.submissionDate?Pr(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),u=[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(u.join(","))}kd(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function zR(t,s,a,r,n){const i=await Ot.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=Yf(o.type||"",o.details),m=[o.timestamp?Pr(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(","))}),kd(l,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function HR(t,s,a,r){const n=await Ot.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?Pr(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(","))}),kd(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function kd(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 GR(){const[t,s]=x.useState(!1),[a,r]=x.useState(!1),[n,i]=x.useState(!1),l=x.useCallback(async(d,m,p)=>{try{s(!0),await VR(d,m,p)}catch(u){console.error("Failed to export lifecycle data:",u),alert("Failed to export lifecycle data. Please try again.")}finally{s(!1)}},[]),o=x.useCallback(async(d,m,p,u,h)=>{try{r(!0),await zR(d,m,p,u,h)}catch(g){console.error("Failed to export activity data:",g),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),c=x.useCallback(async(d,m,p,u)=>{try{i(!0),await HR(d,m,p,u)}catch(h){console.error("Failed to export aging data:",h),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 WR({onBack:t}){const s=Cs(),[a,r]=x.useState(""),[n,i]=x.useState("all"),[l,o]=x.useState("all"),c=So("month"),d=So("month"),m=So("month"),p=BR("7"),u=MR({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),h=OR({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:l}),g=UR({threshold:p.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),f=GR(),b=x.useCallback(()=>{t?t():s("/dashboard")},[t,s]),j=x.useCallback(w=>{ol({requestId:w,navigate:s})},[s]),y=x.useCallback(()=>{f.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[f,c]),N=x.useCallback(()=>{f.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,l)},[f,d,n,l]),S=x.useCallback(()=>{const w=parseInt(p.threshold,10);!isNaN(w)&&w>=1&&f.handleExportAging(w,m.dateRange,m.customStartDate,m.customEndDate)},[f,p.threshold,m]),A=x.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(kR,{onBack:b}),e.jsx(FR,{lifecycleRequests:u.lifecycleRequests,loading:u.loading,loadingPage:u.loadingPage,error:u.error,pagination:u.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:u.fetchData,onExport:y,onViewRequest:j}),e.jsx(IR,{activityLog:h.activityLog,loading:h.loading,loadingPage:h.loadingPage,error:h.error,pagination:h.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:A,onPageChange:h.fetchData,onExport:N,onViewRequest:j}),e.jsx(PR,{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:S,onViewRequest:j})]})})}function Ii({className:t,...s}){return e.jsx("div",{"data-slot":"skeleton",className:Le("bg-accent animate-pulse rounded-md",t),...s})}function YR(){const t=Cs(),[s,a]=x.useState(()=>lh()||[]),[r,n]=x.useState(()=>!lh()),[i,l]=x.useState(""),o=async()=>{try{s.length===0&&n(!0);const m=await _l();a(m||[])}catch(m){console.error("Failed to fetch templates:",m),W.error("Failed to load templates")}finally{n(!1)}};x.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(ms,{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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Re,{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(ce,{children:[e.jsx(Ii,{className:"h-6 w-3/4 mb-2"}),e.jsx(Ii,{className:"h-4 w-1/2"})]}),e.jsxs(J,{children:[e.jsx(Ii,{className:"h-4 w-full mb-2"}),e.jsx(Ii,{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(Fe,{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(ce,{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(Fe,{className:"w-5 h-5"})}),e.jsx(re,{variant:"outline",className:d(m.priority),children:m.priority})]}),e.jsx(de,{className:"line-clamp-1 text-lg",children:m.name}),e.jsx(we,{className:"line-clamp-3 min-h-[4.5rem]",children:m.description})]}),e.jsxs(J,{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(Hj,{className:"w-4 h-4 mr-2"}),"Edit"]})})]})]},m.id)})})]})}function wh(){const t=Cs(),{templateId:s}=Va(),a=!!s,[r,n]=x.useState(!1),[i,l]=x.useState(!1),{searchResults:o,searchLoading:c,searchUsersDebounced:d,clearSearch:m}=K0(),[p,u]=x.useState(""),[h,g]=x.useState({name:"",description:"",category:"General",priority:"medium",estimatedTime:"2 days",suggestedSLA:24,approvers:[]});x.useEffect(()=>{a&&s&&(async()=>{try{l(!0);const D=(await _l()).find(T=>T.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||[]}):(W.error("Template not found"),t("/admin/templates"))}catch(I){console.error("Failed to load template:",I),W.error("Failed to load template details")}finally{l(!1)}})()},[a,s,t]);const f=w=>{const{name:I,value:D}=w.target;g(T=>({...T,[I]:D}))},b=(w,I)=>{g(D=>({...D,[w]:I}))},j=w=>{if(u(w),w.startsWith("@")&&w.slice(1).length>=1){d(w,5);return}m()},y=w=>{if(h.approvers.some(I=>I.userId===w.userId)){W.error("Approver already added");return}g(I=>({...I,approvers:[...I.approvers,{userId:w.userId,name:w.displayName||w.email,email:w.email,level:I.approvers.length+1,tat:24,tatType:"hours"}]})),u(""),m()},N=w=>{const I=[...h.approvers];I.splice(w,1),I.forEach((D,T)=>D.level=T+1),g(D=>({...D,approvers:I}))},S=async w=>{if(w.preventDefault(),!h.name||!h.description){W.error("Please fill in required fields");return}if(h.approvers.length===0){W.error("Please add at least one approver");return}const I={...h,approvers:h.approvers.map(D=>({...D,tat:D.tatType==="days"?parseInt(D.tat)*24:parseInt(D.tat)}))};try{n(!0),a&&s?(await C5(s,I),W.success("Template updated successfully")):(await w5(I),W.success("Template created successfully")),t("/admin/templates")}catch(D){W.error(a?"Failed to update template":"Failed to create template"),console.error(D)}finally{n(!1)}};if(i)return e.jsx("div",{className:"flex h-96 items-center justify-center",children:e.jsx(ze,{className:"h-8 w-8 animate-spin text-gray-400"})});const A=h.name&&h.description&&h.approvers.length>0&&h.approvers.every(w=>{const I=parseInt(String(w.tat))||0,D=w.tatType==="days"?7:24;return I>=1&&I<=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:S,className:"space-y-6",children:[e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Basic Information"}),e.jsx(we,{children:"General details about the template"})]}),e.jsxs(J,{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(se,{htmlFor:"name",children:"Template Name *"}),e.jsx(Re,{id:"name",name:"name",placeholder:"e.g., Office Stationery Request",value:h.name,onChange:f,className:"border-gray-200",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"category",children:"Category"}),e.jsx("div",{className:"relative",children:e.jsx(Re,{id:"category",name:"category",placeholder:"e.g., Admin, HR, Finance",value:h.category,onChange:f,className:"border-gray-200"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description *"}),e.jsx(zs,{id:"description",name:"description",placeholder:"Describe what this request is for...",value:h.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(se,{htmlFor:"priority",children:"Default Priority"}),e.jsxs(He,{name:"priority",value:h.priority,onValueChange:w=>b("priority",w),children:[e.jsx(We,{children:e.jsx(Ge,{placeholder:"Select priority"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"low",children:"Low"}),e.jsx(X,{value:"medium",children:"Medium"}),e.jsx(X,{value:"high",children:"High"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"estimatedTime",children:"Estimated Time"}),e.jsx(Re,{id:"estimatedTime",name:"estimatedTime",placeholder:"e.g., 2 days",value:h.estimatedTime,onChange:f,className:"border-gray-200"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"suggestedSLA",children:"SLA (Hours)"}),e.jsx(Re,{id:"suggestedSLA",name:"suggestedSLA",type:"number",placeholder:"24",value:h.suggestedSLA,onChange:f,className:"border-gray-200"})]})]})]})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Approver Workflow"}),e.jsx(we,{children:"Define static approvers for this template"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[h.approvers.map((w,I)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsxs(re,{variant:"outline",className:"bg-white",children:["Level ",w.level]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:w.name}),e.jsx("div",{className:"text-sm text-gray-500",children:w.email})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(se,{htmlFor:`tat-${I}`,className:"text-xs whitespace-nowrap",children:"TAT"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Re,{id:`tat-${I}`,type:"number",className:"h-8 w-16 border-gray-200",value:w.tat||"",min:1,max:w.tatType==="days"?7:24,placeholder:w.tatType==="days"?"1":"24",onChange:D=>{if((parseInt(D.target.value)||0)<0)return;const v=[...h.approvers];v[I].tat=D.target.value,g(M=>({...M,approvers:v}))}}),e.jsxs(He,{value:w.tatType||"hours",onValueChange:D=>{const T=[...h.approvers];T[I].tatType=D,T[I].tat=1,g(v=>({...v,approvers:T}))},children:[e.jsx(We,{className:"h-8 w-20 text-xs px-2",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"hours",children:"Hours"}),e.jsx(X,{value:"days",children:"Days"})]})]})]})]})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>N(I),children:e.jsx(yt,{className:"w-4 h-4 text-gray-500 hover:text-red-600"})})]},I)),h.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(se,{children:"Add Approver"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Re,{placeholder:"Type '@' to search user by name or email...",value:p,onChange:w=>j(w.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(w=>e.jsxs("div",{className:"p-2 hover:bg-gray-50 cursor-pointer flex items-center gap-3",onClick:()=>y(w),children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{children:(w.displayName||"U").substring(0,2)})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:w.displayName}),e.jsx("div",{className:"text-xs text-gray-500",children:w.email})]})]},w.userId))]})]}),h.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(it,{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 w=h.approvers.reduce((D,T)=>{const v=Number(T.tat||0);return(T.tatType||"hours")==="days"?D+v:D+v/24},0)||0,I=Math.ceil(w);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[I," ",I===1?"Day":"Days"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Duration"})]})})()})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:h.approvers.map((w,I)=>{const D=Number(w.tat||0),v=(w.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 ",I+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[v," ",v===1?"hour":"hours"]})]})},I):null})}),(()=>{const w=h.approvers.reduce((D,T)=>{const v=Number(T.tat||0);return(T.tatType||"hours")==="days"?D+v*24:D+v},0)||0,I=Math.ceil(w/8);return w===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:[w,"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:I}),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||!A,className:"bg-re-green hover:bg-re-green/90",children:r?"Saving...":e.jsxs(e.Fragment,{children:[e.jsx(Ba,{className:"w-4 h-4 mr-2"}),a?"Update Template":"Create Template"]})})]})]})]})}function QR({template:t,formData:s,setFormData:a,documents:r,setDocuments:n}){const i=x.useRef(null),[l,o]=x.useState(null),c=h=>{h.target.files&&h.target.files.length>0&&n([...r,...Array.from(h.target.files)])},d=h=>{const g=[...r];g.splice(h,1),n(g)},m=h=>{const g=URL.createObjectURL(h);o({file:h,url:g})},p=()=>{l!=null&&l.url&&URL.revokeObjectURL(l.url),o(null)},u=h=>h.type.includes("image")||h.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(J,{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(J,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"requestTitle",children:"Request Title *"}),e.jsx(Re,{id:"requestTitle",value:s.title,onChange:h=>a({...s,title:h.target.value}),placeholder:`Request for ${t.name}`,className:"border-gray-200"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(hi,{value:s.description||"",onChange:h=>a({...s,description:h}),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(J,{className:"pt-6 space-y-4",children:[e.jsx(se,{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 h;return(h=i.current)==null?void 0:h.click()},children:[e.jsx(ys,{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((h,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(Fe,{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:h.name}),e.jsxs("p",{className:"text-xs text-gray-500",children:[(h.size/1024/1024).toFixed(2)," MB"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[u(h)&&e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>m(h),children:e.jsx(Nt,{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(yt,{className:"w-4 h-4 text-gray-500 hover:text-red-500"})})]})]},g))})]})}),l&&e.jsx(Yr,{fileName:l.file.name,fileType:l.file.type,fileUrl:l.url,fileSize:l.file.size,open:!!l,onClose:p})]})}function KR({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(Je,{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(ce,{className:"pb-3",children:e.jsx(de,{className:"text-lg",children:"Request Overview"})}),e.jsx(J,{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:_a(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(re,{variant:"secondary",className:"pl-1 pr-2 py-1 flex items-center gap-1.5 h-auto",children:[e.jsx(Fe,{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(ce,{className:"pb-3",children:e.jsx(de,{className:"text-lg",children:"Approval Workflow"})}),e.jsx(J,{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(re,{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(ce,{className:"pb-3",children:e.jsx(de,{className:"text-sm uppercase text-gray-500",children:"Properties"})}),e.jsxs(J,{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(Jt,{}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Priority"}),e.jsx(re,{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(Jt,{}),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 XR(){const{templateId:t}=Va(),s=Cs(),{user:a}=us(),[r,n]=x.useState(!0),[i,l]=x.useState(!1),[o,c]=x.useState(null),[d,m]=x.useState(1),[p,u]=x.useState([]),[h,g]=x.useState({title:"",description:""}),f=["Request Details","Review & Submit"];x.useEffect(()=>{t&&(async()=>{try{n(!0);const N=(await _l()).find(S=>S.id===t);if(N){const S={id:N.id,name:N.name,description:N.description,category:N.category,icon:Fe,estimatedTime:N.estimatedTime,commonApprovers:N.approvers.map(A=>A.name),workflowApprovers:N.approvers,suggestedSLA:N.suggestedSLA,priority:N.priority,fields:N.fields||{}};c(S),g({title:S.name,description:S.description})}else W.error("Template not found")}catch(y){console.error("Error loading template:",y),W.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:h.title,description:h.description,priorityUi:o.priority==="high"?"express":"standard",approverCount:((j=o.workflowApprovers)==null?void 0:j.length)||0,approvers:(o.workflowApprovers||[]).map(S=>({email:S.email,name:S.name,tat:S.tat,tatType:"hours"})),spectators:[],ccList:[]},N=await Uc(y,p);N&&N.id&&await dg(N.id),W.success("Request Submitted Successfully",{description:`Your request "${h.title}" has been created.`}),s("/my-requests")}catch(y){console.error("Submission failed:",y),W.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(Q0,{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(QR,{template:o,formData:h,setFormData:g,documents:p,setDocuments:u}):e.jsx(KR,{template:o,formData:h,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(Ka,{className:"w-4 h-4 ml-1"})]}):e.jsxs(e.Fragment,{children:[i?"Submitting...":"Submit Request"," ",e.jsx($a,{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(Fe,{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 ZR({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(se,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(He,{value:t,onValueChange:a,children:[e.jsx(We,{id:"default-period",children:e.jsx(Ge,{})}),e.jsx(Ye,{children:n.map(i=>e.jsx(X,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(Re,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function JR({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(os,{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(os,{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(os,{checked:a,onCheckedChange:i})]})]})}const qR=["CSV","Excel","PDF","JSON"];function eF({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(se,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:qR.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Sd,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(se,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function tF({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(Re,{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 sF(){const[t,s]=x.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{W.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Analytics & Reporting Configuration"}),e.jsx(we,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(ZR,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(Jt,{}),e.jsx(JR,{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(Jt,{}),e.jsx(eF,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(tF,{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(Ba,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const aF=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"}},rF=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function nF({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{children:[e.jsx(Ae,{children:"User"}),e.jsx(Ae,{children:"Role"}),e.jsx(Ae,{children:"Department"}),e.jsx(Ae,{children:"Status"}),e.jsx(Ae,{className:"text-right",children:"Actions"})]})}),e.jsx($s,{children:t.length===0?e.jsx(at,{children:e.jsx(be,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(at,{className:"hover:bg-muted/50",children:[e.jsx(be,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(cs,{className:"size-10",children:e.jsx(ds,{className:"bg-re-green text-white",children:rF(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(be,{children:e.jsx(re,{className:aF(n.role),children:n.role})}),e.jsx(be,{children:n.department}),e.jsx(be,{children:e.jsxs(re,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(ps,{className:"w-3 h-3 mr-1"}),n.status]})}),e.jsx(be,{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(Nl,{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(Gj,{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(Gr,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function iF({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 lF(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function oF(){const[t,s]=x.useState(""),[a,r]=x.useState([]),[n,i]=x.useState(!1),[l,o]=x.useState(null),[c,d]=x.useState("USER"),[m,p]=x.useState(!1),[u,h]=x.useState(!1),[g,f]=x.useState(null),[b,j]=x.useState([]),[y,N]=x.useState(!1),[S,A]=x.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[w,I]=x.useState("ELEVATED"),[D,T]=x.useState(1),[v,M]=x.useState(1),[P,B]=x.useState(0),k=10,_=x.useRef(null),L=x.useCallback(lF(async q=>{var ee,te,ue;if(!q||!q.startsWith("@")||q.length<2){r([]),i(!1);return}i(!0);try{const _e=q.slice(1),Ue=((ee=(await da.searchUsers(_e,20)).data)==null?void 0:ee.data)||[];r(Ue)}catch(_e){console.error("Search failed:",_e),f({type:"error",text:((ue=(te=_e.response)==null?void 0:te.data)==null?void 0:ue.message)||"Failed to search users"})}finally{i(!1)}},300),[]),R=q=>{const ee=q.target.value;s(ee),L(ee)},C=async q=>{var ee,te;try{const ue=b.find(Pe=>Pe.email.toLowerCase()===q.toLowerCase());if(ue)return ue.role;const Ue=(((te=(ee=(await da.getUsersByRole("ALL",1,1e3)).data)==null?void 0:ee.data)==null?void 0:te.users)||[]).find(Pe=>{var De;return((De=Pe.email)==null?void 0:De.toLowerCase())===q.toLowerCase()});return Ue&&Ue.role?Ue.role:null}catch(ue){return console.error("Failed to fetch user role:",ue),null}},G=async q=>{o(q),s(q.email),r([]),h(!0);try{const ee=await C(q.email);d(ee||"USER")}catch(ee){console.error("Failed to fetch user role:",ee),d("USER")}finally{h(!1)}},U=async()=>{var q,ee;if(!l||!c){f({type:"error",text:"Please select a user and role"});return}p(!0),f(null);try{await da.assignRole(l.email,c),f({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await $(),await F(),W.success("Role assigned successfully")}catch(te){console.error("Role assignment failed:",te);const ue=((ee=(q=te.response)==null?void 0:q.data)==null?void 0:ee.error)||"Failed to assign role";f({type:"error",text:ue}),W.error(ue)}finally{p(!1)}},$=async(q=D)=>{var ee,te,ue,_e,Ze,Ue;N(!0);try{const Pe=await da.getUsersByRole(w,q,k),De=((te=(ee=Pe.data)==null?void 0:ee.data)==null?void 0:te.users)||[],le=(_e=(ue=Pe.data)==null?void 0:ue.data)==null?void 0:_e.pagination,ye=(Ue=(Ze=Pe.data)==null?void 0:Ze.data)==null?void 0:Ue.summary;j(De.map(ae=>({userId:ae.userId,email:ae.email,displayName:ae.displayName||ae.email,role:ae.role||"USER",department:ae.department,designation:ae.designation,isActive:ae.isActive!==!1}))),le&&(T(le.currentPage),M(le.totalPages),B(le.totalUsers)),ye&&A(ae=>({...ae,admins:ye.ADMIN||0,management:ye.MANAGEMENT||0,users:ye.USER||0,total:(ye.ADMIN||0)+(ye.MANAGEMENT||0)+(ye.USER||0)}))}catch(Pe){console.error("Failed to fetch users:",Pe),W.error("Failed to load users")}finally{N(!1)}},F=async()=>{var q,ee,te,ue,_e,Ze;try{const Ue=await da.getRoleStatistics(),Pe=((ee=(q=Ue.data)==null?void 0:q.data)==null?void 0:ee.statistics)||((te=Ue.data)==null?void 0:te.statistics)||[],De={admins:parseInt(((ue=Pe.find(le=>le.role==="ADMIN"))==null?void 0:ue.count)||"0"),management:parseInt(((_e=Pe.find(le=>le.role==="MANAGEMENT"))==null?void 0:_e.count)||"0"),users:parseInt(((Ze=Pe.find(le=>le.role==="USER"))==null?void 0:Ze.count)||"0")};A(le=>({...le,...De,total:De.admins+De.management+De.users,active:le.active||De.admins+De.management+De.users,inactive:le.inactive||0}))}catch(Ue){console.error("Failed to fetch statistics:",Ue)}};x.useEffect(()=>{$(1),F()},[w]);const H=q=>{I(q),T(1)},K=q=>{$(q)},z=async(q,ee)=>{var te,ue;try{await da.updateUserRole(q,ee),W.success("User role updated successfully"),await $(),await F()}catch(_e){console.error("Failed to update user role:",_e),W.error(((ue=(te=_e.response)==null?void 0:te.data)==null?void 0:ue.error)||"Failed to update user role")}},O=async q=>{b.find(te=>te.userId===q)&&W.info("User status toggle functionality coming soon")},V=async q=>{const ee=b.find(te=>te.userId===q);if(ee){if(ee.role==="ADMIN"){W.error("Cannot delete admin user");return}W.info("User deletion functionality coming soon")}};x.useEffect(()=>{const q=ee=>{_.current&&!_.current.contains(ee.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",q),()=>{document.removeEventListener("mousedown",q)}},[a]);const Q={total:S.total,active:S.active,inactive:S.inactive,admins:S.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(iF,{stats:Q}),e.jsxs(Z,{children:[e.jsx(ce,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(de,{children:"Assign User Role"}),e.jsx(we,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(E,{onClick:U,disabled:!l||m,className:"bg-re-green hover:bg-re-green/90",children:m?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ms,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(J,{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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(Re,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:R,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx(ze,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Start with @ to search users (e.g., @john)"}),a.length>0&&e.jsxs("div",{className:"border rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-muted px-4 py-2 border-b",children:e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-3",children:a.map(q=>e.jsxs("button",{onClick:()=>G(q),className:"w-full text-left p-3 hover:bg-muted rounded-lg transition-colors mb-1 last:mb-0",children:[e.jsx("p",{className:"font-medium text-gray-900",children:q.displayName||q.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:q.email}),q.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[q.department,q.designation?` • ${q.designation}`:""]})]},q.userId))})]})]}),l&&e.jsx("div",{className:"border-2 border-re-green/20 bg-re-green/5 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-re-green flex items-center justify-center text-white font-bold shadow-md",children:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-gray-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[l.department,l.designation?` • ${l.designation}`:""]}),u&&e.jsxs("p",{className:"text-xs text-re-green mt-1 flex items-center gap-1",children:[e.jsx(ze,{className:"w-3 h-3 animate-spin"}),"Checking current role..."]})]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>{o(null),s(""),d("USER"),h(!1)},children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Select Role"}),e.jsxs(He,{value:c,onValueChange:q=>d(q),disabled:u,children:[e.jsx(We,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ge,{placeholder:u?"Loading current role...":"Select role"})}),e.jsxs(Ye,{className:"rounded-lg",children:[e.jsx(X,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(X,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(X,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sn,{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(Be,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Je,{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(ce,{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(de,{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(we,{children:["View and manage user accounts and roles (",P," ",w!=="ALL"&&w!=="ELEVATED"?w.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(He,{value:w,onValueChange:H,children:[e.jsx(We,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ge,{placeholder:"Filter by role"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fs,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",S.admins+S.management,")"]})]})}),e.jsx(X,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",S.admins,")"]})]})}),e.jsx(X,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",S.management,")"]})]})}),e.jsx(X,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",S.users,")"]})]})}),e.jsx(X,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",S.admins+S.management+S.users,")"]})]})})]})]})})]})}),e.jsx(J,{className:"pt-6",children:y?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(ze,{className:"w-6 h-6 animate-spin text-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(qt,{className:"w-6 h-6 text-gray-400"})}),e.jsx("p",{className:"font-medium text-gray-700",children:"No users found"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:w==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(nF,{users:b.map(q=>({id:q.userId,name:q.displayName,email:q.email,role:q.role,department:q.department||"N/A",status:q.isActive?"active":"inactive"})),onEdit:q=>{const ee=b.find(te=>te.userId===q);if(ee){const te=ee.role==="USER"?"MANAGEMENT":ee.role==="MANAGEMENT"?"ADMIN":"USER";z(q,te)}},onToggleStatus:O,onDelete:V}),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)*k+1," to ",Math.min(D*k,P)," of ",P," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>K(D-1),disabled:D===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,v)},(q,ee)=>{let te;return v<=5||D<=3?te=ee+1:D>=v-2?te=v-4+ee:te=D-2+ee,e.jsx(E,{variant:D===te?"default":"outline",size:"sm",onClick:()=>K(te),className:`w-9 h-9 p-0 ${D===te?"bg-re-green hover:bg-re-green/90":""}`,children:te},te)})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>K(D+1),disabled:D===v,children:"Next"})]})]})]})})]})]})}function cF({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ce,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hl,{className:"w-5 h-5 text-re-green"}),e.jsx(de,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(we,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(J,{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(se,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(Re,{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(it,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(Re,{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(it,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function dF({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ce,{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(de,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(we,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(J,{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(se,{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(dc,{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(se,{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(dc,{id:"reminder-threshold-2",value:[s],min:1,max:100,step:1,onValueChange:([n])=>{n!==void 0&&r(n)},className:"w-full"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ss,{className:"w-3 h-3"}),"Send escalation warning when ",s,"% of TAT elapsed"]})]})]})})]})}const On=[{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 mF({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(ce,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"w-5 h-5 text-re-green"}),e.jsx(de,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(we,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(J,{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(se,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(Re,{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(it,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(Re,{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(it,{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(se,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(He,{value:a.toString(),onValueChange:p=>l(parseInt(p)),children:[e.jsx(We,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ge,{placeholder:"Select start day"})}),e.jsx(Ye,{children:On.map(p=>e.jsx(X,{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(se,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(He,{value:r.toString(),onValueChange:p=>o(parseInt(p)),children:[e.jsx(We,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ge,{placeholder:"Select end day"})}),e.jsx(Ye,{children:On.map(p=>e.jsx(X,{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=On.find(p=>p.value===a))==null?void 0:c.label} only`:` ${(d=On.find(p=>p.value===a))==null?void 0:d.label} to ${(m=On.find(p=>p.value===r))==null?void 0:m.label}`]})})]})]})}function uF(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({expressHours:24,standardHours:72,reminderThreshold1:50,reminderThreshold2:75,workStartHour:9,workEndHour:18,workStartDay:1,workEndDay:5});x.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await El("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),W.error("Failed to load TAT configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([Gs("DEFAULT_TAT_EXPRESS_HOURS",n.expressHours.toString()),Gs("DEFAULT_TAT_STANDARD_HOURS",n.standardHours.toString()),Gs("TAT_REMINDER_THRESHOLD_1",n.reminderThreshold1.toString()),Gs("TAT_REMINDER_THRESHOLD_2",n.reminderThreshold2.toString()),Gs("WORK_START_HOUR",n.workStartHour.toString()),Gs("WORK_END_HOUR",n.workEndHour.toString()),Gs("WORK_START_DAY",n.workStartDay.toString()),Gs("WORK_END_DAY",n.workEndDay.toString())]),W.success("TAT configuration saved successfully"),await l()}catch(p){console.error("Failed to save TAT configuration:",p),W.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(J,{className:"p-12 text-center",children:[e.jsx(ze,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading TAT configuration..."})]})}):e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ce,{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(it,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(cF,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx(Jt,{}),e.jsx(mF,{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(Jt,{}),e.jsx(dF,{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(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ba,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function xF({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(os,{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(os,{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(os,{checked:a,onCheckedChange:i})]})]})}function hF({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(se,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(He,{value:t,onValueChange:a,children:[e.jsx(We,{id:"notification-frequency",children:e.jsx(Ge,{placeholder:"Select frequency"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"Immediate",children:"Immediate"}),e.jsx(X,{value:"Hourly",children:"Hourly"}),e.jsx(X,{value:"Daily",children:"Daily"}),e.jsx(X,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(Re,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function pF({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(zs,{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 gF(){const[t,s]=x.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=()=>{W.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Notification Configuration"}),e.jsx(we,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(xF,{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(Jt,{}),e.jsx(hF,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(pF,{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(Ba,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function fF({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(ce,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{className:"w-5 h-5 text-re-green"}),e.jsx(de,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(we,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(J,{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(se,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(Re,{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(ys,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(Re,{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(wl,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const bF=[{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 jF({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(ce,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vc,{className:"w-5 h-5 text-re-green"}),e.jsx(de,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(we,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:bF.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(se,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(Re,{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 yF(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({maxFileSizeMB:10,retentionDays:365,allowedFileTypes:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"});x.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await El("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),W.error("Failed to load document configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([Gs("MAX_FILE_SIZE_MB",n.maxFileSizeMB.toString()),Gs("DOCUMENT_RETENTION_DAYS",n.retentionDays.toString()),Gs("ALLOWED_FILE_TYPES",n.allowedFileTypes)]),W.success("Document policy saved successfully"),await l()}catch(p){console.error("Failed to save document configuration:",p),W.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(J,{className:"p-12 text-center",children:[e.jsx(ze,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading document policy configuration..."})]})}):e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ce,{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(Fe,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(fF,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx(Jt,{}),e.jsx(jF,{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(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ba,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function vF(){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 NF=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],wF=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 CF({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(re,{className:wF(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:NF.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Sd,{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 SF(){const[t,s]=x.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=()=>{W.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(ce,{children:[e.jsx(de,{children:"Dashboard Layout Configuration"}),e.jsx(we,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsx(vF,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(CF,{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(Ba,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}function AF({aiEnabled:t,onAiEnabledChange:s}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ce,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(up,{className:"w-5 h-5 text-re-green"}),e.jsx(de,{className:"text-base font-semibold",children:"Vertex AI Gemini Configuration"})]}),e.jsx(we,{className:"text-sm",children:"Configure AI features. Model and region are configured via environment variables."})]}),e.jsx(J,{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(os,{checked:t,onCheckedChange:s})]})})]})}function TF({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ce,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"w-5 h-5 text-re-green"}),e.jsx(de,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(we,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(J,{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(os,{checked:t,onCheckedChange:s})]})})})]})}function kF({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ce,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dp,{className:"w-5 h-5 text-re-green"}),e.jsx(de,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(we,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(J,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Length"}),e.jsx(Re,{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 DF(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({aiEnabled:!0,aiRemarkGeneration:!0,maxRemarkChars:2e3});x.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await El("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),W.error("Failed to load AI configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([Gs("AI_ENABLED",n.aiEnabled.toString()),Gs("AI_REMARK_GENERATION_ENABLED",n.aiRemarkGeneration.toString()),Gs("AI_MAX_REMARK_LENGTH",n.maxRemarkChars.toString())]),W.success("AI configuration saved successfully"),await l()}catch(p){console.error("Failed to save AI configuration:",p),W.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(J,{className:"p-12 text-center",children:[e.jsx(ze,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading AI configuration..."})]})}):e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ce,{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(pl,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Configure Vertex AI Gemini settings and enable/disable AI-powered features"})]})]})}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(AF,{aiEnabled:n.aiEnabled,onAiEnabledChange:d=>c({aiEnabled:d})}),e.jsx(Jt,{}),e.jsx(TF,{aiRemarkGeneration:n.aiRemarkGeneration,onRemarkGenerationChange:d=>c({aiRemarkGeneration:d})}),e.jsx(Jt,{}),e.jsx(kF,{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(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ba,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const Ch=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function RF({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(se,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(He,{value:t,onValueChange:a,children:[e.jsx(We,{id:"spectator-permission",children:e.jsx(Ge,{placeholder:"Select permission"})}),e.jsx(Ye,{children:Ch.map(n=>e.jsx(X,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(He,{value:s,onValueChange:r,children:[e.jsx(We,{id:"link-sharing-permission",children:e.jsx(Ge,{placeholder:"Select permission"})}),e.jsx(Ye,{children:Ch.map(n=>e.jsx(X,{value:n,children:n},n))})]})]})]})}function FF({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(os,{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(os,{checked:s,onCheckedChange:r})]})]})}function IF(){const[t,s]=x.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{W.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Workflow Sharing Policy"}),e.jsx(we,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(RF,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(Jt,{}),e.jsx(FF,{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(Ba,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function PF(){const{user:t}=us(),[s,a]=x.useState(""),[r,n]=x.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(fs,{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:()=>W.info("COB&NDC – Coming soon"),children:"COB&NDC"}),e.jsxs(re,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(fs,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]})]}),e.jsx(Jt,{}),e.jsxs(yi,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(vi,{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($t,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(qi,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs($t,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs($t,{value:"users",className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs($t,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs($t,{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($t,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs($t,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(Wj,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs($t,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(up,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs($t,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(bn,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(Ut,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(Z,{children:[e.jsx(ce,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(de,{children:"KPI Configuration"}),e.jsx(we,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(re,{className:"bg-blue-50 text-blue-700",children:[o," / ",o," KPIs Active"]})]})}),e.jsxs(J,{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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(Re,{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(Bt,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:d.name}),e.jsxs(re,{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(re,{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(Yj,{className:"w-3 h-3"}):e.jsx(Qj,{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(re,{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(Je,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},m.id))})]},d.name))]})]})}),e.jsx(Ut,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(sF,{})}),e.jsx(Ut,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(oF,{})}),e.jsx(Ut,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(uF,{})}),e.jsx(Ut,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(gF,{})}),e.jsx(Ut,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(yF,{})}),e.jsx(Ut,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(SF,{})}),e.jsx(Ut,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(DF,{})}),e.jsx(Ut,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(IF,{})})]})]})}function EF(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 Ao(t){return t==null?"–":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}const To={totalCreditNotes:0,totalAmount:0,activeDealersCount:0};function _F(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function MF(t){if(!t)return"–";try{const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString("en-IN",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}function LF(){const[t,s]=x.useState([]),[a,r]=x.useState(To),[n,i]=x.useState(!0),[l,o]=x.useState(""),[c,d]=x.useState(!1),[m,p]=x.useState(!1),[u,h]=x.useState(null),g=x.useCallback(async y=>{try{i(!0);const N=await Vp(y);s(N.creditNotes),r(N.summary??To)}catch(N){console.error("[Form16CreditNotes] Failed to fetch:",N),W.error(N instanceof Error?N.message:"Failed to load credit notes"),s([]),r(To)}finally{i(!1)}},[]);x.useEffect(()=>{g()},[g]);const f=x.useCallback(async(y,N)=>{var S;d(!0),p(!0),h(null);try{const A=await Ic(y),w=(N||`credit-note-${y}`).trim()+".csv",I=_F(A.sapResponse),D=t.find(M=>Number(M.id)===Number(y)),T=Ao((D==null?void 0:D.amount)??null),v=MF((D==null?void 0:D.issueDate)??null);h({fileName:w,row:I,meta:{amountText:T,issuedAtText:v},downloadUrl:A.url||null})}catch(A){const w=((S=A==null?void 0:A.response)==null?void 0:S.status)===409?"The credit note is being generated, wait.":A instanceof Error?A.message:"Failed to load SAP response";W.error(String(w)),d(!1)}finally{p(!1)}},[t]),b=x.useCallback(async()=>{if(!(u!=null&&u.downloadUrl)){W.error("CSV download link not available");return}window.open(u.downloadUrl,"_blank")},[u]),j=x.useMemo(()=>{if(!l.trim())return t;const y=l.trim().toLowerCase();return t.filter(N=>{var S;return N.creditNoteNumber&&N.creditNoteNumber.toLowerCase().includes(y)||N.dealerName&&N.dealerName.toLowerCase().includes(y)||N.dealerCode&&N.dealerCode.toLowerCase().includes(y)||((S=N.submission)==null?void 0:S.form16aNumber)&&N.submission.form16aNumber.toLowerCase().includes(y)})},[t,l]);return e.jsxs("div",{className:"space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full",children:[e.jsx(xt,{open:c,onOpenChange:y=>{d(y),y||h(null)},children:e.jsxs(dt,{className:"sm:max-w-2xl",children:[e.jsxs(ht,{children:[e.jsx(mt,{children:"SAP Response"}),e.jsx(_t,{children:m?"Loading SAP response CSV…":"Review SAP response details and download the CSV."})]}),m?e.jsxs("div",{className:"py-8 flex items-center justify-center gap-2 text-gray-600",children:[e.jsx(ze,{className:"w-5 h-5 animate-spin"}),"Loading SAP response…"]}):u?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-emerald-200 bg-emerald-50/70 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 text-emerald-700"}),e.jsx("p",{className:"text-xs font-semibold text-emerald-800 tracking-wide uppercase",children:"SAP Response Identifiers"})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-emerald-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-emerald-700 uppercase tracking-wide",children:"TRNS_UNIQ_NO"}),e.jsx("p",{className:"text-sm font-semibold text-emerald-900 break-all mt-1",children:u.row.TRNS_UNIQ_NO||"–"})]}),e.jsxs("div",{className:"rounded-lg border border-emerald-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-emerald-700 uppercase tracking-wide",children:"TDS_TRNS_ID"}),e.jsx("p",{className:"text-sm font-semibold text-emerald-900 break-all mt-1",children:u.row.TDS_TRNS_ID||"–"})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50/70 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Vs,{className:"w-4 h-4 text-amber-700"}),e.jsx("p",{className:"text-xs font-semibold text-amber-800 tracking-wide uppercase",children:"Credit Note Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4"})," Amount"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:u.meta.amountText})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Cl,{className:"w-4 h-4"})," Issued Date"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:u.meta.issuedAtText})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"DOC_NO"}),e.jsx("p",{className:"text-sm font-semibold text-amber-900 break-all mt-1",children:u.row.DOC_NO||"–"})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"MSG_TYP"}),e.jsx("p",{className:"text-sm font-semibold text-amber-900 break-all mt-1",children:u.row.MSG_TYP||"–"})]})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3 mt-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"MESSAGE"}),e.jsx("p",{className:"text-sm font-medium text-amber-900 break-words mt-1",children:u.row.MESSAGE||"–"})]})]})]}):e.jsx("div",{className:"py-8 text-sm text-gray-600",children:"No preview available."}),e.jsxs(Dt,{className:"gap-2 sm:gap-0",children:[e.jsx(E,{variant:"outline",onClick:()=>d(!1),children:"Close"}),e.jsxs(E,{onClick:b,disabled:!u||m||!(u!=null&&u.downloadUrl),children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),"Download CSV"]})]})]})}),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(ce,{className:"pb-3",children:[e.jsx(we,{children:"Total Credit Notes Issued"}),e.jsx(de,{className:"text-3xl",children:n?"...":a.totalCreditNotes})]})}),e.jsx(Z,{children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Total Credit Amount"}),e.jsx(de,{className:"text-3xl text-green-600",children:n?"...":Ao(a.totalAmount)})]})}),e.jsx(Z,{children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Active Dealers"}),e.jsx(de,{className:"text-3xl",children:n?"...":a.activeDealersCount})]})})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"All Credit Notes"}),e.jsx(we,{children:"Search by credit note number, dealer name, or Form 16A number"}),e.jsxs("div",{className:"relative max-w-md mt-2",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(Re,{type:"search",placeholder:"Search credit notes...",value:l,onChange:y=>o(y.target.value),className:"pl-9"})]})]}),e.jsx(J,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{children:[e.jsx(Ae,{children:"Credit Note No."}),e.jsx(Ae,{children:"Dealer Name"}),e.jsx(Ae,{children:"Form 16A No."}),e.jsx(Ae,{children:"Amount"}),e.jsx(Ae,{children:"Issue Date"}),e.jsx(Ae,{children:"Status"}),e.jsx(Ae,{className:"text-right",children:"Actions"})]})}),e.jsx($s,{children:n?e.jsx(at,{children:e.jsxs(be,{colSpan:7,className:"text-center py-12",children:[e.jsx(ze,{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..."})]})}):j.length===0?e.jsx(at,{children:e.jsxs(be,{colSpan:7,className:"text-center py-12 text-gray-500",children:[e.jsx(Mt,{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:l.trim()?"Try a different search.":"Credit notes will appear here once issued."})]})}):j.map(y=>{var N,S,A;return e.jsxs(at,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(be,{className:"font-medium",children:y.creditNoteNumber?y.creditNoteNumber.startsWith("CN")?y.creditNoteNumber:`CN #${y.creditNoteNumber}`:"–"}),e.jsx(be,{children:y.dealerName??y.dealerCode??"–"}),e.jsx(be,{children:((N=y.submission)==null?void 0:N.form16aNumber)??"–"}),e.jsx(be,{children:Ao(y.amount)}),e.jsx(be,{children:EF(y.issueDate)}),e.jsx(be,{children:e.jsx(re,{className:((S=y.status)==null?void 0:S.toLowerCase())==="issued"||((A=y.status)==null?void 0:A.toLowerCase())==="completed"?"bg-green-100 text-green-800 border-green-200":"bg-gray-100 text-gray-700 border-gray-200",children:y.status??"–"})}),e.jsx(be,{className:"text-right",children:e.jsx("div",{className:"flex items-center justify-end gap-2",children:y.sapResponseAvailable?e.jsxs(E,{variant:"outline",size:"sm",onClick:async()=>{await f(Number(y.id),y.creditNoteNumber)},children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),"View"]}):e.jsxs(E,{variant:"outline",size:"sm",onClick:async()=>{W.loading("Pulling credit note...",{id:`pull-cn-${y.id}`});try{await ve.post("/form16/sap/pull"),await g(),W.success("Refreshed.",{id:`pull-cn-${y.id}`})}catch{W.error("Failed to pull credit note",{id:`pull-cn-${y.id}`})}},children:[e.jsx(Et,{className:"w-4 h-4 mr-2"}),"Pull"]})})})]},y.id)})})]})})})]})]})]})}function ko(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 Do(t){return t==null?"–":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function OF(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function $F(t){if(!t)return"–";try{const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString("en-IN",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}function UF(){var T;const t=Cs(),{id:s}=Va(),[a,r]=x.useState(null),[n,i]=x.useState(!0),[l,o]=x.useState(!1),[c,d]=x.useState(!1),[m,p]=x.useState(!1),[u,h]=x.useState(null),[g,f]=x.useState(null);x.useEffect(()=>{const v=s?parseInt(s,10):NaN;if(Number.isNaN(v)){i(!1);return}let M=!1;return Fu(v).then(P=>{M||r(P)}).catch(P=>{M||(W.error(P instanceof Error?P.message:"Failed to load credit note"),t("/form16/credit-notes"))}).finally(()=>{M||i(!1)}),()=>{M=!0}},[s,t]);const b=()=>{W.info("Resend to dealer – integration pending")},j=async()=>{var M;const v=s?parseInt(s,10):NaN;if(!Number.isNaN(v)){o(!0);try{const P=await Fu(v);r(P),(M=P.creditNote)!=null&&M.sapResponseAvailable?W.success("Credit note is available to download."):W.info("Credit note is being generated. Please wait.")}catch(P){W.error(P instanceof Error?P.message:"Failed to pull credit note")}finally{o(!1)}}},y=async()=>{var M;const v=s?parseInt(s,10):NaN;if(!Number.isNaN(v))try{d(!0),p(!0),h(null),f(null);const P=await Ic(v),B=OF(P.sapResponse);h(B),f(P.url||null)}catch(P){const B=((M=P==null?void 0:P.response)==null?void 0:M.status)===409?"The credit note is being generated, wait.":P instanceof Error?P.message:"Failed to download";W.error(String(B))}finally{p(!1)}};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(ze,{className:"w-8 h-8 animate-spin text-teal-600"})});if(!a)return null;const{creditNote:N,dealerName:S,dealerEmail:A,dealerContact:w,dealerCreditNotes:I}=a,D=N.creditNoteNumber?N.creditNoteNumber.startsWith("CN")?N.creditNoteNumber:`CN #${N.creditNoteNumber}`:"–";return e.jsxs("div",{className:"space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full",children:[e.jsx(xt,{open:c,onOpenChange:v=>{d(v),v||(h(null),f(null))},children:e.jsxs(dt,{className:"sm:max-w-2xl",children:[e.jsxs(ht,{children:[e.jsx(mt,{children:"SAP Response"}),e.jsx(_t,{children:m?"Loading SAP response CSV…":"Review SAP response details and download the CSV."})]}),m?e.jsxs("div",{className:"py-8 flex items-center justify-center gap-2 text-gray-600",children:[e.jsx(ze,{className:"w-5 h-5 animate-spin"}),"Loading SAP response…"]}):u?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-emerald-200 bg-emerald-50/70 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 text-emerald-700"}),e.jsx("p",{className:"text-xs font-semibold text-emerald-800 tracking-wide uppercase",children:"SAP Response Identifiers"})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-emerald-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-emerald-700 uppercase tracking-wide",children:"TRNS_UNIQ_NO"}),e.jsx("p",{className:"text-sm font-semibold text-emerald-900 break-all mt-1",children:u.TRNS_UNIQ_NO||"–"})]}),e.jsxs("div",{className:"rounded-lg border border-emerald-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-emerald-700 uppercase tracking-wide",children:"TDS_TRNS_ID"}),e.jsx("p",{className:"text-sm font-semibold text-emerald-900 break-all mt-1",children:u.TDS_TRNS_ID||"–"})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50/70 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Vs,{className:"w-4 h-4 text-amber-700"}),e.jsx("p",{className:"text-xs font-semibold text-amber-800 tracking-wide uppercase",children:"Credit Note Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4"})," Amount"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:Do(N.amount)})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Cl,{className:"w-4 h-4"})," Issued Date"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:$F(N.issueDate)})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"DOC_NO"}),e.jsx("p",{className:"text-sm font-semibold text-amber-900 break-all mt-1",children:u.DOC_NO||"–"})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"MSG_TYP"}),e.jsx("p",{className:"text-sm font-semibold text-amber-900 break-all mt-1",children:u.MSG_TYP||"–"})]})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3 mt-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"MESSAGE"}),e.jsx("p",{className:"text-sm font-medium text-amber-900 break-words mt-1",children:u.MESSAGE||"–"})]})]})]}):e.jsx("div",{className:"py-8 text-sm text-gray-600",children:"No preview available."}),e.jsxs(Dt,{className:"gap-2 sm:gap-0",children:[e.jsx(E,{variant:"outline",onClick:()=>d(!1),children:"Close"}),e.jsxs(E,{onClick:()=>{if(!g){W.error("CSV download link not available");return}window.open(g,"_blank")},disabled:!u||m||!g,children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),"Download CSV"]})]})]})}),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.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(E,{variant:"outline",size:"sm",onClick:b,children:[e.jsx(va,{className:"w-4 h-4 mr-2"}),"Resend to Dealer"]})})]}),e.jsx(Z,{className:"mb-6",children:e.jsxs(J,{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:D}),e.jsx(re,{className:"bg-green-100 text-green-800 border-green-200",children:N.status??"Issued"})]}),e.jsxs("p",{className:"text-sm text-gray-500",children:["Issued on ",ko(N.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:Do(N.amount)})]})]}),e.jsx("div",{className:"flex justify-end gap-2 mt-4",children:N.sapResponseAvailable?e.jsxs(E,{variant:"outline",size:"sm",onClick:y,children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),"Download Credit Note"]}):e.jsxs(E,{variant:"outline",size:"sm",onClick:j,disabled:l,children:[l?e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Et,{className:"w-4 h-4 mr-2"}),"Pull Credit Note"]})}),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:S||"–"})]}),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:((T=N.submission)==null?void 0:T.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:A||"–"})]}),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:w||"–"})]})]})]})}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Dealer Transaction History"}),e.jsxs(we,{children:["All credit notes issued to ",S||"this dealer"]})]}),e.jsx(J,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{children:[e.jsx(Ae,{children:"Submission Date"}),e.jsx(Ae,{children:"Form 16A No."}),e.jsx(Ae,{children:"Amount"}),e.jsx(Ae,{children:"Credit Note Issued"}),e.jsx(Ae,{children:"Credit Note No."}),e.jsx(Ae,{children:"CN Issue Date"}),e.jsx(Ae,{children:"Status"})]})}),e.jsx($s,{children:I.length===0?e.jsx(at,{children:e.jsx(be,{colSpan:7,className:"text-center py-8 text-gray-500",children:"No other credit notes for this dealer"})}):I.map(v=>{var M,P;return e.jsxs(at,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(be,{children:ko(v.submittedDate)}),e.jsx(be,{children:v.form16aNumber??"–"}),e.jsx(be,{children:Do(v.amount)}),e.jsx(be,{children:e.jsx(re,{className:"bg-green-100 text-green-800 border-green-200",children:"Yes"})}),e.jsx(be,{children:v.creditNoteNumber?v.creditNoteNumber.startsWith("CN")?v.creditNoteNumber:`CN #${v.creditNoteNumber}`:"–"}),e.jsx(be,{children:ko(v.issueDate)}),e.jsx(be,{children:e.jsx(re,{className:((M=v.status)==null?void 0:M.toLowerCase())==="withdrawn"?"bg-red-50 text-red-700 border-red-200":"bg-green-100 text-green-800 border-green-200",children:((P=v.status)==null?void 0:P.toLowerCase())==="withdrawn"?"Withdrawn":"Completed"})})]},v.id)})})]})})})]})]})]})}function BF(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 Ro(t){return t==null?"–":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function VF(t){if(!t)return"–";try{const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString("en-IN",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}function zF(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}const Fo={totalDebitNotes:0,totalAmount:0,impactedDealersCount:0};function HF(){const[t,s]=x.useState([]),[a,r]=x.useState(Fo),[n,i]=x.useState(!0),[l,o]=x.useState(""),[c,d]=x.useState(!1),[m,p]=x.useState(!1),[u,h]=x.useState(null),[g,f]=x.useState(null),[b,j]=x.useState(!1),y=x.useCallback(async w=>{try{i(!0);const I=await zp(w);s(I.debitNotes),r(I.summary??Fo)}catch(I){console.error("[Form16DebitNotes] Failed to fetch:",I),W.error(I instanceof Error?I.message:"Failed to load debit notes"),s([]),r(Fo)}finally{i(!1)}},[]);x.useEffect(()=>{y()},[y]);const N=x.useMemo(()=>{if(!l.trim())return t;const w=l.trim().toLowerCase();return t.filter(I=>I.debitNoteNumber&&I.debitNoteNumber.toLowerCase().includes(w)||I.creditNoteNumber&&I.creditNoteNumber.toLowerCase().includes(w)||I.dealerName&&I.dealerName.toLowerCase().includes(w)||I.dealerCode&&I.dealerCode.toLowerCase().includes(w)||I.form16aNumber&&I.form16aNumber.toLowerCase().includes(w))},[t,l]),S=x.useCallback(async w=>{var I;d(!0),p(!0),h(null),f({amountText:Ro(w.amount),issuedAtText:VF(w.issueDate)});try{const D=await Hp(Number(w.id));h(zF(D.sapResponse))}catch(D){const T=((I=D==null?void 0:D.response)==null?void 0:I.status)===409?"The debit note is being generated, wait.":D instanceof Error?D.message:"Failed to load SAP response";W.error(String(T)),d(!1)}finally{p(!1)}},[]),A=x.useCallback(async()=>{var w;j(!0),W.loading("Pulling SAP responses...",{id:"pull-debit"});try{const I=await ve.post("/form16/sap/pull");await y();const D=(w=I.data)==null?void 0:w.data,T=typeof(D==null?void 0:D.debitProcessed)=="number"?D.debitProcessed:D==null?void 0:D.processed;typeof T=="number"&&T>0?W.success(`Pulled. ${T} debit response(s) processed. List refreshed.`,{id:"pull-debit"}):W.success("Pulled. List refreshed. (No new debit responses in folder.)",{id:"pull-debit"})}catch{W.error("Failed to pull SAP responses",{id:"pull-debit"})}finally{j(!1)}},[y]);return e.jsxs("div",{className:"space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full",children:[e.jsx(xt,{open:c,onOpenChange:w=>{d(w),w||(h(null),f(null))},children:e.jsxs(dt,{className:"sm:max-w-2xl",children:[e.jsxs(ht,{children:[e.jsx(mt,{children:"SAP Response"}),e.jsx(_t,{children:m?"Loading SAP response CSV…":"Review SAP response details."})]}),m?e.jsxs("div",{className:"py-8 flex items-center justify-center gap-2 text-gray-600",children:[e.jsx(ze,{className:"w-5 h-5 animate-spin"}),"Loading SAP response…"]}):u?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-emerald-200 bg-emerald-50/70 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 text-emerald-700"}),e.jsx("p",{className:"text-xs font-semibold text-emerald-800 tracking-wide uppercase",children:"SAP Response Identifiers"})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-emerald-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-emerald-700 uppercase tracking-wide",children:"TRNS_UNIQ_NO"}),e.jsx("p",{className:"text-sm font-semibold text-emerald-900 break-all mt-1",children:u.TRNS_UNIQ_NO||"–"})]}),e.jsxs("div",{className:"rounded-lg border border-emerald-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-emerald-700 uppercase tracking-wide",children:"TDS_TRNS_ID"}),e.jsx("p",{className:"text-sm font-semibold text-emerald-900 break-all mt-1",children:u.TDS_TRNS_ID||"–"})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50/70 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Vs,{className:"w-4 h-4 text-amber-700"}),e.jsx("p",{className:"text-xs font-semibold text-amber-800 tracking-wide uppercase",children:"Debit Note Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4"})," Amount"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:(g==null?void 0:g.amountText)??"–"})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Cl,{className:"w-4 h-4"})," Issued Date"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:(g==null?void 0:g.issuedAtText)??"–"})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"DOC_NO"}),e.jsx("p",{className:"text-sm font-semibold text-amber-900 break-all mt-1",children:u.DOC_NO||"–"})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"MSG_TYP"}),e.jsx("p",{className:"text-sm font-semibold text-amber-900 break-all mt-1",children:u.MSG_TYP||"–"})]})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3 mt-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"MESSAGE"}),e.jsx("p",{className:"text-sm font-medium text-amber-900 break-words mt-1",children:u.MESSAGE||"–"})]})]})]}):e.jsx("div",{className:"py-8 text-sm text-gray-600",children:"No preview available."}),e.jsx(Dt,{className:"gap-2 sm:gap-0",children:e.jsx(E,{variant:"outline",onClick:()=>d(!1),children:"Close"})})]})}),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:"Debit Notes"}),e.jsx("p",{className:"text-sm text-gray-600",children:"View all issued debit notes"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-6",children:[e.jsx(Z,{children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Total Debit Notes Issued"}),e.jsx(de,{className:"text-3xl",children:n?"...":a.totalDebitNotes})]})}),e.jsx(Z,{children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Total Debit Amount"}),e.jsx(de,{className:"text-3xl text-red-600",children:n?"...":Ro(a.totalAmount)})]})}),e.jsx(Z,{children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Impacted Dealers"}),e.jsx(de,{className:"text-3xl",children:n?"...":a.impactedDealersCount})]})})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"All Debit Notes"}),e.jsx(we,{children:"Search by debit note number, credit note number, dealer, or Form 16A number"}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(Re,{type:"search",placeholder:"Search debit notes...",value:l,onChange:w=>o(w.target.value),className:"pl-9"})]})]}),e.jsx(J,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{children:[e.jsx(Ae,{children:"Debit Note No."}),e.jsx(Ae,{children:"Credit Note No."}),e.jsx(Ae,{children:"Dealer"}),e.jsx(Ae,{children:"Form 16A No."}),e.jsx(Ae,{children:"Amount"}),e.jsx(Ae,{children:"Issue Date"}),e.jsx(Ae,{children:"Status"}),e.jsx(Ae,{className:"text-right",children:"Actions"})]})}),e.jsx($s,{children:n?e.jsx(at,{children:e.jsxs(be,{colSpan:8,className:"text-center py-12",children:[e.jsx(ze,{className:"w-6 h-6 animate-spin mx-auto mb-2 text-teal-600"}),e.jsx("p",{className:"text-gray-500",children:"Loading debit notes..."})]})}):N.length===0?e.jsx(at,{children:e.jsxs(be,{colSpan:8,className:"text-center py-12 text-gray-500",children:[e.jsx(Mt,{className:"w-12 h-12 mx-auto mb-3 text-gray-400"}),e.jsx("p",{children:"No debit notes found"}),e.jsx("p",{className:"text-sm mt-1",children:l.trim()?"Try a different search.":"Debit notes will appear here once issued."})]})}):N.map(w=>{var I,D;return e.jsxs(at,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(be,{className:"font-medium",children:w.debitNoteNumber??"–"}),e.jsx(be,{className:"font-medium",children:w.creditNoteNumber??"–"}),e.jsx(be,{children:w.dealerName??w.dealerCode??"–"}),e.jsx(be,{children:w.form16aNumber??"–"}),e.jsx(be,{children:Ro(w.amount)}),e.jsx(be,{children:BF(w.issueDate)}),e.jsx(be,{children:e.jsx(re,{className:((I=w.status)==null?void 0:I.toLowerCase())==="issued"||((D=w.status)==null?void 0:D.toLowerCase())==="completed"?"bg-green-100 text-green-800 border-green-200":"bg-gray-100 text-gray-700 border-gray-200",children:w.status??"–"})}),e.jsx(be,{className:"text-right",children:e.jsx("div",{className:"flex items-center justify-end gap-2",children:w.sapResponseAvailable?e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>S(w),children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"View"]}):e.jsxs(E,{variant:"outline",size:"sm",onClick:A,disabled:b,children:[b?e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Et,{className:"w-4 h-4 mr-2"}),"Pull"]})})})]},w.id)})})]})})})]})]})]})}function GF(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 WF(t){if(!t)return"–";try{const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString("en-IN",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}function Sh(t){return t==null?"–":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function YF(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function QF(t){var s;return{id:Number(t.id),type:"credit",referenceNumber:t.creditNoteNumber||"–",dealer:t.dealerName||t.dealerCode||"–",amount:t.amount,issueDate:t.issueDate,sapResponseAvailable:!!t.sapResponseAvailable,searchText:[t.creditNoteNumber,t.dealerName,t.dealerCode,(s=t.submission)==null?void 0:s.form16aNumber,"credit","cr"].filter(Boolean).join(" ").toLowerCase()}}function KF(t){return{id:Number(t.id),type:"debit",referenceNumber:t.debitNoteNumber||"–",dealer:t.dealerName||t.dealerCode||"–",amount:t.amount,issueDate:t.issueDate,sapResponseAvailable:!!t.sapResponseAvailable,searchText:[t.debitNoteNumber,t.dealerName,t.dealerCode,t.form16aNumber,"debit","db"].filter(Boolean).join(" ").toLowerCase()}}function XF(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState(""),[l,o]=x.useState([]),[c,d]=x.useState(!1),[m,p]=x.useState(!1),[u,h]=x.useState(null),g=x.useCallback(async()=>{try{s(!0);const[y,N]=await Promise.all([Vp(),zp()]),S=[...y.creditNotes.map(QF),...N.debitNotes.map(KF)].sort((A,w)=>{const I=A.issueDate?new Date(A.issueDate).getTime():0;return(w.issueDate?new Date(w.issueDate).getTime():0)-I});o(S)}catch(y){console.error("[Form16Transactions] Failed to fetch:",y),W.error(y instanceof Error?y.message:"Failed to load transactions"),o([])}finally{s(!1)}},[]);x.useEffect(()=>{g()},[g]);const f=x.useMemo(()=>{if(!n.trim())return l;const y=n.trim().toLowerCase();return l.filter(N=>N.searchText.includes(y))},[l,n]),b=x.useCallback(async y=>{d(!0),p(!0),h(null);try{const N=y.type==="credit"?await Ic(y.id):await Hp(y.id);h({type:y.type,referenceNumber:y.referenceNumber,amountText:Sh(y.amount),issuedAtText:WF(y.issueDate),row:YF(N.sapResponse)})}catch(N){const S=N instanceof Error?N.message:"Failed to load SAP response";W.error(S),d(!1)}finally{p(!1)}},[]),j=x.useCallback(async()=>{r(!0),W.loading("Pulling SAP responses...",{id:"pull-transactions"});try{await ve.post("/form16/sap/pull"),await g(),W.success("Pulled and refreshed transactions.",{id:"pull-transactions"})}catch{W.error("Failed to pull SAP responses",{id:"pull-transactions"})}finally{r(!1)}},[g]);return e.jsxs("div",{className:"space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full",children:[e.jsx(xt,{open:c,onOpenChange:y=>{d(y),y||h(null)},children:e.jsxs(dt,{className:"sm:max-w-2xl",children:[e.jsxs(ht,{children:[e.jsx(mt,{children:"SAP Response"}),e.jsx(_t,{children:m?"Loading SAP response CSV...":"Review SAP response details."})]}),m?e.jsxs("div",{className:"py-8 flex items-center justify-center gap-2 text-gray-600",children:[e.jsx(ze,{className:"w-5 h-5 animate-spin"}),"Loading SAP response..."]}):u?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-emerald-200 bg-emerald-50/70 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 text-emerald-700"}),e.jsx("p",{className:"text-xs font-semibold text-emerald-800 tracking-wide uppercase",children:"SAP Response Identifiers"})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-emerald-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-emerald-700 uppercase tracking-wide",children:"TRNS_UNIQ_NO"}),e.jsx("p",{className:"text-sm font-semibold text-emerald-900 break-all mt-1",children:u.row.TRNS_UNIQ_NO||"–"})]}),e.jsxs("div",{className:"rounded-lg border border-emerald-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-emerald-700 uppercase tracking-wide",children:"CLAIM_NUMBER"}),e.jsx("p",{className:"text-sm font-semibold text-emerald-900 break-all mt-1",children:u.row.TDS_TRNS_ID||"–"})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50/70 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Vs,{className:"w-4 h-4 text-amber-700"}),e.jsx("p",{className:"text-xs font-semibold text-amber-800 tracking-wide uppercase",children:u.type==="credit"?"Credit Note Details":"Debit Note Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4"})," Amount"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:u.amountText})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Cl,{className:"w-4 h-4"})," Issued Date"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:u.issuedAtText})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"DOC_NO"}),e.jsx("p",{className:"text-sm font-semibold text-amber-900 break-all mt-1",children:u.row.DOC_NO||"–"})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"MSG_TYP"}),e.jsx("p",{className:"text-sm font-semibold text-amber-900 break-all mt-1",children:u.row.MSG_TYP||"–"})]})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3 mt-3",children:[e.jsx("p",{className:"text-xs text-amber-700 uppercase tracking-wide",children:"MESSAGE"}),e.jsx("p",{className:"text-sm font-medium text-amber-900 break-words mt-1",children:u.row.MESSAGE||"–"})]})]})]}):e.jsx("div",{className:"py-8 text-sm text-gray-600",children:"No preview available."}),e.jsx(Dt,{children:e.jsx(E,{variant:"outline",onClick:()=>d(!1),children:"Close"})})]})}),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:"Transactions"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Credit and debit notes in one place"})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"All Transactions"}),e.jsx(we,{children:"CR/DB reference number, dealer, amount, issue date, and SAP status"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"relative max-w-md w-full",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(Re,{type:"search",placeholder:"Search transactions...",value:n,onChange:y=>i(y.target.value),className:"pl-9"})]}),e.jsxs(E,{variant:"outline",onClick:j,disabled:a,children:[a?e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Et,{className:"w-4 h-4 mr-2"}),"Pull SAP Response"]})]})]}),e.jsx(J,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{children:[e.jsx(Ae,{children:"TDS_TRANS_ID"}),e.jsx(Ae,{children:"Dealer"}),e.jsx(Ae,{children:"Transaction Amount"}),e.jsx(Ae,{children:"Issued Date"}),e.jsx(Ae,{children:"Status"}),e.jsx(Ae,{className:"text-right",children:"Actions"})]})}),e.jsx($s,{children:t?e.jsx(at,{children:e.jsxs(be,{colSpan:6,className:"text-center py-12",children:[e.jsx(ze,{className:"w-6 h-6 animate-spin mx-auto mb-2 text-teal-600"}),e.jsx("p",{className:"text-gray-500",children:"Loading transactions..."})]})}):f.length===0?e.jsx(at,{children:e.jsxs(be,{colSpan:6,className:"text-center py-12 text-gray-500",children:[e.jsx(Mt,{className:"w-12 h-12 mx-auto mb-3 text-gray-400"}),e.jsx("p",{children:"No transactions found"})]})}):f.map(y=>e.jsxs(at,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(be,{className:"font-medium",children:y.referenceNumber}),e.jsx(be,{children:y.dealer}),e.jsx(be,{children:e.jsxs("div",{className:`inline-flex items-center gap-1.5 font-semibold ${y.type==="credit"?"text-green-600":"text-red-600"}`,children:[y.type==="credit"?e.jsx(Kj,{className:"w-4 h-4"}):e.jsx(Xj,{className:"w-4 h-4"}),e.jsxs("span",{children:[y.type==="credit"?"+ ":"- ",Sh(y.amount)]})]})}),e.jsx(be,{children:GF(y.issueDate)}),e.jsx(be,{children:y.sapResponseAvailable?e.jsx(re,{className:"bg-green-100 text-green-800 border-green-200",children:"Completed"}):e.jsx(re,{className:"bg-orange-100 text-orange-800 border-orange-200",children:"OUTGOING"})}),e.jsx(be,{className:"text-right",children:y.sapResponseAvailable?e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>b(y),children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"View"]}):e.jsxs(E,{variant:"outline",size:"sm",onClick:j,disabled:a,children:[a?e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Et,{className:"w-4 h-4 mr-2"}),"Pull"]})})]},`${y.type}-${y.id}`))})]})})})]})]})]})}function ZF({state:t="idle",onFileSelect:s,errorMessage:a,className:r="",disabled:n=!1}){const[i,l]=x.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)},u={idle:{icon:ys,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:ys,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:ze,text:"Validating Form 16A...",subtext:"Please wait",bgColor:"bg-blue-50",borderColor:"border-blue-300",iconColor:"text-blue-600 animate-spin"},extracting:{icon:ze,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:ps,text:"Form 16A uploaded successfully",subtext:"Document ready for submission",bgColor:"bg-green-50",borderColor:"border-green-300",iconColor:"text-green-600"},error:{icon:Je,text:"Upload failed",subtext:a||"Please try again",bgColor:"bg-red-50",borderColor:"border-red-300",iconColor:"text-red-600"}},h=u[o]??u.idle,g=h.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 ${(h==null?void 0:h.bgColor)??""} ${(h==null?void 0:h.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 ${(h==null?void 0:h.iconColor)??""}`}),e.jsx("p",{className:"mb-2 text-gray-700 font-medium",children:(h==null?void 0:h.text)??""}),e.jsx("p",{className:"text-sm text-gray-500",children:(h==null?void 0:h.subtext)??""})]}),o==="idle"&&!n&&e.jsx("input",{type:"file",className:"hidden",accept:".pdf,application/pdf",onChange:p})]})})}const Pi=10;function JF(t){if(!t)return"—";try{return new Date(t).toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}catch{return String(t)}}function qs(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 qF(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 eI(){const t=Cs(),[s,a]=x.useState([]),[r,n]=x.useState(!0),[i,l]=x.useState(0),[o,c]=x.useState(""),[d,m]=x.useState(""),[p,u]=x.useState(null),[h,g]=x.useState("idle"),[f,b]=x.useState(null),[j,y]=x.useState(null),[N,S]=x.useState(!1),[A,w]=x.useState(""),[I,D]=x.useState(""),[T,v]=x.useState(null),[M,P]=x.useState(!1);x.useEffect(()=>{let z=!1;return Wp().then(O=>{z||(a(Array.isArray(O)?O:[]),l(0))}).catch(()=>{z||a([])}).finally(()=>{z||n(!1)}),()=>{z=!0}},[]);const B=Math.max(1,Math.ceil(s.length/Pi)),k=i>0,_=i<B-1,L=Math.max(0,Math.min(i-4,B-9)),R=Math.min(B-1,L+8),C=Array.from({length:R-L+1},(z,O)=>L+O),G=s.slice(i*Pi,(i+1)*Pi),U=x.useCallback(()=>{if(!p)return;const z=URL.createObjectURL(p);v(z),P(!0)},[p]),$=x.useCallback(()=>{P(!1),T&&(URL.revokeObjectURL(T),v(null))},[T]),F=x.useCallback(async z=>{if(!z.name.toLowerCase().endsWith(".pdf")){W.error("Please upload a PDF file");return}u(z),b(null),y(null),g("extracting");try{W.loading("Extracting data with Google Gemini...",{id:"form16-ocr"});const O=await Vv(z);b(O.extractedData),y(O.ocrProvider||null),w(O.extractedData.tanNumber??O.extractedData.tanOfDeductor??""),D(O.extractedData.deductorName??O.extractedData.nameAndAddressOfDeductor??""),c(O.extractedData.financialYear??""),m(O.extractedData.quarter??""),g("success"),W.success(O.ocrProvider?`Data extracted via ${O.ocrProvider}`:"Data extracted",{id:"form16-ocr"})}catch(O){g("error");const V=O instanceof Error?O.message:"Failed to extract data from PDF";W.error(V,{id:"form16-ocr"})}},[]),H=async()=>{var ee;if(!o||!d){W.error("Financial year and quarter could not be extracted from the PDF. Please ensure you upload a valid Form 16A certificate.");return}if(!p){W.error("Please upload Form 16A PDF");return}const z=((f==null?void 0:f.form16aNumber)??"").trim()||`F16-${o}-${d}-${Date.now()}`,O=(f==null?void 0:f.tdsAmount)??(f==null?void 0:f.totalTaxDeducted)??0,V=(f==null?void 0:f.totalAmount)??(f==null?void 0:f.totalAmountPaid)??0,Q=(A||((f==null?void 0:f.tanNumber)??(f==null?void 0:f.tanOfDeductor)??"")).trim(),q=(I||((f==null?void 0:f.deductorName)??(f==null?void 0:f.nameAndAddressOfDeductor)??"")).trim();if(!Q||!q){W.error("TAN and Deductor name are required. Please enter or correct them below.");return}S(!0);try{const te=await zv({financialYear:o,quarter:d,form16aNumber:z,tdsAmount:Number(O)||0,totalAmount:Number(V)||0,tanNumber:Q,deductorName:q,file:p,extractedData:f??void 0}),ue=te.validationStatus,_e=ue==="success"?"success":ue==="duplicate"?"duplicate":ue==="failed"?"mismatch":"error",Ze=_e==="duplicate"?"A credit note has already been issued for this financial year and quarter. This submission is recorded as a new version.":void 0,Ue=_e==="mismatch"?te.validationNotes||"Form 16A details did not match with 26AS data.":void 0;W.success(_e==="success"?"Form 16A matched with 26AS. Credit note generated.":"Form 16A submitted successfully"),t("/form16/submit/result",{state:{status:_e,requestId:te.requestId,requestNumber:te.requestNumber,creditNoteNumber:te.creditNoteNumber??void 0,message:Ze??Ue}})}catch(te){const ue=te&&typeof te=="object"&&"response"in te?te.response:void 0,_e=((ee=ue==null?void 0:ue.data)==null?void 0:ee.message)??(te instanceof Error?te.message:"Failed to submit");(ue==null?void 0:ue.status)===400&&typeof _e=="string"&&(_e.toLowerCase().includes("duplicate")||_e.toLowerCase().includes("already exist"))?t("/form16/submit/result",{state:{status:"duplicate",requestId:"",message:_e}}):W.error(String(_e))}finally{S(!1)}},K=!!p;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(ce,{children:[e.jsx(de,{children:"Upload Form 16A Certificate"}),e.jsx(we,{children:"PDF only. Financial year and quarter are taken from the certificate via OCR; no need to enter them manually."})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsx(ZF,{state:h==="extracting"?"extracting":h==="error"?"error":h==="success"?"success":"idle",onFileSelect:F,disabled:h==="extracting"}),p&&e.jsxs("div",{className:`flex items-center justify-between p-3 rounded-lg border ${h==="extracting"?"bg-blue-50 border-blue-200":h==="error"?"bg-red-50 border-red-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[h==="extracting"?e.jsx(ze,{className:"w-5 h-5 text-blue-600 shrink-0 animate-spin"}):h==="error"?e.jsx(Je,{className:"w-5 h-5 text-red-600 shrink-0"}):e.jsx(ps,{className:"w-5 h-5 text-green-600 shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:p.name}),e.jsxs("span",{className:"text-xs text-gray-500",children:[(p.size/1024).toFixed(1)," KB",h==="extracting"&&" • Extracting...",h==="error"&&" • Extraction failed",h==="success"&&f&&" • Data extracted"]})]}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>{u(null),b(null),y(null),w(""),D(""),c(""),m(""),g("idle"),$()},disabled:h==="extracting",children:"Remove"})]}),p&&e.jsxs(E,{type:"button",variant:"outline",className:"w-full",onClick:U,disabled:h==="extracting",children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"View Uploaded Form 16A"]})]})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Quarters Pending Submission"}),e.jsx(we,{children:"These quarters don't have completed Form 16A submissions. Please submit Form 16A for these quarters."})]}),e.jsxs(J,{children:[e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{className:"bg-gray-50",children:[e.jsx(Ae,{children:"Dealer Name"}),e.jsx(Ae,{children:"Financial Year"}),e.jsx(Ae,{children:"Quarter"}),e.jsx(Ae,{children:"Version"}),e.jsx(Ae,{children:"Status"}),e.jsx(Ae,{children:"26AS start date"}),e.jsx(Ae,{children:"Days Status"}),e.jsx(Ae,{className:"text-right",children:"Action"})]})}),e.jsx($s,{children:r?e.jsx(at,{children:e.jsxs(be,{colSpan:8,className:"text-center py-12 text-gray-500",children:[e.jsx(ze,{className:"w-8 h-8 animate-spin mx-auto mb-2"}),e.jsx("p",{children:"Loading..."})]})}):s.length===0?e.jsx(at,{children:e.jsx(be,{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(Fe,{className:"w-12 h-12 text-gray-300"}),e.jsx("p",{children:"No pending submissions. All quarters are complete."})]})})}):G.map(z=>e.jsxs(at,{className:"hover:bg-gray-50",children:[e.jsx(be,{className:"text-sm text-gray-900",children:z.dealer_name??"Your submission"}),e.jsx(be,{children:e.jsxs("span",{className:"text-sm text-gray-900",children:["FY ",z.financial_year]})}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:z.quarter})}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:z.has_submission?"V1":"—"})}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:z.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":z.has_submission?"bg-slate-50 text-slate-600 border-slate-200":"bg-gray-100 text-gray-600 border-gray-200",children:z.latest_submission_status==="failed"?"Failed":z.has_submission?"Under review":"Not Submitted"})}),e.jsx(be,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-700",children:JF(z.twenty_six_as_start_date??z.audit_start_date)})]})}),e.jsx(be,{children:z.days_since_26as_uploaded!=null&&z.days_since_26as_uploaded>=0?e.jsxs("span",{className:"text-sm font-medium text-gray-700",children:["due from ",z.days_since_26as_uploaded," days"]}):e.jsx("span",{className:"text-sm text-gray-500",children:"—"})}),e.jsx(be,{className:"text-right",children:e.jsx(E,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>t("/form16/submit"),children:"Submit Now"})})]},`${z.financial_year}|${z.quarter}`))})]})}),!r&&s.length>Pi&&e.jsxs("div",{className:"flex items-center justify-between mt-4 px-1",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Page ",i+1," of ",B," (",s.length," 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:!k,onClick:()=>l(z=>z-1),children:[e.jsx(pn,{className:"w-4 h-4"}),"Previous"]}),C.map(z=>e.jsx(E,{variant:z===i?"default":"outline",size:"sm",className:z===i?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>l(z),children:z+1},z)),e.jsxs(E,{variant:"outline",size:"sm",disabled:!_,onClick:()=>l(z=>z+1),children:["Next",e.jsx(Ka,{className:"w-4 h-4"})]})]})]})]})]}),e.jsxs(Z,{className:"border-blue-200 bg-blue-50",children:[e.jsx(ce,{children:e.jsxs(de,{className:"text-blue-900 flex items-center gap-2",children:[e.jsx(Hr,{className:"w-5 h-5"}),"Important Notes"]})}),e.jsx(J,{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"})]})})]}),K&&e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"w-5 h-5 text-blue-600"}),e.jsx(de,{children:"Form 16A Extracted Details"})]}),e.jsx(we,{children:h==="extracting"?"Extracting with Google Gemini (or regex fallback)...":f?j?`Extracted via ${j}. Unmapped fields show N/A.`:"Certificate details extracted from uploaded document.":h==="error"?"Extraction failed. You can remove the file and try again.":"Waiting for extraction..."})]}),e.jsx(J,{className:"space-y-6",children:h==="extracting"?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(ze,{className:"w-8 h-8 text-blue-600 animate-spin mr-3"}),e.jsx("p",{className:"text-gray-600",children:"Extracting data..."})]}):h==="error"?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(Je,{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."})]}):f?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:qF(f)})]}),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:qs(f.tanOfDeductor??f.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:(f.totalAmountPaid??f.totalAmount)!=null?`₹ ${qs(f.totalAmountPaid??f.totalAmount)}`:qs(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:(f.totalTaxDeducted??f.tdsAmount)!=null?`₹ ${qs(f.totalTaxDeducted??f.tdsAmount)}`:qs(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:(f.totalTdsDeposited??f.tdsAmount)!=null?`₹ ${qs(f.totalTdsDeposited??f.tdsAmount)}`:qs(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:qs(f.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:qs(f.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:qs(f.statusOfMatchingOltas)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Last updated on"}),e.jsx("p",{className:"text-sm mt-1 font-medium",children:qs(f.dateOfBooking||f.certificateDate)})]}),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:qs(f.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:qs(f.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:qs(f.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(se,{htmlFor:"form16-tan",children:"TAN of deductor *"}),e.jsx(Re,{id:"form16-tan",value:A,onChange:z=>w(z.target.value),placeholder:"e.g. BLRH07660C",maxLength:10})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(se,{htmlFor:"form16-deductor",children:"Deductor name *"}),e.jsx(Re,{id:"form16-deductor",value:I,onChange:z=>D(z.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(ps,{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:N,children:"Cancel"}),e.jsxs(E,{type:"button",className:"bg-re-green hover:bg-re-green/90",onClick:H,disabled:!o||!d||N,children:[N?e.jsx(ze,{className:"w-4 h-4 animate-spin mr-2"}):null,"Submit Form 16A"]})]})]}):null})]}),e.jsx(xt,{open:M,onOpenChange:z=>!z&&$(),children:e.jsxs(dt,{className:"max-w-4xl max-h-[90vh] flex flex-col","aria-describedby":"form16-pdf-description",children:[e.jsxs(ht,{children:[e.jsx(mt,{children:"Form 16A Certificate"}),e.jsx(_t,{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:T&&e.jsx("iframe",{title:"Form 16A PDF",src:T,className:"w-full h-[70vh] rounded"})})]})})]})})}const tI={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 sI({variant:t,label:s,showIcon:a=!0}){const r=t==="success"?ps:t==="failed"?St:it;return e.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm font-medium ${tI[t]}`,children:[a&&e.jsx(r,{className:"h-4 w-4 shrink-0"}),s]})}function aI({step:t,label:s,state:a,isLast:r}){const n=a==="completed"?ps:a==="failed"?St:bc,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 rI({status:t,requestId:s,requestDisplayId:a,creditNoteNumber:r,message:n,onComplete:i,onResubmit:l,onViewRequest:o}){const c=t==="success",d=t==="mismatch",m=d&&(n||"").toLowerCase().includes("26as")&&(n||"").toLowerCase().includes("no 26as"),p=(()=>{const f=(n||"").toLowerCase();return f.includes("no 26as")?"26AS data is not uploaded for this TAN / FY / Quarter.":f.includes("amount mismatch")?"TDS amount in Form 16A does not match 26AS amount.":f.includes("tan")?"TAN details in Form 16A do not match 26AS records.":f.includes("pan")?"PAN details in Form 16A do not match 26AS records.":f.includes("quarter")?"Quarter in Form 16A does not match 26AS records.":f.includes("financial year")||f.includes("fy")?"Financial year in Form 16A does not match 26AS records.":"Form 16A details do not match with 26AS data."})(),u=t==="duplicate",h=t==="error";x.useEffect(()=>{if(!c)return;const f=setTimeout(i,5e3);return()=>clearTimeout(f)},[c,i]);const g=[{label:"Form 16A Uploaded",state:u?"failed":"completed"},{label:"Validation",state:u?"failed":h?"pending":"completed"},{label:"26AS Matching",state:c?"completed":d||u?"failed":"pending"},{label:"Credit Note",state:c?"completed":"pending"}];return e.jsx("div",{className:"min-h-[calc(100vh-10rem)] flex items-center justify-center",children:e.jsx(Wt.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:c?"border-teal-200 shadow-xl":u?"border-red-300 shadow-xl bg-red-50/50":d?"border-amber-200 shadow-xl bg-amber-50/30":"border-gray-200 shadow-xl bg-gray-50/30",children:e.jsxs(J,{className:"pt-12 pb-10",children:[e.jsx(Wt.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{delay:.15},className:"flex justify-center mb-6",children:e.jsx(sI,{variant:c?"success":u?"failed":h?"pending":"failed",label:c?"Matched & Credit Note Generated":u?"Duplicate Submission":d?"Value Mismatch":"Request Received",showIcon:!0})}),e.jsx(Wt.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 ${c?"bg-teal-100":u?"bg-red-100":h?"bg-gray-100":"bg-amber-100"}`,children:c?e.jsx(ps,{className:"w-12 h-12 text-teal-600"}):u?e.jsx(Zj,{className:"w-12 h-12 text-red-600"}):h?e.jsx(Je,{className:"w-12 h-12 text-gray-500"}):e.jsx(Je,{className:"w-12 h-12 text-amber-600"})})}),e.jsx(Wt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.3},className:"text-center mb-6",children:c?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."})]}):u?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."}),n&&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:n})]})]}):d?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.jsxs("p",{className:"text-gray-600 text-sm mt-1",children:[p," Please verify the certificate and resubmit with correct details."]}),n&&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:n})]}),m&&e.jsxs("div",{className:"mt-3 p-3 bg-white border border-amber-200 rounded-md",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 mb-1",children:"Contact administrator: FORM 26AS does not match FORM 16A."}),e.jsx("p",{className:"text-sm text-gray-700",children:"If you have submitted the updated Form 16A but the latest 26AS is not uploaded for this quarter yet, please notify RE so they can upload/update 26AS."}),e.jsx("p",{className:"text-sm text-amber-900 mt-2",children:"contact at - service@royalenfield.com"})]})]}):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."}),n&&e.jsx("p",{className:"text-sm text-gray-600 mt-2 italic",children:n})]})}),e.jsxs(Wt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.4},className:`rounded-lg p-4 mb-6 text-center ${c?"bg-teal-50 border border-teal-200":u?"bg-red-50 border-2 border-red-200":"bg-white border border-amber-200"}`,children:[e.jsx("p",{className:`text-sm mb-1 ${u?"text-red-700":"text-gray-600"}`,children:"Request ID"}),e.jsx("p",{className:`font-mono tracking-wide ${u?"text-red-800 font-semibold":"text-gray-900"}`,children:a||s||"—"}),c&&r&&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:r})]})]}),e.jsxs(Wt.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:g.map((f,b)=>e.jsx(aI,{step:b+1,label:f.label,state:f.state,isLast:b===g.length-1},b))})]}),e.jsx(Wt.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.6},className:"flex flex-col sm:flex-row items-center justify-center gap-3",children:c?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:i,variant:"outline",className:"border-teal-300 text-teal-700",children:"Back to My Requests"})]}):e.jsxs(e.Fragment,{children:[h&&o&&e.jsx(E,{onClick:o,className:"bg-teal-600 hover:bg-teal-700",children:"View Request"}),l&&(d||u||h)&&e.jsx(E,{onClick:l,className:u?"bg-red-600 hover:bg-red-700":d?"bg-amber-600 hover:bg-amber-700":"bg-gray-600 hover:bg-gray-700",children:u?"Back to New Submission":d?"Resubmit Form 16A":"Try Again"}),e.jsx(E,{onClick:i,variant:"outline",children:"Back to My Requests"})]})})]})})})})}const $n="form16_submission_result";function nI(){const t=Cs(),a=ty().state,r=(()=>{try{const d=sessionStorage.getItem($n);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);x.useEffect(()=>{i&&sessionStorage.setItem($n,JSON.stringify(n))},[i,n]);const l=x.useCallback(()=>{sessionStorage.removeItem($n),t("/my-requests",{replace:!0})},[t]),o=x.useCallback(()=>{sessionStorage.removeItem($n),t("/form16/submit",{replace:!0})},[t]),c=x.useCallback(()=>{n!=null&&n.requestNumber&&(sessionStorage.removeItem($n),t(`/request/${n.requestNumber}`,{replace:!0}))},[t,n==null?void 0:n.requestNumber]);return i?e.jsx(rI,{status:n.status,requestId:n.requestId,requestDisplayId: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 Un=50,Ei=10,iI=["Q1","Q2","Q3","Q4"],lI=[{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 Ah(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 _i(t){return t==null?"–":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function oI(){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 cI(t){switch((t||"").trim().toUpperCase().slice(0,1)){case"F":return e.jsx(re,{className:"bg-green-100 text-green-700 border-green-300",children:"F"});case"O":return e.jsx(re,{className:"bg-orange-100 text-orange-700 border-orange-300",children:"O"});case"M":return e.jsx(re,{className:"bg-blue-100 text-blue-700 border-blue-300",children:"M"});case"U":return e.jsx(re,{className:"bg-red-100 text-red-700 border-red-300",children:"U"});case"P":return e.jsx(re,{className:"bg-amber-100 text-amber-700 border-amber-300",children:"P"});default:return t?e.jsx(re,{variant:"secondary",children:t}):null}}function dI(){const[t,s]=x.useState(!1),[a,r]=x.useState({assessmentYear:"all",quarter:"all",section:"all",tanNumber:"",deductor:"",status:"all"}),[n,i]=x.useState(""),l=x.useRef(null),[o,c]=x.useState(!1),[d,m]=x.useState(!1),[p,u]=x.useState(0),[h,g]=x.useState(0),[f,b]=x.useState(null),j=x.useRef(null),y=x.useRef(null),[N,S]=x.useState([]),[A,w]=x.useState(0),[I,D]=x.useState({totalRecords:0,booked:0,notBooked:0,pending:0,totalTaxDeducted:0}),[T,v]=x.useState(!0),[M,P]=x.useState(0),[B,k]=x.useState([]),[_,L]=x.useState(0),[R,C]=x.useState(0),[G,U]=x.useState(!1),$=oI(),F=x.useCallback(async(ae=0)=>{try{U(!0);const{history:he,total:ne}=await Gv({limit:Ei,offset:ae*Ei});k(he),L(ne),C(ae)}catch(he){console.error("[Form16_26AS] upload history",he),k([]),L(0),C(0)}finally{U(!1)}},[]),H=x.useCallback(async(ae=0)=>{try{v(!0);const he={limit:Un,offset:ae*Un};a.assessmentYear!=="all"&&(he.financialYear=a.assessmentYear),a.quarter!=="all"&&(he.quarter=a.quarter),a.section!=="all"&&(he.sectionCode=a.section),a.tanNumber.trim()&&(he.tanNumber=a.tanNumber.trim()),a.deductor.trim()&&(he.search=a.deductor.trim()),a.status!=="all"&&(he.status=a.status);const ne=await Hv(he);S(ne.entries),w(ne.total),D(ne.summary),P(ae)}catch(he){console.error("[Form16_26AS]",he),W.error(he instanceof Error?he.message:"Failed to load 26AS entries"),S([]),w(0),D({totalRecords:0,booked:0,notBooked:0,pending:0,totalTaxDeducted:0})}finally{v(!1)}},[a.assessmentYear,a.quarter,a.section,a.tanNumber,a.deductor,a.status]);x.useEffect(()=>{H(0)},[H]),x.useEffect(()=>{F(0)},[F]),x.useEffect(()=>(l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{r(ae=>({...ae,deductor:n.trim()}))},300),()=>{l.current&&clearTimeout(l.current)}),[n]),x.useEffect(()=>()=>{y.current&&(clearInterval(y.current),y.current=null)},[]);const K=ae=>{var ne;const he=(ne=ae.target.files)==null?void 0:ne[0];if(he){if(he.size>50*1024*1024){W.error("File size must be less than 50MB");return}if(!he.name.toLowerCase().endsWith(".txt")){W.error("Only .txt files are supported");return}b(he)}},z=async()=>{var ae,he;if(!f){W.error("Please select a file");return}m(!0),u(0),g(0),y.current&&(clearInterval(y.current),y.current=null);try{const ne=await Yv(f,ge=>{if(u(ge),ge>=100&&!y.current){g(0);let ke=0;y.current=setInterval(()=>{ke+=1,g(Oe=>Math.min(99,Oe+4+Math.floor(ke/3)))},300)}});y.current&&(clearInterval(y.current),y.current=null),g(100),ne.imported>0?(W.success(`Successfully imported ${ne.imported} entries.${(ae=ne.errors)!=null&&ae.length?` ${ne.errors.length} warnings.`:""}`),c(!1),b(null),j.current&&(j.current.value=""),H(0),F(0)):(he=ne.errors)!=null&&he.length&&W.error(ne.errors[0]||"Upload failed")}catch(ne){y.current&&(clearInterval(y.current),y.current=null),W.error(ne instanceof Error?ne.message:"Upload failed")}finally{m(!1),u(0),g(0)}},O=()=>{r({assessmentYear:"all",quarter:"all",section:"all",tanNumber:"",deductor:"",status:"all"}),i("")},V=a.assessmentYear!=="all"||a.quarter!=="all"||a.section!=="all"||a.tanNumber!==""||a.deductor!==""||a.status!=="all",Q=Math.max(1,Math.ceil(A/Un)),q=M>0,ee=M<Q-1,te=Math.max(0,Math.min(M-4,Q-9)),ue=Math.min(Q-1,te+8),_e=Array.from({length:ue-te+1},(ae,he)=>te+he),Ze=Math.max(1,Math.ceil(_/Ei)),Ue=R>0,Pe=R<Ze-1,De=Math.max(0,Math.min(R-4,Ze-9)),le=Math.min(Ze-1,De+8),ye=Array.from({length:le-De+1},(ae,he)=>De+he);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(Zt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(Re,{placeholder:"Search...",value:n,onChange:ae=>i(ae.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(ys,{className:"w-4 h-4"}),"Upload 26AS File"]}),e.jsxs(E,{variant:"outline",onClick:()=>s(!t),className:"gap-2",children:[e.jsx(Ua,{className:"w-4 h-4"}),"Filters",V&&e.jsx(re,{className:"ml-1 bg-teal-600 hover:bg-teal-700 text-white",children:[a.assessmentYear,a.quarter,a.section,a.tanNumber,a.deductor,a.status].filter(ae=>ae!==""&&ae!=="all").length}),t?e.jsx(ul,{className:"w-4 h-4"}):e.jsx(jn,{className:"w-4 h-4"})]})]})]}),e.jsx(xt,{open:o,onOpenChange:c,children:e.jsxs(dt,{className:"max-w-md",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ys,{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(se,{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:K,disabled:d,className:"hidden"}),e.jsxs(E,{variant:"outline",onClick:()=>{var ae;return(ae=j.current)==null?void 0:ae.click()},disabled:d,className:"gap-2",children:[e.jsx(Fe,{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(ia,{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(h),"%"]})]}),e.jsx(ia,{value:h,className:"h-2",indicatorClassName:"bg-teal-600"})]})]})]}),e.jsxs(Dt,{children:[e.jsx(E,{variant:"outline",onClick:()=>{c(!1),b(null),j.current&&(j.current.value="")},disabled:d,children:"Cancel"}),e.jsx(E,{onClick:z,disabled:!f||d,className:"bg-teal-600 hover:bg-teal-700 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ys,{className:"w-4 h-4"}),"Upload"]})})]})]})}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Management"}),e.jsxs(we,{children:["History of 26AS file uploads: when and which user added or uploaded 26AS data",_>0?` (${_} total)`:""]})]}),e.jsxs(J,{children:[e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{children:[e.jsx(Ae,{children:"Date & Time"}),e.jsx(Ae,{children:"User"}),e.jsx(Ae,{children:"File Name"}),e.jsx(Ae,{className:"text-right",children:"Records Imported"}),e.jsx(Ae,{className:"text-right",children:"Errors"})]})}),e.jsx($s,{children:G?e.jsx(at,{children:e.jsxs(be,{colSpan:5,className:"text-center py-8",children:[e.jsx(ze,{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..."})]})}):B.length===0?e.jsx(at,{children:e.jsx(be,{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."})}):B.map(ae=>e.jsxs(at,{className:"hover:bg-gray-50",children:[e.jsx(be,{className:"text-sm whitespace-nowrap",children:ae.uploadedAt?new Date(ae.uploadedAt).toLocaleString("en-IN",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"–"}),e.jsx(be,{className:"text-sm",children:ae.uploadedByDisplayName||ae.uploadedByEmail||ae.uploadedBy||"–"}),e.jsx(be,{className:"text-sm text-gray-600 max-w-[200px] truncate",title:ae.fileName||void 0,children:ae.fileName||"–"}),e.jsx(be,{className:"text-right font-medium",children:ae.recordsImported}),e.jsx(be,{className:"text-right",children:ae.errorsCount>0?ae.errorsCount:"–"})]},ae.id))})]})}),!G&&_>Ei&&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 ",R+1," of ",Ze," (",_," uploads)"]}),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:!Ue,onClick:()=>F(R-1),children:[e.jsx(pn,{className:"w-4 h-4"}),"Previous"]}),ye.map(ae=>e.jsx(E,{variant:ae===R?"default":"outline",size:"sm",className:ae===R?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>F(ae),children:ae+1},ae)),e.jsxs(E,{variant:"outline",size:"sm",disabled:!Pe,onClick:()=>F(R+1),children:["Next",e.jsx(Ka,{className:"w-4 h-4"})]})]})]})]})]}),t&&e.jsxs(Z,{children:[e.jsx(ce,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{children:"Filter TDS Records"}),V&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:O,className:"gap-2 text-gray-600",children:[e.jsx(yt,{className:"w-4 h-4"}),"Clear All"]})]})}),e.jsx(J,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Assessment Year"}),e.jsxs(He,{value:a.assessmentYear,onValueChange:ae=>r(he=>({...he,assessmentYear:ae})),children:[e.jsx(We,{children:e.jsx(Ge,{placeholder:"Select year"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Years"}),$.map(ae=>e.jsx(X,{value:ae,children:ae},ae))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Quarter"}),e.jsxs(He,{value:a.quarter,onValueChange:ae=>r(he=>({...he,quarter:ae})),children:[e.jsx(We,{children:e.jsx(Ge,{placeholder:"Select quarter"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Quarters"}),iI.map(ae=>e.jsx(X,{value:ae,children:ae},ae))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Section"}),e.jsxs(He,{value:a.section,onValueChange:ae=>r(he=>({...he,section:ae})),children:[e.jsx(We,{children:e.jsx(Ge,{placeholder:"Select section"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Sections"}),lI.map(ae=>e.jsx(X,{value:ae.value,children:ae.label},ae.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"TAN"}),e.jsx(Re,{placeholder:"Search TAN...",value:a.tanNumber,onChange:ae=>r(he=>({...he,tanNumber:ae.target.value})),className:"h-9 font-mono"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Deductor"}),e.jsx(Re,{placeholder:"Search deductor / TAN...",value:a.deductor,onChange:ae=>r(he=>({...he,deductor:ae.target.value})),className:"h-9"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(He,{value:a.status,onValueChange:ae=>r(he=>({...he,status:ae})),children:[e.jsx(We,{children:e.jsx(Ge,{placeholder:"Select status"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Status"}),e.jsx(X,{value:"F",children:"F – Final (Booked)"}),e.jsx(X,{value:"O",children:"O – Overbooked"}),e.jsx(X,{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(ce,{className:"pb-3",children:[e.jsx(we,{children:"Total Records"}),e.jsx(de,{className:"text-2xl",children:I.totalRecords})]})}),e.jsx(Z,{children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Booked"}),e.jsx(de,{className:"text-2xl text-green-600",children:I.booked})]})}),e.jsx(Z,{children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Not Booked"}),e.jsx(de,{className:"text-2xl text-red-600",children:I.notBooked})]})}),e.jsx(Z,{children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Pending"}),e.jsx(de,{className:"text-2xl text-amber-600",children:I.pending})]})}),e.jsx(Z,{className:"lg:col-span-1",children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Total Tax Deducted"}),e.jsx(de,{className:"text-xl",children:_i(I.totalTaxDeducted)})]})})]}),e.jsxs(Z,{children:[e.jsx(ce,{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(de,{children:"TDS Records from Form 26AS"}),e.jsx(we,{children:V?`Showing ${N.length} of ${A} records`:`Complete list of TDS deduction records (${A} total)`})]}),e.jsxs(E,{variant:"outline",size:"sm",disabled:!0,children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),"Export"]})]})}),e.jsxs(J,{className:"p-0",children:[e.jsx("div",{className:"overflow-auto min-h-[320px]",style:{maxHeight:"calc(100vh - 380px)"},children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{className:"bg-gray-50",children:[e.jsx(Ae,{className:"w-14",children:"Sr No"}),e.jsx(Ae,{className:"min-w-[180px]",children:"Name of Deductor"}),e.jsx(Ae,{className:"text-right min-w-[110px]",children:"Total Amount Paid"}),e.jsx(Ae,{className:"text-right min-w-[110px]",children:"Total Tax Deducted"}),e.jsx(Ae,{className:"text-right min-w-[110px]",children:"Total TDS Deposited"}),e.jsx(Ae,{className:"min-w-[100px]",children:"TAN of Deductor"}),e.jsx(Ae,{className:"min-w-[72px]",children:"Section"}),e.jsx(Ae,{className:"min-w-[64px]",children:"Quarter"}),e.jsx(Ae,{className:"min-w-[90px]",children:"Assessment Year"}),e.jsx(Ae,{className:"min-w-[90px]",children:"Financial Year"}),e.jsx(Ae,{className:"min-w-[100px]",children:"Transaction Date"}),e.jsx(Ae,{className:"min-w-[64px]",children:"Status"}),e.jsx(Ae,{className:"min-w-[100px]",children:"Date of Booking"})]})}),e.jsx($s,{children:T?e.jsx(at,{children:e.jsx(be,{colSpan:13,className:"text-center py-12",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(ze,{className:"w-6 h-6 animate-spin text-teal-600"}),e.jsx("p",{className:"text-gray-500",children:"Loading 26AS data..."})]})})}):N.length===0?e.jsx(at,{children:e.jsxs(be,{colSpan:13,className:"text-center py-12 text-gray-500",children:[V?"No records match your filters":"No TDS records found. Upload a 26AS file to get started.",V&&e.jsx(E,{variant:"outline",size:"sm",onClick:O,className:"mt-2",children:"Clear Filters"})]})}):N.map((ae,he)=>e.jsxs(at,{className:"hover:bg-gray-50",children:[e.jsx(be,{className:"text-center text-sm text-gray-900",children:M*Un+he+1}),e.jsx(be,{className:"text-sm text-gray-900",children:ae.deductorName||"–"}),e.jsx(be,{className:"text-right text-sm text-gray-900",children:_i(ae.amountPaid??0)}),e.jsx(be,{className:"text-right text-sm text-gray-900",children:_i(ae.taxDeducted)}),e.jsx(be,{className:"text-right text-sm text-gray-900",children:_i(ae.totalTdsDeposited??0)}),e.jsx(be,{className:"text-sm text-gray-700 font-mono",children:ae.tanNumber}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:ae.sectionCode||"–"})}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:ae.quarter})}),e.jsx(be,{className:"text-sm text-gray-700 font-medium",children:ae.assessmentYear||"–"}),e.jsx(be,{className:"text-sm text-gray-700 font-medium",children:ae.financialYear||"–"}),e.jsx(be,{className:"text-sm text-gray-700",children:Ah(ae.transactionDate)}),e.jsx(be,{children:cI(ae.statusOltas)}),e.jsx(be,{className:"text-sm text-gray-700",children:Ah(ae.dateOfBooking)})]},ae.id))})]})}),!T&&A>Un&&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 ",M+1," of ",Q," (",A," 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:!q,onClick:()=>H(M-1),children:[e.jsx(pn,{className:"w-4 h-4"}),"Previous"]}),_e.map(ae=>e.jsx(E,{variant:ae===M?"default":"outline",size:"sm",className:ae===M?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>H(ae),children:ae+1},ae)),e.jsxs(E,{variant:"outline",size:"sm",disabled:!ee,onClick:()=>H(M+1),children:["Next",e.jsx(Ka,{className:"w-4 h-4"})]})]})]})]})]})]})})}function ks(t){const s=Number(t??0);return Number.isFinite(s)?new Intl.NumberFormat("en-IN",{maximumFractionDigits:0}).format(s):"0"}const Th={kpi:{collectionPct:0,pendingPct:0,submittedPct:0,submissionPendingPct:0},overall:{totalAmount:0,submittedAmount:0,pendingAmount:0,totalDealers:0,submittedDealerCount:0,pendingDealerCount:0},yearWise:[],zoneWise:[]};function kh({rows:t,label:s="Total"}){const a=x.useMemo(()=>t.reduce((r,n)=>(r.totalAmount+=Number(n.totalAmount||0),r.dealerCount+=Number(n.dealerCount||0),r.submittedAmount+=Number(n.submittedAmount||0),r.submittedDealerCount+=Number(n.submittedDealerCount||0),r.pendingAmount+=Number(n.pendingAmount||0),r),{totalAmount:0,dealerCount:0,submittedAmount:0,submittedDealerCount:0,pendingAmount:0}),[t]);return e.jsxs(at,{className:"bg-gray-50 font-semibold",children:[e.jsx(be,{children:s}),e.jsx(be,{className:"text-right",children:ks(a.totalAmount)}),e.jsx(be,{className:"text-right",children:ks(a.dealerCount)}),e.jsx(be,{className:"text-right text-green-700",children:ks(a.submittedAmount)}),e.jsx(be,{className:"text-right",children:ks(a.submittedDealerCount)}),e.jsx(be,{className:"text-right text-red-700",children:ks(a.pendingAmount)})]})}function mI(){const[t,s]=x.useState(Th),[a,r]=x.useState(!0);return x.useEffect(()=>{let n=!0;return(async()=>{try{r(!0);const i=await $v();if(!n)return;s(i)}catch(i){if(!n)return;console.error("[Form16Dashboard] fetch error:",i),W.error(i instanceof Error?i.message:"Failed to load Form16A dashboard"),s(Th)}finally{n&&r(!1)}})(),()=>{n=!1}},[]),a?e.jsx("div",{className:"min-h-[50vh] flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-gray-600",children:[e.jsx(ze,{className:"w-5 h-5 animate-spin"}),"Loading Form16A dashboard..."]})}):e.jsx("div",{className:"min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"w-full max-w-[98vw] xl:max-w-[1920px] mx-auto space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-1",children:"Form16A Dashboard"}),e.jsx("p",{className:"text-gray-600 text-sm",children:"Collection and submission status with year-wise and zone-wise breakdown."})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(Z,{className:"bg-green-500 text-white",children:e.jsxs(J,{className:"py-4 flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:"Collection"}),e.jsxs("span",{className:"text-2xl font-bold",children:[t.kpi.collectionPct,"%"]})]})}),e.jsx(Z,{className:"bg-red-500 text-white",children:e.jsxs(J,{className:"py-4 flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:"Pending"}),e.jsxs("span",{className:"text-2xl font-bold",children:[t.kpi.pendingPct,"%"]})]})}),e.jsx(Z,{className:"bg-green-50 border-green-200",children:e.jsxs(J,{className:"py-4 flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Submitted / Credit"}),e.jsxs("span",{className:"text-2xl font-bold text-green-700",children:[t.kpi.submittedPct,"%"]})]})}),e.jsx(Z,{className:"bg-red-500 text-white",children:e.jsxs(J,{className:"py-4 flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:"Submission Pending"}),e.jsxs("span",{className:"text-2xl font-bold",children:[t.kpi.submissionPendingPct,"%"]})]})})]}),e.jsxs(Z,{children:[e.jsx(ce,{children:e.jsx(de,{children:"Overall Summary"})}),e.jsxs(J,{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("div",{className:"text-sm text-gray-600",children:"Total Amount"}),e.jsx("div",{className:"text-3xl font-semibold",children:ks(t.overall.totalAmount)})]}),e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("div",{className:"text-sm text-gray-600",children:"Submitted"}),e.jsx("div",{className:"text-3xl font-semibold text-green-700",children:ks(t.overall.submittedAmount)})]}),e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("div",{className:"text-sm text-gray-600",children:"Pending"}),e.jsx("div",{className:"text-3xl font-semibold text-red-700",children:ks(t.overall.pendingAmount)})]})]})]}),e.jsxs(Z,{children:[e.jsx(ce,{children:e.jsx(de,{children:"Year-wise Breakdown"})}),e.jsx(J,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{className:"bg-gray-50",children:[e.jsx(Ae,{children:"Year"}),e.jsx(Ae,{className:"text-right",children:"Total Amount"}),e.jsx(Ae,{className:"text-right",children:"Dealer Count"}),e.jsx(Ae,{className:"text-right",children:"Submitted Amount"}),e.jsx(Ae,{className:"text-right",children:"Submitted Dealer Count"}),e.jsx(Ae,{className:"text-right",children:"Pending Amount"})]})}),e.jsx($s,{children:t.yearWise.length===0?e.jsx(at,{children:e.jsx(be,{colSpan:6,className:"text-center py-8 text-gray-500",children:"No year-wise data available."})}):e.jsxs(e.Fragment,{children:[t.yearWise.map(n=>e.jsxs(at,{children:[e.jsx(be,{className:"font-medium",children:n.label}),e.jsx(be,{className:"text-right",children:ks(n.totalAmount)}),e.jsx(be,{className:"text-right",children:ks(n.dealerCount)}),e.jsx(be,{className:"text-right text-green-700",children:ks(n.submittedAmount)}),e.jsx(be,{className:"text-right",children:ks(n.submittedDealerCount)}),e.jsx(be,{className:"text-right text-red-700",children:ks(n.pendingAmount)})]},n.label)),e.jsx(kh,{rows:t.yearWise})]})})]})})})]}),e.jsxs(Z,{children:[e.jsx(ce,{children:e.jsx(de,{children:"Zone-wise Breakdown"})}),e.jsx(J,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{className:"bg-gray-50",children:[e.jsx(Ae,{children:"Zone"}),e.jsx(Ae,{className:"text-right",children:"Total Amount"}),e.jsx(Ae,{className:"text-right",children:"Dealer Count"}),e.jsx(Ae,{className:"text-right",children:"Submitted Amount"}),e.jsx(Ae,{className:"text-right",children:"Submitted Dealer Count"}),e.jsx(Ae,{className:"text-right",children:"Pending Amount"})]})}),e.jsx($s,{children:t.zoneWise.length===0?e.jsx(at,{children:e.jsx(be,{colSpan:6,className:"text-center py-8 text-gray-500",children:"No zone-wise data available."})}):e.jsxs(e.Fragment,{children:[t.zoneWise.map(n=>e.jsxs(at,{children:[e.jsx(be,{className:"font-medium",children:n.label}),e.jsx(be,{className:"text-right",children:ks(n.totalAmount)}),e.jsx(be,{className:"text-right",children:ks(n.dealerCount)}),e.jsx(be,{className:"text-right text-green-700",children:ks(n.submittedAmount)}),e.jsx(be,{className:"text-right",children:ks(n.submittedDealerCount)}),e.jsx(be,{className:"text-right text-red-700",children:ks(n.pendingAmount)})]},n.label)),e.jsx(kh,{rows:t.zoneWise})]})})]})})})]})]})})}function Dh(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 uI=[{value:"2024-25",label:"2024-25"},{value:"2023-24",label:"2023-24"},{value:"2022-23",label:"2022-23"},{value:"",label:"All Years"}];function xI(){const[t,s]=x.useState(null),[a,r]=x.useState([]),[n,i]=x.useState({totalDealers:0,nonSubmittedCount:0,neverSubmittedCount:0,overdue90Count:0}),[l,o]=x.useState(!0),[c,d]=x.useState("2024-25");x.useEffect(()=>{m()},[c]);const m=async()=>{try{o(!0);const u=await Qv(c||void 0);r(u.dealers),i(u.summary)}catch(u){console.error("Error fetching non-submitted dealers:",u),W.error("Failed to load non-submitted dealers"),r([]),i({totalDealers:0,nonSubmittedCount:0,neverSubmittedCount:0,overdue90Count:0})}finally{o(!1)}},p=async u=>{s(u.id);try{await Kv({dealerCode:u.dealerCode,dealerId:u.id,email:u.email,financialYear:c||void 0}),W.success(`Notification sent to ${u.dealerName}`,{description:`Reminder sent for missing quarters: ${u.missingQuarters.join(", ")}. Last notified column updated.`}),await m()}catch(h){console.error("Notify dealer error:",h),W.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:u=>d(u.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:uI.map(u=>e.jsx("option",{value:u.value,children:u.value?`FY ${u.label}`:u.label},u.value||"all"))})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(Z,{children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Non-Submitted / Total Dealers"}),e.jsx(de,{className:"text-3xl text-red-600",children:l?"...":`${n.nonSubmittedCount}/${n.totalDealers}`})]})}),e.jsx(Z,{children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Never Submitted"}),e.jsx(de,{className:"text-3xl text-amber-600",children:l?"...":n.neverSubmittedCount})]})}),e.jsx(Z,{children:e.jsxs(ce,{className:"pb-3",children:[e.jsx(we,{children:"Overdue (90+ days)"}),e.jsx(de,{className:"text-3xl text-orange-600",children:l?"...":n.overdue90Count})]})})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Dealer List"}),e.jsx(we,{children:"Dealers with missing Form 16A submissions"})]}),e.jsx(J,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{children:[e.jsx(Ae,{children:"Dealer Details"}),e.jsx(Ae,{children:"Contact Information"}),e.jsx(Ae,{children:"Location"}),e.jsx(Ae,{children:"Missing Quarters"}),e.jsx(Ae,{children:"Last Submission"}),e.jsx(Ae,{children:"Last Notified"}),e.jsx(Ae,{className:"text-right",children:"Action"})]})}),e.jsx($s,{children:l?e.jsx(at,{children:e.jsxs(be,{colSpan:7,className:"text-center py-12",children:[e.jsx(ze,{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(at,{children:e.jsxs(be,{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(u=>{var h;return e.jsxs(at,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(be,{children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:u.dealerName}),e.jsx("p",{className:"text-xs text-gray-500",children:u.dealerCode})]})}),e.jsx(be,{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(va,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:u.email||"—"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-600",children:[e.jsx(oi,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:u.phone||"—"})]})]})}),e.jsx(be,{className:"text-sm",children:u.location||"—"}),e.jsx(be,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:u.missingQuarters.map((g,f)=>e.jsx(re,{variant:"destructive",className:"text-xs",children:g},f))})}),e.jsx(be,{children:u.lastSubmissionDate?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:Dh(u.lastSubmissionDate)}),e.jsxs("p",{className:`text-xs ${u.daysSinceLastSubmission!=null&&u.daysSinceLastSubmission>90?"text-red-600":"text-gray-500"}`,children:[u.daysSinceLastSubmission," days ago"]})]}):e.jsx(re,{variant:"outline",className:"text-xs bg-red-50 text-red-700 border-red-200",children:"Never Submitted"})}),e.jsx(be,{children:u.lastNotifiedDate?e.jsx(Gn,{children:e.jsxs($i,{children:[e.jsx(Ui,{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(ft,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:Dh(u.lastNotifiedDate)})]}),u.notificationCount>1&&e.jsxs(re,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[u.notificationCount,"x"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-600",children:[e.jsx(Ht,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:u.lastNotifiedBy})]})]})}),e.jsx(Bi,{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 (",u.notificationCount,")"]}),e.jsx("div",{className:"space-y-1.5",children:(h=u.notificationHistory)==null?void 0:h.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(re,{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(re,{variant:"outline",className:"text-xs bg-gray-50 text-gray-600 border-gray-200",children:"Never Notified"})}),e.jsx(be,{className:"text-right",children:e.jsxs(E,{size:"sm",onClick:()=>p(u),disabled:t===u.id,className:"bg-teal-600 hover:bg-teal-700 text-white",children:[e.jsx(_s,{className:"w-4 h-4 mr-1"}),t===u.id?"Sending...":"Notify"]})})]},u.id)})})]})})})]})]})})}function hI(){const t=Cs(),[s,a]=x.useState([]),[r,n]=x.useState([]),[i,l]=x.useState(!0),[o,c]=x.useState(!1),[d,m]=x.useState({financialYear:"all",quarter:"all"});x.useEffect(()=>{let w=!1;return(async()=>{l(!0);try{const[I,D]=await Promise.all([Wp(),Xv({status:"pending,failed,completed"})]);w||(a(Array.isArray(I)?I:[]),n(Array.isArray(D)?D:[]))}catch{w||(W.error("Failed to load pending submissions"),a([]),n([]))}finally{w||l(!1)}})(),()=>{w=!0}},[]);const p=s.filter(w=>!(d.financialYear!=="all"&&w.financial_year!==d.financialYear||d.quarter!=="all"&&w.quarter!==d.quarter)),u=p.length,h=p.filter(w=>(w.days_overdue??0)>0).length,g=p.filter(w=>(w.days_remaining??0)>0).length,f=()=>m({financialYear:"all",quarter:"all"}),b=d.financialYear!=="all"||d.quarter!=="all",j=w=>{if(!w)return"—";try{return new Date(w).toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}catch{return w}},y=w=>w==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(w),N=w=>{const I=(w||"").toLowerCase();return I==="completed"?"bg-emerald-50 text-emerald-700 border-emerald-200":I==="balance mismatch"||I==="failed"?"bg-red-50 text-red-700 border-red-200":I==="resubmission needed"||I==="duplicate"||I==="duplicate submission"?"bg-amber-50 text-amber-700 border-amber-200":"bg-slate-50 text-slate-600 border-slate-200"},S=w=>{t("/form16/submit")},A=[...new Set(s.map(w=>w.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(Ua,{className:"w-4 h-4"}),"Filters",b&&e.jsx(re,{variant:"default",className:"ml-1 bg-teal-600 hover:bg-teal-700",children:[d.financialYear,d.quarter].filter(w=>w!=="all").length}),o?e.jsx(ul,{className:"w-4 h-4"}):e.jsx(jn,{className:"w-4 h-4"})]})]})]}),o&&e.jsxs(Z,{children:[e.jsx(ce,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{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(yt,{className:"w-4 h-4"}),"Clear All"]})]})}),e.jsx(J,{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(se,{children:"Financial Year"}),e.jsxs(He,{value:d.financialYear,onValueChange:w=>m(I=>({...I,financialYear:w})),children:[e.jsx(We,{children:e.jsx(Ge,{placeholder:"All years"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Years"}),A.map(w=>e.jsx(X,{value:w,children:w},w))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Quarter"}),e.jsxs(He,{value:d.quarter,onValueChange:w=>m(I=>({...I,quarter:w})),children:[e.jsx(We,{children:e.jsx(Ge,{placeholder:"All quarters"})}),e.jsxs(Ye,{children:[e.jsx(X,{value:"all",children:"All Quarters"}),e.jsx(X,{value:"Q1",children:"Q1"}),e.jsx(X,{value:"Q2",children:"Q2"}),e.jsx(X,{value:"Q3",children:"Q3"}),e.jsx(X,{value:"Q4",children:"Q4"})]})]})]})]})})]}),h>0&&e.jsx(Z,{className:"border-red-200 bg-red-50",children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ss,{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:[h," overdue submission",h>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(J,{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:u})]}),e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center",children:e.jsx(Fe,{className:"w-6 h-6 text-gray-600"})})]})})}),e.jsx(Z,{children:e.jsx(J,{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:h})]}),e.jsx("div",{className:"w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center",children:e.jsx(ss,{className:"w-6 h-6 text-red-600"})})]})})}),e.jsx(Z,{children:e.jsx(J,{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(ft,{className:"w-6 h-6 text-amber-600"})})]})})})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Pending Form 16A Submissions"}),e.jsx(we,{children:"Complete list of quarters awaiting submission."})]}),e.jsx(J,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{className:"bg-gray-50",children:[e.jsx(Ae,{children:"Dealer Name"}),e.jsx(Ae,{children:"Financial Year"}),e.jsx(Ae,{children:"Quarter"}),e.jsx(Ae,{children:"Version"}),e.jsx(Ae,{children:"Status"}),e.jsx(Ae,{children:"26AS start date"}),e.jsx(Ae,{children:"Days Status"}),e.jsx(Ae,{className:"text-right",children:"Action"})]})}),e.jsx($s,{children:i?e.jsx(at,{children:e.jsxs(be,{colSpan:8,className:"text-center py-12 text-gray-500",children:[e.jsx(ze,{className:"w-8 h-8 animate-spin mx-auto mb-2"}),e.jsx("p",{children:"Loading..."})]})}):p.length===0?e.jsx(at,{children:e.jsx(be,{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(Fe,{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(w=>e.jsxs(at,{className:"hover:bg-gray-50",children:[e.jsx(be,{className:"text-sm text-gray-900",children:w.dealer_name??"Your submission"}),e.jsx(be,{children:e.jsxs("span",{className:"text-sm text-gray-900",children:["FY ",w.financial_year]})}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:w.quarter})}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:w.has_submission?"V1":"—"})}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:w.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":w.has_submission?"bg-slate-50 text-slate-600 border-slate-200":"bg-gray-100 text-gray-600 border-gray-200",children:w.latest_submission_status==="failed"?"Failed":w.has_submission?"Under review":"Not Submitted"})}),e.jsx(be,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-700",children:j(w.twenty_six_as_start_date??w.audit_start_date)})]})}),e.jsx(be,{children:w.days_since_26as_uploaded!=null&&w.days_since_26as_uploaded>=0?e.jsxs("span",{className:"text-sm font-medium text-gray-700",children:["due from ",w.days_since_26as_uploaded," days"]}):e.jsx("span",{className:"text-sm text-gray-500",children:"—"})}),e.jsx(be,{className:"text-right",children:e.jsx(E,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>S(),children:"Submit Now"})})]},`${w.financial_year}|${w.quarter}`))})]})})})]}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Your Form 16 Submissions"}),e.jsx(we,{children:"Requests you have submitted. Total amount and credit note (when issued) are shown. Status is never shown as Pending."})]}),e.jsx(J,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(at,{className:"bg-gray-50",children:[e.jsx(Ae,{children:"Request ID"}),e.jsx(Ae,{children:"Financial Year"}),e.jsx(Ae,{children:"Quarter"}),e.jsx(Ae,{className:"text-right",children:"Total Amount"}),e.jsx(Ae,{children:"Credit Note No."}),e.jsx(Ae,{children:"Status"}),e.jsx(Ae,{children:"Submitted"}),e.jsx(Ae,{className:"text-right",children:"Action"})]})}),e.jsx($s,{children:i?e.jsx(at,{children:e.jsx(be,{colSpan:8,className:"text-center py-8 text-gray-500",children:e.jsx(ze,{className:"w-6 h-6 animate-spin mx-auto"})})}):r.length===0?e.jsx(at,{children:e.jsx(be,{colSpan:8,className:"text-center py-8 text-gray-500",children:'No Form 16 submissions yet. Use "New Submission" to submit.'})}):r.map(w=>e.jsxs(at,{className:"hover:bg-gray-50",children:[e.jsx(be,{className:"font-mono text-sm",children:w.requestId?String(w.requestId).slice(0,8)+"…":"—"}),e.jsxs(be,{children:["FY ",w.financial_year]}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:w.quarter})}),e.jsx(be,{className:"text-right font-medium",children:y(w.total_amount)}),e.jsx(be,{children:w.credit_note_number??"—"}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:N(w.display_status),children:w.display_status??(w.status==="completed"?"Completed":w.status==="failed"?"Failed":"Under review")})}),e.jsx(be,{className:"text-sm text-gray-600",children:j(w.submitted_date)}),e.jsx(be,{className:"text-right",children:e.jsx(E,{variant:"outline",size:"sm",onClick:()=>t(`/request/${w.requestId}`),children:"View Request"})})]},w.id))})]})})})]}),s.length>0&&e.jsxs(Z,{className:"border-amber-200 bg-amber-50/50",children:[e.jsxs(ce,{children:[e.jsx(de,{className:"text-amber-900",children:"Quarters Pending Submission"}),e.jsx(we,{className:"text-amber-700",children:"These quarters don't have completed Form 16A submissions. Please submit Form 16A for these quarters."})]}),e.jsx(J,{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(w=>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:w.quarter}),e.jsx("p",{className:"text-sm text-gray-600",children:w.financial_year}),w.has_submission&&w.latest_submission_status&&e.jsx(re,{variant:"outline",className:`mt-1 text-xs ${w.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":"bg-slate-50 text-slate-600 border-slate-200"}`,children:w.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"})]})},`${w.financial_year}|${w.quarter}`))})})]})]})}function pI({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[l,o]=x.useState(""),[c,d]=x.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()},h=a==="approve"?{title:"Approve Request",description:"Please provide your approval comments and remarks",icon:Be,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=h.icon;return e.jsx(xt,{open:t,onOpenChange:p,children:e.jsxs(dt,{className:"max-w-2xl bg-white",children:[e.jsxs(ht,{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 ${h.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl",children:h.title}),e.jsx(_t,{className:"mt-1",children:h.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(re,{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(re,{className:h.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(se,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(zs,{id:"comment",placeholder:h.placeholder,value:l,onChange:f=>o(f.target.value.slice(0,500)),className:"min-h-[120px] resize-none",rows:6}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ss,{className:"w-3 h-3"}),"Comments are required and will be visible to all participants"]}),e.jsxs("span",{children:[l.length,"/500"]})]})]}),a==="reject"&&e.jsx("div",{className:"p-3 bg-orange-50 border border-orange-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ss,{className:"w-4 h-4 text-orange-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium text-orange-800",children:"Rejection Guidelines"}),e.jsx("p",{className:"text-orange-700 mt-1",children:"Please provide specific, actionable feedback to help the initiator improve their request."})]})]})}),a==="approve"&&e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Be,{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(Dt,{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:h.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 gI=(t,s,a,r,n,i,l,o)=>{let c=document.documentElement,d=["light","dark"];function m(h){(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[h]?i[h]:h)):c.setAttribute(g,h)}),p(h)}function p(h){o&&d.includes(h)&&(c.style.colorScheme=h)}function u(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let h=localStorage.getItem(s)||a,g=l&&h==="system"?u():h;m(g)}catch{}},fI=x.createContext(void 0),bI={setTheme:t=>{},themes:[]},jI=()=>{var t;return(t=x.useContext(fI))!=null?t:bI};x.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 x.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${gI.toString()})(${m})`}})});const yI=({...t})=>{const{theme:s="system"}=jI();return e.jsx(Jj,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function vI({open:t,onClose:s,onSelect:a,managers:r=[],errorType:n,message:i,isLoading:l=!1}){const o=c=>{a(c)};return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[600px]",children:[e.jsxs(ht,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:n==="NO_MANAGER_FOUND"?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-amber-500"}),"Manager Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ps,{className:"w-5 h-5 text-blue-500"}),"Select Your Manager"]})}),e.jsx(_t,{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(Je,{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(Ht,{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(va,{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(fc,{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 Rh({children:t}){const[s,a]=x.useState(!0),[r,n]=x.useState(!1);return x.useEffect(()=>{let i=!0;return(async()=>{try{const l=await Fc();if(!i)return;n(!!l.canView26AS)}catch{if(!i)return;n(!1)}finally{i&&a(!1)}})(),()=>{i=!1}},[]),s?e.jsx("div",{className:"flex items-center justify-center min-h-[240px]",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Checking access..."})}):r?e.jsx(e.Fragment,{children:t}):e.jsx("div",{className:"flex items-center justify-center min-h-[320px]",children:e.jsxs("div",{className:"max-w-lg w-full rounded-lg border bg-card p-6 text-center",children:[e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Unauthorized access"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You do not have permission to access the Form 26AS page."})]})})}function NI({onViewRequest:t}){const{user:s}=us();return Sl(s)?e.jsx(OD,{onViewRequest:t}):e.jsx(BD,{onViewRequest:t})}function Fh({onNavigate:t,onNewRequest:s}){const[a,r]=x.useState(!1),[n,i]=x.useState(!0);return x.useEffect(()=>{try{const l=tt.getUserData();r((l==null?void 0:l.jobTitle)==="Dealer")}catch(l){console.error("[App] Error checking dealer status:",l),r(!1)}finally{i(!1)}},[]),n?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"w-8 h-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})}):a?e.jsx(a6,{onNavigate:t,onNewRequest:s}):e.jsx(w1,{onNavigate:t,onNewRequest:s})}function wI({onLogout:t}){const s=Cs(),[a,r]=x.useState(null),[n,i]=x.useState([]),[l,o]=x.useState(""),[c,d]=x.useState(""),[m,p]=x.useState(!1),[u,h]=x.useState(null);x.useEffect(()=>{const w=localStorage.getItem("dynamicRequests");if(w)try{const I=JSON.parse(w);i(I)}catch(I){console.error("Error parsing dynamic requests:",I)}},[]),x.useEffect(()=>{n.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(n))},[n]);const g=w=>{if(w==="profile"){s("/profile");return}if(w==="settings"){s("/settings");return}w.startsWith("/")?s(w):s(`/${w}`)},f=(w,I,D,T)=>{o(w),d(I||"Unknown Request"),ol({requestId:w,status:D,request:T,navigate:s})},b=()=>{s(-1)},j=()=>{s("/new-request")},y=w=>{var T,v,M,P,B,k,_,L,R,C,G;if(w.templateType){w.templateType==="claim-management"&&s("/claim-management");return}if(w.backendId){s("/my-requests");return}const D={id:`RE-REQ-2024-${String(n.length+1).padStart(3,"0")}`,title:w.title,description:w.description||"",category:w.category||"General",subcategory:w.subcategory||"",status:"pending",priority:w.priority||"standard",amount:w.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:((T=w.approvers)==null?void 0:T.length)||1,currentApprover:((M=(v=w.approvers)==null?void 0:v[0])==null?void 0:M.name)||((k=(B=(P=w.approvers)==null?void 0:P[0])==null?void 0:B.email)==null?void 0:k.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((_=w.approvers)==null?void 0:_.length)||1}`,template:"custom",initiator:{name:"Current User",role:w.initiatorRole||"Employee",department:w.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:w.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:(w.approvers||[]).filter(U=>U).map((U,$)=>{var K;const F=(U==null?void 0:U.name)||((K=U==null?void 0:U.email)==null?void 0:K.split("@")[0])||`Approver ${$+1}`,H=(U==null?void 0:U.email)||"";return{step:$+1,approver:`${F}${H?` (${H})`:""}`,role:(U==null?void 0:U.role)||`Level ${(U==null?void 0:U.level)||$+1} Approver`,status:$===0?"pending":"waiting",tatHours:U!=null&&U.tat?typeof U.tat=="string"?parseInt(U.tat):U.tat:48,elapsedHours:0,assignedAt:$===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(w.spectators||[]).filter(U=>U&&(U.name||U.email)).map(U=>{var F;const $=(U==null?void 0:U.name)||((F=U==null?void 0:U.email)==null?void 0:F.split("@")[0])||"Observer";return{name:$,role:(U==null?void 0:U.role)||(U==null?void 0:U.department)||"Observer",avatar:$.split(" ").map(H=>H[0]).join("").toUpperCase().slice(0,2)||"OB"}}),auditTrail:[{type:"created",action:"Request Created",details:`Custom request "${w.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 ${((R=(L=w.approvers)==null?void 0:L[0])==null?void 0:R.name)||((G=(C=w.approvers)==null?void 0:C[0])==null?void 0:G.email)||"first approver"}`,user:"System",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}],tags:w.tags||["custom-request"]};i([...n,D]),s("/my-requests")},N=(w,I)=>new Promise(D=>{setTimeout(()=>{w==="approve"?W.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):W.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),r(null),D(!0)},1e3)}),S=()=>{r(null)},A=async(w,I)=>{var D,T,v,M,P,B,k;try{const _={activityName:w.activityName,activityType:w.activityType,dealerCode:w.dealerCode,dealerName:w.dealerName,dealerEmail:w.dealerEmail||void 0,dealerPhone:w.dealerPhone||void 0,dealerAddress:w.dealerAddress||void 0,activityDate:w.activityDate?new Date(w.activityDate).toISOString():void 0,location:w.location,requestDescription:w.requestDescription,periodStartDate:w.periodStartDate?new Date(w.periodStartDate).toISOString():void 0,periodEndDate:w.periodEndDate?new Date(w.periodEndDate).toISOString():void 0,estimatedBudget:w.estimatedBudget||void 0,approvers:w.approvers||[]},L=await k4(_);if(!L||!L.request)throw new Error("Invalid response from server: Request object not found");const R=L.request;if(!R.requestNumber&&!R.requestId)throw new Error("Invalid response from server: Request identifier not found");p(!1),h(null),W.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),R.requestNumber?s(`/request/${R.requestNumber}`):R.requestId?s(`/request/${R.requestId}`):s("/my-requests")}catch(_){console.error("[App] Error creating claim request:",_);const L=(D=_==null?void 0:_.response)==null?void 0:D.data,R=(L==null?void 0:L.code)||((T=L==null?void 0:L.error)==null?void 0:T.code);if(R==="NO_MANAGER_FOUND"){h({errorType:"NO_MANAGER_FOUND",message:(L==null?void 0:L.message)||((v=L==null?void 0:L.error)==null?void 0:v.message)||"No reporting manager found. Please ensure your manager is correctly configured in the system.",pendingClaimData:w}),p(!0);return}if(R==="MULTIPLE_MANAGERS_FOUND"){const G=(L==null?void 0:L.managers)||((M=L==null?void 0:L.error)==null?void 0:M.managers)||[];h({errorType:"MULTIPLE_MANAGERS_FOUND",managers:G,message:(L==null?void 0:L.message)||((P=L==null?void 0:L.error)==null?void 0:P.message)||"Multiple managers found. Please select one.",pendingClaimData:w}),p(!0);return}const C=((k=(B=_==null?void 0:_.response)==null?void 0:B.data)==null?void 0:k.message)||(_==null?void 0:_.message)||"Failed to create claim request";W.error("Failed to Submit Claim Request",{description:C})}};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(ay,{children:[e.jsx(kt,{path:"/login/callback",element:e.jsx(Fp,{})}),e.jsx(kt,{path:"/",element:e.jsx(zt,{currentPage:"dashboard",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(Fh,{onNavigate:g,onNewRequest:j})})}),e.jsx(kt,{path:"/dashboard",element:e.jsx(zt,{currentPage:"dashboard",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(Fh,{onNavigate:g,onNewRequest:j})})}),e.jsxs(kt,{element:e.jsx(zt,{currentPage:"admin",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(ry,{})}),children:[e.jsx(kt,{path:"/admin",element:e.jsx(PF,{})}),e.jsx(kt,{path:"/admin/create-template",element:e.jsx(wh,{})}),e.jsx(kt,{path:"/admin/edit-template/:templateId",element:e.jsx(wh,{})}),e.jsx(kt,{path:"/admin/templates",element:e.jsx(YR,{})})]}),e.jsx(kt,{path:"/create-admin-request/:templateId",element:e.jsx(XR,{})}),e.jsx(kt,{path:"/open-requests",element:e.jsx(zt,{currentPage:"open-requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(x6,{onViewRequest:f})})}),e.jsx(kt,{path:"/closed-requests",element:e.jsx(zt,{currentPage:"closed-requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(L6,{onViewRequest:f})})}),e.jsx(kt,{path:"/shared-summaries",element:e.jsx(zt,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(H6,{})})}),e.jsx(kt,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(zt,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(G6,{})})}),e.jsx(kt,{path:"/form16/credit-notes",element:e.jsx(zt,{currentPage:"form16-credit-notes",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(LF,{})})}),e.jsx(kt,{path:"/form16/credit-notes/:id",element:e.jsx(zt,{currentPage:"form16-credit-notes",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(UF,{})})}),e.jsx(kt,{path:"/form16/debit-notes",element:e.jsx(zt,{currentPage:"form16-debit-notes",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(HF,{})})}),e.jsx(kt,{path:"/form16/transactions",element:e.jsx(zt,{currentPage:"form16-transactions",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(XF,{})})}),e.jsx(kt,{path:"/form16/submit",element:e.jsx(zt,{currentPage:"form16-submit",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(eI,{})})}),e.jsx(kt,{path:"/form16/submit/result",element:e.jsx(zt,{currentPage:"form16-submit",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(nI,{})})}),e.jsx(kt,{path:"/form16/dashboard",element:e.jsx(zt,{currentPage:"form16-dashboard",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(Rh,{children:e.jsx(mI,{})})})}),e.jsx(kt,{path:"/form16/26as",element:e.jsx(zt,{currentPage:"form16-26as",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(Rh,{children:e.jsx(dI,{})})})}),e.jsx(kt,{path:"/form16/pending-submissions",element:e.jsx(zt,{currentPage:"form16-pending-submissions",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(hI,{})})}),e.jsx(kt,{path:"/form16/non-submitted-dealers",element:e.jsx(zt,{currentPage:"form16-non-submitted-dealers",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(xI,{})})}),e.jsx(kt,{path:"/my-requests",element:e.jsx(zt,{currentPage:"my-requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(dD,{onViewRequest:f,dynamicRequests:n})})}),e.jsx(kt,{path:"/requests",element:e.jsx(zt,{currentPage:"requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(NI,{onViewRequest:f})})}),e.jsx(kt,{path:"/approver-performance",element:e.jsx(zt,{currentPage:"approver-performance",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(tR,{})})}),e.jsx(kt,{path:"/request/:requestId",element:e.jsx(zt,{currentPage:"request-detail",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(z6,{requestId:"",onBack:b,dynamicRequests:n})})}),e.jsx(kt,{path:"/work-notes/:requestId",element:e.jsx(W6,{})}),e.jsx(kt,{path:"/new-request",element:e.jsx(dh,{onBack:b,onSubmit:y})}),e.jsx(kt,{path:"/edit-request/:requestId",element:e.jsx(dh,{onBack:b,onSubmit:y,requestId:void 0,isEditMode:!0})}),e.jsx(kt,{path:"/claim-management",element:e.jsx(W4,{onBack:b,onSubmit:A})}),e.jsx(kt,{path:"/profile",element:e.jsx(zt,{currentPage:"profile",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(sR,{})})}),e.jsx(kt,{path:"/settings",element:e.jsx(zt,{currentPage:"settings",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(yR,{})})}),e.jsx(kt,{path:"/settings/security",element:e.jsx(zt,{currentPage:"settings",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(AR,{})})}),e.jsx(kt,{path:"/notifications",element:e.jsx(zt,{currentPage:"notifications",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(TR,{onNavigate:g})})}),e.jsx(kt,{path:"/detailed-reports",element:e.jsx(zt,{currentPage:"detailed-reports",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(WR,{})})})]}),e.jsx(yI,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),e.jsx(vI,{open:m,onClose:()=>{p(!1),h(null)},onSelect:async w=>{u!=null&&u.pendingClaimData&&await A(u.pendingClaimData)},managers:u==null?void 0:u.managers,errorType:(u==null?void 0:u.errorType)||"NO_MANAGER_FOUND",message:u==null?void 0:u.message,isLoading:!1}),a&&e.jsx(pI,{isOpen:!!a,onClose:S,action:a,requestId:l,requestTitle:c,onSubmit:N})]})}function CI(t){const{onLogout:s}=t||{};return e.jsx(sy,{children:e.jsx(wI,{onLogout:s})})}function SI(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=us(),[i,l]=x.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(u){console.error("🔵 Logout error in handleLogout:",u);try{localStorage.clear(),sessionStorage.clear(),window.location.href="/"}catch(h){console.error("🔵 Error during emergency cleanup:",h)}}};x.useEffect(()=>{},[t,s,a,r]);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");return o&&(m||p||t)?(typeof window<"u"?sessionStorage.getItem("auth_provider"):null)==="tanflow"?e.jsx(Pv,{}):e.jsx(Fp,{}):s&&tt.getAuthError()!=="SESSION_SUPERSEDED"?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(CI,{onLogout:c}),i&&e.jsx(_v,{isOpen:i,onClose:()=>l(!1)})]}):e.jsx(Iv,{})}const Wi=()=>{try{return!0}catch{return!1}},AI=()=>{if(Wi())return null;try{return localStorage.getItem("token")}catch{return null}},TI={user:null,token:AI(),isAuthenticated:!1,isLoading:!1,error:null},Qf=yn({name:"auth",initialState:TI,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,!Wi())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,!Wi())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!Wi())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:UI,loginSuccess:BI,loginFailure:VI,logout:zI,clearError:HI,updateUser:GI}=Qf.actions,kI=ey({reducer:{auth:Qf.reducer,dashboard:Yp.reducer,requests:Mf.reducer,myRequests:If.reducer,openRequests:ng.reducer,closedRequests:Df.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});Lo.createRoot(document.getElementById("root")).render(e.jsx(qb.StrictMode,{children:e.jsx(Cy,{store:kI,children:e.jsx(qy,{children:e.jsx(SI,{})})})}));export{ve as a};
|