Re_Backend/build/assets/index-BVr6jLdd.js
2026-04-09 15:39:13 +05:30

65 lines
1.6 MiB
Raw Blame History

This file contains invisible Unicode characters

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

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

const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-BFrrhPzD.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 Yf=Object.defineProperty;var Qf=(t,s,a)=>s in t?Yf(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var El=(t,s,a)=>Qf(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Rh,R as Fh,I as Ih,F as Ph,a as Kf,T as Xf,P as Zf,C as Jf,b as qf,O as Eh,c as _h,d as eb,e as tb,f as sb,D as ab,g as rb,A as nb,h as ib,i as lb,k as ob,l as cb,m as db,n as mb,V as ub,o as xb,p as hb,q as pb,r as gb,s as fb,t as bb,u as jb,v as yb,w as vb,x as Nb,y as wb,z as Cb,B as Sb,E as Ab,G as Tb,H as kb,J as Db,K as Rb,L as Fb,M as Ib,N as Pb,Q as cc,U as dc,W as Eb,X as Mh,Y as Lh,Z as Oh,_ as $h,$ as _b,a0 as Mb,a1 as Lb,a2 as Ob,a3 as $b,a4 as Ub,a5 as Bb,a6 as Vb,a7 as zb,a8 as on,a9 as pr,aa as Kn,ab as Hb,ac as Gb,ad as Wb,ae as Yb}from"./radix-vendor-CLtqm-Ae.js";import{a as Qb,r as x,d as Uh,e as cn,B as Ro,C as Hi,X as Gi,Y as Wi,T as dn,L as Yi,f as Ea,P as Bh,g as Vh,h as zh,i as Kb,j as lu,k as il,l as ll,b as Xb}from"./charts-vendor-CmYZJIYl.js";import{a as ol,f as Hh,s as ma,e as mc,b as ou,c as Zb,d as Oa,g as Xn,i as uc,h as Gh,j as ea,k as oa,l as _l,m as Qa,n as Jb,o as Fo,p as qb,q as tt,r as Io,t as ej,u as tj,v as sj,w as aj,x as Ml,y as cu,z as rj,A as Wh,B as Yh,C as xc,D as hc,E as nj,F as ij,G as Qh,H as Zr,I as Ll,J as lj,K as oj,L as cj}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 dj,b as Kh,U as Ht,F as Fe,c as Be,d as fn,R as Mt,e as bn,f as Ka,P as ms,g as mj,h as uj,B as _s,i as cr,j as Ol,k as pc,l as $a,m as cl,n as hn,o as ft,p as Ua,q as Et,I as zr,T as ts,r as it,s as Ia,t as xj,v as ss,M as Ys,w as dl,x as Bt,y as Po,D as Tt,Z as ml,z as qt,E as hj,G as pj,J as gj,K as fj,N as bj,O as jj,Q as yj,V as vj,W as Nj,Y as Xh,_ as wj,$ as Cj,a0 as Zh,a1 as va,a2 as ii,a3 as dr,a4 as Qi,a5 as du,a6 as vi,a7 as Ki,a8 as Jh,a9 as St,aa as Sj,ab as Qs,ac as gc,ad as ws,ae as ul,af as qh,ag as Nt,ah as Aj,ai as Tj,aj as ep,ak as xl,al as tp,am as kj,an as fc,ao as ys,ap as Da,aq as sp,ar as hl,as as pl,at as Zt,au as Dj,av as Rj,aw as ap,ax as rp,ay as Pi,az as lr,aA as bc,aB as gl,aC as Zn,aD as np,aE as ip,aF as jc,aG as fl,aH as bl,aI as Eo,aJ as Fj,aK as Vs,aL as lp,aM as Xi,aN as Ij,aO as Pj,aP as Ej,aQ as jl,aR as yl,aS as yc,aT as _j,aU as mu,aV as Ba,aW as Hr,aX as Mj,aY as tn,aZ as uu,a_ as Lj,a$ as Oj,b0 as op,b1 as xu,b2 as cp,b3 as $j,b4 as Uj,b5 as Bj,b6 as Vj,b7 as dp,b8 as zj,b9 as Hj,ba as Gj,bb as vl,bc as Wj,bd as Yj,be as Qj,bf as Kj}from"./ui-vendor-DgwXkk2Y.js";import{l as Xj}from"./socket-vendor-TjCxX7sJ.js";import{c as jn,a as Zj}from"./redux-vendor-tbZCm13o.js";import{u as Cs,a as Va,b as mp,c as Jj,B as qj,R as ey,d as kt,O as ty}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 _o={},hu=Qb;_o.createRoot=hu.createRoot,_o.hydrateRoot=hu.hydrateRoot;var up={exports:{}},xp={};var li=x;function sy(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var ay=typeof Object.is=="function"?Object.is:sy,ry=li.useSyncExternalStore,ny=li.useRef,iy=li.useEffect,ly=li.useMemo,oy=li.useDebugValue;xp.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=ny(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=ly(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,ay(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=ry(t,i[0],i[1]);return iy(function(){l.hasValue=!0,l.value=o},[o]),oy(o),o};up.exports=xp;var cy=up.exports;function dy(t){t()}function my(){let t=null,s=null;return{clear(){t=null,s=null},notify(){dy(()=>{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 pu={notify(){},get:()=>[]};function uy(t,s){let a,r=pu,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=my())}function p(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=pu)}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 xy=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",hy=xy(),py=()=>typeof navigator<"u"&&navigator.product==="ReactNative",gy=py(),fy=()=>hy||gy?x.useLayoutEffect:x.useEffect,by=fy(),$l=Symbol.for("react-redux-context"),Ul=typeof globalThis<"u"?globalThis:{};function jy(){if(!x.createContext)return{};const t=Ul[$l]??(Ul[$l]=new Map);let s=t.get(x.createContext);return s||(s=x.createContext(null),t.set(x.createContext,s)),s}var mr=jy();function yy(t){const{children:s,context:a,serverState:r,store:n}=t,i=x.useMemo(()=>{const c=uy(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=x.useMemo(()=>n.getState(),[n]);by(()=>{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||mr;return x.createElement(o.Provider,{value:i},s)}var vy=yy;function vc(t=mr){return function(){return x.useContext(t)}}var hp=vc();function pp(t=mr){const s=t===mr?hp:vc(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var Ny=pp();function wy(t=mr){const s=t===mr?Ny:pp(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var Cy=wy(),Sy=(t,s)=>t===s;function Ay(t=mr){const s=t===mr?hp:vc(t),a=(r,n={})=>{const{equalityFn:i=Sy}=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=cy.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return x.useDebugValue(p),p};return Object.assign(a,{withTypes:()=>a}),a}var Ty=Ay(),Mo=function(t,s){return Mo=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])},Mo(t,s)};function ky(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");Mo(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var Zi=function(){return Zi=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},Zi.apply(this,arguments)};var Fr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Nc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function wc(t,s){return t(s={exports:{}},s.exports),s.exports}var Tr=wc(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()}});Nc(Tr);var Dy=Nc(wc(function(t,s){var a=Fr&&Fr.__awaiter||function(m,p,u,h){return new(u||(u=Promise))(function(g,f){function b(v){try{y(h.next(v))}catch(w){f(w)}}function j(v){try{y(h.throw(v))}catch(w){f(w)}}function y(v){v.done?g(v.value):new u(function(w){w(v.value)}).then(b,j)}y((h=h.apply(m,p||[])).next())})},r=Fr&&Fr.__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(v){return function(w){if(u)throw new TypeError("Generator is already executing.");for(;b;)try{if(u=1,h&&(g=2&w[0]?h.return:w[0]?h.throw||((g=h.return)&&g.call(h),0):h.next)&&!(g=g.call(h,w[1])).done)return g;switch(h=0,g&&(w=[2&w[0],g.value]),w[0]){case 0:case 1:g=w;break;case 4:return b.label++,{value:w[1],done:!1};case 5:b.label++,h=w[1],w=[0];continue;case 7:w=b.ops.pop(),b.trys.pop();continue;default:if(g=b.trys,!((g=g.length>0&&g[g.length-1])||w[0]!==6&&w[0]!==2)){b=0;continue}if(w[0]===3&&(!g||w[1]>g[0]&&w[1]<g[3])){b.label=w[1];break}if(w[0]===6&&b.label<g[1]){b.label=g[1],g=w;break}if(g&&b.label<g[2]){b.label=g[2],b.ops.push(w);break}g[2]&&b.ops.pop(),b.trys.pop();continue}w=p.call(m,b)}catch(A){w=[6,A],h=0}finally{u=g=0}if(5&w[0])throw w[1];return{value:w[0]?w[1]:void 0,done:!0}}([y,v])}}},n=Fr;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,v;return r(this,function(w){switch(w.label){case 0:h=Date.now()+c(4),g=Date.now()+u,f=i+"-"+p,b=this.storageHandler===void 0?l:this.storageHandler,w.label=1;case 1:return Date.now()<g?[4,o(30)]:[3,8];case 2:return w.sent(),b.getItemSync(f)!==null?[3,5]:(j=this.id+"-"+p+"-"+h,[4,o(Math.floor(25*Math.random()))]);case 3:return w.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 w.sent(),(y=b.getItemSync(f))!==null&&(v=JSON.parse(y)).id===this.id&&v.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:w.sent(),w.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,Tr.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?(Tr.default().unlock(u),[2]):((j=JSON.parse(b)).timeRefreshed=Date.now(),f.setItemSync(p,JSON.stringify(j)),Tr.default().unlock(u),this.refreshLockWhileAcquired(p,u),[2])):(Tr.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 v=50-(Date.now()-f);v>0?setTimeout(h,v):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,Tr.default().lock(f.iat)];case 1:b.sent(),this.acquiredIatSet.delete(f.iat),u.removeItemSync(h),Tr.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 v=g[y];if(v.includes(i)){var w=h.getItemSync(v);if(w!==null){var A=JSON.parse(w);(A.timeRefreshed===void 0&&A.timeAcquired<u||A.timeRefreshed!==void 0&&A.timeRefreshed<u)&&(h.removeItemSync(v),j=!0)}}}j&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var Pr=wc(function(t,s){var a=Fr&&Fr.__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}))}});Nc(Pr),Pr.encode,Pr.parse,Pr.getAll;Pr.get;Pr.set;Pr.remove;var gu;(function(t){t.Code="code",t.ConnectCode="connect_code"})(gu||(gu={}));var fu;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(fu||(fu={}));new Dy;var Ry={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Zs=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},Fy=Zi(Zi({},Ry),{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}),Iy=x.createContext(Fy);(function(t){ky(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 Py=function(t){return t===void 0&&(t=Iy),x.useContext(t)};const Bl="idToken",Vl="userData",Ey=()=>!0;class nt{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(Bl,s)}static getIdToken(){return sessionStorage.getItem(Bl)}static setUserData(s){localStorage.setItem(Vl,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(Vl);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(Vl),sessionStorage.removeItem(Bl)}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 Ey()}static setAuthError(s){s?sessionStorage.setItem("__auth_error__",s):sessionStorage.removeItem("__auth_error__")}static getAuthError(){return sessionStorage.getItem("__auth_error__")}}function zl(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 gp="https://ssodev.rebridge.co.in/realms/RE",fp="REFLOW",bp=`${window.location.origin}/login/callback`,bu="http://localhost:5000/api/v1".trim(),_y=typeof window<"u"&&/^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname),My=(!_y&&/localhost:5000/i.test(bu)?"":bu.replace(/\/$/,""))||"/api/v1";function Ly(){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=`${gp}/protocol/openid-connect/auth?client_id=${fp}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(bp)}&state=${a}`;s&&(r+="&prompt=login"),window.location.href=r}async function Oy(t,s){var a,r,n;try{const i=await ol.post(`${My}/auth/tanflow/token-exchange`,{code:t,redirectUri:bp,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),l=((a=i.data)==null?void 0:a.data)||i.data;return l.accessToken&&nt.setAccessToken(l.accessToken),l.refreshToken&&nt.setRefreshToken(l.refreshToken),l.idToken&&nt.setIdToken(l.idToken),l.user&&nt.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 jp(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(`${gp}/protocol/openid-connect/logout`);s.searchParams.set("client_id",fp),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 yp(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 ju="http://localhost:5000/api/v1".trim(),$y=typeof window<"u"&&/^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname),Cc=(!$y&&/localhost:5000/i.test(ju)?"":ju.replace(/\/$/,""))||"/api/v1",ve=ol.create({baseURL:Cc,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=nt.getIdToken(),o=sessionStorage.getItem("auth_provider")||(l!=null&&l.includes("tanflow")?"tanflow":"okta");return nt.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?jp(l):yp(l||void 0)},1e3),Promise.reject(t)}if(!s._retry){s._retry=!0;const l=!0;try{const o=nt.getRefreshToken(),c=await ol.post(`${Cc}/auth/refresh`,l?{}:{refreshToken:o},{withCredentials:!0}),m=(c.data.data||c.data).accessToken;return ve(s)}catch(o){return nt.clearAll(),window.location.href="/",Promise.reject(o)}}}return Promise.reject(t)});async function Uy(t,s){const r=(await ve.post("/auth/login",{username:t,password:s},{withCredentials:!0})).data,n=r.data||r;return n.user&&nt.setUserData(n.user),n.accessToken&&n.refreshToken&&(nt.setAccessToken(n.accessToken),nt.setRefreshToken(n.refreshToken)),n}async function By(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&&nt.setUserData(l.user),l.idToken&&nt.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(nt.setAccessToken(l.accessToken),nt.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 Vy(){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 $n(){const s=(await ve.get("/auth/me")).data;return s.data||s}async function zy(){var t,s;try{await ol.post(`${Cc}/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 Cr=null;function Hy(){return"http://localhost:5000"}function Br(t){const s=Hy();return Cr||(Cr=Xj(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),Cr.on("connect",()=>{}),Cr.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),Cr.on("disconnect",a=>{}),Cr)}function Lo(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function vp(t,s){t.emit("leave:request",s)}function Sc(t,s){t.emit("join:user",{userId:s})}const Np=x.createContext(void 0);function Gy({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);x.useEffect(()=>{const w=sessionStorage.getItem("__logout_in_progress__"),A=sessionStorage.getItem("__force_logout__");if(w==="true"||A==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),nt.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(N){console.error("Error clearing storage:",N)}a(!1),l(null),n(!1),c(null);return}const C=new URLSearchParams(window.location.search),E=C.has("code"),D=sessionStorage.getItem("__logout_type__");if((C.has("logout")||C.has("okta_logged_out")||C.has("tanflow_logged_out")||D)&&!E){console.log("🚪 Logout parameter detected in URL, clearing all tokens and backend session"),zy().catch(N=>console.warn("🚪 Final backend logout cleanup failed:",N)),nt.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(N){console.warn("Could not set force reauth flag:",N)}window.history.replaceState({},document.title,"/");return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(nt.getUserData(),d?n(!1):h())},[d]),x.useEffect(()=>{if(!s)return;const w=async()=>{try{await y()}catch(E){console.error("Silent refresh failed:",E)}},A=10*60*1e3,C=setInterval(w,A);return()=>clearInterval(C)},[s]),x.useEffect(()=>{},[s]),x.useEffect(()=>{if(!s||!(i!=null&&i.userId))return;const w=Br();Sc(w,i.userId);const A=C=>{console.log("📡 [Socket] Session superseded event received:",C),nt.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(()=>{b()},1e3)};return w.on("SESSION_SUPERSEDED",A),()=>{w.off("SESSION_SUPERSEDED",A)}},[s,i==null?void 0:i.userId]);const p=x.useRef(!1),u=()=>{const w="http://localhost:5000".trim().replace(/\/+$/,""),A=/^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname);return`${A||!A&&/localhost(:\d+)?$/i.test(w)?window.location.origin:w||window.location.origin}/login/callback`};x.useEffect(()=>{if(p.current||window.location.pathname!=="/login/callback")return;(async()=>{const A=new URLSearchParams(window.location.search);if(sessionStorage.getItem("auth_provider")==="tanflow")return;const E=sessionStorage.getItem("__logout_type__");if((A.has("logout")||A.has("tanflow_logged_out")||A.has("okta_logged_out")||E)&&!A.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const _=new URLSearchParams;(A.has("tanflow_logged_out")||E==="tanflow")&&_.set("tanflow_logged_out","true"),(A.has("okta_logged_out")||E==="okta")&&_.set("okta_logged_out","true"),A.has("logout")&&_.set("logout",A.get("logout")||Date.now().toString());const I=_.toString()?`/?${_.toString()}`:"/?logout="+Date.now();window.location.replace(I);return}p.current=!0;const T=A.get("code"),N=A.get("error");if(window.history.replaceState({},document.title,"/login/callback"),N){c(new Error(`Authentication error: ${N}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!T){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),c(null);const _=u(),I=await By(T,_);l(I.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(_){console.error("❌ Token exchange error in AuthContext:",_),c(_),a(!1),l(null),sessionStorage.removeItem("auth_provider"),p.current=!1}finally{n(!1)}})()},[]);const h=async()=>{var A;if(d){n(!1);return}const w=!0;try{if(n(!0),w){const D=nt.getUserData();try{const T=await $n();l(T),nt.setUserData(T),a(!0)}catch(T){if(((A=T==null?void 0:T.response)==null?void 0:A.status)===401)try{await y();const N=await $n();l(N),nt.setUserData(N),a(!0)}catch{nt.clearAll(),a(!1),l(null)}else T!=null&&T.isConnectionError?D?(l(D),a(!0)):(a(!1),l(null)):(nt.clearAll(),a(!1),l(null))}return}const C=nt.getAccessToken(),E=nt.getUserData();if(!C){a(!1),l(null),n(!1);return}if(zl(C))try{await y();const D=nt.getAccessToken();if(D&&!zl(D)){const T=nt.getUserData();if(T)l(T),a(!0);else try{const N=await $n();l(N),nt.setUserData(N),a(!0)}catch{nt.clearAll(),a(!1),l(null)}}else nt.clearAll(),a(!1),l(null)}catch{nt.clearAll(),a(!1),l(null)}else if(E)l(E),a(!0);else try{const D=await $n();l(D),nt.setUserData(D),a(!0)}catch{nt.clearAll(),a(!1),l(null)}}catch(C){console.error("Error checking auth status:",C),c(C),nt.clearAll(),a(!1),l(null)}finally{n(!1)}},g=async()=>{try{c(null);const w="https://royalenfield.okta.com",A="0oa18b98aari6I6eo2p8",C=u(),E="code",D="openid profile email",T=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const N=new URLSearchParams(window.location.search),_=N.has("logout")||N.has("okta_logged_out")||N.has("tanflow_logged_out"),I=sessionStorage.getItem("__force_reauth_after_logout__")==="true",B=_||I;let k=`${w}/oauth2/default/v1/authorize?client_id=${A}&redirect_uri=${encodeURIComponent(C)}&response_type=${E}&scope=${encodeURIComponent(D)}&state=${T}`;B&&(k+="&prompt=login",sessionStorage.removeItem("__force_reauth_after_logout__")),window.location.href=k}catch(w){throw c(w),w}},f=async(w,A)=>{c(null),n(!0);try{const C=await Uy(w,A);l(C.user),a(!0),window.history.replaceState({},document.title,"/")}catch(C){throw c(C),a(!1),l(null),C}finally{n(!1)}},b=async()=>{try{const w=nt.getIdToken(),A=sessionStorage.getItem("auth_provider")||(w&&w.includes("tanflow")?"tanflow":null)||"okta";sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),l(null),c(null),n(!0);const C=sessionStorage.getItem("__logout_in_progress__"),E=sessionStorage.getItem("__force_logout__"),D=sessionStorage.getItem("auth_provider");if(nt.clearAll(),C&&sessionStorage.setItem("__logout_in_progress__",C),E&&sessionStorage.setItem("__force_logout__",E),w&&nt.setIdToken(w),D&&sessionStorage.setItem("auth_provider",D),await new Promise(T=>setTimeout(T,100)),A==="tanflow"&&w){console.log("🚪 Initiating Tanflow logout...");try{jp(w);return}catch(T){console.error("🚪 Tanflow logout error:",T)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),yp(w||void 0)}catch(w){console.error("🚪 Logout error:",w);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const A=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(A)}catch{window.location.replace("/?logout="+Date.now())}}},j=async()=>{{if(s)return"cookie-based-auth";try{return await y(),s?"cookie-based-auth":null}catch{return null}}const w=nt.getAccessToken();if(w&&!zl(w))return w;try{return await y(),nt.getAccessToken()}catch{return null}},y=async()=>{try{const A=await Vy();return}catch(A){throw nt.clearAll(),a(!1),l(null),A}},v={isAuthenticated:s,isLoading:r,user:i,error:o,login:g,loginWithPassword:f,logout:b,getAccessTokenSilently:j,refreshTokenSilently:y};return e.jsx(Np.Provider,{value:v,children:t})}function Wy({children:t}){return e.jsx(Gy,{children:t})}function us(){const t=x.useContext(Np);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function kr(t){return(t==null?void 0:t.role)==="ADMIN"}function Rn(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function Nl(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const yu=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,vu=Uh,Ac=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return vu(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=yu(m)||yu(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 vu(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},Tc="-",Yy=t=>{const s=Ky(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(Tc);return o[0]===""&&o.length!==1&&o.shift(),wp(o,s)||Qy(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},wp=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?wp(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Tc);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Nu=/^\[(.+)\]$/,Qy=t=>{if(Nu.test(t)){const s=Nu.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Ky=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Zy(Object.entries(t.classGroups),a).forEach(([i,l])=>{Oo(l,r,i,s)}),r},Oo=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:wu(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Xy(n)){Oo(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{Oo(l,wu(s,i),a,r)})})},wu=(t,s)=>{let a=t;return s.split(Tc).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Xy=t=>t.isThemeGetter,Zy=(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,Jy=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)}}},Cp="!",qy=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(Cp),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},ev=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},tv=t=>({cache:Jy(t.cacheSize),parseClassName:qy(t),...Yy(t)}),sv=/\s+/,av=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(sv);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=ev(m).join(":"),j=p?b+Cp:b,y=j+f;if(i.includes(y))continue;i.push(y);const v=n(f,g);for(let w=0;w<v.length;++w){const A=v[w];i.push(j+A)}o=d+(o.length>0?" "+o:o)}return o};function rv(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=Sp(s))&&(r&&(r+=" "),r+=a);return r}const Sp=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=Sp(t[r]))&&(a&&(a+=" "),a+=s);return a};function nv(t,...s){let a,r,n,i=l;function l(c){const d=s.reduce((m,p)=>p(m),t());return a=tv(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=av(c,a);return n(c,m),m}return function(){return i(rv.apply(null,arguments))}}const Kt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},Ap=/^\[(?:([a-z-]+):)?(.+)\]$/i,iv=/^\d+\/\d+$/,lv=new Set(["px","full","screen"]),ov=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,cv=/\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$/,dv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,mv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,uv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ga=t=>mn(t)||lv.has(t)||iv.test(t),rr=t=>yn(t,"length",yv),mn=t=>!!t&&!Number.isNaN(Number(t)),Hl=t=>yn(t,"number",mn),Fn=t=>!!t&&Number.isInteger(Number(t)),xv=t=>t.endsWith("%")&&mn(t.slice(0,-1)),jt=t=>Ap.test(t),nr=t=>ov.test(t),hv=new Set(["length","size","percentage"]),pv=t=>yn(t,hv,Tp),gv=t=>yn(t,"position",Tp),fv=new Set(["image","url"]),bv=t=>yn(t,fv,Nv),jv=t=>yn(t,"",vv),In=()=>!0,yn=(t,s,a)=>{const r=Ap.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},yv=t=>cv.test(t)&&!dv.test(t),Tp=()=>!1,vv=t=>mv.test(t),Nv=t=>uv.test(t),wv=()=>{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"),v=Kt("saturate"),w=Kt("scale"),A=Kt("sepia"),C=Kt("skew"),E=Kt("space"),D=Kt("translate"),T=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],_=()=>["auto",jt,s],I=()=>[jt,s],B=()=>["",Ga,rr],k=()=>["auto",mn,jt],M=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],F=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],S=()=>["start","end","center","between","around","evenly","stretch"],G=()=>["","0",jt],U=()=>["auto","avoid","all","avoid-page","page","left","right","column"],$=()=>[mn,jt];return{cacheSize:500,separator:":",theme:{colors:[In],spacing:[Ga,rr],blur:["none","",nr,jt],brightness:$(),borderColor:[t],borderRadius:["none","","full",nr,jt],borderSpacing:I(),borderWidth:B(),contrast:$(),grayscale:G(),hueRotate:$(),invert:G(),gap:I(),gradientColorStops:[t],gradientColorStopPositions:[xv,rr],inset:_(),margin:_(),opacity:$(),padding:I(),saturate:$(),scale:$(),sepia:G(),skew:$(),space:I(),translate:I()},classGroups:{aspect:[{aspect:["auto","square","video",jt]}],container:["container"],columns:[{columns:[nr]}],"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:[...M(),jt]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],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",Fn,jt]}],basis:[{basis:_()}],"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",Fn,jt]}],"grid-cols":[{"grid-cols":[In]}],"col-start-end":[{col:["auto",{span:["full",Fn,jt]},jt]}],"col-start":[{"col-start":k()}],"col-end":[{"col-end":k()}],"grid-rows":[{"grid-rows":[In]}],"row-start-end":[{row:["auto",{span:[Fn,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",...S()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...S(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...S(),"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":[E]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[E]}],"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:[nr]},nr]}],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",nr,rr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Hl]}],"font-family":[{font:[In]}],"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",mn,Hl]}],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,rr]}],"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:I()}],"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:[...M(),gv]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",pv]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},bv]}],"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,rr]}],"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,rr]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",nr,jv]}],"shadow-color":[{shadow:[In]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...F(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":F()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",nr,jt]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[v]}],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":[v]}],"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:[w]}],"scale-x":[{"scale-x":[w]}],"scale-y":[{"scale-y":[w]}],rotate:[{rotate:[Fn,jt]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",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":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"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,rr,Hl]}],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"]}}},Cv=nv(wv);function Le(...t){return Cv(Uh(t))}const Jn=Ac("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"}}),P=x.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Rh:"button";return e.jsx(l,{"data-slot":"button",className:Le(Jn({variant:s,size:a,className:t})),ref:i,...n})});P.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 wl="/assets/Re_Logo-By51taPS.png",Cu="/assets/landing_page_image-ClTD-4qZ.jpg";function Sv(){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=Cu,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{Ly()}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(${Cu})`:"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:wl,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 sites 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(P,{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(P,{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 kp(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=us(),[n,i]=x.useState("exchanging");x.useEffect(()=>{if(a){i("error");return}if(s){const c=new URLSearchParams(window.location.search).get("code");i(c&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&i("complete")},[t,s,a,r]);const l=()=>{switch(n){case"exchanging":return"Exchanging authorization code...";case"fetching":return"Fetching your profile...";case"complete":return"Authentication successful!";case"error":return"Authentication failed";default:return"Completing authentication..."}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"}),e.jsxs("div",{className:"relative z-10 text-center px-4 max-w-md w-full",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:wl,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:l()})]}),n!=="error"&&e.jsxs("div",{className:"space-y-3 mb-6",children:[e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="exchanging"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="exchanging"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Validating credentials"})]}),e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="fetching"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="fetching"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Loading your profile"})]}),n==="complete"&&e.jsxs("div",{className:"flex items-center gap-3 text-sm transition-all duration-500 text-white",children:[e.jsx("div",{className:"w-2 h-2 rounded-full transition-all duration-500 bg-green-500"}),e.jsx("span",{children:"Setting up your session"})]})]}),n==="error"&&a&&e.jsxs("div",{className:"mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx("p",{className:"text-red-400 text-sm",children:a.message||"An error occurred during authentication"}),e.jsx("button",{onClick:()=>{window.location.href="/"},className:"mt-4 text-sm text-red-400 hover:text-red-300 underline",children:"Return to login"})]}),n!=="error"&&n!=="complete"&&e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"h-1.5 bg-slate-700/50 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-re-red rounded-full animate-pulse",style:{animation:"progress 2s ease-in-out infinite"}})}),e.jsx("style",{children:`
@keyframes progress {
0%, 100% { width: 20%; }
50% { width: 80%; }
}
`})]})]}),e.jsx("p",{className:"mt-6 text-slate-500 text-xs",children:n==="complete"?"Loading dashboard...":"Please wait while we secure your session"})]}),e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute top-1/4 left-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-1/4 right-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse delay-1000"})]})]})}function Av(){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 v=sessionStorage.getItem("tanflow_auth_state");if(j&&j!==v){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 w=await Oy(b,j||"");sessionStorage.removeItem("tanflow_auth_state"),i("fetching");const A=w.user||await $n();if(A)nt.setUserData(A),i("complete"),setTimeout(()=>{window.history.replaceState({},document.title,"/"),window.location.href="/"},1e3);else throw new Error("User data not received")}catch(w){console.error("Tanflow callback error:",w),i("error"),o(w.message||"Authentication failed"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state")}})()},[]);const d=()=>{switch(n){case"exchanging":return"Exchanging authorization code...";case"fetching":return"Fetching your profile...";case"complete":return"Authentication successful!";case"error":return"Authentication failed";default:return"Completing authentication..."}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"}),e.jsxs("div",{className:"relative z-10 text-center px-4 max-w-md w-full",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:wl,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 Tv=Ac("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?Rh:"span";return e.jsx(n,{"data-slot":"badge",className:Le(Tv({variant:s}),t),...r})}function kv({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=Py();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(P,{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(Fh,{ref:a,"data-slot":"avatar",className:Le("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));cs.displayName=Fh.displayName;const Cl=x.forwardRef(({className:t,...s},a)=>e.jsx(Ih,{ref:a,"data-slot":"avatar-image",className:Le("aspect-square size-full",t),...s}));Cl.displayName=Ih.displayName;const ds=x.forwardRef(({className:t,...s},a)=>e.jsx(Ph,{ref:a,"data-slot":"avatar-fallback",className:Le("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));ds.displayName=Ph.displayName;function Su({...t}){return e.jsx(Kf,{"data-slot":"dropdown-menu",...t})}function Au({...t}){return e.jsx(Xf,{"data-slot":"dropdown-menu-trigger",...t})}function Tu({className:t,sideOffset:s=4,...a}){return e.jsx(Zf,{children:e.jsx(Jf,{"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 Gl({className:t,inset:s,variant:a="default",...r}){return e.jsx(qf,{"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 Dp({...t}){return e.jsx(tb,{"data-slot":"alert-dialog",...t})}function Dv({...t}){return e.jsx(eb,{"data-slot":"alert-dialog-portal",...t})}const Rp=x.forwardRef(({className:t,...s},a)=>e.jsx(Eh,{"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}));Rp.displayName=Eh.displayName;const kc=x.forwardRef(({className:t,...s},a)=>e.jsxs(Dv,{children:[e.jsx(Rp,{}),e.jsx(_h,{"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})]}));kc.displayName=_h.displayName;function Fp({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 Ip({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 Pp({className:t,...s}){return e.jsx(sb,{"data-slot":"alert-dialog-title",className:Le("text-lg font-semibold",t),...s})}function Ep({className:t,...s}){return e.jsx(ab,{"data-slot":"alert-dialog-description",className:Le("text-muted-foreground text-sm",t),...s})}function _p({className:t,...s}){return e.jsx(nb,{className:Le(Jn(),t),...s})}function Mp({className:t,...s}){return e.jsx(rb,{className:Le(Jn({variant:"outline"}),t),...s})}const or={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}},Rv=async()=>(await ve.get("/notifications/subscriptions")).data.data.subscriptions,ku="http://localhost:5000/api/v1".trim(),Fv=typeof window<"u"&&/^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname),Lp=(!Fv&&/localhost:5000/i.test(ku)?"":ku.replace(/\/$/,""))||"/api/v1";async function Op(t,s={}){const a=nt.getAccessToken(),r={...s.headers||{}};s.body instanceof FormData||(r["Content-Type"]="application/json"),a&&(r.Authorization=`Bearer ${a}`);const n=await fetch(`${Lp}${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 Dc(){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 Iv(){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 $p(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 Up(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 Bp(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 Rc(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 Vp(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 Pv(t){await ve.post(`/form16/requests/${encodeURIComponent(t)}/cancel-submission`)}async function Ev(t){await ve.post(`/form16/requests/${encodeURIComponent(t)}/resubmission-needed`)}async function Du(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 _v(t){const s=new FormData;s.append("document",t);const a=await Op("/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 Mv(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 Op("/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 Lv(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 Ov(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 $v=5*60*1e3;function Uv(t,s){return new Promise((a,r)=>{const n=new FormData;n.append("file",t);const i=new XMLHttpRequest,l=`${Lp}/form16/26as/upload`,o=nt.getAccessToken(),c=setTimeout(()=>{i.abort(),r(new Error("Upload timed out. Try a smaller file or try again."))},$v);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 Bv(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 Vv(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 zv(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 zp(){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:v}=us(),w=x.useMemo(()=>{try{const L=nt.getUserData();return(L==null?void 0:L.jobTitle)==="Dealer"}catch(L){return console.error("[PageLayout] Error checking dealer status:",L),!1}},[]),A=(v==null?void 0:v.role)==="ADMIN",C=()=>{var L,F;try{if(v!=null&&v.displayName&&typeof v.displayName=="string"){const S=v.displayName.split(" ").filter(Boolean);return S.length>=2?`${((L=S[0])==null?void 0:L[0])||""}${((F=S[S.length-1])==null?void 0:F[0])||""}`.toUpperCase():v.displayName.substring(0,2).toUpperCase()}return v!=null&&v.email&&typeof v.email=="string"?v.email.substring(0,2).toUpperCase():"U"}catch(S){return console.error("[PageLayout] Error getting user initials:",S),"U"}},E=x.useMemo(()=>{const L=[{id:"dashboard",label:"Dashboard",icon:dj},{id:"requests",label:"All Requests",icon:Kh,adminOnly:!1}];return w||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:fn}),L},[w,A]);x.useEffect(()=>{if(!(v!=null&&v.userId)){y(null);return}let L=!0;return Dc().then(F=>{L&&y(F)}).catch(F=>{L&&(y({canViewForm16Submission:!1,canView26AS:!1}),console.warn("[PageLayout] Form 16 permissions could not be loaded Form 16 menu will be hidden.",F))}),()=>{L=!1}},[v==null?void 0:v.userId]);const D=!!j&&(w?!!j.canViewForm16Submission:!!j.canView26AS),T=!!(j!=null&&j.canViewForm16Submission),N=!!(j!=null&&j.canView26AS),_=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",I=o||_,B=()=>{l(!i)},k=async L=>{var F;try{if(L.isRead||(await or.markAsRead(L.notificationId),u(S=>S.map(G=>G.notificationId===L.notificationId?{...G,isRead:!0}:G)),g(S=>Math.max(0,S-1))),L.actionUrl&&a){const S=(F=L.metadata)==null?void 0:F.requestNumber;if(S){let G=`request/${S}`;(L.notificationType==="mention"||L.notificationType==="comment"||L.notificationType==="worknote")&&(G+="?tab=worknotes"),a(G)}}b(!1)}catch(S){console.error("[PageLayout] Error handling notification click:",S)}},M=async()=>{try{await or.markAllAsRead(),u(L=>L.map(F=>({...F,isRead:!0}))),g(0)}catch(L){console.error("[PageLayout] Error marking all as read:",L)}};return x.useEffect(()=>{const L=v==null?void 0:v.userId;if(!L)return;let F=!0;(async()=>{var U,$;try{const R=await or.list({page:1,limit:4,unreadOnly:!1});if(!F)return;const H=((U=R.data)==null?void 0:U.notifications)||[];u(H),g((($=R.data)==null?void 0:$.unreadCount)||0)}catch(R){console.error("[PageLayout] Failed to fetch notifications:",R)}})();const G=Br();if(G){Sc(G,L);const U=$=>{F&&(u(R=>[$.notification,...R].slice(0,4)),g(R=>R+1))};return G.on("notification:new",U),()=>{F=!1,G.off("notification:new",U)}}return()=>{F=!1}},[v]),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:wl,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:[E.filter(L=>!L.adminOnly||(v==null?void 0:v.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(!I),className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${_?"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"}),I?e.jsx(bn,{className:"w-4 h-4 shrink-0"}):e.jsx(Ka,{className:"w-4 h-4 shrink-0"})]}),I&&e.jsx("div",{className:"mt-1 ml-4 pl-2 border-l border-gray-700 space-y-0.5",children:w?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:[N&&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"})]}),N&&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"})]})]})]})})]})]}),!w&&e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(P,{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(P,{variant:"ghost",size:"icon",onClick:B,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(mj,{className:"w-5 h-5 text-gray-600"}):e.jsx(uj,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[!w&&e.jsxs(P,{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(Su,{open:f,onOpenChange:b,children:[e.jsx(Au,{asChild:!0,children:e.jsxs(P,{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(Tu,{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(P,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:L=>{L.stopPropagation(),M()},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:Hh(new Date(L.createdAt),{addSuffix:!0})})]})]})},L.notificationId))})}),p.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(P,{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(Su,{children:[e.jsx(Au,{asChild:!0,children:e.jsxs(cs,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Cl,{src:(v==null?void 0:v.picture)||""}),e.jsx(ds,{className:"bg-re-green text-white text-sm",children:C()})]})}),e.jsxs(Tu,{align:"end",children:[e.jsxs(Gl,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(Ht,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(Gl,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(cr,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(Gl,{onClick:()=>m(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(Ol,{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(Dp,{open:d,onOpenChange:m,children:e.jsxs(kc,{children:[e.jsxs(Fp,{children:[e.jsxs(Pp,{className:"flex items-center gap-2",children:[e.jsx(Ol,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(Ep,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(Ip,{children:[e.jsx(Mp,{onClick:()=>m(!1),children:"Cancel"}),e.jsxs(_p,{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(Ol,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const oi=()=>Cy(),vn=Ty,Hv=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},Gv={viewAsUser:Hv()},Hp=jn({name:"dashboard",initialState:Gv,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:Wv}=Hp.actions;function Yv(){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 Qv(){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 Kv{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 Kv;function Xv({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([]),[v,w]=x.useState(null),[A,C]=x.useState([]),[E,D]=x.useState(!0),[T,N]=x.useState(!1),_=x.useRef(l);_.current=l;const I=x.useCallback(async(F=!1)=>{try{F?N(!0):D(!0);const S=[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)]:[],[$,R,H]=await Promise.all([Promise.all(S),G,Promise.all(U)]),K=$[0],z=$[1],O=$[2],V=$[3];if(!t&&R&&(K.requestVolume=R),c(K),m(z.activities),_.current.activity(z.pagination.currentPage,z.pagination.totalPages,z.pagination.totalRecords),u(O.criticalRequests),_.current.critical(O.pagination.currentPage,O.pagination.totalPages,O.pagination.totalRecords),y(V.deadlines),_.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),w(ee),C(te.performance),_.current.approver(te.pagination.currentPage,te.pagination.totalPages,te.pagination.totalRecords)}else t||(g([]),b([]),w(null),C([]))}catch(S){console.error("Failed to fetch dashboard data:",S)}finally{D(!1),N(!1)}},[t,s,a,r,n,i]),B=x.useCallback(async(F=1)=>{try{const S=await Ot.getRecentActivity(F,10,s);m(S.activities),_.current.activity(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch recent activities:",S)}},[s]),k=x.useCallback(async(F=1)=>{try{const S=await Ot.getCriticalRequests(F,10,s);u(S.criticalRequests),_.current.critical(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch critical requests:",S)}},[s]),M=x.useCallback(async(F=1)=>{try{const S=await Ot.getUpcomingDeadlines(F,10,s);y(S.deadlines),_.current.deadlines(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch upcoming deadlines:",S)}},[s]),L=x.useCallback(async(F=1)=>{try{const S=await Ot.getApproverPerformance(r,F,10,n,i);C(S.performance),_.current.approver(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch approver performance:",S)}},[r,n,i]);return{kpis:o,recentActivity:d,criticalRequests:p,departmentStats:h,priorityDistribution:f,upcomingDeadlines:j,aiRemarkUtilization:v,approverPerformance:A,loading:E,refreshing:T,fetchDashboardData:I,fetchRecentActivities:B,fetchCriticalRequests:k,fetchUpcomingDeadlines:M,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 Zv{constructor(){El(this,"config",null);El(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 Jv=new Zv;let qv=9,eN=18,tN=1,sN=5,Ru=!1;async function aN(){if(!Ru)try{const t=await Jv.getConfig();qv=t.workingHours.START_HOUR,eN=t.workingHours.END_HOUR,tN=t.workingHours.START_DAY,sN=t.workingHours.END_DAY,Ru=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}aN().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 rN(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 nN(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 iN(){const[t,s]=x.useState(!1),[a,r]=x.useState(!1),n=x.useCallback(async(l,o,c)=>{try{s(!0),await nN(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 rN(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(ib,{"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(lb,{"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(ob,{"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 lN({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(pc,{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(P,{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(cb,{"data-slot":"select",...t})}function Ge({...t}){return e.jsx(ub,{"data-slot":"select-value",...t})}function We({className:t,size:s="default",children:a,...r}){return e.jsxs(db,{"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(mb,{asChild:!0,children:e.jsx(bn,{className:"size-4 opacity-50"})})]})}function Ye({className:t,children:s,position:a="popper",...r}){return e.jsx(xb,{children:e.jsxs(hb,{"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(oN,{}),e.jsx(pb,{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(cN,{})]})})}function X({className:t,children:s,...a}){return e.jsxs(gb,{"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(fb,{children:e.jsx($a,{className:"size-4"})})}),e.jsx(bb,{children:s})]})}function oN({className:t,...s}){return e.jsx(jb,{"data-slot":"select-scroll-up-button",className:Le("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(cl,{className:"size-4"})})}function cN({className:t,...s}){return e.jsx(yb,{"data-slot":"select-scroll-down-button",className:Le("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(bn,{className:"size-4"})})}function Jt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(vb,{"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(Nb,{"data-slot":"popover",...t})}function ra({...t}){return e.jsx(wb,{"data-slot":"popover-trigger",...t})}function na({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(Cb,{children:e.jsx(Sb,{"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 dN(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 Gp(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 ci(t){return t.mode==="multiple"}function di(t){return t.mode==="range"}function Sl(t){return t.mode==="single"}var mN={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 uN(t,s){return tt(t,"LLLL y",s)}function xN(t,s){return tt(t,"d",s)}function hN(t,s){return tt(t,"LLLL",s)}function pN(t){return"".concat(t)}function gN(t,s){return tt(t,"cccccc",s)}function fN(t,s){return tt(t,"yyyy",s)}var bN=Object.freeze({__proto__:null,formatCaption:uN,formatDay:xN,formatMonthCaption:hN,formatWeekNumber:pN,formatWeekdayName:gN,formatYearCaption:fN}),jN=function(t,s,a){return tt(t,"do MMMM (EEEE)",a)},yN=function(){return"Month: "},vN=function(){return"Go to next month"},NN=function(){return"Go to previous month"},wN=function(t,s){return tt(t,"cccc",s)},CN=function(t){return"Week n. ".concat(t)},SN=function(){return"Year: "},AN=Object.freeze({__proto__:null,labelDay:jN,labelMonthDropdown:yN,labelNext:vN,labelPrevious:NN,labelWeekNumber:CN,labelWeekday:wN,labelYearDropdown:SN});function TN(){var t="buttons",s=mN,a=Zb,r={},n={},i=1,l={},o=new Date;return{captionLayout:t,classNames:s,formatters:bN,labels:AN,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:l,today:o,mode:"default"}}function kN(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=mc(n):a&&(l=new Date(a,11,31)),{fromDate:i?ou(i):void 0,toDate:l?ou(l):void 0}}var Wp=x.createContext(void 0);function DN(t){var s,a=t.initialProps,r=TN(),n=kN(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;(Sl(a)||ci(a)||di(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(Wp.Provider,{value:d,children:t.children})}function Yt(){var t=x.useContext(Wp);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function Yp(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 RN(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 Qp(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:RN;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 FN(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(aj(r,n))for(var u=ma(r),h=r.getMonth();h<=n.getMonth();h++)p.push(Ml(u,h));else for(var u=ma(new Date),h=0;h<=11;h++)p.push(Ml(u,h));var g=function(b){var j=Number(b.target.value),y=Ml(ma(t.displayMonth),j);t.onChange(y)},f=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Qp;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 IN(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(cu(rj(new Date),f));var b=function(y){var v=cu(ma(a),Number(y.target.value));t.onChange(v)},j=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Qp;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 PN(t,s){var a=x.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function EN(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&&Xn(i,n)<0){var d=-1*(c-1);n=Oa(i,d)}return l&&Xn(n,l)<0&&(n=l),ma(n)}function _N(){var t=Yt(),s=EN(t),a=PN(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 MN(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=ma(t),i=ma(Oa(n,r)),l=Xn(i,n),o=[],c=0;c<l;c++){var d=Oa(n,c);o.push(d)}return a&&(o=o.reverse()),o}function LN(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=Xn(a,t);if(!(c<i))return Oa(o,l)}}function ON(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=Xn(o,a);if(!(c<=0))return Oa(o,-l)}}var Kp=x.createContext(void 0);function $N(t){var s=Yt(),a=_N(),r=a[0],n=a[1],i=MN(r,s),l=LN(r,s),o=ON(r,s),c=function(p){return i.some(function(u){return uc(p,u)})},d=function(p,u){c(p)||(u&&Gh(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(Kp.Provider,{value:m,children:t.children})}function mi(){var t=x.useContext(Kp);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function Fu(t){var s,a=Yt(),r=a.classNames,n=a.styles,i=a.components,l=mi().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:Yp,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(FN,{onChange:o,displayMonth:t.displayMonth}),e.jsx(IN,{onChange:o,displayMonth:t.displayMonth})]})}function UN(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 BN(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 Ji=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 VN(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:BN,j=(a=p==null?void 0:p.IconLeft)!==null&&a!==void 0?a:UN;return e.jsxs("div",{className:l.nav,style:o.nav,children:[!t.hidePrevious&&e.jsx(Ji,{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(Ji,{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 Iu(t){var s=Yt().numberOfMonths,a=mi(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,l=a.displayMonths,o=l.findIndex(function(g){return uc(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(VN,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:p,nextMonth:n,previousMonth:r,onPreviousClick:u,onNextClick:h})}function zN(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:Yp,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):l==="dropdown"?d=e.jsx(Fu,{displayMonth:t.displayMonth,id:t.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Fu,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(Iu,{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(Iu,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function HN(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 GN(t,s,a){for(var r=a?xc(new Date):hc(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var l=oa(r,i);n.push(l)}return n}function WN(){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=GN(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 YN(){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:WN;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function QN(t){var s=Yt(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var Fc=x.createContext(void 0);function KN(t){if(!ci(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(Fc.Provider,{value:s,children:t.children})}return e.jsx(XN,{initialProps:t.initialProps,children:t.children})}function XN(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?Gp([],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(Fc.Provider,{value:c,children:a})}function Ic(){var t=x.useContext(Fc);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function ZN(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:Io(r,t)?{from:t,to:n}:{from:r,to:t}:n?Io(t,n)?{from:n,to:t}:{from:t,to:n}:r?Gh(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var Pc=x.createContext(void 0);function JN(t){if(!di(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(Pc.Provider,{value:s,children:t.children})}return e.jsx(qN,{initialProps:t.initialProps,children:t.children})}function qN(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=ZN(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:_l(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:_l(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:_l(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(Pc.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function Ec(){var t=x.useContext(Pc);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function Ei(t){return Array.isArray(t)?Gp([],t):t!==void 0?[t]:[]}function ew(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=Ei(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 tw=Ra.Selected,Ya=Ra.Disabled,sw=Ra.Hidden,aw=Ra.Today,Wl=Ra.RangeEnd,Yl=Ra.RangeMiddle,Ql=Ra.RangeStart,rw=Ra.Outside;function nw(t,s,a){var r,n=(r={},r[tw]=Ei(t.selected),r[Ya]=Ei(t.disabled),r[sw]=Ei(t.hidden),r[aw]=[t.today],r[Wl]=[],r[Yl]=[],r[Ql]=[],r[rw]=[],r);return t.fromDate&&n[Ya].push({before:t.fromDate}),t.toDate&&n[Ya].push({after:t.toDate}),ci(t)?n[Ya]=n[Ya].concat(s.modifiers[Ya]):di(t)&&(n[Ya]=n[Ya].concat(a.modifiers[Ya]),n[Ql]=a.modifiers[Ql],n[Yl]=a.modifiers[Yl],n[Wl]=a.modifiers[Wl]),n}var Xp=x.createContext(void 0);function iw(t){var s=Yt(),a=Ic(),r=Ec(),n=nw(s,a,r),i=ew(s.modifiers),l=ct(ct({},n),i);return e.jsx(Xp.Provider,{value:l,children:t.children})}function Zp(){var t=x.useContext(Xp);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function lw(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function ow(t){return!!(t&&typeof t=="object"&&"from"in t)}function cw(t){return!!(t&&typeof t=="object"&&"after"in t)}function dw(t){return!!(t&&typeof t=="object"&&"before"in t)}function mw(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function uw(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 xw(t){return Qh(t)}function hw(t){return Array.isArray(t)&&t.every(Qh)}function pw(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(xw(a))return ea(t,a);if(hw(a))return a.includes(t);if(ow(a))return uw(t,a);if(mw(a))return a.dayOfWeek.includes(t.getDay());if(lw(a)){var r=Qa(a.before,t),n=Qa(a.after,t),i=r>0,l=n<0,o=Io(a.before,a.after);return o?l&&i:i||l}return cw(a)?Qa(t,a.after)>0:dw(a)?Qa(a.before,t)>0:typeof a=="function"?a(t):!1})}function _c(t,s,a){var r=Object.keys(s).reduce(function(i,l){var o=s[l];return pw(t,o)&&i.push(l),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!uc(t,a)&&(n.outside=!0),n}function gw(t,s){for(var a=ma(t[0]),r=mc(t[t.length-1]),n,i,l=a;l<=r;){var o=_c(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 fw=365;function Jp(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:Fo,month:Oa,year:ej,startOfWeek:function(b){return n.ISOWeek?xc(b):hc(b,{locale:p,weekStartsOn:c})},endOfWeek:function(b){return n.ISOWeek?Wh(b):Yh(b,{locale:p,weekStartsOn:c})}},h=u[a](t,r==="after"?1:-1);r==="before"&&d?h=tj([d,h]):r==="after"&&m&&(h=sj([m,h]));var g=!0;if(i){var f=_c(h,i);g=!f.disabled&&!f.hidden}return g?h:o.count>fw?o.lastFocused:Jp(h,{moveBy:a,direction:r,context:n,modifiers:i,retry:ct(ct({},o),{count:o.count+1})})}var qp=x.createContext(void 0);function bw(t){var s=mi(),a=Zp(),r=x.useState(),n=r[0],i=r[1],l=x.useState(),o=l[0],c=l[1],d=gw(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=Jp(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(qp.Provider,{value:f,children:t.children})}function Mc(){var t=x.useContext(qp);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function jw(t,s){var a=Zp(),r=_c(t,a,s);return r}var Lc=x.createContext(void 0);function yw(t){if(!Sl(t.initialProps)){var s={selected:void 0};return e.jsx(Lc.Provider,{value:s,children:t.children})}return e.jsx(vw,{initialProps:t.initialProps,children:t.children})}function vw(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(Lc.Provider,{value:n,children:a})}function eg(){var t=x.useContext(Lc);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function Nw(t,s){var a=Yt(),r=eg(),n=Ic(),i=Ec(),l=Mc(),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,v=function(F){var S,G,U,$;Sl(a)?(S=r.onDayClick)===null||S===void 0||S.call(r,t,s,F):ci(a)?(G=n.onDayClick)===null||G===void 0||G.call(n,t,s,F):di(a)?(U=i.onDayClick)===null||U===void 0||U.call(i,t,s,F):($=a.onDayClick)===null||$===void 0||$.call(a,t,s,F)},w=function(F){var S;u(t),(S=a.onDayFocus)===null||S===void 0||S.call(a,t,s,F)},A=function(F){var S;p(),(S=a.onDayBlur)===null||S===void 0||S.call(a,t,s,F)},C=function(F){var S;(S=a.onDayMouseEnter)===null||S===void 0||S.call(a,t,s,F)},E=function(F){var S;(S=a.onDayMouseLeave)===null||S===void 0||S.call(a,t,s,F)},D=function(F){var S;(S=a.onDayPointerEnter)===null||S===void 0||S.call(a,t,s,F)},T=function(F){var S;(S=a.onDayPointerLeave)===null||S===void 0||S.call(a,t,s,F)},N=function(F){var S;(S=a.onDayTouchCancel)===null||S===void 0||S.call(a,t,s,F)},_=function(F){var S;(S=a.onDayTouchEnd)===null||S===void 0||S.call(a,t,s,F)},I=function(F){var S;(S=a.onDayTouchMove)===null||S===void 0||S.call(a,t,s,F)},B=function(F){var S;(S=a.onDayTouchStart)===null||S===void 0||S.call(a,t,s,F)},k=function(F){var S;(S=a.onDayKeyUp)===null||S===void 0||S.call(a,t,s,F)},M=function(F){var S;switch(F.key){case"ArrowLeft":F.preventDefault(),F.stopPropagation(),a.dir==="rtl"?o():c();break;case"ArrowRight":F.preventDefault(),F.stopPropagation(),a.dir==="rtl"?c():o();break;case"ArrowDown":F.preventDefault(),F.stopPropagation(),d();break;case"ArrowUp":F.preventDefault(),F.stopPropagation(),m();break;case"PageUp":F.preventDefault(),F.stopPropagation(),F.shiftKey?f():h();break;case"PageDown":F.preventDefault(),F.stopPropagation(),F.shiftKey?b():g();break;case"Home":F.preventDefault(),F.stopPropagation(),j();break;case"End":F.preventDefault(),F.stopPropagation(),y();break}(S=a.onDayKeyDown)===null||S===void 0||S.call(a,t,s,F)},L={onClick:v,onFocus:w,onBlur:A,onKeyDown:M,onKeyUp:k,onMouseEnter:C,onMouseLeave:E,onPointerEnter:D,onPointerLeave:T,onTouchCancel:N,onTouchEnd:_,onTouchMove:I,onTouchStart:B};return L}function ww(){var t=Yt(),s=eg(),a=Ic(),r=Ec(),n=Sl(t)?s.selected:ci(t)?a.selected:di(t)?r.selected:void 0;return n}function Cw(t){return Object.values(Ra).includes(t)}function Sw(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(Cw(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function Aw(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 Tw(t,s,a){var r,n,i,l=Yt(),o=Mc(),c=jw(t,s),d=Nw(t,c),m=ww(),p=!!(l.onDayClick||l.mode!=="default");x.useEffect(function(){var C;c.outside||o.focusedDay&&p&&ea(o.focusedDay,t)&&((C=a.current)===null||C===void 0||C.focus())},[o.focusedDay,t,a,p,c.outside]);var u=Sw(l,c).join(" "),h=Aw(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:QN,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,v=o.focusedDay&&ea(o.focusedDay,t),w=ct(ct(ct({},j),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=v||y?0:-1,r)),d),A={isButton:p,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:w,divProps:j};return A}function kw(t){var s=x.useRef(null),a=Tw(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(Ji,ct({name:"day",ref:s},a.buttonProps)):e.jsx("div",ct({},a.divProps))}function Dw(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(Ji,{name:"week-number","aria-label":p,className:l.weeknumber,style:i.weeknumber,onClick:u,children:m})}function Rw(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:kw,d=(a=o==null?void 0:o.WeekNumber)!==null&&a!==void 0?a:Dw,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})},qb(p))})]})}function Pu(t,s,a){for(var r=a!=null&&a.ISOWeek?Wh(s):Yh(s,a),n=a!=null&&a.ISOWeek?xc(t):hc(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?nj(m):ij(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 Fw(t,s){var a=Pu(ma(t),mc(t),s);if(s!=null&&s.useFixedWeeks){var r=Jb(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],l=Fo(i,6-r),o=Pu(Fo(i,1),l,s);a.push.apply(a,o)}}return a}function Iw(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=Fw(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:YN,b=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:Rw,j=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:HN;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 Pw(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Ew=Pw()?x.useLayoutEffect:x.useEffect,Kl=!1,_w=0;function Eu(){return"react-day-picker-".concat(++_w)}function Mw(t){var s,a=t??(Kl?Eu():null),r=x.useState(a),n=r[0],i=r[1];return Ew(function(){n===null&&i(Eu())},[]),x.useEffect(function(){Kl===!1&&(Kl=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function Lw(t){var s,a,r=Yt(),n=r.dir,i=r.classNames,l=r.styles,o=r.components,c=mi().displayMonths,d=Mw(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:zN;return e.jsxs("div",{className:p.join(" "),style:u,children:[e.jsx(b,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(Iw,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function Ow(t){var s=Yt(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function $w(t){var s,a,r=t.initialProps,n=Yt(),i=Mc(),l=mi(),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:Ow;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(Lw,{displayIndex:f,displayMonth:g},f)})})}))}function Uw(t){var s=t.children,a=dN(t,["children"]);return e.jsx(DN,{initialProps:a,children:e.jsx($N,{children:e.jsx(yw,{initialProps:a,children:e.jsx(KN,{initialProps:a,children:e.jsx(JN,{initialProps:a,children:e.jsx(iw,{children:e.jsx(bw,{children:s})})})})})})})}function Bw(t){return e.jsx(Uw,ct({},t,{children:e.jsx($w,{initialProps:t})}))}function _i({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(Bw,{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(Jn({variant:"outline"}),"size-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-x-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell: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(Jn({variant:"ghost"}),"size-8 p-0 font-normal aria-selected:opacity-100"),day_range_start:"day-range-start aria-selected:bg-primary aria-selected:text-primary-foreground",day_range_end:"day-range-end aria-selected:bg-primary aria-selected:text-primary-foreground",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground aria-selected:text-muted-foreground",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...s},components:{IconLeft:({className:n,...i})=>e.jsx(hn,{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 Zr(t)?t:void 0;if(typeof t=="string")try{const j=Ll(t,"yyyy-MM-dd",new Date);return Zr(j)?j:void 0}catch{return}}},[t]),g=x.useMemo(()=>{if(a){if(a instanceof Date)return Zr(a)?a:void 0;if(typeof a=="string"){const j=Ll(a,"yyyy-MM-dd",new Date);return Zr(j)?j:void 0}}},[a]),f=x.useMemo(()=>{if(r){if(r instanceof Date)return Zr(r)?r:void 0;if(typeof r=="string"){const j=Ll(r,"yyyy-MM-dd",new Date);return Zr(j)?j:void 0}}},[r]),b=j=>{if(u(!1),!!s){if(!j){s(null);return}s(tt(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(P,{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?tt(h,d):e.jsx("span",{children:n})]})}),e.jsx(na,{className:"w-auto p-0",align:"start",children:e.jsx(_i,{mode:"single",selected:h,onSelect:b,disabled:j=>!!(g&&j<g||f&&j>f),initialFocus:!0})})]})})}function Vw({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(P,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(ft,{className:"w-4 h-4"}),a&&r?`${tt(a,"MMM d, yyyy")} - ${tt(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(P,{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(P,{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(P,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(ft,{className:"w-4 h-4"}),a&&r?`${tt(a,"MMM d, yyyy")} - ${tt(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(P,{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(P,{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(P,{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 Er({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(zr,{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(Ab,{"data-slot":"progress",className:Le("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(Tb,{"data-slot":"progress-indicator",className:Le("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function zw({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(Er,{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(Er,{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(Er,{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 Hw({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(Er,{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(Er,{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(Er,{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(Er,{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 Gw=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)))},Ww=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 Yw({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=Gw(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(xj,{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:Ww(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 Qw(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 Kw(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function Xw(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 Zw(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 tg(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 Jw({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(Yw,{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(P,{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"})}),tg(a.page,a.totalPages,3).map(i=>e.jsx(P,{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(P,{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 qw=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"}},e1=t=>{const s=new Date,a=new Date(t),r=lj(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=oj(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=cj(s,a);return`${i} day${i>1?"s":""} ago`},t1=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()},s1=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(dl,{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 a1({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(Cl,{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:s1(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 ${qw(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:t1(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:e1(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 r1({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(P,{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(a1,{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(P,{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"})}),tg(a.page,a.totalPages,3).map(m=>e.jsx(P,{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(P,{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 n1({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(Po,{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(P,{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(cn,{width:"100%",height:400,children:e.jsxs(Ro,{data:r,children:[e.jsx(Hi,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Gi,{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(Wi,{stroke:"#999",tick:{fontSize:11}}),e.jsx(dn,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Yi,{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 i1({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 l1({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(cn,{width:"100%",height:300,children:e.jsxs(Bh,{children:[e.jsx(Vh,{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(zh,{fill:a.priority==="express"?"#ef4444":"#3b82f6",className:"cursor-pointer"},`cell-${r}`))}),e.jsx(dn,{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 Gr({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(P,{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(P,{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(P,{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(P,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${o}-page-${s}`,children:s})]}),e.jsx(P,{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 o1(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${tt(s,"MMM d, yyyy")} - ${tt(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 c1(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${tt(s,"MMM d, yyyy")} to ${tt(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 d1({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 - ",c1(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:Xw(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(Gr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function m1({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(Gr,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function u1({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(ml,{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(cn,{width:"100%",height:250,children:e.jsxs(Kb,{data:t.monthlyTrends,children:[e.jsx(Hi,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Gi,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(Wi,{stroke:"#999",tick:{fontSize:11}}),e.jsx(dn,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Yi,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(lu,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(lu,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function x1({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(P,{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 ${Zw(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(Gr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:o,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function h1(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 p1(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:cr,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 g1({onNavigate:t,onNewRequest:s}){const{user:a}=us(),r=oi(),n=vn(Se=>Se.dashboard.viewAsUser),i=x.useMemo(()=>Nl(a),[a]),l=i&&!n,o=x.useCallback(Se=>{r(Wv(Se))},[r]),c=Yv(),{dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:u,handleDateRangeChange:h,handleApplyCustomDate:g,resetCustomDates:f,setCustomStartDate:b,setCustomEndDate:j,setShowCustomDatePicker:y}=c,v=Qv(),{activity:w,critical:A,deadlines:C,approver:E,updateActivityPagination:D,updateCriticalPagination:T,updateDeadlinesPagination:N,updateApproverPagination:_,handleActivityPageChange:I,handleCriticalPageChange:B,handleDeadlinesPageChange:k,handleApproverPageChange:M}=v,L=Xv({isAdmin:l,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:p,onPaginationUpdate:{activity:D,critical:T,deadlines:N,approver:_}}),{kpis:F,recentActivity:S,criticalRequests:G,departmentStats:U,priorityDistribution:$,upcomingDeadlines:R,aiRemarkUtilization:H,approverPerformance:K,loading:z,refreshing:O,fetchDashboardData:V,fetchRecentActivities:Q,fetchCriticalRequests:q,fetchUpcomingDeadlines:ee,fetchApproverPerformance:te}=L,ue=iN(),{exportingDeptStats:_e,exportingApproverPerformance:Ze,handleExportDepartmentStats:Ue,handleExportApproverPerformance:Pe}=ue,De=x.useMemo(()=>Qw(G),[G]),le=x.useMemo(()=>Kw(R),[R]),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=>{I(Se,Q)},[I,Q]),ne=x.useCallback(Se=>{B(Se,q)},[B,q]),ge=x.useCallback(Se=>{k(Se,ee)},[k,ee]),ke=x.useCallback(Se=>{M(Se,()=>te(Se))},[M,te]);x.useEffect(()=>{d==="custom"?m&&p&&V(!1):V(!1)},[d,m,p,n]);const Oe=x.useMemo(()=>{try{const Se=nt.getUserData();return(Se==null?void 0:Se.jobTitle)==="Dealer"}catch(Se){return console.error("[Dashboard] Error checking dealer status:",Se),!1}},[]),je=x.useMemo(()=>p1(i,s,t,Oe),[i,s,t,Oe]),ie=x.useCallback(Se=>{const qe=h1(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(lN,{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(Vw,{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(zw,{kpis:F,priorityDistribution:$,dateRange:d,customStartDate:m,customEndDate:p,onKPIClick:ie}):e.jsx(Hw,{kpis:F,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(Jw,{isAdmin:l,breachedRequests:De,pagination:A,onPageChange:ne,onNavigate:t}),e.jsx(r1,{isAdmin:l,recentActivity:S,pagination:w,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&&F&&e.jsx(n1,{kpis:F,upcomingDeadlines:R,criticalRequests:G,departmentStats:U,dateRange:d,customStartDate:m,customEndDate:p,exportingDeptStats:_e,onKPIClick:ie,onExportDepartmentStats:Ue}),!l&&F&&e.jsx(i1,{kpis:F}),l&&$.length>0&&e.jsx(l1,{priorityDistribution:$,onNavigate:t}),l&&De.length>0&&e.jsx(d1,{breachedRequests:De,pagination:A,dateRange:d,customStartDate:m,customEndDate:p,onPageChange:ne,onKPIClick:ie,onNavigate:t}),le.length>0&&e.jsx(m1,{isAdmin:l,upcomingDeadlines:le,pagination:C,onPageChange:ge,onNavigate:t}),l&&H&&e.jsx(u1,{aiRemarkUtilization:H}),l&&K.length>0&&e.jsx(x1,{approverPerformance:K,pagination:E,dateRange:d,customStartDate:m,customEndDate:p,loading:z,exportingApproverPerformance:Ze,onPageChange:ke,onExport:Pe,onNavigate:t})]})}const f1={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},sg=jn({name:"openRequests",initialState:f1,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:b1,setStatusFilter:j1,setPriorityFilter:y1,setTemplateTypeFilter:v1,setForm16FinancialYear:N1,setForm16Quarter:w1,setSortBy:C1,setSortOrder:S1,setCurrentPage:A1,clearFilters:T1}=sg.actions;function k1(){const t=oi(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,form16FinancialYear:i,form16Quarter:l,sortBy:o,sortOrder:c,currentPage:d}=vn(A=>A.openRequests),m=x.useCallback(A=>t(b1(A)),[t]),p=x.useCallback(A=>t(j1(A)),[t]),u=x.useCallback(A=>t(y1(A)),[t]),h=x.useCallback(A=>t(v1(A)),[t]),g=x.useCallback(A=>t(N1(A)),[t]),f=x.useCallback(A=>t(w1(A)),[t]),b=x.useCallback(A=>t(C1(A)),[t]),j=x.useCallback(A=>t(S1(A)),[t]),y=x.useCallback(A=>t(A1(A)),[t]),v=x.useCallback(()=>t(T1()),[t]),w=[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:v,activeFiltersCount:w}}function Xl(){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 D1(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:Xl(),approverEmail:f,approverName:b,tatHours:g>0?g:24,isFinalApprover:u===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:Xl(),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:Xl(),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 Oc(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 R1(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 F1(t={}){var y,v,w,A,C;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:((v=(y=j.data)==null?void 0:y.data)==null?void 0:v.data)||((w=j.data)==null?void 0:w.data)||[],pagination:((C=(A=j.data)==null?void 0:A.data)==null?void 0:C.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function I1(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 P1(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 E1(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 _1(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 un(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 ag(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 rg(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 M1(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 ng(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 L1(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 O1(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 $1(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 _u(t){var a;const s=await ve.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function U1(t){return`http://localhost:5000/api/v1/workflows/work-notes/attachments/${t}/preview`}function Nn(t){return`http://localhost:5000/api/v1/workflows/documents/${t}/preview`}function ig(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=`http://localhost:5000/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=ig(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 Mu(t){const a=`http://localhost:5000/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=ig(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:D1,createWorkflowMultipart:Oc,listWorkflows:R1,listParticipantRequests:F1,listMyWorkflows:I1,listMyInitiatedWorkflows:P1,listOpenForMe:E1,listClosedByMe:_1,submitWorkflow:lg,getWorkflowDetails:Ps,getWorkNotes:un,createWorkNoteMultipart:ag,handleInitiatorAction:og};async function lg(t){var a;const s=await ve.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function B1(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 V1(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 Un(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 Dr(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 z1(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 og(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 H1(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 cg(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 G1(t){return t?t.jobTitle==="Dealer"||t.jobTitle==="DEALER":!1}function $c(t){return G1(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 Ni=[{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 ui({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),[v,w]=x.useState(null),[A,C]=x.useState("#000000");x.useEffect(()=>{l.current&&l.current.innerHTML!==t&&l.current.innerHTML!==t&&(l.current.innerHTML=_a(t||""))},[t]);const E=x.useCallback(F=>(F=F.replace(/<!--[\s\S]*?-->/g,""),F=F.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),F=F.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),F=F.replace(/<meta[^>]*>/gi,""),F=F.replace(/\s*class="Mso[^"]*"/gi,""),F=F.replace(/\s*class="mso[^"]*"/gi,""),F=F.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),F=F.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),F=F.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),F=F.replace(/<\/?o:p[^>]*>/gi,""),F=F.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),F=F.replace(/<v:[^>]*\/>/gi,""),F=F.replace(/<p[^>]*>\s*<\/p>/gi,""),F=F.replace(/<div[^>]*>\s*<\/div>/gi,""),F=F.replace(/\s+/g," "),F=F.trim(),F),[]),D=x.useCallback(F=>{F.preventDefault();const S=F.clipboardData;let G=S.getData("text/html")||S.getData("text/plain");if((G.includes("<!--")||G.includes("<style")||G.includes("MsoNormal"))&&(G=E(G)),!l.current)return;const U=window.getSelection();if(!U||U.rangeCount===0)return;const $=U.getRangeAt(0);$.deleteContents();const R=document.createElement("div");R.innerHTML=G;const H=document.createDocumentFragment();Array.from(R.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&&S.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,E]),T=x.useCallback(()=>{if(!l.current||!o)return;const F=new Set,S=window.getSelection();if(S&&S.rangeCount>0){const U=S.getRangeAt(0).commonAncestorContainer;let $=null;for(U.nodeType===Node.TEXT_NODE?$=U.parentElement:$=U;$&&$!==l.current;){const R=$.tagName.toLowerCase();(R==="strong"||R==="b")&&F.add("bold"),(R==="em"||R==="i")&&F.add("italic"),R==="u"&&F.add("underline"),R==="h1"&&F.add("h1"),R==="h2"&&F.add("h2"),R==="h3"&&F.add("h3"),R==="ul"&&F.add("ul"),R==="ol"&&F.add("ol");const H=window.getComputedStyle($);H.textAlign==="center"&&F.add("center"),H.textAlign==="right"&&F.add("right"),H.textAlign==="left"&&F.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"){F.add("highlight");const Q=K(z);if(Q){const q=Ni.find(ee=>ee.value==="transparent"?!1:ee.value.toUpperCase()===Q);g(q?q.value:Q)}}else F.has("highlight")||g(null);const O=H.color,V=K(O);if(O&&V&&O!=="rgba(0, 0, 0, 0)"&&V!=="#000000"){F.add("textColor");const Q=Ni.find(q=>q.value==="transparent"?!1:q.value.toUpperCase()===V);w(Q?Q.value:V)}else F.has("textColor")||w(V==="#000000"||!V?"#000000":null);$=$.parentElement}}m(F)},[o]),N=x.useCallback((F,S)=>{if(!l.current)return;o||l.current.focus();const G=window.getSelection();if(!G||G.rangeCount===0){l.current.focus();return}document.execCommand(F,!1,S),l.current&&s(_a(l.current.innerHTML)),setTimeout(T,10)},[o,s,T]),_=x.useCallback(F=>{if(!l.current)return;o||l.current.focus();const S=window.getSelection();if(!S||S.rangeCount===0){l.current.focus();return}let G=!1;if(S.rangeCount>0){const R=S.getRangeAt(0).commonAncestorContainer;let H=null;for(R.nodeType===Node.TEXT_NODE?H=R.parentElement:H=R;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===F.toUpperCase()){G=!0;break}}H=H.parentElement}}if(F==="transparent"||G){const $=S.getRangeAt(0);if($.collapsed)document.execCommand("removeFormat",!1);else{const R=$.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(R.childNodes).forEach(z=>{const O=K(z);O&&H.appendChild(O)}),$.insertNode(H),document.execCommand("removeFormat",!1)}g(null),b("#FFEB3B")}else if(S.rangeCount>0&&!S.getRangeAt(0).collapsed)document.execCommand("backColor",!1,F),g(F),F!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(F)&&b(F);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]),I=x.useCallback(F=>{if(!l.current)return;o||l.current.focus();const S=window.getSelection();if(!S||S.rangeCount===0){l.current.focus();return}let G=!1;if(S.rangeCount>0){const $=S.getRangeAt(0).commonAncestorContainer;let R=null;for($.nodeType===Node.TEXT_NODE?R=$.parentElement:R=$;R&&R!==l.current;){const K=window.getComputedStyle(R).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(F==="#000000"){if(O==="#000000"||!O){G=!0;break}}else if(O&&O===F.toUpperCase()){G=!0;break}}R=R.parentElement}}if(F==="transparent"||F==="default"||G){if(F==="#000000"&&G){y(!1);return}document.execCommand("removeFormat",!1),w(null),C("#000000")}else document.execCommand("foreColor",!1,F),w(F),F!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(F)&&C(F);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(F=>{if(F.ctrlKey&&F.key==="b"){F.preventDefault(),N("bold");return}if(F.ctrlKey&&F.key==="i"){F.preventDefault(),N("italic");return}if(F.ctrlKey&&F.key==="u"){F.preventDefault(),N("underline");return}},[N]),M=x.useCallback(()=>{c(!0)},[]),L=x.useCallback(()=>{c(!1),l.current&&s(_a(l.current.innerHTML))},[s]);return x.useEffect(()=>{if(!o)return;const F=()=>{T()};return document.addEventListener("selectionchange",F),()=>{document.removeEventListener("selectionchange",F)}},[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(P,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>N("bold"),title:"Bold (Ctrl+B)",children:e.jsx(hj,{className:"h-4 w-4"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>N("italic"),title:"Italic (Ctrl+I)",children:e.jsx(pj,{className:"h-4 w-4"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>N("underline"),title:"Underline (Ctrl+U)",children:e.jsx(gj,{className:"h-4 w-4"})}),e.jsxs(aa,{open:p,onOpenChange:u,children:[e.jsx(ra,{asChild:!0,children:e.jsx(P,{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(fj,{className:"h-4 w-4"})})}),e.jsx(na,{className:"w-auto p-2",align:"start",onPointerDownOutside:F=>{F.target.closest("[data-popover-content]")&&F.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:F=>F.stopPropagation(),children:[e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:F=>{F.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:Ni.map(F=>{const S=h===F.value,G=F.value==="transparent";return e.jsxs("button",{type:"button",onClick:U=>{U.preventDefault(),U.stopPropagation(),_(S&&!G?"transparent":F.value)},className:Le("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",F.class,S&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",G&&"border-gray-400 bg-white",!G&&!S&&"border-gray-300"),title:S&&!G?`${F.name} (Click to remove)`:F.name,style:G?{}:{backgroundColor:F.value},children:[G&&e.jsx("span",{className:"text-[10px] text-gray-600 font-bold",children:"×"}),S&&!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"})})]},F.value)})}),h&&h!=="transparent"&&e.jsx("div",{className:"mb-2",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:F=>{F.stopPropagation(),_("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:F=>{const S=F.target.value;b(S);const G=window.getSelection();G&&G.rangeCount>0&&!G.getRangeAt(0).collapsed&&_(S)},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:F=>{F.stopPropagation();const S=F.target.value;b(S)},onKeyDown:F=>{if(F.stopPropagation(),F.key==="Enter"){F.preventDefault();const S=F.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(S)&&_(S)}},onPaste:F=>{F.stopPropagation();const S=F.clipboardData.getData("text").trim();F.preventDefault(),setTimeout(()=>{if(/^#[0-9A-Fa-f]{6}$/i.test(S)){b(S);const G=window.getSelection();G&&G.rangeCount>0&&!G.getRangeAt(0).collapsed&&_(S)}else{const G=S.match(/^([0-9A-Fa-f]{6})$/);if(G){const U=`#${G[1]}`;b(U);const $=window.getSelection();$&&$.rangeCount>0&&!$.getRangeAt(0).collapsed&&_(U)}}},0)},onClick:F=>{F.stopPropagation()},onFocus:F=>{F.stopPropagation(),F.target.select()},onBlur:F=>{const S=F.target.value.trim();if(/^#[0-9A-Fa-f]{6}$/i.test(S)){const G=window.getSelection();G&&G.rangeCount>0&&!G.getRangeAt(0).collapsed&&_(S)}else b(S===""?h||"#FFEB3B":S)},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(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{const F=f.trim();/^#[0-9A-Fa-f]{6}$/i.test(F)?_(F):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(P,{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(bj,{className:"h-4 w-4"})})}),e.jsx(na,{className:"w-auto p-2",align:"start",onPointerDownOutside:F=>{F.target.closest("[data-popover-content]")&&F.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:F=>F.stopPropagation(),children:[e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:F=>{F.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:F=>{F.preventDefault(),F.stopPropagation(),v==="#000000"||!v&&!d.has("textColor")||I("#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",(v==="#000000"||!v&&!d.has("textColor"))&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",v!=="#000000"&&(v||d.has("textColor"))&&"border-gray-300"),title:"Default (Black)",children:[e.jsx("span",{className:"text-[10px] text-white font-bold",children:"A"}),(v==="#000000"||!v&&!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"})})]}),Ni.filter(F=>F.value!=="transparent").map(F=>{const S=v===F.value;return e.jsxs("button",{type:"button",onClick:G=>{G.preventDefault(),G.stopPropagation(),I(S?"#000000":F.value)},className:Le("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center relative",S&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",!S&&"border-gray-300"),title:S?`${F.name} (Click to reset to default)`:F.name,style:{color:F.value,borderColor:S?"#2563eb":F.value},children:[e.jsx("span",{className:"text-xs font-bold",children:"A"}),S&&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-${F.value}`)})]}),v&&v!=="#000000"&&e.jsx("div",{className:"mb-2",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:F=>{F.stopPropagation(),I("#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:v||A,onChange:F=>{const S=F.target.value;C(S),I(S)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom text color"}),e.jsx("input",{type:"text",value:v||A,onChange:F=>{const S=F.target.value;C(S)},onKeyDown:F=>{if(F.key==="Enter"){F.preventDefault();const S=F.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(S)&&I(S)}},onBlur:F=>{const S=F.target.value;/^#[0-9A-Fa-f]{6}$/.test(S)?I(S):S===""&&C(v||"#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(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>I(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(P,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>N("formatBlock","<h1>"),title:"Heading 1",children:e.jsx(jj,{className:"h-4 w-4"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>N("formatBlock","<h2>"),title:"Heading 2",children:e.jsx(yj,{className:"h-4 w-4"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>N("formatBlock","<h3>"),title:"Heading 3",children:e.jsx(vj,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>N("insertUnorderedList"),title:"Bullet List",children:e.jsx(Kh,{className:"h-4 w-4"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>N("insertOrderedList"),title:"Numbered List",children:e.jsx(Nj,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>N("justifyLeft"),title:"Align Left",children:e.jsx(Xh,{className:"h-4 w-4"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>N("justifyCenter"),title:"Align Center",children:e.jsx(wj,{className:"h-4 w-4"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:Le("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>N("justifyRight"),title:"Align Right",children:e.jsx(Cj,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:l,contentEditable:!0,onPaste:D,onInput:B,onFocus:M,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 dg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(il,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 M=["th","st","nd","rd"],L=k%100;return"["+k+(M[(L-20)%10]||M[L]||M[0])+"]"}},v=function(k,M,L){var F=String(k);return!F||F.length>=M?k:""+Array(M+1-F.length).join(L)+k},w={s:v,z:function(k){var M=-k.utcOffset(),L=Math.abs(M),F=Math.floor(L/60),S=L%60;return(M<=0?"+":"-")+v(F,2,"0")+":"+v(S,2,"0")},m:function k(M,L){if(M.date()<L.date())return-k(L,M);var F=12*(L.year()-M.year())+(L.month()-M.month()),S=M.clone().add(F,p),G=L-S<0,U=M.clone().add(F+(G?-1:1),p);return+(-(F+(L-S)/(G?S-U:U-S))||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",C={};C[A]=y;var E="$isDayjsObject",D=function(k){return k instanceof I||!(!k||!k[E])},T=function k(M,L,F){var S;if(!M)return A;if(typeof M=="string"){var G=M.toLowerCase();C[G]&&(S=G),L&&(C[G]=L,S=G);var U=M.split("-");if(!S&&U.length>1)return k(U[0])}else{var $=M.name;C[$]=M,S=$}return!F&&S&&(A=S),S||!F&&A},N=function(k,M){if(D(k))return k.clone();var L=typeof M=="object"?M:{};return L.date=k,L.args=arguments,new I(L)},_=w;_.l=T,_.i=D,_.w=function(k,M){return N(k,{locale:M.$L,utc:M.$u,x:M.$x,$offset:M.$offset})};var I=function(){function k(L){this.$L=T(L.locale,null,!0),this.parse(L),this.$x=this.$x||L.x||{},this[E]=!0}var M=k.prototype;return M.parse=function(L){this.$d=function(F){var S=F.date,G=F.utc;if(S===null)return new Date(NaN);if(_.u(S))return new Date;if(S instanceof Date)return new Date(S);if(typeof S=="string"&&!/Z$/i.test(S)){var U=S.match(b);if(U){var $=U[2]-1||0,R=(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,R)):new Date(U[1],$,U[3]||1,U[4]||0,U[5]||0,U[6]||0,R)}}return new Date(S)}(L),this.init()},M.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()},M.$utils=function(){return _},M.isValid=function(){return this.$d.toString()!==f},M.isSame=function(L,F){var S=N(L);return this.startOf(F)<=S&&S<=this.endOf(F)},M.isAfter=function(L,F){return N(L)<this.startOf(F)},M.isBefore=function(L,F){return this.endOf(F)<N(L)},M.$g=function(L,F,S){return _.u(L)?this[F]:this.set(S,L)},M.unix=function(){return Math.floor(this.valueOf()/1e3)},M.valueOf=function(){return this.$d.getTime()},M.startOf=function(L,F){var S=this,G=!!_.u(F)||F,U=_.p(L),$=function(q,ee){var te=_.w(S.$u?Date.UTC(S.$y,ee,q):new Date(S.$y,ee,q),S);return G?te:te.endOf(d)},R=function(q,ee){return _.w(S.toDate()[q].apply(S.toDate("s"),(G?[0,0,0,0]:[23,59,59,999]).slice(ee)),S)},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 R(O+"Hours",0);case c:return R(O+"Minutes",1);case o:return R(O+"Seconds",2);case l:return R(O+"Milliseconds",3);default:return this.clone()}},M.endOf=function(L){return this.startOf(L,!1)},M.$set=function(L,F){var S,G=_.p(L),U="set"+(this.$u?"UTC":""),$=(S={},S[d]=U+"Date",S[g]=U+"Date",S[p]=U+"Month",S[h]=U+"FullYear",S[c]=U+"Hours",S[o]=U+"Minutes",S[l]=U+"Seconds",S[i]=U+"Milliseconds",S)[G],R=G===d?this.$D+(F-this.$W):F;if(G===p||G===h){var H=this.clone().set(g,1);H.$d[$](R),H.init(),this.$d=H.set(g,Math.min(this.$D,H.daysInMonth())).$d}else $&&this.$d[$](R);return this.init(),this},M.set=function(L,F){return this.clone().$set(L,F)},M.get=function(L){return this[_.p(L)]()},M.add=function(L,F){var S,G=this;L=Number(L);var U=_.p(F),$=function(K){var z=N(G);return _.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 R=(S={},S[o]=r,S[c]=n,S[l]=a,S)[U]||1,H=this.$d.getTime()+L*R;return _.w(H,this)},M.subtract=function(L,F){return this.add(-1*L,F)},M.format=function(L){var F=this,S=this.$locale();if(!this.isValid())return S.invalidDate||f;var G=L||"YYYY-MM-DDTHH:mm:ssZ",U=_.z(this),$=this.$H,R=this.$m,H=this.$M,K=S.weekdays,z=S.months,O=S.meridiem,V=function(ee,te,ue,_e){return ee&&(ee[te]||ee(F,G))||ue[te].slice(0,_e)},Q=function(ee){return _.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(F.$y).slice(-2);case"YYYY":return _.s(F.$y,4,"0");case"M":return H+1;case"MM":return _.s(H+1,2,"0");case"MMM":return V(S.monthsShort,H,z,3);case"MMMM":return V(z,H);case"D":return F.$D;case"DD":return _.s(F.$D,2,"0");case"d":return String(F.$W);case"dd":return V(S.weekdaysMin,F.$W,K,2);case"ddd":return V(S.weekdaysShort,F.$W,K,3);case"dddd":return K[F.$W];case"H":return String($);case"HH":return _.s($,2,"0");case"h":return Q(1);case"hh":return Q(2);case"a":return q($,R,!0);case"A":return q($,R,!1);case"m":return String(R);case"mm":return _.s(R,2,"0");case"s":return String(F.$s);case"ss":return _.s(F.$s,2,"0");case"SSS":return _.s(F.$ms,3,"0");case"Z":return U}return null}(ee)||U.replace(":","")})},M.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},M.diff=function(L,F,S){var G,U=this,$=_.p(F),R=N(L),H=(R.utcOffset()-this.utcOffset())*r,K=this-R,z=function(){return _.m(U,R)};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 S?G:_.a(G)},M.daysInMonth=function(){return this.endOf(p).$D},M.$locale=function(){return C[this.$L]},M.locale=function(L,F){if(!L)return this.$L;var S=this.clone(),G=T(L,F,!0);return G&&(S.$L=G),S},M.clone=function(){return _.w(this.$d,this)},M.toDate=function(){return new Date(this.valueOf())},M.toJSON=function(){return this.isValid()?this.toISOString():null},M.toISOString=function(){return this.$d.toISOString()},M.toString=function(){return this.$d.toUTCString()},k}(),B=I.prototype;return N.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(M){return this.$g(M,k[0],k[1])}}),N.extend=function(k,M){return k.$i||(k(M,I,N),k.$i=!0),N},N.locale=T,N.isDayjs=D,N.unix=function(k){return N(1e3*k)},N.en=C[A],N.Ls=C,N.p={},N})})(dg);var W1=dg.exports;const rs=ll(W1);var mg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(il,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"}],v=y.length,w=0;w<v;w+=1){var A=y[w];A.d&&(g=u?n(d).diff(p,A.d,!0):p.diff(d,A.d,!0));var C=(a.rounding||Math.round)(Math.abs(g));if(b=g>0,C<=A.r||!A.r){C<=1&&w>0&&(A=y[w-1]);var E=j[A.l];h&&(C=h(""+C)),f=typeof E=="string"?E.replace("%d",C):E(C,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)}}})})(mg);var Y1=mg.exports;const Q1=ll(Y1);rs.extend(Q1);function K1({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,$,R,H,K,z,O;const{user:v}=us(),w=t==null?void 0:t.pauseInfo,A=(w==null?void 0:w.isPaused)||!1,C=(G=w==null?void 0:w.pausedBy)==null?void 0:G.userId,E=(v==null?void 0:v.userId)||"",D=A&&p&&(h||s),T=A&&s&&C&&C!==E&&u,_=((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"),I=t==null?void 0:t.form16Submission,B=_&&(I!=null&&I.ocrExtractedData)&&typeof I.ocrExtractedData=="object"?I.ocrExtractedData:null,k=_&&B&&Object.keys(B).length>0?B:_&&I?{deductorName:I.deductorName,deductor_name:I.deductorName,tanNumber:I.tanNumber,tan_number:I.tanNumber,financialYear:I.financialYear,financial_year:I.financialYear,quarter:I.quarter,form16aNumber:I.form16aNumber,form16a_number:I.form16aNumber,totalAmount:I.totalAmount,total_amount:I.totalAmount,tdsAmount:I.tdsAmount,tds_amount:I.tdsAmount,acknowledgementNumber:I.acknowledgementNumber,acknowledgement_number:I.acknowledgementNumber,dateOfIssue:I.dateOfIssue,date_of_issue:I.dateOfIssue,deduceeName:I.deduceeName,deducee_name:I.deduceeName,deduceePan:I.deduceePan,deducee_pan:I.deduceePan}:null,M=V=>V!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(Number(V)):"",L=V=>V==null||V===""?"":String(V),F=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"},S=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:[_&&(I==null?void 0:I.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:F(I.displayStatus),children:I.displayStatus})]}),S(I)&&e.jsx("p",{className:`text-sm ${(I.displayStatus||"").toLowerCase()==="balance mismatch"||(I.displayStatus||"").toLowerCase()==="failed"?"text-red-700 font-medium":"text-gray-600"}`,children:S(I)})]}),_&&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:I?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:I.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:I.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:I.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:I.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:I.quarter?`${I.quarter} (${I.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:"})," ",I.deductorName||""]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TAN:"})," ",I.tanNumber||""]})]})]}),(I.deduceeName||I.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:[I.deduceeName&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Name:"})," ",I.deduceeName]}),I.deduceePan&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"PAN:"})," ",I.deduceePan]}),I.deduceeAddress&&e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("span",{className:"text-gray-500",children:"Address:"})," ",I.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:[I.section&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Section:"})," ",I.section]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Amount Paid:"})," ",M(I.totalAmount??I.amountPaid)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TDS Deducted:"})," ",M(I.tdsAmount)]}),I.dateOfPayment&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Date of Payment:"})," ",I.dateOfPayment]})]})]}),(I.bsrCode||I.challanSerialNo||I.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:[I.bsrCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"BSR Code:"})," ",I.bsrCode]}),I.challanSerialNo&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Challan Serial No.:"})," ",I.challanSerialNo]}),I.dateOfDeposit&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Date of Deposit:"})," ",I.dateOfDeposit]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Amount:"})," ",M(I.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:M(I.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."})]})})]}),_&&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(Zh,{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:M(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:M(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:((R=t.initiator)==null?void 0:R.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(ii,{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&&w&&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(dr,{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:[w.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:w.pauseReason,className:"text-sm text-gray-900 mt-1"})]}),w.pausedBy&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused By"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:w.pausedBy.name||w.pausedBy.email})]}),w.pauseResumeDate&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Auto-Resume Date"}),e.jsxs("p",{className:"text-sm text-gray-900 mt-1",children:[bs(w.pauseResumeDate),rs(w.pauseResumeDate).isAfter(rs())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",rs(w.pauseResumeDate).fromNow(),")"]})]})]}),w.pausedAt&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused At"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:bs(w.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[D&&p&&e.jsxs(P,{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(Qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),T&&u&&e.jsxs(P,{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?cg(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(P,{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(ui,{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(P,{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 zn({delayDuration:t=0,...s}){return e.jsx(kb,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function Mi({...t}){return e.jsx(zn,{children:e.jsx(Db,{"data-slot":"tooltip",...t})})}function Li({...t}){return e.jsx(Rb,{"data-slot":"tooltip-trigger",...t})}function Oi({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(Fb,{children:e.jsxs(Ib,{"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(Pb,{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($h,{"data-slot":"dialog",...t})}function X1({...t}){return e.jsx(Oh,{"data-slot":"dialog-portal",...t})}const ug=x.forwardRef(({className:t,...s},a)=>e.jsx(cc,{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}));ug.displayName=cc.displayName;const dt=x.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(X1,{"data-slot":"dialog-portal",children:[e.jsx(ug,{}),e.jsxs(dc,{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(Eb,{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=dc.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(Mh,{ref:a,"data-slot":"dialog-title",className:Le("text-lg leading-none font-semibold",t),...s}));mt.displayName=Mh.displayName;const _t=x.forwardRef(({className:t,...s},a)=>e.jsx(Lh,{ref:a,"data-slot":"dialog-description",className:Le("text-muted-foreground text-sm",t),...s}));_t.displayName=Lh.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 Lu=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`},Z1=(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(Jh,{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 J1({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",v=t.status==="rejected",w=t.status==="waiting",A=t.status==="paused",C=Number(t.tatHours||0),E=t.actualHours??0,D=y&&E?Math.max(0,C-E):0,T=C>0?E/C*100:0,N=T>=100,_=(d==null?void 0:d.role)==="ADMIN",I=Nl(d),B=t.approverId===(d==null?void 0:d.userId),k=_||I||B,M=async()=>{var L,F;if(!u.trim()){W.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}f(!0);try{await z1(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(S){console.error("Error updating breach reason:",S);const G=((F=(L=S==null?void 0:S.response)==null?void 0:L.data)==null?void 0:F.error)||(S==null?void 0:S.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":v?"border-red-500 bg-red-50":w?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${c}-${t.step}`,children:[e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 md:gap-4",children:[e.jsx("div",{className:`p-2 sm:p-2.5 md:p-3 rounded-xl flex-shrink-0 ${t.isSkipped?"bg-orange-100":A?"bg-yellow-100":j?"bg-blue-100":y?"bg-green-100":v?"bg-red-100":w?"bg-gray-200":"bg-gray-100"}`,children:Z1(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":v?"bg-red-100 text-red-800 border-red-200":w?"bg-gray-200 text-gray-600 border-gray-300":"bg-gray-100 text-gray-800 border-gray-200"}`,"data-testid":`${c}-status-badge`,children:t.isSkipped?"skipped":t.status}),t.isSkipped&&t.skipReason&&e.jsx(zn,{delayDuration:200,children:e.jsxs(Mi,{children:[e.jsx(Li,{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(Oi,{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(du,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),y&&E&&e.jsx(re,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:Lu(E)})]}),e.jsx("p",{className:"text-sm font-semibold text-gray-900","data-testid":`${c}-approver-name`,children:r?e.jsx("span",{className:"text-blue-600",children:"You"}):t.approver}),e.jsx("p",{className:"text-xs text-gray-600","data-testid":`${c}-role`,children:t.role})]}),e.jsxs("div",{className:"text-left sm:text-right flex-shrink-0",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium",children:"Turnaround Time (TAT)"}),e.jsxs("p",{className:"text-lg font-bold text-gray-900","data-testid":`${c}-tat-hours`,children:[C," hours"]})]})]}),y&&E!==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:Lu(E)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const L=Math.min(100,T),F=()=>N?"bg-red-600":T>=75?"bg-orange-500":T>=50?"bg-amber-500":"bg-green-600",S=()=>N?"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:F(),"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 ${S()}`,children:[Math.round(L),"% of TAT used"]}),N&&k&&e.jsx(zn,{children:e.jsxs(Mi,{children:[e.jsx(Li,{asChild:!0,children:e.jsx(P,{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(vi,{className:"w-3 h-3"})})}),e.jsx(Oi,{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)]})]})]})})()}),N&&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(vi,{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(C)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const L=a.sla.percentageUsed||0,F=()=>A?"bg-gray-500":L>=100?"bg-red-600":L>=75?"bg-orange-500":L>=50?"bg-amber-500":"bg-green-600",S=()=>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:F(),"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 ${S()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&k&&e.jsx(zn,{children:e.jsxs(Mi,{children:[e.jsx(Li,{asChild:!0,children:e.jsx(P,{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(vi,{className:"w-3 h-3"})})}),e.jsx(Oi,{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(Ki,{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(vi,{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"]})]})]})]}),w&&e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"bg-gray-100 border border-gray-300 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-gray-600 mb-1 flex items-center gap-1.5",children:[e.jsx(Jh,{className:"w-3.5 h-3.5 text-gray-500"}),"Awaiting Previous Approval"]}),e.jsx("p",{className:"text-sm font-medium text-gray-700",children:"Will be assigned after previous step"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Allocated ",C," hours for approval"]})]})}),v&&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(du,{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,F)=>{var S,G,U,$,R,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-${F}`,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(Sj,{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(Ki,{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 ",F+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)),((S=L.metadata)==null?void 0:S.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"]}),(((R=L.metadata)==null?void 0:R.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)"})]})]})]})},F)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[y?"Approved":v?"Rejected":"Actioned"," on ",bs(t.timestamp)]}),n&&!A&&(j||t.status==="pending")&&!y&&!v&&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(P,{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(P,{variant:"outline",onClick:()=>{p(!1),h("")},disabled:g,children:"Cancel"}),e.jsx(P,{onClick:M,disabled:!u.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function q1({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(J1,{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 Sr(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 eC(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 Ou="Failed - data mismatch with 26AS, submit the Form 16 with correct data.";function tC(t){const s=(t||"").toLowerCase();return/notnull|violation|sequelize|econnrefused|database|error\./i.test(s)}function $u(t){const s=((t==null?void 0:t.displayStatus)||"").toLowerCase(),a=String((t==null?void 0:t.validationNotes)||"");return s==="balance mismatch"||s==="failed"?tC(a)?Ou:a.trim()||Ou: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 sC({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:eC(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:"})," ",Sr(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]})]}),$u(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:$u(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:"})," ",Sr(s.totalAmount??s.amountPaid)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TDS Deducted:"})," ",Sr(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:"})," ",Sr(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:Sr(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(Zh,{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:Sr(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:Sr(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 aC=[{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 rC({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 Vp(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:aC.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(gc,{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 Uc=x.createContext({});function Bc(t){const s=x.useRef(null);return s.current===null&&(s.current=t()),s.current}const Vc=typeof window<"u",xg=Vc?x.useLayoutEffect:x.useEffect,Al=x.createContext(null);function zc(t,s){t.indexOf(s)===-1&&t.push(s)}function Hc(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 Gc=()=>{};const Za={},hg=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function pg(t){return typeof t=="object"&&t!==null}const gg=t=>/^0[^.\s]+$/u.test(t);function Wc(t){let s;return()=>(s===void 0&&(s=t()),s)}const ja=t=>t,nC=(t,s)=>a=>s(t(a)),xi=(...t)=>t.reduce(nC),qn=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class Yc{constructor(){this.subscriptions=[]}add(s){return zc(this.subscriptions,s),()=>Hc(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 fg(t,s){return s?t*(1e3/s):0}const bg=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,iC=1e-7,lC=12;function oC(t,s,a,r,n){let i,l,o=0;do l=s+(a-s)/2,i=bg(l,r,n)-t,i>0?a=l:s=l;while(Math.abs(i)>iC&&++o<lC);return l}function hi(t,s,a,r){if(t===s&&a===r)return ja;const n=i=>oC(i,0,1,t,a);return i=>i===0||i===1?i:bg(n(i),s,r)}const jg=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,yg=t=>s=>1-t(1-s),vg=hi(.33,1.53,.69,.99),Qc=yg(vg),Ng=jg(Qc),wg=t=>(t*=2)<1?.5*Qc(t):.5*(2-Math.pow(2,-10*(t-1))),Kc=t=>1-Math.sin(Math.acos(t)),Cg=yg(Kc),Sg=jg(Kc),cC=hi(.42,0,1,1),dC=hi(0,0,.58,1),Ag=hi(.42,0,.58,1),mC=t=>Array.isArray(t)&&typeof t[0]!="number",Tg=t=>Array.isArray(t)&&typeof t[0]=="number",uC={linear:ja,easeIn:cC,easeInOut:Ag,easeOut:dC,circIn:Kc,circInOut:Sg,circOut:Cg,backIn:Qc,backInOut:Ng,backOut:vg,anticipate:wg},xC=t=>typeof t=="string",Uu=t=>{if(Tg(t)){Gc(t.length===4);const[s,a,r,n]=t;return hi(s,a,r,n)}else if(xC(t))return uC[t];return t},wi=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function hC(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 pC=40;function kg(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,l=wi.reduce((v,w)=>(v[w]=hC(i),v),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:m,update:p,preRender:u,render:h,postRender:g}=l,f=()=>{const v=Za.useManualTiming?n.timestamp:performance.now();a=!1,Za.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(v-n.timestamp,pC),1)),n.timestamp=v,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:wi.reduce((v,w)=>{const A=l[w];return v[w]=(C,E=!1,D=!1)=>(a||b(),A.schedule(C,E,D)),v},{}),cancel:v=>{for(let w=0;w<wi.length;w++)l[wi[w]].cancel(v)},state:n,steps:l}}const{schedule:es,cancel:ur,state:Is,steps:Zl}=kg(typeof requestAnimationFrame<"u"?requestAnimationFrame:ja,!0);let $i;function gC(){$i=void 0}const sa={now:()=>($i===void 0&&sa.set(Is.isProcessing||Za.useManualTiming?Is.timestamp:performance.now()),$i),set:t=>{$i=t,queueMicrotask(gC)}},Dg=t=>s=>typeof s=="string"&&s.startsWith(t),Xc=Dg("--"),fC=Dg("var(--"),Zc=t=>fC(t)?bC.test(t.split("/*")[0].trim()):!1,bC=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,wn={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},ei={...wn,transform:t=>Xa(0,1,t)},Ci={...wn,default:1},Hn=t=>Math.round(t*1e5)/1e5,Jc=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function jC(t){return t==null}const yC=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,qc=(t,s)=>a=>!!(typeof a=="string"&&yC.test(a)&&a.startsWith(t)||s&&!jC(a)&&Object.prototype.hasOwnProperty.call(a,s)),Rg=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,l,o]=r.match(Jc);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},vC=t=>Xa(0,255,t),Jl={...wn,transform:t=>Math.round(vC(t))},_r={test:qc("rgb","red"),parse:Rg("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+Jl.transform(t)+", "+Jl.transform(s)+", "+Jl.transform(a)+", "+Hn(ei.transform(r))+")"};function NC(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 $o={test:qc("#"),parse:NC,transform:_r.transform},pi=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),ir=pi("deg"),La=pi("%"),ot=pi("px"),wC=pi("vh"),CC=pi("vw"),Bu={...La,parse:t=>La.parse(t)/100,transform:t=>La.transform(t*100)},sn={test:qc("hsl","hue"),parse:Rg("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+La.transform(Hn(s))+", "+La.transform(Hn(a))+", "+Hn(ei.transform(r))+")"},gs={test:t=>_r.test(t)||$o.test(t)||sn.test(t),parse:t=>_r.test(t)?_r.parse(t):sn.test(t)?sn.parse(t):$o.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?_r.transform(t):sn.transform(t),getAnimatableNone:t=>{const s=gs.parse(t);return s.alpha=0,gs.transform(s)}},SC=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function AC(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(Jc))==null?void 0:s.length)||0)+(((a=t.match(SC))==null?void 0:a.length)||0)>0}const Fg="number",Ig="color",TC="var",kC="var(",Vu="${}",DC=/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 ti(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const o=s.replace(DC,c=>(gs.test(c)?(r.color.push(i),n.push(Ig),a.push(gs.parse(c))):c.startsWith(kC)?(r.var.push(i),n.push(TC),a.push(c)):(r.number.push(i),n.push(Fg),a.push(parseFloat(c))),++i,Vu)).split(Vu);return{values:a,split:o,indexes:r,types:n}}function Pg(t){return ti(t).values}function Eg(t){const{split:s,types:a}=ti(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===Fg?i+=Hn(n[l]):o===Ig?i+=gs.transform(n[l]):i+=n[l]}return i}}const RC=t=>typeof t=="number"?0:gs.test(t)?gs.getAnimatableNone(t):t;function FC(t){const s=Pg(t);return Eg(t)(s.map(RC))}const xr={test:AC,parse:Pg,createTransformer:Eg,getAnimatableNone:FC};function ql(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 IC({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=ql(c,o,t+1/3),i=ql(c,o,t),l=ql(c,o,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function qi(t,s){return a=>a>0?s:t}const ns=(t,s,a)=>t+(s-t)*a,eo=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},PC=[$o,_r,sn],EC=t=>PC.find(s=>s.test(t));function zu(t){const s=EC(t);if(!s)return!1;let a=s.parse(t);return s===sn&&(a=IC(a)),a}const Hu=(t,s)=>{const a=zu(t),r=zu(s);if(!a||!r)return qi(t,s);const n={...a};return i=>(n.red=eo(a.red,r.red,i),n.green=eo(a.green,r.green,i),n.blue=eo(a.blue,r.blue,i),n.alpha=ns(a.alpha,r.alpha,i),_r.transform(n))},Uo=new Set(["none","hidden"]);function _C(t,s){return Uo.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function MC(t,s){return a=>ns(t,s,a)}function ed(t){return typeof t=="number"?MC:typeof t=="string"?Zc(t)?qi:gs.test(t)?Hu:$C:Array.isArray(t)?_g:typeof t=="object"?gs.test(t)?Hu:LC:qi}function _g(t,s){const a=[...t],r=a.length,n=t.map((i,l)=>ed(i)(i,s[l]));return i=>{for(let l=0;l<r;l++)a[l]=n[l](i);return a}}function LC(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=ed(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function OC(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 $C=(t,s)=>{const a=xr.createTransformer(s),r=ti(t),n=ti(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?Uo.has(t)&&!n.values.length||Uo.has(s)&&!r.values.length?_C(t,s):xi(_g(OC(r,n),n.values),a):qi(t,s)};function Mg(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?ns(t,s,a):ed(t)(t,s)}const UC=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>es.update(s,a),stop:()=>ur(s),now:()=>Is.isProcessing?Is.timestamp:sa.now()}},Lg=(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)})`},el=2e4;function td(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<el;)s+=a,r=t.next(s);return s>=el?1/0:s}function BC(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(td(r),el);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:fa(n)}}const VC=5;function Og(t,s,a){const r=Math.max(s-VC,0);return fg(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},to=.001;function zC({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=Bo(d,l),g=Math.exp(-p);return to-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=Bo(Math.pow(d,2),l);return(-n(d)+to>0?-1:1)*((u-h)*g)/f}):(n=d=>{const m=Math.exp(-d*t),p=(d-a)*t+1;return-to+m*p},i=d=>{const m=Math.exp(-d*t),p=(a-d)*(t*t);return m*p});const o=5/t,c=GC(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 HC=12;function GC(t,s,a){let r=a;for(let n=1;n<HC;n++)r=r-t(r)/s(r);return r}function Bo(t,s){return t*Math.sqrt(1-s*s)}const WC=["duration","bounce"],YC=["stiffness","damping","mass"];function Gu(t,s){return s.some(a=>t[a]!==void 0)}function QC(t){let s={velocity:ls.velocity,stiffness:ls.stiffness,damping:ls.damping,mass:ls.mass,isResolvedFromDuration:!1,...t};if(!Gu(t,YC)&&Gu(t,WC))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=zC(t);s={...s,...a,mass:ls.mass},s.isResolvedFromDuration=!0}return s}function tl(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}=QC({...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 v;if(f<1){const A=Bo(j,f);v=C=>{const E=Math.exp(-f*j*C);return l-E*((g+f*j*b)/A*Math.sin(A*C)+b*Math.cos(A*C))}}else if(f===1)v=A=>l-Math.exp(-j*A)*(b+(g+j*b)*A);else{const A=j*Math.sqrt(f*f-1);v=C=>{const E=Math.exp(-f*j*C),D=Math.min(A*C,300);return l-E*((g+f*j*b)*Math.sinh(D)+A*b*Math.cosh(D))/A}}const w={calculatedDuration:h&&p||null,next:A=>{const C=v(A);if(h)o.done=A>=p;else{let E=A===0?g:0;f<1&&(E=A===0?Ma(g):Og(v,A,C));const D=Math.abs(E)<=r,T=Math.abs(l-C)<=n;o.done=D&&T}return o.value=o.done?l:C,o},toString:()=>{const A=Math.min(td(w),el),C=Lg(E=>w.next(A*E).value,A,30);return A+"ms "+C},toTransition:()=>{}};return w}tl.applyToOptions=t=>{const s=BC(t,100,tl);return t.ease=s.ease,t.duration=Ma(s.duration),t.type="keyframes",t};function Vo({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),v=D=>j+y(D),w=D=>{const T=y(D),N=v(D);u.done=Math.abs(T)<=d,u.value=u.done?j:N};let A,C;const E=D=>{h(u.value)&&(A=D,C=tl({keyframes:[u.value,g(u.value)],velocity:Og(v,D,u.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return E(0),{calculatedDuration:null,next:D=>{let T=!1;return!C&&A===void 0&&(T=!0,w(D),E(D)),A!==void 0&&D>=A?C.next(D-A):(!T&&w(D),u)}}}function KC(t,s,a){const r=[],n=a||Za.mix||Mg,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=xi(c,o)}r.push(o)}return r}function XC(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(Gc(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=KC(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=qn(t[p],t[p+1],m);return o[p](u)};return a?m=>d(Xa(t[0],t[i-1],m)):d}function ZC(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=qn(0,s,r);t.push(ns(a,1,n))}}function JC(t){const s=[0];return ZC(s,t.length-1),s}function qC(t,s){return t.map(a=>a*s)}function e2(t,s){return t.map(()=>s||Ag).splice(0,t.length-1)}function Gn({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=mC(r)?r.map(Uu):Uu(r),i={done:!1,value:s[0]},l=qC(a&&a.length===s.length?a:JC(s),t),o=XC(l,s,{ease:Array.isArray(n)?n:e2(s,n)});return{calculatedDuration:t,next:c=>(i.value=o(c),i.done=c>=t,i)}}const t2=t=>t!==null;function sd(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(t2),o=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const s2={decay:Vo,inertia:Vo,tween:Gn,keyframes:Gn,spring:tl};function $g(t){typeof t.type=="string"&&(t.type=s2[t.type])}class ad{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 a2=t=>t/100;class rd extends ad{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;$g(s);const{type:a=Gn,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:l=0}=s;let{keyframes:o}=s;const c=a||Gn;c!==Gn&&typeof o[0]!="number"&&(this.mixKeyframes=xi(a2,Mg(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=td(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 v=this.currentTime,w=r;if(p){const D=Math.min(this.currentTime,n)/o;let T=Math.floor(D),N=D%1;!N&&D>=1&&(N=1),N===1&&T--,T=Math.min(T,p+1),!!(T%2)&&(u==="reverse"?(N=1-N,h&&(N-=h/o)):u==="mirror"&&(w=l)),v=Xa(0,1,N)*o}const A=y?{done:!1,value:m[0]}:w.next(v);i&&(A.value=i(A.value));let{done:C}=A;!y&&c!==null&&(C=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const E=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&C);return E&&g!==Vo&&(A.value=sd(m,this.options,b,this.speed)),f&&f(A.value),E&&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=UC,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 r2(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const Mr=t=>t*180/Math.PI,zo=t=>{const s=Mr(Math.atan2(t[1],t[0]));return Ho(s)},n2={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:zo,rotateZ:zo,skewX:t=>Mr(Math.atan(t[1])),skewY:t=>Mr(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Ho=t=>(t=t%360,t<0&&(t+=360),t),Wu=zo,Yu=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Qu=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),i2={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Yu,scaleY:Qu,scale:t=>(Yu(t)+Qu(t))/2,rotateX:t=>Ho(Mr(Math.atan2(t[6],t[5]))),rotateY:t=>Ho(Mr(Math.atan2(-t[2],t[0]))),rotateZ:Wu,rotate:Wu,skewX:t=>Mr(Math.atan(t[4])),skewY:t=>Mr(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Go(t){return t.includes("scale")?1:0}function Wo(t,s){if(!t||t==="none")return Go(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=i2,n=a;else{const o=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=n2,n=o}if(!n)return Go(s);const i=r[s],l=n[1].split(",").map(o2);return typeof i=="function"?i(l):l[i]}const l2=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return Wo(a,s)};function o2(t){return parseFloat(t.trim())}const Cn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Sn=new Set(Cn),Ku=t=>t===wn||t===ot,c2=new Set(["x","y","z"]),d2=Cn.filter(t=>!c2.has(t));function m2(t){const s=[];return d2.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const Lr={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})=>Wo(s,"x"),y:(t,{transform:s})=>Wo(s,"y")};Lr.translateX=Lr.x;Lr.translateY=Lr.y;const Or=new Set;let Yo=!1,Qo=!1,Ko=!1;function Ug(){if(Qo){const t=Array.from(Or).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=m2(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)})}Qo=!1,Yo=!1,Or.forEach(t=>t.complete(Ko)),Or.clear()}function Bg(){Or.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Qo=!0)})}function u2(){Ko=!0,Bg(),Ug(),Ko=!1}class nd{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?(Or.add(this),Yo||(Yo=!0,es.read(Bg),es.resolveKeyframes(Ug))):(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])}r2(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),Or.delete(this)}cancel(){this.state==="scheduled"&&(Or.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const x2=t=>t.startsWith("--");function h2(t,s,a){x2(s)?t.style.setProperty(s,a):t.style[s]=a}const p2=Wc(()=>window.ScrollTimeline!==void 0),g2={};function f2(t,s){const a=Wc(t);return()=>g2[s]??a()}const Vg=f2(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Bn=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,Xu={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Bn([0,.65,.55,1]),circOut:Bn([.55,0,1,.45]),backIn:Bn([.31,.01,.66,-.59]),backOut:Bn([.33,1.53,.69,.99])};function zg(t,s){if(t)return typeof t=="function"?Vg()?Lg(t,s):"ease-out":Tg(t)?Bn(t):Array.isArray(t)?t.map(a=>zg(a,s)||Xu.easeOut):Xu[t]}function b2(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=zg(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 Hg(t){return typeof t=="function"&&"applyToOptions"in t}function j2({type:t,...s}){return Hg(t)&&Vg()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class y2 extends ad{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,Gc(typeof s.type!="string");const d=j2(s);this.animation=b2(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=sd(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(m):h2(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&&p2()?(this.animation.timeline=s,ja):a(this)}}const Gg={anticipate:wg,backInOut:Ng,circInOut:Sg};function v2(t){return t in Gg}function N2(t){typeof t.ease=="string"&&v2(t.ease)&&(t.ease=Gg[t.ease])}const Zu=10;class w2 extends y2{constructor(s){N2(s),$g(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 rd({...l,autoplay:!1}),c=Ma(this.finishedTime??this.time);a.setWithVelocity(o.sample(c-Zu).value,o.sample(c).value,Zu),o.stop()}}const Ju=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(xr.test(t)||t==="0")&&!t.startsWith("url("));function C2(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 S2(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=Ju(n,s),o=Ju(i,s);return!l||!o?!1:C2(t)||(a==="spring"||Hg(a))&&r}function Xo(t){t.duration=0,t.type="keyframes"}const A2=new Set(["opacity","clipPath","filter","transform"]),T2=Wc(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function k2(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 T2()&&a&&A2.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&l!=="inertia"}const D2=40;class R2 extends ad{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)||nd;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(),S2(s,i,l,o)||((Za.instantAnimations||!c)&&(m==null||m(sd(s,r,a))),s[0]=s[s.length-1],Xo(r),r.repeat=0);const u={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>D2?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},h=!d&&k2(u)?new w2({...u,element:u.motionValue.owner.current}):new rd(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(),u2()),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 F2=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function I2(t){const s=F2.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Wg(t,s,a=1){const[r,n]=I2(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const l=i.trim();return hg(l)?parseFloat(l):l}return Zc(n)?Wg(n,s,a+1):n}function id(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const Yg=new Set(["width","height","top","left","right","bottom",...Cn]),P2={test:t=>t==="auto",parse:t=>t},Qg=t=>s=>s.test(t),Kg=[wn,ot,La,ir,CC,wC,P2],qu=t=>Kg.find(Qg(t));function E2(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||gg(t):!0}const _2=new Set(["brightness","contrast","saturate","opacity"]);function M2(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(Jc)||[];if(!r)return t;const n=a.replace(r,"");let i=_2.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const L2=/\b([a-z-]*)\(.*?\)/gu,Zo={...xr,getAnimatableNone:t=>{const s=t.match(L2);return s?s.map(M2).join(" "):t}},ex={...wn,transform:Math.round},O2={rotate:ir,rotateX:ir,rotateY:ir,rotateZ:ir,scale:Ci,scaleX:Ci,scaleY:Ci,scaleZ:Ci,skew:ir,skewX:ir,skewY:ir,distance:ot,translateX:ot,translateY:ot,translateZ:ot,x:ot,y:ot,z:ot,perspective:ot,transformPerspective:ot,opacity:ei,originX:Bu,originY:Bu,originZ:ot},ld={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,...O2,zIndex:ex,fillOpacity:ei,strokeOpacity:ei,numOctaves:ex},$2={...ld,color:gs,backgroundColor:gs,outlineColor:gs,fill:gs,stroke:gs,borderColor:gs,borderTopColor:gs,borderRightColor:gs,borderBottomColor:gs,borderLeftColor:gs,filter:Zo,WebkitFilter:Zo},Xg=t=>$2[t];function Zg(t,s){let a=Xg(t);return a!==Zo&&(a=xr),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const U2=new Set(["auto","none","0"]);function B2(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!U2.has(i)&&ti(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=Zg(a,n)}class V2 extends nd{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(),Zc(d))){const m=Wg(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!Yg.has(r)||s.length!==2)return;const[n,i]=s,l=qu(n),o=qu(i);if(l!==o)if(Ku(l)&&Ku(o))for(let c=0;c<s.length;c++){const d=s[c];typeof d=="string"&&(s[c]=parseFloat(d))}else Lr[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||E2(s[n]))&&r.push(n);r.length&&B2(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=Lr[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]=Lr[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 z2(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 Jg=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function qg(t){return pg(t)&&"offsetHeight"in t}const tx=30,H2=t=>!isNaN(parseFloat(t));class G2{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=H2(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 Yc);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>tx)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,tx);return fg(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 pn(t,s){return new G2(t,s)}const{schedule:od}=kg(queueMicrotask,!1),ka={x:!1,y:!1};function e0(){return ka.x||ka.y}function W2(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 t0(t,s){const a=z2(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function sx(t){return!(t.pointerType==="touch"||e0())}function Y2(t,s,a={}){const[r,n,i]=t0(t,a),l=o=>{if(!sx(o))return;const{target:c}=o,d=s(c,o);if(typeof d!="function"||!c)return;const m=p=>{sx(p)&&(d(p),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(o=>{o.addEventListener("pointerenter",l,n)}),i}const s0=(t,s)=>s?t===s?!0:s0(t,s.parentElement):!1,cd=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Q2=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function K2(t){return Q2.has(t.tagName)||t.tabIndex!==-1}const Ui=new WeakSet;function ax(t){return s=>{s.key==="Enter"&&t(s)}}function so(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const X2=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=ax(()=>{if(Ui.has(a))return;so(a,"down");const n=ax(()=>{so(a,"up")}),i=()=>so(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 rx(t){return cd(t)&&!e0()}function Z2(t,s,a={}){const[r,n,i]=t0(t,a),l=o=>{const c=o.currentTarget;if(!rx(o))return;Ui.add(c);const d=s(c,o),m=(h,g)=>{window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",u),Ui.has(c)&&Ui.delete(c),rx(h)&&typeof d=="function"&&d(h,{success:g})},p=h=>{m(h,c===window||c===document||a.useGlobalTarget||s0(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),qg(o)&&(o.addEventListener("focus",d=>X2(d,n)),!K2(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function a0(t){return pg(t)&&"ownerSVGElement"in t}function J2(t){return a0(t)&&t.tagName==="svg"}const Bs=t=>!!(t&&t.getVelocity),q2=[...Kg,gs,xr],eS=t=>q2.find(Qg(t)),dd=x.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function nx(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function tS(...t){return s=>{let a=!1;const r=t.map(n=>{const i=nx(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():nx(t[n],null)}}}}function sS(...t){return x.useCallback(tS(...t),t)}class aS extends x.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=qg(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 rS({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(dd),c=sS(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(aS,{isPresent:s,childRef:i,sizeRef:l,children:x.cloneElement(t,{ref:c})})}const nS=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=Bc(iS),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(rS,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(Al.Provider,{value:u,children:t})};function iS(){return new Map}function r0(t=!0){const s=x.useContext(Al);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 Si=t=>t.key||"";function ix(t){const s=[];return x.Children.forEach(t,a=>{x.isValidElement(a)&&s.push(a)}),s}const Tl=({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]=r0(l),p=x.useMemo(()=>ix(t),[t]),u=l&&!d?[]:p.map(Si),h=x.useRef(!0),g=x.useRef(p),f=Bc(()=>new Map),[b,j]=x.useState(p),[y,v]=x.useState(p);xg(()=>{h.current=!1,g.current=p;for(let C=0;C<y.length;C++){const E=Si(y[C]);u.includes(E)?f.delete(E):f.get(E)!==!0&&f.set(E,!1)}},[y,u.length,u.join("-")]);const w=[];if(p!==b){let C=[...p];for(let E=0;E<y.length;E++){const D=y[E],T=Si(D);u.includes(T)||(C.splice(E,0,D),w.push(D))}return i==="wait"&&w.length&&(C=w),v(ix(C)),j(p),null}const{forceRender:A}=x.useContext(Uc);return e.jsx(e.Fragment,{children:y.map(C=>{const E=Si(C),D=l&&!d?!1:p===y||u.includes(E),T=()=>{if(f.has(E))f.set(E,!0);else return;let N=!0;f.forEach(_=>{_||(N=!1)}),N&&(A==null||A(),v(g.current),l&&(m==null||m()),r&&r())};return e.jsx(nS,{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:C},E)})})},n0=x.createContext({strict:!1}),lx={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"]},gn={};for(const t in lx)gn[t]={isEnabled:s=>lx[t].some(a=>!!s[a])};function lS(t){for(const s in t)gn[s]={...gn[s],...t[s]}}const oS=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 sl(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||oS.has(t)}let i0=t=>!sl(t);function cS(t){typeof t=="function"&&(i0=s=>s.startsWith("on")?!sl(s):t(s))}try{cS(require("@emotion/is-prop-valid").default)}catch{}function dS(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(i0(n)||a===!0&&sl(n)||!s&&!sl(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const kl=x.createContext({});function Dl(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function si(t){return typeof t=="string"||Array.isArray(t)}const md=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ud=["initial",...md];function Rl(t){return Dl(t.animate)||ud.some(s=>si(t[s]))}function l0(t){return!!(Rl(t)||t.variants)}function mS(t,s){if(Rl(t)){const{initial:a,animate:r}=t;return{initial:a===!1||si(a)?a:void 0,animate:si(r)?r:void 0}}return t.inherit!==!1?s:{}}function uS(t){const{initial:s,animate:a}=mS(t,x.useContext(kl));return x.useMemo(()=>({initial:s,animate:a}),[ox(s),ox(a)])}function ox(t){return Array.isArray(t)?t.join(" "):t}const ai={};function xS(t){for(const s in t)ai[s]=t[s],Xc(s)&&(ai[s].isCSSVariable=!0)}function o0(t,{layout:s,layoutId:a}){return Sn.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!ai[t]||t==="opacity")}const hS={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},pS=Cn.length;function gS(t,s,a){let r="",n=!0;for(let i=0;i<pS;i++){const l=Cn[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=Jg(o,ld[l]);if(!c){n=!1;const m=hS[l]||l;r+=`${m}(${d}) `}a&&(s[l]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function xd(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(Sn.has(c)){l=!0;continue}else if(Xc(c)){n[c]=d;continue}else{const m=Jg(d,ld[c]);c.startsWith("origin")?(o=!0,i[c]=m):r[c]=m}}if(s.transform||(l||a?r.transform=gS(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 hd=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function c0(t,s,a){for(const r in s)!Bs(s[r])&&!o0(r,a)&&(t[r]=s[r])}function fS({transformTemplate:t},s){return x.useMemo(()=>{const a=hd();return xd(a,s,t),Object.assign({},a.vars,a.style)},[s])}function bS(t,s){const a=t.style||{},r={};return c0(r,a,t),Object.assign(r,fS(t,s)),r}function jS(t,s){const a={},r=bS(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 yS={offset:"stroke-dashoffset",array:"stroke-dasharray"},vS={offset:"strokeDashoffset",array:"strokeDasharray"};function NS(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?yS:vS;t[i.offset]=ot.transform(-r);const l=ot.transform(s),o=ot.transform(a);t[i.array]=`${l} ${o}`}function d0(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(xd(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&&NS(p,n,i,l,!1)}const m0=()=>({...hd(),attrs:{}}),u0=t=>typeof t=="string"&&t.toLowerCase()==="svg";function wS(t,s,a,r){const n=x.useMemo(()=>{const i=m0();return d0(i,s,u0(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};c0(i,t.style,t),n.style={...i,...n.style}}return n}const CS=["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 pd(t){return typeof t!="string"||t.includes("-")?!1:!!(CS.indexOf(t)>-1||/[A-Z]/u.test(t))}function SS(t,s,a,{latestValues:r},n,i=!1){const o=(pd(t)?wS:jS)(s,r,n,t),c=dS(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 cx(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function gd(t,s,a,r){if(typeof s=="function"){const[n,i]=cx(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]=cx(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Bi(t){return Bs(t)?t.get():t}function AS({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:TS(a,r,n,t),renderState:s()}}function TS(t,s,a,r){const n={},i=r(t,{});for(const u in i)n[u]=Bi(i[u]);let{initial:l,animate:o}=t;const c=Rl(t),d=l0(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const p=m?o:l;if(p&&typeof p!="boolean"&&!Dl(p)){const u=Array.isArray(p)?p:[p];for(let h=0;h<u.length;h++){const g=gd(t,u[h]);if(g){const{transitionEnd:f,transition:b,...j}=g;for(const y in j){let v=j[y];if(Array.isArray(v)){const w=m?v.length-1:0;v=v[w]}v!==null&&(n[y]=v)}for(const y in f)n[y]=f[y]}}}return n}const x0=t=>(s,a)=>{const r=x.useContext(kl),n=x.useContext(Al),i=()=>AS(t,s,r,n);return a?i():Bc(i)};function fd(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(Bs(r[l])||s.style&&Bs(s.style[l])||o0(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const kS=x0({scrapeMotionValuesFromProps:fd,createRenderState:hd});function h0(t,s,a){const r=fd(t,s,a);for(const n in t)if(Bs(t[n])||Bs(s[n])){const i=Cn.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const DS=x0({scrapeMotionValuesFromProps:h0,createRenderState:m0}),RS=Symbol.for("motionComponentSymbol");function an(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function FS(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):an(a)&&(a.current=r))},[s])}const bd=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),IS="framerAppearId",p0="data-"+bd(IS),g0=x.createContext({});function PS(t,s,a,r,n){var f,b;const{visualElement:i}=x.useContext(kl),l=x.useContext(n0),o=x.useContext(Al),c=x.useContext(dd).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(g0);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&ES(d.current,a,n,p);const u=x.useRef(!1);x.useInsertionEffect(()=>{m&&u.current&&m.update(a,o)});const h=a[p0],g=x.useRef(!!h&&!((f=window.MotionHandoffIsComplete)!=null&&f.call(window,h))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,h)));return xg(()=>{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 ES(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:f0(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&an(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function f0(t){if(t)return t.options.allowProjection!==!1?t.projection:f0(t.parent)}function ao(t,{forwardMotionProps:s=!1}={},a,r){a&&lS(a);const n=pd(t)?DS:kS;function i(o,c){let d;const m={...x.useContext(dd),...o,layoutId:_S(o)},{isStatic:p}=m,u=uS(o),h=n(o,p);if(!p&&Vc){MS();const g=LS(m);d=g.MeasureLayout,u.visualElement=PS(t,h,m,r,g.ProjectionNode)}return e.jsxs(kl.Provider,{value:u,children:[d&&u.visualElement?e.jsx(d,{visualElement:u.visualElement,...m}):null,SS(t,o,FS(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[RS]=t,l}function _S({layoutId:t}){const s=x.useContext(Uc).id;return s&&t!==void 0?s+"-"+t:t}function MS(t,s){x.useContext(n0).strict}function LS(t){const{drag:s,layout:a}=gn;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 OS(t,s){if(typeof Proxy>"u")return ao;const a=new Map,r=(i,l)=>ao(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,ao(l,void 0,t,s)),a.get(l))})}function b0({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function $S({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function US(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 ro(t){return t===void 0||t===1}function Jo({scale:t,scaleX:s,scaleY:a}){return!ro(t)||!ro(s)||!ro(a)}function Rr(t){return Jo(t)||j0(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function j0(t){return dx(t.x)||dx(t.y)}function dx(t){return t&&t!=="0%"}function al(t,s,a){const r=t-a,n=s*r;return a+n}function mx(t,s,a,r,n){return n!==void 0&&(t=al(t,n,r)),al(t,a,r)+s}function qo(t,s=0,a=1,r,n){t.min=mx(t.min,s,a,r,n),t.max=mx(t.max,s,a,r,n)}function y0(t,{x:s,y:a}){qo(t.x,s.translate,s.scale,s.originPoint),qo(t.y,a.translate,a.scale,a.originPoint)}const ux=.999999999999,xx=1.0000000000001;function BS(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&&nn(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),l&&(s.x*=l.x.scale,s.y*=l.y.scale,y0(t,l)),r&&Rr(i.latestValues)&&nn(t,i.latestValues))}s.x<xx&&s.x>ux&&(s.x=1),s.y<xx&&s.y>ux&&(s.y=1)}function rn(t,s){t.min=t.min+s,t.max=t.max+s}function hx(t,s,a,r,n=.5){const i=ns(t.min,t.max,n);qo(t,s,a,i,r)}function nn(t,s){hx(t.x,s.x,s.scaleX,s.scale,s.originX),hx(t.y,s.y,s.scaleY,s.scale,s.originY)}function v0(t,s){return b0(US(t.getBoundingClientRect(),s))}function VS(t,s,a){const r=v0(t,a),{scroll:n}=s;return n&&(rn(r.x,n.offset.x),rn(r.y,n.offset.y)),r}const px=()=>({translate:0,scale:1,origin:0,originPoint:0}),ln=()=>({x:px(),y:px()}),gx=()=>({min:0,max:0}),hs=()=>({x:gx(),y:gx()}),ec={current:null},N0={current:!1};function zS(){if(N0.current=!0,!!Vc)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>ec.current=t.matches;t.addEventListener("change",s),s()}else ec.current=!1}const HS=new WeakMap;function GS(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,pn(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,pn(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const fx=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class WS{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=nd,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=Rl(a),this.isVariantNode=l0(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,HS.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)),N0.current||zS(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ec.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),ur(this.notifyUpdate),ur(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=Sn.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 gn){const a=gn[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<fx.length;r++){const n=fx[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=GS(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=pn(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"&&(hg(r)||gg(r))?r=parseFloat(r):!eS(r)&&xr.test(a)&&(r=Zg(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=gd(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 Yc),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){od.render(this.render)}}class w0 extends WS{constructor(){super(...arguments),this.KeyframeResolver=V2}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 C0(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 YS(t){return window.getComputedStyle(t)}class QS extends w0{constructor(){super(...arguments),this.type="html",this.renderInstance=C0}readValueFromInstance(s,a){var r;if(Sn.has(a))return(r=this.projection)!=null&&r.isProjecting?Go(a):l2(s,a);{const n=YS(s),i=(Xc(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return v0(s,a)}build(s,a,r){xd(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return fd(s,a,r)}}const S0=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 KS(t,s,a,r){C0(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(S0.has(n)?n:bd(n),s.attrs[n])}class XS extends w0{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=hs}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Sn.has(a)){const r=Xg(a);return r&&r.default||0}return a=S0.has(a)?a:bd(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return h0(s,a,r)}build(s,a,r){d0(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){KS(s,a,r,n)}mount(s){this.isSVGTag=u0(s.tagName),super.mount(s)}}const ZS=(t,s)=>pd(t)?new XS(s):new QS(s,{allowProjection:t!==x.Fragment});function xn(t,s,a){const r=t.getProps();return gd(r,s,a!==void 0?a:r.custom,t)}const tc=t=>Array.isArray(t);function JS(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,pn(a))}function qS(t){return tc(t)?t[t.length-1]||0:t}function eA(t,s){const a=xn(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=qS(i[l]);JS(t,l,o)}}function tA(t){return!!(Bs(t)&&t.add)}function sc(t,s){const a=t.getValue("willChange");if(tA(a))return a.add(s);if(!a&&Za.WillChange){const r=new Za.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function A0(t){return t.props[p0]}const sA=t=>t!==null;function aA(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(sA),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const rA={type:"spring",stiffness:500,damping:25,restSpeed:10},nA=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),iA={type:"keyframes",duration:.8},lA={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},oA=(t,{keyframes:s})=>s.length>2?iA:Sn.has(t)?t.startsWith("scale")?nA(s[1]):rA:lA;function cA({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 jd=(t,s,a,r={},n,i)=>l=>{const o=id(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};cA(o)||Object.assign(m,oA(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)&&(Xo(m),m.delay===0&&(p=!0)),(Za.instantAnimations||Za.skipAnimations)&&(p=!0,Xo(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,p&&!i&&s.get()!==void 0){const u=aA(m.keyframes,o);if(u!==void 0){es.update(()=>{m.onUpdate(u),m.onComplete()});return}}return o.isSync?new rd(m):new R2(m)};function dA({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function T0(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&&dA(d,m))continue;const h={delay:a,...id(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=A0(t);if(j){const y=window.MotionHandoffAnimation(j,m,es);y!==null&&(h.startTime=y,f=!0)}}sc(t,m),p.start(jd(m,p,u,t.shouldReduceMotion&&Yg.has(m)?{type:!1}:h,t,f));const b=p.animation;b&&c.push(b)}return l&&Promise.all(c).then(()=>{es.update(()=>{l&&eA(t,l)})}),c}function k0(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 ac(t,s,a={}){var c;const r=xn(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(T0(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:p,staggerDirection:u}=n;return mA(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 mA(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(ac(c,s,{...l,delay:a+(typeof r=="function"?0:r)+k0(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function uA(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>ac(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=ac(t,s,a);else{const n=typeof s=="function"?xn(t,s,a.custom):s;r=Promise.all(T0(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function D0(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 xA=ud.length;function R0(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?R0(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<xA;a++){const r=ud[a],n=t.props[r];(si(n)||n===!1)&&(s[r]=n)}return s}const hA=[...md].reverse(),pA=md.length;function gA(t){return s=>Promise.all(s.map(({animation:a,options:r})=>uA(t,a,r)))}function fA(t){let s=gA(t),a=bx(),r=!0;const n=c=>(d,m)=>{var u;const p=xn(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=R0(t.parent)||{},p=[],u=new Set;let h={},g=1/0;for(let b=0;b<pA;b++){const j=hA[b],y=a[j],v=d[j]!==void 0?d[j]:m[j],w=si(v),A=j===c?y.isActive:null;A===!1&&(g=b);let C=v===m[j]&&v!==d[j]&&w;if(C&&r&&t.manuallyAnimateOnMount&&(C=!1),y.protectedKeys={...h},!y.isActive&&A===null||!v&&!y.prevProp||Dl(v)||typeof v=="boolean")continue;const E=bA(y.prevProp,v);let D=E||j===c&&y.isActive&&!C&&w||b>g&&w,T=!1;const N=Array.isArray(v)?v:[v];let _=N.reduce(n(j),{});A===!1&&(_={});const{prevResolvedValues:I={}}=y,B={...I,..._},k=F=>{D=!0,u.has(F)&&(T=!0,u.delete(F)),y.needsAnimating[F]=!0;const S=t.getValue(F);S&&(S.liveStyle=!1)};for(const F in B){const S=_[F],G=I[F];if(h.hasOwnProperty(F))continue;let U=!1;tc(S)&&tc(G)?U=!D0(S,G):U=S!==G,U?S!=null?k(F):u.add(F):S!==void 0&&u.has(F)?k(F):y.protectedKeys[F]=!0}y.prevProp=v,y.prevResolvedValues=_,y.isActive&&(h={...h,..._}),r&&t.blockInitialAnimation&&(D=!1);const M=C&&E;D&&(!M||T)&&p.push(...N.map(F=>{const S={type:j};if(typeof F=="string"&&r&&!M&&t.manuallyAnimateOnMount&&t.parent){const{parent:G}=t,U=xn(G,F);if(G.enteringChildren&&U){const{delayChildren:$}=U.transition||{};S.delay=k0(G.enteringChildren,t,$)}}return{animation:F,options:S}}))}if(u.size){const b={};if(typeof d.initial!="boolean"){const j=xn(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),v=t.getValue(j);v&&(v.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=bx()}}}function bA(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!D0(s,t):!1}function Ar(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function bx(){return{animate:Ar(!0),whileInView:Ar(),whileHover:Ar(),whileTap:Ar(),whileDrag:Ar(),whileFocus:Ar(),exit:Ar()}}class gr{constructor(s){this.isMounted=!1,this.node=s}update(){}}class jA extends gr{constructor(s){super(s),s.animationState||(s.animationState=fA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Dl(s)&&(this.unmountControls=s.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:s}=this.node.getProps(),{animate:a}=this.node.prevProps||{};s!==a&&this.updateAnimationControlsSubscription()}unmount(){var s;this.node.animationState.reset(),(s=this.unmountControls)==null||s.call(this)}}let yA=0;class vA extends gr{constructor(){super(...arguments),this.id=yA++}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 NA={animation:{Feature:jA},exit:{Feature:vA}};function ri(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function gi(t){return{point:{x:t.pageX,y:t.pageY}}}const wA=t=>s=>cd(s)&&t(s,gi(s));function Wn(t,s,a,r){return ri(t,s,wA(a),r)}const F0=1e-4,CA=1-F0,SA=1+F0,I0=.01,AA=0-I0,TA=0+I0;function Ws(t){return t.max-t.min}function kA(t,s,a){return Math.abs(t-s)<=a}function jx(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>=CA&&t.scale<=SA||isNaN(t.scale))&&(t.scale=1),(t.translate>=AA&&t.translate<=TA||isNaN(t.translate))&&(t.translate=0)}function Yn(t,s,a,r){jx(t.x,s.x,a.x,r?r.originX:void 0),jx(t.y,s.y,a.y,r?r.originY:void 0)}function yx(t,s,a){t.min=a.min+s.min,t.max=t.min+Ws(s)}function DA(t,s,a){yx(t.x,s.x,a.x),yx(t.y,s.y,a.y)}function vx(t,s,a){t.min=s.min-a.min,t.max=t.min+Ws(s)}function Qn(t,s,a){vx(t.x,s.x,a.x),vx(t.y,s.y,a.y)}function ga(t){return[t("x"),t("y")]}const P0=({current:t})=>t?t.ownerDocument.defaultView:null,Nx=(t,s)=>Math.abs(t-s);function RA(t,s){const a=Nx(t.x,s.x),r=Nx(t.y,s.y);return Math.sqrt(a**2+r**2)}class E0{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=io(this.lastMoveEventInfo,this.history),h=this.startEvent!==null,g=RA(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=no(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=io(u.type==="pointercancel"?this.lastMoveEventInfo:no(h,this.transformPagePoint),this.history);this.startEvent&&g&&g(u,j),f&&f(u,j)},!cd(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=gi(s),c=no(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=Is;this.history=[{...d,timestamp:m}];const{onSessionStart:p}=a;p&&p(s,io(c,this.history)),this.removeListeners=xi(Wn(this.contextWindow,"pointermove",this.handlePointerMove),Wn(this.contextWindow,"pointerup",this.handlePointerUp),Wn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),ur(this.updatePoint)}}function no(t,s){return s?{point:s(t.point)}:t}function wx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function io({point:t},s){return{point:t,delta:wx(t,_0(s)),offset:wx(t,FA(s)),velocity:IA(s,.1)}}function FA(t){return t[0]}function _0(t){return t[t.length-1]}function IA(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=_0(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 PA(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 Cx(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 EA(t,{top:s,left:a,bottom:r,right:n}){return{x:Cx(t.x,a,n),y:Cx(t.y,s,r)}}function Sx(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 _A(t,s){return{x:Sx(t.x,s.x),y:Sx(t.y,s.y)}}function MA(t,s){let a=.5;const r=Ws(t),n=Ws(s);return n>r?a=qn(s.min,s.max-r,t.min):r>n&&(a=qn(t.min,t.max-n,s.min)),Xa(0,1,a)}function LA(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 rc=.35;function OA(t=rc){return t===!1?t=0:t===!0&&(t=rc),{x:Ax(t,"left","right"),y:Ax(t,"top","bottom")}}function Ax(t,s,a){return{min:Tx(t,s),max:Tx(t,a)}}function Tx(t,s){return typeof t=="number"?t:t[s]||0}const $A=new WeakMap;class UA{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(gi(p).point)},l=(p,u)=>{const{drag:h,dragPropagation:g,onDragStart:f}=this.getProps();if(h&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=W2(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:v}=this.visualElement;if(v&&v.layout){const w=v.layout.layoutBox[j];w&&(y=Ws(w)*(parseFloat(y)/100))}}this.originPoint[j]=y}),f&&es.postRender(()=>f(p,u)),sc(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=BA(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 E0(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:P0(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||!Ai(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=PA(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&&an(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=EA(r.layoutBox,s):this.constraints=!1,this.elastic=OA(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&ga(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=LA(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!an(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=VS(r,n.root,this.visualElement.getTransformPagePoint());let l=_A(n.layout.layoutBox,i);if(a){const o=a($S(l));this.hasMutatedConstraints=!!o,o&&(l=b0(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(!Ai(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 sc(this.visualElement,s),r.start(jd(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(!Ai(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(!an(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]=MA({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(!Ai(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;$A.set(this.visualElement,this);const s=this.visualElement.current,a=Wn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();an(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=ri(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=rc,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Ai(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function BA(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class VA extends gr{constructor(s){super(s),this.removeGroupControls=ja,this.removeListeners=ja,this.controls=new UA(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 kx=t=>(s,a)=>{t&&es.postRender(()=>t(s,a))};class zA extends gr{constructor(){super(...arguments),this.removePointerDownListener=ja}onPointerDown(s){this.session=new E0(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:P0(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:kx(s),onStart:kx(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&es.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=Wn(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 Vi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Dx(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const Pn={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(ot.test(t))t=parseFloat(t);else return t;const a=Dx(t,s.target.x),r=Dx(t,s.target.y);return`${a}% ${r}%`}},HA={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=xr.parse(t);if(n.length>5)return r;const i=xr.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 lo=!1;class GA extends x.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;xS(WA),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),lo&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Vi.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,lo=!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(),od.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;lo=!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 M0(t){const[s,a]=r0(),r=x.useContext(Uc);return e.jsx(GA,{...t,layoutGroup:r,switchLayoutGroup:x.useContext(g0),isPresent:s,safeToRemove:a})}const WA={borderRadius:{...Pn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Pn,borderTopRightRadius:Pn,borderBottomLeftRadius:Pn,borderBottomRightRadius:Pn,boxShadow:HA};function YA(t,s,a){const r=Bs(t)?t:pn(t);return r.start(jd("",r,s,a)),r.animation}const QA=(t,s)=>t.depth-s.depth;class KA{constructor(){this.children=[],this.isDirty=!1}add(s){zc(this.children,s),this.isDirty=!0}remove(s){Hc(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(QA),this.isDirty=!1,this.children.forEach(s)}}function XA(t,s){const a=sa.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(ur(r),t(i-s))};return es.setup(r,!0),()=>ur(r)}const L0=["TopLeft","TopRight","BottomLeft","BottomRight"],ZA=L0.length,Rx=t=>typeof t=="string"?parseFloat(t):t,Fx=t=>typeof t=="number"||ot.test(t);function JA(t,s,a,r,n,i){n?(t.opacity=ns(0,a.opacity??1,qA(r)),t.opacityExit=ns(s.opacity??1,0,eT(r))):i&&(t.opacity=ns(s.opacity??1,a.opacity??1,r));for(let l=0;l<ZA;l++){const o=`border${L0[l]}Radius`;let c=Ix(s,o),d=Ix(a,o);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||Fx(c)===Fx(d)?(t[o]=Math.max(ns(Rx(c),Rx(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 Ix(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const qA=O0(0,.5,Cg),eT=O0(.5,.95,ja);function O0(t,s,a){return r=>r<t?0:r>s?1:a(qn(t,s,r))}function Px(t,s){t.min=s.min,t.max=s.max}function pa(t,s){Px(t.x,s.x),Px(t.y,s.y)}function Ex(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function _x(t,s,a,r,n){return t-=s,t=al(t,1/a,r),n!==void 0&&(t=al(t,1/n,r)),t}function tT(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=_x(t.min,s,a,o,n),t.max=_x(t.max,s,a,o,n)}function Mx(t,s,[a,r,n],i,l){tT(t,s[a],s[r],s[n],s.scale,i,l)}const sT=["x","scaleX","originX"],aT=["y","scaleY","originY"];function Lx(t,s,a,r){Mx(t.x,s,sT,a?a.x:void 0,r?r.x:void 0),Mx(t.y,s,aT,a?a.y:void 0,r?r.y:void 0)}function Ox(t){return t.translate===0&&t.scale===1}function $0(t){return Ox(t.x)&&Ox(t.y)}function $x(t,s){return t.min===s.min&&t.max===s.max}function rT(t,s){return $x(t.x,s.x)&&$x(t.y,s.y)}function Ux(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function U0(t,s){return Ux(t.x,s.x)&&Ux(t.y,s.y)}function Bx(t){return Ws(t.x)/Ws(t.y)}function Vx(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class nT{constructor(){this.members=[]}add(s){zc(this.members,s),s.scheduleRender()}remove(s){if(Hc(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 iT(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 oo=["","X","Y","Z"],lT=1e3;let oT=0;function co(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function B0(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=A0(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&&B0(r)}function V0({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=oT++,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(mT),this.nodes.forEach(pT),this.nodes.forEach(gT),this.nodes.forEach(uT)},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 KA)}addEventListener(l,o){return this.eventHandlers.has(l)||this.eventHandlers.set(l,new Yc),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=a0(l)&&!J2(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=XA(u,250),Vi.hasAnimatedSinceResize&&(Vi.hasAnimatedSinceResize=!1,this.nodes.forEach(Gx)))})}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()||vT,{onLayoutAnimationStart:f,onLayoutAnimationComplete:b}=d.getProps(),j=!this.targetLayout||!U0(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 v={...id(g,"layout"),onPlay:f,onComplete:b};(d.shouldReduceMotion||this.options.layoutRoot)&&(v.delay=0,v.type=!1),this.startAnimation(v),this.setAnimationOrigin(m,y)}else p||Gx(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(),ur(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(fT),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&&B0(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(zx);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Hx);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(hT),this.nodes.forEach(cT),this.nodes.forEach(dT)):this.nodes.forEach(Hx),this.clearAllSnapshots();const o=sa.now();Is.delta=Xa(0,1e3/60,o-Is.timestamp),Is.timestamp=o,Is.isProcessing=!0,Zl.update.process(Is),Zl.preRender.process(Is),Zl.render.process(Is),Is.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,od.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(xT),this.sharedNodes.forEach(bT)}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&&!$0(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,m=d!==this.prevTransformTemplateValue;l&&this.instance&&(o||Rr(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)),NT(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(wT))){const{scroll:m}=this.root;m&&(rn(o.x,m.offset.x),rn(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),rn(o.x,p.offset.x),rn(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&&nn(c,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),Rr(m.latestValues)&&nn(c,m.latestValues)}return Rr(this.latestValues)&&nn(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||!Rr(d.latestValues))continue;Jo(d.latestValues)&&d.updateSnapshot();const m=hs(),p=d.measurePageBox();pa(m,p),Lx(o,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return Rr(this.latestValues)&&Lx(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(),Qn(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(),DA(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):pa(this.target,this.layout.layoutBox),y0(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(),Qn(this.relativeTargetOrigin,this.target,h.target),pa(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Jo(this.parent.latestValues)||j0(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;BS(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():(Ex(this.prevProjectionDelta.x,this.projectionDelta.x),Ex(this.prevProjectionDelta.y,this.projectionDelta.y)),Yn(this.projectionDelta,this.layoutCorrected,h,this.latestValues),(this.treeScale.x!==p||this.treeScale.y!==u||!Vx(this.projectionDelta.x,this.prevProjectionDelta.x)||!Vx(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=ln(),this.projectionDelta=ln(),this.projectionDeltaWithTransform=ln()}setAnimationOrigin(l,o=!1){const c=this.snapshot,d=c?c.latestValues:{},m={...this.latestValues},p=ln();(!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(yT));this.animationProgress=0;let v;this.mixTargetDelta=w=>{const A=w/1e3;Wx(p.x,l.x,A),Wx(p.y,l.y,A),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Qn(u,this.layout.layoutBox,this.relativeParent.layout.layoutBox),jT(this.relativeTarget,this.relativeTargetOrigin,u,A),v&&rT(this.relativeTarget,v)&&(this.isProjectionDirty=!1),v||(v=hs()),pa(v,this.relativeTarget)),f&&(this.animationValues=m,JA(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&&(ur(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=es.update(()=>{Vi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=pn(0)),this.currentAnimation=YA(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(lT),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&&z0(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),nn(o,m),Yn(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new nT),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&&co("z",l,d,this.animationValues);for(let m=0;m<oo.length;m++)co(`rotate${oo[m]}`,l,d,this.animationValues),co(`skew${oo[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=Bi(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=Bi(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!Rr(this.latestValues)&&(l.transform=c?c({},""):"none",this.hasProjected=!1);return}l.visibility="";const m=d.animationValues||d.latestValues;this.applyTransformsToTarget();let p=iT(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 ai){if(m[g]===void 0)continue;const{correct:f,applyTo:b,isCSSVariable:j}=ai[g],y=p==="none"?m[g]:f(m[g],d);if(b){const v=b.length;for(let w=0;w<v;w++)l[b[w]]=y}else j?this.options.visualElement.renderState.vars[g]=y:l[g]=y}this.options.layoutId&&(l.pointerEvents=d===this?Bi(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(zx),this.root.sharedNodes.clear()}}}function cT(t){t.updateLayout()}function dT(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}):z0(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=ln();Yn(o,r,s.layoutBox);const c=ln();l?Yn(c,t.applyTransform(n,!0),s.measuredBox):Yn(c,r,s.layoutBox);const d=!$0(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();Qn(g,s.layoutBox,u.layoutBox);const f=hs();Qn(f,r,h.layoutBox),U0(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 mT(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 uT(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function xT(t){t.clearSnapshot()}function zx(t){t.clearMeasurements()}function Hx(t){t.isLayoutDirty=!1}function hT(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function Gx(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function pT(t){t.resolveTargetDelta()}function gT(t){t.calcProjection()}function fT(t){t.resetSkewAndRotation()}function bT(t){t.removeLeadSnapshot()}function Wx(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 Yx(t,s,a,r){t.min=ns(s.min,a.min,r),t.max=ns(s.max,a.max,r)}function jT(t,s,a,r){Yx(t.x,s.x,a.x,r),Yx(t.y,s.y,a.y,r)}function yT(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const vT={duration:.45,ease:[.4,0,.1,1]},Qx=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Kx=Qx("applewebkit/")&&!Qx("chrome/")?Math.round:ja;function Xx(t){t.min=Kx(t.min),t.max=Kx(t.max)}function NT(t){Xx(t.x),Xx(t.y)}function z0(t,s,a){return t==="position"||t==="preserve-aspect"&&!kA(Bx(s),Bx(a),.2)}function wT(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const CT=V0({attachResizeListener:(t,s)=>ri(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),mo={current:void 0},H0=V0({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!mo.current){const t=new CT({});t.mount(window),t.setOptions({layoutScroll:!0}),mo.current=t}return mo.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),ST={pan:{Feature:zA},drag:{Feature:VA,ProjectionNode:H0,MeasureLayout:M0}};function Zx(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,gi(s)))}class AT extends gr{mount(){const{current:s}=this.node;s&&(this.unmount=Y2(s,(a,r)=>(Zx(this.node,r,"Start"),n=>Zx(this.node,n,"End"))))}unmount(){}}class TT extends gr{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=xi(ri(this.node.current,"focus",()=>this.onFocus()),ri(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Jx(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,gi(s)))}class kT extends gr{mount(){const{current:s}=this.node;s&&(this.unmount=Z2(s,(a,r)=>(Jx(this.node,r,"Start"),(n,{success:i})=>Jx(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const nc=new WeakMap,uo=new WeakMap,DT=t=>{const s=nc.get(t.target);s&&s(t)},RT=t=>{t.forEach(DT)};function FT({root:t,...s}){const a=t||document;uo.has(a)||uo.set(a,{});const r=uo.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(RT,{root:t,...s})),r[n]}function IT(t,s,a){const r=FT(s);return nc.set(t,a),r.observe(t),()=>{nc.delete(t),r.unobserve(t)}}const PT={some:0,all:1};class ET extends gr{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:PT[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 IT(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(_T(s,a))&&this.startObserver()}unmount(){}}function _T({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const MT={inView:{Feature:ET},tap:{Feature:kT},focus:{Feature:TT},hover:{Feature:AT}},LT={layout:{ProjectionNode:H0,MeasureLayout:M0}},OT={...NA,...MT,...ST,...LT},Wt=OS(OT,ZS),En=[{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:qh,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 $T({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=nt.getUserData();l((u==null?void 0:u.jobTitle)==="Dealer")},[]);const o=u=>{if(i)return;const h=En.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(ul,{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:En.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(P,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(P,{onClick:c,disabled:!r||i||((d=En.find(u=>u.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=En.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(Tl,{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=En.find(u=>u.id===r))==null?void 0:p.name})]})})})]})})]})})}function Wr({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"),v=s.toLowerCase().includes("pdf"),w=y||v;x.useEffect(()=>{if(!l||!w||!a){h(null);return}return(async()=>{f(!0),j(null);try{let I=a;a.startsWith("/")&&!a.startsWith("//")&&(I=`${window.location.origin}${a}`);const k=await fetch(I,{headers:{Accept:v?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!k.ok){const F=await k.text().catch(()=>"");throw new Error(`Failed to load file: ${k.status} ${k.statusText}. ${F}`)}const M=await k.blob();if(M.size===0)throw new Error("File is empty or could not be loaded");v&&!M.type.includes("pdf")&&M.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${M.type}`);const L=window.URL.createObjectURL(M);h(L)}catch(N){console.error("Failed to load file for preview:",N),j(N instanceof Error?N.message:"Failed to load file for preview")}finally{f(!1)}})(),()=>{u&&(window.URL.revokeObjectURL(u),h(null))}},[l,a,w,v]);const A=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},C=()=>d(T=>Math.min(T+25,200)),E=()=>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(P,{variant:"ghost",size:"sm",onClick:E,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(Aj,{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(P,{variant:"ghost",size:"sm",onClick:C,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(Tj,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(ep,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(P,{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(P,{onClick:A,className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",t]})]}):w&&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"})}),v&&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(P,{onClick:A,className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function fi({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(P,{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},Fl=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})},UT=async t=>{await ve.post(`/admin/configurations/${t}/reset`)},BT=async()=>{const t=await ve.get("/admin/form16-config");return t.data.data??t.data},VT=async t=>{await ve.put("/admin/form16-config",t)},zT=async t=>{const s=t?{year:t}:{};return(await ve.get("/admin/holidays",{params:s})).data.data},HT=async t=>(await ve.post("/admin/holidays",t)).data.data,GT=async(t,s)=>(await ve.put(`/admin/holidays/${t}`,s)).data.data,WT=async t=>{await ve.delete(`/admin/holidays/${t}`)},YT=async()=>(await ve.get("/config/activity-types")).data.data,QT=async t=>{const s={activeOnly:t.toString()};return(await ve.get("/admin/activity-types",{params:s})).data.data},KT=async t=>(await ve.post("/admin/activity-types",t)).data.data,XT=async(t,s)=>(await ve.put(`/admin/activity-types/${t}`,s)).data.data,ZT=async t=>{await ve.delete(`/admin/activity-types/${t}`)},JT={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 qT(t,s,a){const[r,n]=x.useState(JT),[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"),v={};y.forEach(_=>{v[_.configKey]=_.configValue});const w=parseInt(v.MAX_FILE_SIZE_MB||"10"),C=(v.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(_=>_.trim().toLowerCase());u({maxFileSizeMB:w,allowedFileTypes:C});const E=await ua("SYSTEM_SETTINGS"),D=await ua("WORKFLOW_SHARING"),T=[...E,...D],N={};T.forEach(_=>{N[_.configKey]=_.configValue}),m({maxApprovalLevels:parseInt(N.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(N.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((j=N.ALLOW_ADD_SPECTATOR)==null?void 0:j.toLowerCase())==="true",maxSpectators:parseInt(N.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||{},v=Array.isArray(j.approvals)?j.approvals:[],w=Array.isArray(j.participants)?j.participants:[],A=Array.isArray(j.documents)?j.documents.filter(I=>!I.isDeleted):[];g(A);const C=(y.priority||"").toString().toLowerCase(),E={standard:"standard",express:"express"},D=y.templateType==="TEMPLATE"?"existing-template":"custom",T=a.find(I=>I.id===D)||a[0]||null;l(T);const N=v.sort((I,B)=>(I.levelNumber||0)-(B.levelNumber||0)).map(I=>{const B=Number(I.tatHours||24),k=Math.floor(B/24),M=B%24;return{id:I.approverId||`temp-${I.levelNumber}`,name:I.approverName||I.approverEmail||"",email:I.approverEmail||"",role:I.levelName||`Level ${I.levelNumber}`,department:"",avatar:(I.approverName||I.approverEmail||"XX").substring(0,2).toUpperCase(),level:I.levelNumber||1,canClose:!1,tat:k>0?k:M,tatType:k>0?"days":"hours",userId:I.approverId}}),_=w.filter(I=>(I.participantType||I.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(I.userEmail||I.user_email||I.email):!1).map((I,B)=>{const k=I.userId||I.user_id||I.id,M=I.userName||I.user_name||I.name||"",L=I.userEmail||I.user_email||I.email||"",S=(M||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:M||L||"Spectator",email:L,role:"Spectator",department:I.department||"",avatar:S,level:1,canClose:!1}});n(I=>({...I,template:D,title:y.title||"",description:y.description||"",priority:E[C]||"standard",approvers:N,approverCount:N.length||1,spectators:_,maxLevel:Math.max(...N.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 qx=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function e5(t,s,a){const[r,n]=x.useState(t?2:1),i=qx.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:qx,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 t5(){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 s5(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function a5(t,s,a){var n;const r=s5(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 r5(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return a5(a,n,n===s)})}function eh(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 th(t,s,a,r=!1){const n=r5(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 n5(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 sh(t,s){return{id:(await Oc(t,s||[],"SUPPORTING")).id}}async function ah(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await V1(t,s,a||[],r):await B1(t,s)}function i5({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=n5(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const j=th(t,n,r,!1);await ah(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=eh(t,s,n,!1),y=await sh(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=th(t,n,r,!0);await ah(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=eh(t,s,n,!0),j=await sh(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 l5(t,s){return await ve.post("/admin/users/assign-role",{email:t,role:s})}async function o5(t,s){return await ve.put(`/admin/users/${t}/role`,{role:s})}async function c5(t,s=1,a=10){return await ve.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function d5(){return await ve.get("/admin/users/role-statistics")}async function m5(t){var a;const s=await ve.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function u5(){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:m5,ensureUserExists:ya,assignRole:l5,updateUserRole:o5,getUsersByRole:c5,getRoleStatistics:d5,getAllUsers:u5};async function x5(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 h5(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 x5(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 p5({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 _=r.approverCount||1;if(_>m.maxApprovalLevels){p([{type:"Maximum Approval Levels Exceeded",message:`The request has ${_} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:_,maxValue:m.maxApprovalLevels}]);return}}const T=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",N=await h5(r.approvers,T);if(!N.success&&N.error){d(N.error.type,N.error.email,N.error.message);return}N.validatedApprovers&&a("approvers",N.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(D,T)=>{if(T){const N=D.documentId||D.document_id||"";j({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:Nn(N),fileSize:Number(D.fileSize||D.file_size||0),documentId:N})}else{const N=URL.createObjectURL(D);j({fileName:D.name,fileType:D.type||"application/octet-stream",fileUrl:N,fileSize:D.size,file:D})}},closePreview:()=>{b!=null&&b.fileUrl&&(b!=null&&b.file)&&URL.revokeObjectURL(b.fileUrl),j(null)}}}const rh=[{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:xl,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 $r=null;const nh=()=>$r,g5=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 $r&&$r.push(r),r},Il=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 $r=a,a},f5=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 $r&&($r=$r.map(i=>i.id===t?n:i)),n};function G0({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 b5({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(P,{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(P,{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(P,{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(tp,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(P,{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 ih=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 j5({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(P,{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(kj,{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}),ih(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(Tl,{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(zr,{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:[ih(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 y5({className:t,...s}){return e.jsx(_b,{"data-slot":"radio-group",className:Le("grid gap-3",t),...s})}function lh({className:t,...s}){return e.jsx(Mb,{"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(Lb,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(gc,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function v5({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(ui,{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(y5,{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(lh,{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(ml,{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(lh,{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 W0(){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 Y0(){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 N5({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var p;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=Y0();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,v,w,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||(v=g[u])==null?void 0:v.name,department:b||(w=g[u])==null?void 0:w.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((w,A)=>{var C,E;return A!==u&&(w.userId===h.userId||((C=w.email)==null?void 0:C.toLowerCase())===((E=h.email)==null?void 0:E.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(w=>{var A,C;return w.userId===h.userId||((A=w.email)==null?void 0:A.toLowerCase())===((C=h.email)==null?void 0:C.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}),v=[...t.approvers];v[u]={...v[u],email:h.email,name:h.displayName||[h.firstName,h.lastName].filter(Boolean).join(" "),userId:y.userId,level:u+1},s("approvers",v),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(cr,{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(P,{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(fc,{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(P,{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@undefined",value:b.email||"",onChange:v=>d(h,v.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(v=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(h,v),"data-testid":`approval-workflow-approver-${g}-search-result-${v.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:v.displayName||v.email}),e.jsx("div",{className:"text-xs text-gray-600",children:v.email})]},v.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:v=>{const w=[...t.approvers];w[h]={...w[h],tat:parseInt(v.target.value)||"",level:g,tatType:b.tatType||"hours"},s("approvers",w)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(He,{value:b.tatType||"hours",onValueChange:v=>{const w=[...t.approvers];w[h]={...w[h],tatType:v,level:g,tat:""},s("approvers",w)},"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(zr,{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 w5({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=x.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=W0(),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(v=>{var w,A;return v.userId===g.userId||((w=v.email)==null?void 0:w.toLowerCase())===((A=g.email)==null?void 0:A.toLowerCase())}),y=(f=t.approvers)==null?void 0:f.some(v=>{var w,A;return v.userId===g.userId||((w=v.email)==null?void 0:w.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 v=await m(g),w={id:v.userId,userId:v.userId,name:v.displayName||g.email.split("@")[0],email:v.email,avatar:(v.displayName||v.email).substring(0,2).toUpperCase(),role:"Spectator",department:v.department||"",level:1,canClose:!1},A=[...t.spectators,w];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(v=>{var w;return((w=v.email)==null?void 0:w.toLowerCase())===n.toLowerCase()}),y=(b=t.approvers)==null?void 0:b.some(v=>{var w;return((w=v.email)==null?void 0:w.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(P,{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(zr,{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(P,{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 C5({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=[],v=[];b.forEach(w=>{if(w.size>j){y.push({fileName:w.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(w.size/1048576).toFixed(2)}MB`});return}const A=w.name.toLowerCase(),C=A.substring(A.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(C)){y.push({fileName:w.name,reason:`File type "${C}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}v.push(w)}),v.length>0&&i([...a,...v]),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(P,{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(P,{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(P,{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(P,{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(P,{variant:"ghost",size:"sm",onClick:()=>u(b),"data-testid":`documents-new-${b}-remove`,children:e.jsx(yt,{className:"h-4 w-4"})})]})]},b))})})]})]})]})}const S5=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({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(tp,{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:[S5(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 T5({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(P,{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 k5({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(Tl,{mode:"wait",children:t})})})}function D5({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(xl,{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(P,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function R5({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(P,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function oh({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 Il()).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(()=>[...rh,...d],[d]),{formData:u,updateFormData:h,selectedTemplate:g,setSelectedTemplate:f,loadingDraft:b,systemPolicy:j,documentPolicy:y,existingDocuments:v,setExistingDocuments:w}=qT(o,l,p),{currentStep:A,totalSteps:C,stepNames:E,isStepValid:D,nextStep:T,prevStep:N}=e5(o,g,u),[_,I]=x.useState([]),[B,k]=x.useState([]),M=x.useRef(null),{validationModal:L,policyViolationModal:F,documentErrorModal:S,openValidationModal:G,closeValidationModal:U,openPolicyViolationModal:$,closePolicyViolationModal:R,openDocumentErrorModal:H,closeDocumentErrorModal:K}=t5(),{submitting:z,savingDraft:O,handleSubmit:V,handleSaveDraft:Q}=i5({formData:u,selectedTemplate:g,documents:_,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}=p5({selectedTemplate:g,setSelectedTemplate:f,updateFormData:h,formData:u,currentStep:A,isStepValid:D,wizardNextStep:T,wizardPrevStep:N,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&&(I(u.documents),ae.current=!0),ye.current=!1},[u.documents]);const he=x.useRef(!1),ne=x.useRef(_);x.useEffect(()=>{if(he.current){he.current=!1,ne.current=_;return}ne.current!==_&&(h("documents",_),ne.current=_)},[_]);const ge=()=>{switch(A){case 1:return e.jsx(j5,{templates:rh,selectedTemplate:g,onSelectTemplate:ue,adminTemplates:d});case 2:return e.jsx(v5,{formData:u,selectedTemplate:g,updateFormData:h});case 3:return e.jsx(N5,{formData:u,updateFormData:h,systemPolicy:j,onValidationError:ke=>G(ke.type,ke.email,ke.message),onPolicyViolation:$});case 4:return e.jsx(w5,{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(C5,{documentPolicy:y,isEditing:o,documents:_,existingDocuments:v,documentsToDelete:B,onDocumentsChange:I,onExistingDocumentsChange:w,onDocumentsToDeleteChange:k,onPreviewDocument:Pe,onDocumentErrors:ke=>H(ke),fileInputRef:M});case 6:return e.jsx(A5,{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(T5,{isEditing:o,currentStep:A,totalSteps:C,stepNames:E,onBack:le}),e.jsx(G0,{currentStep:A,totalSteps:C,stepNames:E}),e.jsx(k5,{children:ge()}),e.jsx(b5,{currentStep:A,totalSteps:C,isStepValid:D(),onPrev:Ue,onNext:Ze,onSubmit:V,onSaveDraft:Q,submitting:z,savingDraft:O,loadingDraft:b,isEditing:o}),e.jsx($T,{open:q,onClose:()=>ee(!1),onSelectTemplate:_e}),te&&e.jsx(Wr,{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(D5,{modal:L,onClose:U}),e.jsx(R5,{modal:S,documentPolicy:y,onClose:K}),e.jsx(fi,{open:F.open,onClose:R,violations:F.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}function bi({className:t,...s}){return e.jsx(Ob,{"data-slot":"tabs",className:Le("flex flex-col gap-2",t),...s})}function ji({className:t,...s}){return e.jsx($b,{"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(Ub,{"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(Bb,{"data-slot":"tabs-content",className:Le("flex-1 outline-none",t),...s})}function ni(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 yd(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=(C,E)=>(C||E||"NA").toString().split(" ").map(T=>T[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),b=C=>{const E=(C||"").toUpperCase();return E==="IN_PROGRESS"?"in-review":E==="PENDING"?"pending":E==="APPROVED"?"approved":E==="REJECTED"?"rejected":E==="CLOSED"?"closed":E==="SKIPPED"?"skipped":(C||"").toLowerCase()},j=C=>{const E=String(C||"").trim();if(!E)return"Document";const D=E.lastIndexOf("."),T=D>0&&D<E.length-1,N=T?E.slice(0,D):E,_=T?E.slice(D):"";return`${N.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"}${_}`},y=x.useCallback(async()=>{var C,E,D,T,N,_,I,B,k,M,L,F,S,G,U;l(!0);try{const $=await Ks.getWorkflowDetails(t);if(!$){console.warn("[useRequestDetails] No details returned from API");return}const R=$.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)||R.currentLevel||1,q=H.map(je=>{const ie=je.levelNumber||0,Se=(je.status||"").toString().toUpperCase(),qe=je.levelId||je.level_id;let at=b(je.status);ie>Q&&Se!=="APPROVED"&&Se!=="REJECTED"?at="waiting":ie===Q&&Se==="PENDING"&&(at="pending");const gt=V.filter(It=>It.levelId===qe);return{step:ie,levelId:qe,role:je.levelName||je.approverName||"Approver",status:at,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(at=>at.userId===je||at.user_id===je);return ie!=null&&ie.userName||ie!=null&&ie.user_name?ie.userName||ie.user_name:R.initiatorId===je?((Se=R.initiator)==null?void 0:Se.displayName)||((qe=R.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(R.isPaused||!1)try{Ze=await _u(R.requestId)}catch{}let Pe=null,De=null,le=null,ye=null,ae=[],he=null;if(ni(R)){try{const je=await ve.get(`/dealer-claims/${R.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/${R.requestId}`),ie=((C=je.data)==null?void 0:C.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,at=ie.creditNote||ie.credit_note||null,gt=ie.completionExpenses||ie.completion_expenses||null;Pe&&(Pe.budgetTracking=Se,Pe.invoice=qe,Pe.creditNote=at,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:(E=je==null?void 0:je.response)==null?void 0:E.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:R.requestId})}}const ne={...R,id:R.requestNumber||R.requestId,requestId:R.requestId,requestNumber:R.requestNumber,initiatorId:R.initiatorId||R.initiator_id,title:R.title,description:R.description,status:b(R.status),priority:(R.priority||"").toString().toLowerCase(),workflowType:R.workflowType||(R.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)||R.sla||null,initiator:{userId:((N=R.initiator)==null?void 0:N.userId)||((_=R.initiator)==null?void 0:_.user_id)||R.initiatorId||R.initiator_id,name:((I=R.initiator)==null?void 0:I.displayName)||((B=R.initiator)==null?void 0:B.email),role:((k=R.initiator)==null?void 0:k.designation)||void 0,department:((M=R.initiator)==null?void 0:M.department)||void 0,email:((L=R.initiator)==null?void 0:L.email)||void 0,phone:((F=R.initiator)==null?void 0:F.phone)||void 0,avatar:f((S=R.initiator)==null?void 0:S.displayName,(G=R.initiator)==null?void 0:G.email)},createdAt:R.createdAt,updatedAt:R.updatedAt,totalSteps:R.totalLevels||1,currentStepRaw:(O==null?void 0:O.currentLevel)||R.currentLevel||1,currentStep:Math.min(Math.max(1,(O==null?void 0:O.currentLevel)||R.currentLevel||1),R.totalLevels||1),auditTrail:_e,conclusionRemark:R.conclusionRemark||null,closureDate:R.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:R.templateType||R.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 C=!0;return c(!0),m(null),(async()=>{var E,D,T,N,_,I,B,k,M,L,F,S,G,U;try{const $=await Ks.getWorkflowDetails(t);if(!C||!$){C&&c(!1);return}const R=$.workflow||{},H=Array.isArray($.approvals)?$.approvals:[],K=Array.isArray($.participants)?$.participants:[],z=Array.isArray($.documents)?$.documents:[],O=$.summary||{},V=Array.isArray($.tatAlerts)?$.tatAlerts:[],Q=(R.priority||"").toString().toLowerCase(),q=(O==null?void 0:O.currentLevel)||R.currentLevel||1,ee=H.map(ie=>{const Se=ie.levelNumber||0,qe=(ie.status||"").toString().toUpperCase(),at=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===at);return{step:Se,levelId:at,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,at;if(!ie)return;const Se=K.find(gt=>gt.userId===ie);return Se!=null&&Se.userName?Se.userName:R.initiatorId===ie?((qe=R.initiator)==null?void 0:qe.displayName)||((at=R.initiator)==null?void 0:at.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(R.isPaused||!1)try{Ue=await _u(R.requestId)}catch{}let De=null,le=null,ye=null,ae=null,he=[],ne=null;if(ni(R)){try{const ie=await ve.get(`/dealer-claims/${R.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/${R.requestId}`),Se=((E=ie.data)==null?void 0:E.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,at=Se.invoice||null,gt=Se.creditNote||Se.credit_note||null,It=Se.completionExpenses||Se.completion_expenses||null;De&&(De.budgetTracking=qe,De.invoice=at,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:R.requestId})}}const ge={id:R.requestNumber||R.requestId,requestId:R.requestId,title:R.title,description:R.description,priority:Q,status:b(R.status),workflowType:R.workflowType||(R.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:O,initiator:{name:((T=R.initiator)==null?void 0:T.displayName)||((N=R.initiator)==null?void 0:N.email),role:((_=R.initiator)==null?void 0:_.designation)||void 0,department:((I=R.initiator)==null?void 0:I.department)||void 0,email:((B=R.initiator)==null?void 0:B.email)||void 0,phone:((k=R.initiator)==null?void 0:k.phone)||void 0,avatar:f((M=R.initiator)==null?void 0:M.displayName,(L=R.initiator)==null?void 0:L.email)},createdAt:R.createdAt,updatedAt:R.updatedAt,totalSteps:R.totalLevels||1,currentStepRaw:(O==null?void 0:O.currentLevel)||R.currentLevel||1,currentStep:Math.min(Math.max(1,(O==null?void 0:O.currentLevel)||R.currentLevel||1),R.totalLevels||1),approvalFlow:ee,approvals:H,documents:_e,spectators:te,auditTrail:Ze,conclusionRemark:R.conclusionRemark||null,closureDate:R.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:R.templateType||R.template_type,form16Submission:$.form16Submission||null};n(ge);const ke=(F=a==null?void 0:a.email)==null?void 0:F.toLowerCase(),Oe=H.find(ie=>{const Se=(ie.status||"").toString().toUpperCase(),qe=(ie.approverEmail||"").toLowerCase(),at=ie.levelNumber||0;return(Se==="PENDING"||Se==="IN_PROGRESS"||Se==="PAUSED")&&qe===ke&&at===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:",$),C){if(((S=$==null?void 0:$.response)==null?void 0:S.status)===403){const R=((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:R})}n(null)}}finally{C&&c(!1)}})(),()=>{C=!1}},[t,a]);const v=x.useMemo(()=>{if(r)return r;const C=s.find(E=>E.id===t||E.requestNumber===t||E.request_number===t);return C||null},[t,s,r]),w=x.useMemo(()=>{var D,T,N;if(!v||!a)return!1;const C=(D=a==null?void 0:a.email)==null?void 0:D.toLowerCase(),E=(N=(T=v.initiator)==null?void 0:T.email)==null?void 0:N.toLowerCase();return C===E},[v,a]),A=x.useMemo(()=>{var E;if(!v)return[];const C=[];return(E=v.initiator)!=null&&E.email&&C.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(D=>{D.approverEmail&&C.push({email:D.approverEmail.toLowerCase(),participantType:"APPROVER",name:D.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(D=>{D.email&&C.push({email:D.email.toLowerCase(),participantType:"SPECTATOR",name:D.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(D=>{const T=(D.userEmail||D.email||"").toLowerCase(),N=(D.participantType||D.participant_type||"").toUpperCase(),_=D.userName||D.user_name||D.name;T&&N&&!C.find(I=>I.email===T)&&C.push({email:T,participantType:N,name:_})}),C},[v]);return x.useEffect(()=>{if(!t||!r)return;const C=Br();if(!C)return;const E=D=>{((D==null?void 0:D.requestId)===r.requestId||(D==null?void 0:D.requestNumber)===t)&&y()};return C.on("request:updated",E),()=>{C.off("request:updated",E)}},[t,r,y]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:y,currentApprovalLevel:p,isSpectator:h,isInitiator:w,existingParticipants:A,accessDenied:d}}function Q0(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=Br();if(!u){console.error("[useRequestSocket] Socket not available");return}const h=r==null?void 0:r.userId,g=()=>{Lo(u,p,h)};return u.connected?g():u.on("connect",g),()=>{m&&(u.off("connect",g),vp(u,p))}})(),()=>{m=!1}},[t,r]),x.useEffect(()=>{!t||!s||(async()=>{try{const m=await un(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=Br();if(!m)return;const p=h=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await un(t),f=(s==null?void 0:s.auditTrail)||[],b=[...g,...f].sort((j,y)=>{const v=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime(),w=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime();return v-w});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 Vn(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 F5=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],I5={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 vd(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(!F5.includes(a))return!1;const r=I5[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 K0(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(v=>{f[v.configKey]=v.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(v=>v.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,v;const g=h.target.files;if(!g||g.length===0)return;const f=Array.from(g),b=[],j=[];if(f.forEach(w=>{const A=m(w);A.valid?j.push(w):b.push({fileName:w.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 w=j[0],A=t==null?void 0:t.requestId;if(!A){W.error("Request ID not found");return}w&&await Vn(w,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(w){console.error("[useDocumentUpload] Upload error:",w),vd(w)||W.error(((v=(y=w==null?void 0:w.response)==null?void 0:y.data)==null?void 0:v.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 P5="modulepreload",E5=function(t){return"/"+t},ch={},xo=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=E5(c),c in ch)return;ch[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":P5,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 X0(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),[v,w]=x.useState(!1),[A,C]=x.useState(0),E=async()=>{var I;const N=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),_=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(N||_){c(N||_),g(!!_);return}try{const{getConclusion:B}=await xo(async()=>{const{getConclusion:M}=await import("./conclusionApi-BFrrhPzD.js");return{getConclusion:M}},__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){((I=B==null?void 0:B.response)==null?void 0:I.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",B)}},D=async()=>{if(!v)try{m(!0),y(!1);const{generateConclusion:N}=await xo(async()=>{const{generateConclusion:k}=await import("./conclusionApi-BFrrhPzD.js");return{generateConclusion:k}},__vite__mapDeps([0,1,2,3,4,5,6,7])),_=await N(t.requestId||s),I=f+1;if(b(I),!(_!=null&&_.aiGeneratedRemark)||_.aiGeneratedRemark.toLowerCase().includes("unable to generate")||_.aiGeneratedRemark.toLowerCase().includes("sorry")){const k=A+1;C(k),k>=2?(w(!0),i==null||i({success:!1,title:"AI Generation Limit Reached",message:"We're unable to process a conclusion remark at this time after 2 attempts. Please proceed with a manual approach using the editor below."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process a conclusion remark at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0),c((_==null?void 0:_.aiGeneratedRemark)||""),g(!1);return}c(_.aiGeneratedRemark),g(!0),C(0),I>=2&&(w(!0),i==null||i({success:!0,title:"Maximum Attempts Reached",message:"You've reached the maximum of 2 regeneration attempts. Feel free to manually edit the current suggestion to fit your specific needs."}),l==null||l(!0))}catch(N){console.error("[useConclusionRemark] AI generation failed:",N);const _=A+1;C(_),g(!1),_>=2?(w(!0),i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. Since the maximum of 2 attempts is reached, please proceed with a manual approach."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0)}finally{m(!1)}},T=async()=>{var _,I;const N=o.replace(/<[^>]*>/g,"").trim();if(!N){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(N.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),l==null||l(!0);return}try{u(!0);const{finalizeConclusion:B}=await xo(async()=>{const{finalizeConclusion:k}=await import("./conclusionApi-BFrrhPzD.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:((I=(_=B.response)==null?void 0:_.data)==null?void 0:I.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{u(!1)}};return x.useEffect(()=>{var k;const N=(k=t==null?void 0:t.status)==null?void 0:k.toLowerCase();if(!((N==="approved"||N==="rejected"||N==="closed")&&a&&!o))return;const I=(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);I||B?(c(I||B),g(!!B)):E()},[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:v}}function Z0(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 N,_;const T=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!T){alert("Approval level not found");return}await Un(t,T,D||""),await new Promise(I=>setTimeout(I,500)),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(_=window==null?void 0:window.toast)==null||_.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var N,_;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 Dr(t,T,D.trim(),D.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(_=window==null?void 0:window.toast)==null||_.call(window,"Rejected successfully")},handleAddApprover:async(D,T,N)=>{var _,I;try{await rg(t,D,T,N),await a(),c(!1),y==null||y({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${T}h TAT`}),g==null||g(!0)}catch(B){throw y==null||y({success:!1,title:"Failed to Add Approver",message:((I=(_=B==null?void 0:B.response)==null?void 0:_.data)==null?void 0:I.error)||"Failed to add approver. Please try again."}),g==null||g(!0),B}},handleSkipApprover:async D=>{var T,N;if(f)try{await M1(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(_){throw y==null||y({success:!1,title:"Failed to Skip Approver",message:((N=(T=_==null?void 0:_.response)==null?void 0:T.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),_}},handleAddSpectator:async D=>{var T,N;try{await ng(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(_){throw y==null||y({success:!1,title:"Failed to Add Spectator",message:((N=(T=_==null?void 0:_.response)==null?void 0:T.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),_}}}}function _5({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 Vp(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 Pv(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 Ev(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(P,{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(P,{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(sp,{className:"w-3 h-3 mr-1"}),"Resubmission needed"]})]})]})}const M5=t=>{const s=(t||"").toLowerCase();return s.includes("image")||s.includes("pdf")||s.includes("jpg")||s.includes("jpeg")||s.includes("png")||s.includes("gif")};function Ur({document:t,onPreview:s,onDownload:a,showPreview:r=!0,testId:n="document-card"}){return e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors","data-testid":`${n}-${t.documentId}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(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&&M5(t.fileType)&&s&&e.jsx(P,{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(P,{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 L5({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,v=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"}${v}`};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 v=j.documentId??j.document_id,w=d(j.originalFileName??j.original_file_name??j.fileName??j.file_name??"Document"),A=Number(j.fileSize??j.file_size??0),C=A>0?(A/(1024*1024)).toFixed(2)+" MB":"—";return e.jsx(Ur,{document:{documentId:v,name:w,fileType:j.fileType??j.file_type??"",size:C,sizeBytes:A,uploadedBy:j.uploadedBy??j.uploaded_by,uploadedAt:j.uploadedAt??j.uploaded_at},onPreview:E=>i(E),onDownload:l,testId:"form16-previous-document"},v||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(P,{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(Ur,{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(Ur,{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 O5=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"}}},dh=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"}}},$5=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(hl,{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(dl,{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 U5(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 B5({request:t}){const s=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",a=s?U5(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:$5(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 J0({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(P,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function q0({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,v]=x.useState({open:!1,violations:[]}),[w,A]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});x.useEffect(()=>{t&&(async()=>{var _;try{const I=await ua("WORKFLOW_SHARING"),B=await ua("TAT_SETTINGS"),k=[...I,...B],M={};k.forEach(L=>{M[L.configKey]=L.configValue}),A({maxApprovalLevels:parseInt(M.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(M.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((_=M.ALLOW_ADD_SPECTATOR)==null?void 0:_.toLowerCase())==="true",maxSpectators:parseInt(M.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(I){console.error("Failed to load system policy:",I)}})()},[t]);const C=async()=>{var F,S;const N=n.trim().toLowerCase();if(!N){j({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){j({open:!0,type:"error",email:N,message:"Please enter a valid email address"});return}const I=r.find(G=>(G.email||"").toLowerCase()===N);if(I){const G=((F=I.participantType)==null?void 0:F.toUpperCase())||"PARTICIPANT",U=I.name||N;if(G==="INITIATOR"){j({open:!0,type:"error",email:N,message:`${U} is the request initiator and cannot be added as a spectator.`});return}else if(G==="APPROVER"){j({open:!0,type:"error",email:N,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:N,message:`${U} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:N,message:`${U} is already a participant on this request.`});return}}const B=[];w.allowSpectators||B.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const M=r.filter(G=>(G.participantType||"").toUpperCase()==="SPECTATOR").length;M>=w.maxSpectators&&B.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:M,maxValue:w.maxSpectators});const L=r.length+1;if(L>w.maxParticipants&&B.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:L,maxValue:w.maxParticipants}),B.length>0){v({open:!0,violations:B});return}if(!u||u.email.toLowerCase()!==N)try{const U=((S=(await Na(N,1)).data)==null?void 0:S.data)||[];if(U.length===0){j({open:!0,type:"not-found",email:N,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:N,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(N),i(""),h(null),s()}catch(G){console.error("Failed to add spectator:",G)}finally{o(!1)}},E=()=>{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=N=>{if(i(N),u&&u.email.toLowerCase()!==N.toLowerCase()&&h(null),g.current&&clearTimeout(g.current),!N||!N.startsWith("@")||N.length<2){d([]),p(!1);return}p(!0),g.current=setTimeout(async()=>{var _;try{const I=N.slice(1),k=((_=(await Na(I,10)).data)==null?void 0:_.data)||[];d(k)}catch(I){console.error("Search failed:",I),d([])}finally{p(!1)}},300)},T=async N=>{try{await ya({userId:N.userId,email:N.email,displayName:N.displayName,firstName:N.firstName,lastName:N.lastName,department:N.department,phone:N.phone,mobilePhone:N.mobilePhone,designation:N.designation,jobTitle:N.jobTitle,manager:N.manager,employeeId:N.employeeId,employeeNumber:N.employeeNumber,secondEmail:N.secondEmail,location:N.location}),i(N.email),h(N),d([]),p(!1)}catch(_){console.error("Failed to ensure user exists:",_),j({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(xt,{open:t,onOpenChange:E,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:E,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled: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(pl,{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:N=>D(N.target.value),className:"pl-10 h-11 border-gray-300",disabled:l,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>T(N),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:(N.displayName||N.email).split(" ").map(_=>_[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:N.displayName||[N.firstName,N.lastName].filter(Boolean).join(" ")||N.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:N.email}),N.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:N.designation})]})]})},N.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(P,{type:"button",variant:"outline",onClick:E,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(P,{type:"button",onClick:C,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:N=>j(_=>({..._,open:N})),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(xl,{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(P,{onClick:()=>j(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(fi,{open:y.open,onClose:()=>v({open:!1,violations:[]}),violations:y.violations,policyDetails:{maxApprovalLevels:w.maxApprovalLevels,maxParticipants:w.maxParticipants,allowSpectators:w.allowSpectators,maxSpectators:w.maxSpectators}})]})}function ef({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),[v,w]=x.useState(null),A=x.useRef(null),C=x.useRef(null),[E,D]=x.useState({open:!1,type:"error",email:"",message:""}),T=n.filter(S=>S&&(S.status==="approved"||S.status==="rejected"||S.status==="skipped")),N=Math.max(1,T.length+1),_=Math.max(1,n.length+1),I=_>=N?Array.from({length:_-N+1},(S,G)=>N+G):[N];x.useEffect(()=>{I.length>0&&p===null&&u(I[0]||null)},[I.length,p]);const B=async()=>{var H,K;const S=o.trim().toLowerCase();if(!S){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(S)){D({open:!0,type:"error",email:S,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<N){D({open:!0,type:"error",email:"",message:`Cannot add approver at level ${p}. Minimum allowed level is ${N} (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 R=r.find(z=>(z.email||"").toLowerCase()===S);if(R){const z=((H=R.participantType)==null?void 0:H.toUpperCase())||"PARTICIPANT",O=R.name||S;if(z==="INITIATOR"){D({open:!0,type:"error",email:S,message:`${O} is the request initiator and cannot be added as an approver.`});return}else if(z==="APPROVER"){D({open:!0,type:"error",email:S,message:`${O} is already an approver on this request.`});return}else if(z==="SPECTATOR"){D({open:!0,type:"error",email:S,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:S,message:`${O} is already a participant on this request.`});return}}if(!v||v.email.toLowerCase()!==S)try{const O=((K=(await Na(S,1)).data)==null?void 0:K.data)||[];if(O.length===0){D({open:!0,type:"not-found",email:S,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:S,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(S,d,p),c(""),m(24),u(null),w(null),s()}catch(z){console.error("Failed to add approver:",z)}finally{g(!1)}},k=()=>{h||(c(""),m(24),u(null),w(null),b([]),y(!1),s())},M=S=>{const G=S.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&&C.current&&C.current.scrollTo({top:C.current.scrollHeight,behavior:"smooth"})},[f.length]),x.useEffect(()=>()=>{A.current&&clearTimeout(A.current)},[]);const L=S=>{if(c(S),v&&v.email.toLowerCase()!==S.toLowerCase()&&w(null),A.current&&clearTimeout(A.current),!S||!S.startsWith("@")||S.length<2){b([]),y(!1);return}y(!0),A.current=setTimeout(async()=>{var G;try{const U=S.slice(1),R=((G=(await Na(U,10)).data)==null?void 0:G.data)||[];b(R)}catch(U){console.error("Search failed:",U),b([])}finally{y(!1)}},300)},F=async S=>{try{await ya({userId:S.userId,email:S.email,displayName:S.displayName,firstName:S.firstName,lastName:S.lastName,department:S.department,phone:S.phone,mobilePhone:S.mobilePhone,designation:S.designation,jobTitle:S.jobTitle,manager:S.manager,employeeId:S.employeeId,employeeNumber:S.employeeNumber,secondEmail:S.secondEmail,location:S.location}),c(S.email),w(S),b([]),y(!1)}catch(G){console.error("Failed to ensure user exists:",G),D({open:!0,type:"error",email:S.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:C,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a new approver at a specific level. Existing approvers at and after the selected level will be shifted down."}),i&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-2",children:e.jsxs("p",{className:"text-xs text-blue-800",children:[" Max: ",i," level",i!==1?"s":"",n.length>0&&e.jsxs("span",{className:"ml-2",children:["(",Math.max(...n.map(S=>S.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(S=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${S.status==="approved"?"bg-green-100 border border-green-200":S.status==="rejected"?"bg-red-100 border border-red-200":S.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:S.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:S.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[S.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[M(S.status),e.jsx(re,{variant:"outline",className:`text-xs ${S.status==="approved"?"bg-green-50 text-green-700 border-green-300":S.status==="rejected"?"bg-red-50 text-red-700 border-red-300":S.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:S.status})]})]},S.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:[" New approver can only be added at level ",N," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(He,{value:(p==null?void 0:p.toString())||"",onValueChange:S=>u(Number(S)),disabled:h,children:[e.jsx(We,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select level"})}),e.jsx(Ye,{children:I.map(S=>e.jsx(X,{value:S.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 ",S]}),S<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",S,")"]})]})},S))})]}),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:S=>m(Number(S.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(pl,{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:S=>L(S.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(S=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>F(S),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:(S.displayName||S.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:S.displayName||[S.firstName,S.lastName].filter(Boolean).join(" ")||S.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:S.email}),S.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:S.designation})]})]})},S.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(P,{type:"button",variant:"outline",onClick:k,className:"flex-1 h-11 border-gray-300",disabled:h,children:"Cancel"}),e.jsxs(P,{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:E.open,onOpenChange:S=>D(G=>({...G,open:S})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:E.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:[E.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:E.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(xl,{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."]})})]}),E.type==="error"&&e.jsxs(e.Fragment,{children:[E.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:E.email}),"."]}),E.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:E.message})})]})]})})]}),e.jsx(Dt,{children:e.jsx(P,{onClick:()=>D(S=>({...S,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const V5=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"}},z5=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},H5=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)},G5=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",mh=({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(rp,{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(Pi,{className:`${s} text-purple-600`}):e.jsx(dl,{className:`${s} text-gray-600`})};function tf({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,v]=x.useState(!1),[w,A]=x.useState([]),[C,E]=x.useState(!1),[D,T]=x.useState([]),[N,_]=x.useState(null),[I,B]=x.useState(null),[k,M]=x.useState(!1),[L,F]=x.useState(!1),[S,G]=x.useState(!1),[U,$]=x.useState({success:!0,title:"",message:""}),R=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=w.filter(oe=>oe.content.toLowerCase().includes(b.toLowerCase())||oe.user.name.toLowerCase().includes(b.toLowerCase())),Ue=x.useMemo(()=>o!==void 0?o:!N||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===N&&(me==="SPECTATOR"||Xe==="SPECTATOR")}),[o,N,te]);x.useEffect(()=>{},[te]),x.useEffect(()=>{!h||!N||s||(async()=>{try{const oe=await un(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===N,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,N,s]);const Pe=x.useMemo(()=>{const oe=[];return w.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},[w]);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=R.current)==null||oe.scrollIntoView({behavior:"smooth"})};x.useEffect(()=>{ye()},[w]);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,rt=()=>{K.current&&K.current.connected?(K.current.emit("request:online-users",{requestId:h}),Xe++,Xe<Qe&&setTimeout(rt,500)):(Xe++,Xe<Qe&&setTimeout(rt,200))};setTimeout(rt,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;_(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"),rt=(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:rt})}catch(Me){console.error("Failed to load document policy:",Me)}})()},[]),x.useEffect(()=>{if(!N)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=Br();r?ue(vt=>vt.map(Pt=>Pt.userId===N?{...Pt,status:"online"}:Pt)):(Lo(me,oe,N),ue(vt=>vt.map(Pt=>Pt.userId===N?{...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),fr=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:fr===N,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))},rt=vt=>{vt.userId!==N&&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===N)return{...Ss,status:"online"};const Ha=vt.userIds.includes(as);return{...Ss,status:Ha?"online":"offline"}}))},lt=()=>{ue(vt=>vt.map(Pt=>Pt.userId===N?{...Pt,status:"online"}:Pt)),r||Lo(me,oe,N),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===N?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",rt),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",rt),me.off("presence:online",Ke),me.offAny(Hs),r||vp(me,oe),K.current=null};window.__wn_cleanup=is}catch{}})(),()=>{var Me;try{(Me=window.__wn_cleanup)==null||Me.call(window)}catch{}}},[h,N,r]);const he=async()=>{if(g.trim()||D.length>0){const oe=at(g),Me=oe.map(Qe=>{const rt=te.find(Ke=>Ke.name.toLowerCase().includes(Qe.toLowerCase()));return rt==null?void 0:rt.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 ag(h,{message:g,mentions:Me},D);const Qe=await un(h),rt=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===N,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(rt)}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 rt=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:rt,avatar:rt.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===N}}}).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 un(h),Me=Array.isArray(oe)?oe.map(me=>{const Xe=me.userName||me.user_name||"User",Qe=me.userRole||me.user_role,rt=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:rt},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===N}}):[];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 rt=ne(Qe);rt.valid?Xe.push(Qe):me.push({fileName:Qe.name,reason:rt.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),v(!1)},je=()=>{var oe;(oe=H.current)==null||oe.click()},ie=async oe=>{var Me,me;try{await ng(h,oe);const Xe=await Ps(h),Qe=Array.isArray(Xe==null?void 0:Xe.participants)?Xe.participants:[];if(Qe.length){const rt=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(rt),K.current&&K.current.connected&&K.current.emit("request:online-users",{requestId:h})}M(!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),F(!1);else try{await rg(h,oe,Me,me);const rt=await Ps(h),Ke=Array.isArray(rt==null?void 0:rt.participants)?rt.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})}F(!1),$({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${me} with ${Me}h TAT`}),G(!0)}catch(rt){throw console.error("Failed to add approver:",rt),$({success:!1,title:"Failed to Add Approver",message:((Qe=(Xe=rt==null?void 0:rt.response)==null?void 0:Xe.data)==null?void 0:Qe.error)||"Failed to add approver. Please try again."}),G(!0),rt}},qe=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","","","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],at=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,rt=oe.slice(Qe),Ke=oe[Qe];(rt.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||[],rt=Qe.find(Ke=>Ke.emoji===Me);if(rt)if(rt.users.includes("You")){if(rt.users=rt.users.filter(Ke=>Ke!=="You"),rt.users.length===0)return{...Xe,reactions:Qe.filter(Ke=>Ke.emoji!==Me)}}else rt.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(P,{variant:"outline",size:"sm",onClick:()=>E(!C),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(Dj,{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:H5(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,rt=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(mh,{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:rt}),Qe&&e.jsx("p",{className:"text-xs text-gray-500",children:G5(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(P,{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=U1(lt);B({fileName:rt,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(P,{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 Mu(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(P,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>v(!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:R})]})}),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(mh,{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(P,{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(" "),rt=Xe.length>0,Ke=Xe.includes(" ")&&!Qe,lt=Qe&&rt;if(!(Me&&me.length<=20&&!Ke&&!lt))return null;const ut=Xe.toLowerCase(),Hs=te.filter(is=>is.userId===N?!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(P,{variant:"ghost",size:"sm",onClick:()=>v(!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(P,{variant:"ghost",size:"sm",onClick:je,disabled:Ue,title:Ue?"Spectators cannot attach files":"Attach file",children:e.jsx(dl,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>v(!y),disabled:Ue,title:Ue?"Spectators cannot add emojis":"Add emoji",children:e.jsx(Rj,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>f(oe=>oe+"@"),disabled:Ue,title:Ue?"Spectators cannot mention users":"Mention someone",children:e.jsx(pl,{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(P,{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(ap,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),C&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>E(!1)}),e.jsxs("div",{className:`
w-72 sm:w-80 bg-white border-l border-gray-200 flex flex-col
lg:relative lg:translate-x-0 lg:shadow-none
${C?"fixed right-0 top-0 bottom-0 z-50 shadow-xl":"hidden lg:flex"}
`,children:[e.jsxs("div",{className:"p-4 sm:p-6 border-b border-gray-200 flex-1 flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900",children:"Participants"}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>E(!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===N;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 ${V5(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:z5(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(P,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>F(!0),children:[e.jsx(hl,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(P,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>M(!0),children:[e.jsx(Nt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),I&&e.jsx(Wr,{fileName:I.fileName,fileType:I.fileType,fileUrl:I.fileUrl,fileSize:I.fileSize,attachmentId:I.attachmentId,onDownload:Mu,open:!!I,onClose:()=>B(null)}),!Ue&&e.jsx(q0,{open:k,onClose:()=>M(!1),onConfirm:ie,requestIdDisplay:h,requestTitle:ee.title,existingParticipants:De}),!Ue&&l&&e.jsx(ef,{open:L,onClose:()=>F(!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(P,{onClick:()=>q({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(J0,{open:S,onClose:()=>G(!1),success:U.success,title:U.title,message:U.message})]})}function W5({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(tf,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d})})}function Y5({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(P,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(fn,{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:tt(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:tt(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 Q5({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(lr,{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(lr,{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(Ki,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function K5({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var g,f;const c=O5((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:dh((t==null?void 0:t.status)||"pending").icon,label:m}:dh((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(P,{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())||"",v=y==="FORM_16",w=b==="CLAIM_MANAGEMENT"||j==="claim-management",A=b==="DEALER_CLAIM"||y==="DEALER CLAIM"||y==="DEALER_CLAIM";let C="Non-Templatized",E="bg-purple-100 !text-purple-600 border-purple-200";return v?(C="Form 16",E="bg-emerald-100 !text-emerald-700 border-emerald-200"):A?(C="Dealer Claim",E="bg-blue-100 !text-blue-700 border-blue-200"):w?(C="Claim Management",E="bg-blue-100 !text-blue-700 border-blue-200"):y==="TEMPLATE"&&(C="Template"),e.jsx(re,{className:`${E} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:C})})()]})]})]})]}),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(P,{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(fn,{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(P,{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(Q5,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function Nd(t){return(await ve.get(`/summaries/${t}`)).data.data}async function X5(t,s){return(await ve.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function Z5(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 sf(t){await ve.patch(`/summaries/shared/${t}/view`)}async function af(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 J5(t){return(await ve.get(`/summaries/${t}/recipients`)).data.data||[]}function q5({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 tt(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(bc,{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 ek({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(gl,{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(ii,{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(bc,{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 tk({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 tt(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(P,{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(P,{variant:"outline",size:"sm",onClick:i,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(Zn,{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 sk({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 tt(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return tt(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 ak({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(ii,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function rf(t,s){var a,r,n,i,l;try{if(!ni(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||"",v=o.location||"",w=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),C=A!=null?Number(A):void 0,E=Array.isArray(g)&&g.length>0?g.map(S=>({description:S.description||S.itemDescription||S.item_description||"",amount:Number(S.amount)||0,gstRate:S.gstRate??S.gst_rate,gstAmt:S.gstAmt??S.gst_amt,cgstAmt:S.cgstAmt??S.cgst_amt,sgstAmt:S.sgstAmt??S.sgst_amt,igstAmt:S.igstAmt??S.igst_amt,totalAmt:S.totalAmt??S.total_amt,hsnCode:S.hsnCode||S.hsn_code||S.hsnCd||S.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:v,period:f&&b?{startDate:f,endDate:b}:void 0,estimatedBudget:w,closedExpenses:C,closedExpensesBreakdown:E,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 N=(c==null?void 0:c.expectedCompletionDate)||(c==null?void 0:c.expected_completion_date),I=!!(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(S=>({description:S.description||S.itemDescription||S.item_description||"",amount:Number(S.amount)||0,gstRate:Number(S.gstRate??S.gst_rate??0),gstAmt:Number(S.gstAmt??S.gst_amt??0),cgstAmt:Number(S.cgstAmt??S.cgst_amt??0),sgstAmt:Number(S.sgstAmt??S.sgst_amt??0),igstAmt:Number(S.igstAmt??S.igst_amt??0),totalAmt:Number(S.totalAmt??S.total_amt??0),hsnCode:S.hsnCode||S.hsn_code||""})):Array.isArray(c.costBreakup||c.cost_breakup)?(c.costBreakup||c.cost_breakup).map(S=>({description:S.description||S.itemDescription||S.item_description||"",amount:Number(S.amount)||0,gstRate:S.gstRate??S.gst_rate,gstAmt:S.gstAmt??S.gst_amt,cgstAmt:S.cgstAmt??S.cgst_amt,sgstAmt:S.sgstAmt??S.sgst_amt,igstAmt:S.igstAmt??S.igst_amt,totalAmt:S.totalAmt??S.total_amt,hsnCode:S.hsnCode||S.hsn_code||""})):[],totalEstimatedBudget:c.totalEstimatedBudget||c.total_estimated_budget||0,timelineMode:c.timelineMode||c.timeline_mode,expectedCompletionDate:N,timelineForClosure:N,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||{},M=o||{},L={eInvoiceNumber:k.invoiceNumber||k.invoice_number||M.eInvoiceNumber||M.e_invoice_number||k.dmsNumber||k.dms_number,eInvoiceDate:k.invoiceDate||k.invoice_date||M.eInvoiceDate||M.e_invoice_date,dmsNumber:k.dmsNumber||k.dms_number||M.dmsNumber||M.dms_number,creditNoteNumber:h.creditNoteNumber||h.credit_note_number||M.creditNoteNumber||M.credit_note_number,creditNoteDate:h.creditNoteDate||h.credit_note_date||M.creditNoteDate||M.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):M.creditNoteAmount!==void 0&&M.creditNoteAmount!==null?Number(M.creditNoteAmount):M.credit_note_amount!==void 0&&M.credit_note_amount!==null?Number(M.credit_note_amount):void 0,irn:k.irn||M.irn,ackNo:k.ackNo||k.ack_no||M.ackNo||M.ack_no,ackDate:k.ackDate||k.ack_date||M.ackDate||M.ack_date,signedInvoiceUrl:k.signedInvoiceUrl||k.signed_invoice_url||M.signedInvoiceUrl||M.signed_invoice_url,taxBreakdown:k.taxBreakdown||M.taxBreakdown,creditNoteWfmData:(((l=t.creditNote)==null?void 0:l.items)||t.creditNoteWfmData||o.creditNoteWfmData||[]).map(S=>{var G;return{...S,DOC_NO:S.creditNoteNumber||((G=t.creditNote)==null?void 0:G.creditNoteNumber)||S.DOC_NO,TRNS_UNIQ_NO:S.transactionNo||S.TRNS_UNIQ_NO,MESSAGE:S.description||S.MESSAGE,TDS_AMT:S.tdsAmount||S.TDS_AMT,CREDITED_TOTAL_AMT:S.creditAmount||S.amount||S.CREDITED_TOTAL_AMT}})},F={estimated:D.estimatedBudget||0,closed:D.closedExpenses||0};return{activityInfo:D,dealerInfo:T,proposalDetails:I,ioDetails:Object.keys(B).some(S=>B[S])?B:void 0,dmsDetails:Object.keys(L).some(S=>L[S])?L:void 0,claimAmount:F}}catch(o){return console.error("[claimDataMapper] Error mapping claim data:",o),null}}function nf(t,s){var a,r,n,i,l,o,c,d;try{const m=v=>(v||"").toString().trim().toLowerCase(),p=Array.isArray(t.participants)?t.participants:[],u=p.find(v=>{var w;return v.userId===s||v.user_id===s||((w=v.user)==null?void 0:w.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(v=>{var w,A;return(v.userId===s||v.user_id===s||((w=v.user)==null?void 0:w.userId)===s||((A=v.user)==null?void 0:A.user_id)===s)&&(v.participantType||v.participant_type||v.type||"").toString().toUpperCase()==="DEALER"}))return"DEALER";const b=t.approvalLevels||[];return b.find(v=>{var w;return v.levelNumber===3&&(v.approverId===s||((w=v.approver)==null?void 0:w.userId)===s)})?"DEPARTMENT_LEAD":b.find(v=>{var w;return(v.approverId===s||((w=v.approver)==null?void 0:w.userId)===s)&&v.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(m){return console.error("[claimDataMapper] Error determining user role:",m),"SPECTATOR"}}function lf(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 rk({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 F,S,G,U,$;const{user:y}=us(),[v,w]=x.useState([]),[A,C]=x.useState(!1),[E,D]=x.useState(!1),T=(t==null?void 0:t.status)==="closed",N=((F=t==null?void 0:t.pauseInfo)==null?void 0:F.isPaused)||!1,_=h||((G=(S=t==null?void 0:t.pauseInfo)==null?void 0:S.pausedBy)==null?void 0:G.userId),I=g||(y==null?void 0:y.userId)||"",B=!N&&!T&&(r||s),k=N&&d&&(r||s),M=N&&s&&_&&_!==I&&m;x.useEffect(()=>{if(!N||!r||!(t!=null&&t.requestId)){D(!1);return}(async()=>{var H;try{const O=(((H=(await or.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)}})()},[N,r,t==null?void 0:t.requestId,u]),x.useEffect(()=>{(async()=>{if(!T||!p||!s){w([]);return}try{C(!0);const H=await J5(p);w(H)}catch(H){console.error("Failed to fetch shared recipients:",H),w([])}finally{C(!1)}})()},[T,p,s,u]);const L=x.useMemo(()=>{if(!f||!ni(f))return null;const R=rf(f);if(!R)return null;const H=nf(f,I),K=lf(H);return{claimRequest:R,visibility:K}},[f,I]);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(P,{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(hl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(P,{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(P,{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(dr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),k&&e.jsxs(P,{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(Qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),M&&e.jsxs(P,{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&&!N&&!j&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{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(P,{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"]})]}),N&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:_===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&&e.jsx(Je,{className:"w-3.5 h-3.5"}),E?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:E?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&_!==I&&E?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&&_!==I?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&&_&&_!==I?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:M?'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((R,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:R.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:R.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:R.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(fn,{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..."})}):v.length>0?v.map((R,H)=>{const K=(R.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:R.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:R.email}),R.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},R.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(tk,{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 nk({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(P,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(P,{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 ik({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(P,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(P,{variant:"destructive",onClick:h,disabled:d,children:[e.jsx(St,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function lk({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(P,{type:"button",variant:"outline",onClick:u,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(P,{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 ok({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:v,setShowActionStatusModal:w,setPreviewDocument:A,setDocumentError:C,setSkipApproverData:E,setActionStatus:D,handleApproveConfirm:T,handleRejectConfirm:N,handleAddApprover:_,handleAddSpectator:I,handleSkipApprover:B,downloadDocument:k,documentPolicy:M}){return e.jsxs(e.Fragment,{children:[e.jsx(nk,{open:t,onClose:()=>f(!1),onConfirm:T,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(ik,{open:s,onClose:()=>b(!1),onConfirm:N,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(ef,{open:a,onClose:()=>j(!1),onConfirm:_,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p,currentLevels:u,maxApprovalLevels:h,onPolicyViolation:g}),e.jsx(q0,{open:r,onClose:()=>y(!1),onConfirm:I,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p}),e.jsx(lk,{open:n,onClose:()=>{v(!1),E(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(Wr,{fileName:l.fileName,fileType:l.fileType,fileUrl:Nn(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:k,open:!!l,onClose:()=>A(null)}),m&&e.jsx(J0,{open:i,onClose:()=>{w(!1),D(null)},success:m.success,title:m.title,message:m.message}),e.jsx(xt,{open:o.show,onOpenChange:L=>C(F=>({...F,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,F)=>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})]},F))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",M.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",M.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Dt,{children:e.jsx(P,{onClick:()=>C({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const of={DocumentsTab:L5,ActivityTab:B5,WorkNotesTab:W5,SummaryTab:Y5,RequestDetailHeader:K5,QuickActionsSidebar:rk,RequestDetailModals:ok};function wd({className:t,...s}){return e.jsx(Vb,{"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(zb,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx($a,{className:"size-3.5"})})})}function cf({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 v;try{u(!0);const w=i.slice(1),A=await Na(w,10),C=((v=A==null?void 0:A.data)==null?void 0:v.data)||(A==null?void 0:A.data)||[];c(Array.isArray(C)?C:[])}catch(w){console.error("Failed to search users:",w),W.error("Failed to search users")}finally{u(!1)}},300);return()=>clearTimeout(y)},[i,t]);const f=y=>{m(v=>{const w=new Set(v);return w.has(y)?w.delete(y):w.add(y),w})},b=async()=>{var y,v;if(d.size===0){W.error("Please select at least one user to share with");return}try{g(!0),await X5(a,Array.from(d)),W.success(`Summary shared with ${d.size} user(s)`),m(new Set),l(""),c([]),n==null||n(),s()}catch(w){console.error("Failed to share summary:",w),W.error(((v=(y=w==null?void 0:w.response)==null?void 0:y.data)==null?void 0:v.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 v=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:w=>w.stopPropagation(),onMouseDown:w=>w.stopPropagation(),className:"flex items-center",children:e.jsx(wd,{checked:v,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 v=o.find(w=>w.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:(v==null?void 0:v.displayName)||(v==null?void 0:v.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(P,{variant:"outline",onClick:j,disabled:h,children:"Cancel"}),e.jsx(P,{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 df({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 v,w,A,C;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 L1(a,r,i.trim(),b.toDate()),W.success("Workflow paused successfully"),n&&await n(),l(""),c(p()),s()}catch(E){console.error("Failed to pause workflow:",E),W.error(((w=(v=E==null?void 0:E.response)==null?void 0:v.data)==null?void 0:w.error)||((C=(A=E==null?void 0:E.response)==null?void 0:A.data)==null?void 0:C.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(dr,{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(P,{variant:"outline",onClick:f,disabled:d,children:"Cancel"}),e.jsx(P,{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(dr,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function mf({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 O1(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(Qi,{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(P,{variant:"outline",onClick:d,disabled:l,children:"Cancel"}),e.jsx(P,{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(Qi,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function uf({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 $1(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(P,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(P,{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:ck,ActivityTab:dk,WorkNotesTab:mk,SummaryTab:uk,RequestDetailHeader:xk,QuickActionsSidebar:hk,RequestDetailModals:pk}=of;let gk=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(P,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(P,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function fk({requestId:t,onBack:s,dynamicRequests:a=[]}){var Kr,Ja,jr,qa,yr,vr,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),[v,w]=x.useState(!1),[A,C]=x.useState(!1),[E,D]=x.useState(!1),[T,N]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[_,I]=x.useState({open:!1,violations:[]}),{user:B}=us(),{request:k,apiRequest:M,loading:L,refreshing:F,refreshDetails:S,currentApprovalLevel:G,isSpectator:U,isInitiator:$,existingParticipants:R,accessDenied:H}=yd(n,a,B),{mergedMessages:K,unreadWorkNotes:z,workNoteAttachments:O,setWorkNoteAttachments:V}=Q0(n,M,o,B),{uploadingDocument:Q,triggerFileInput:q,previewDocument:ee,setPreviewDocument:te,documentPolicy:ue,documentError:_e,setDocumentError:Ze}=K0(M,S),{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:at,handleApproveConfirm:gt,handleRejectConfirm:It,handleAddApprover:oe,handleSkipApprover:Me,handleAddSpectator:me}=Z0(n,G,S),{conclusionRemark:Xe,setConclusionRemark:Qe,conclusionLoading:rt,conclusionSubmitting:Ke,aiGenerated:lt,handleGenerateConclusion:et,handleFinalizeConclusion:ut,generationAttempts:Hs,generationFailed:is,maxAttemptsReached:vt}=X0(k,n,$,S,s,at,je);x.useEffect(()=>{(async()=>{var As;try{const la=await ua("SYSTEM_SETTINGS"),Nr=await ua("WORKFLOW_SHARING"),wr=[...la,...Nr],Sa={};wr.forEach(sr=>{Sa[sr.configKey]=sr.configValue}),N({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=()=>{S()},Pt=()=>{w(!0)},Ss=()=>{C(!0)},as=async()=>{await S()},za=()=>{D(!0)},Ha=async()=>{await S()},fr=async()=>{await S()},wa=async()=>{if(!(M!=null&&M.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||!(M!=null&&M.requestId)){g(null),u(null);return}try{b(!0);const As=await af(M.requestId);if(As!=null&&As.summaryId){u(As.summaryId);try{const la=await Nd(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,M==null?void 0:M.requestId]);const Yr=((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&&!M)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(np,{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(P,{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(P,{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(P,{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(P,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});const Qr=(B==null?void 0:B.role)==="MANAGEMENT"||(B==null?void 0:B.role)==="ADMIN",br=((Kr=nt.getUserData())==null?void 0:Kr.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(xk,{request:k,refreshing:F,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:((jr=k==null?void 0:k.pauseInfo)==null?void 0:jr.isPaused)||!1}),e.jsxs(bi,{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(ji,{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(ip,{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(jc,{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(sC,{request:k}):e.jsx(K1,{request:k,isInitiator:$,needsClosure:Lt,conclusionRemark:Xe,setConclusionRemark:Qe,conclusionLoading:rt,conclusionSubmitting:Ke,aiGenerated:lt,handleGenerateConclusion:et,handleFinalizeConclusion:ut,onPause:Pt,onResume:Ss,onRetrigger:za,currentUserIsApprover:!!G,pausedByUserId:(yr=(qa=k==null?void 0:k.pauseInfo)==null?void 0:qa.pausedBy)==null?void 0:yr.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(uk,{summary:h,loading:f,onShare:wa,isInitiator:$})}),e.jsx(Ut,{value:"workflow",className:"mt-0",children:Us?e.jsx(rC,{request:k,requestId:(M==null?void 0:M.requestId)||n,isReUser:Qr,onRefresh:S}):e.jsx(q1,{request:k,user:B,isInitiator:$,onSkipApprover:Qt=>{if(!Qt.levelId){alert("Level ID not available");return}Se(Qt),ke(!0)},onRefresh:S})}),e.jsx(Ut,{value:"documents",className:"mt-0",children:e.jsx(ck,{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(dk,{request:k})}),!Us&&e.jsx(Ut,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(mk,{requestId:n,requestTitle:k.title,mergedMessages:K,setWorkNoteAttachments:V,isInitiator:$,isSpectator:U,currentLevels:Yr,onAddApprover:oe,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Qt=>I({open:!0,violations:Qt})})})]}),!br&&o!=="worknotes"&&e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[Us&&Qr&&e.jsx(_5,{requestId:(M==null?void 0:M.requestId)||n,request:k,onRefresh:S}),e.jsx(hk,{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=(vr=k==null?void 0:k.pauseInfo)==null?void 0:vr.pausedBy)==null?void 0:er.userId,currentUserId:B==null?void 0:B.userId,apiRequest:M,hideApproveReject:br})]})]})]})]})}),d&&p&&e.jsx(cf,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(k==null?void 0:k.title)||"N/A",onSuccess:()=>{S(),y(Qt=>Qt+1)}}),v&&(M==null?void 0:M.requestId)&&e.jsx(df,{isOpen:v,onClose:()=>w(!1),requestId:M.requestId,levelId:(G==null?void 0:G.levelId)||null,onSuccess:Ha}),A&&(M==null?void 0:M.requestId)&&e.jsx(mf,{isOpen:A,onClose:()=>C(!1),requestId:M.requestId,onSuccess:as}),E&&(M==null?void 0:M.requestId)&&e.jsx(uf,{isOpen:E,onClose:()=>D(!1),requestId:M.requestId,approverName:(tr=(Pa=k==null?void 0:k.pauseInfo)==null?void 0:Pa.pausedBy)==null?void 0:tr.name,onSuccess:fr}),e.jsx(pk,{showApproveModal:Ue,showRejectModal:De,showAddApproverModal:ye,showAddSpectatorModal:he,showSkipApproverModal:ge,showActionStatusModal:Oe,previewDocument:ee,documentError:_e,request:k,skipApproverData:ie,actionStatus:qe,existingParticipants:R,currentLevels:Yr,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Qt=>I({open:!0,violations:Qt}),setShowApproveModal:Pe,setShowRejectModal:le,setShowAddApproverModal:ae,setShowAddSpectatorModal:ne,setShowSkipApproverModal:ke,setShowActionStatusModal:je,setPreviewDocument:te,setDocumentError:Ze,setSkipApproverData:Se,setActionStatus:at,handleApproveConfirm:gt,handleRejectConfirm:It,handleAddApprover:oe,handleAddSpectator:me,handleSkipApprover:Me,downloadDocument:Ms,documentPolicy:ue}),e.jsx(fi,{open:_.open,onClose:()=>I({open:!1,violations:[]}),violations:_.violations,policyDetails:{maxApprovalLevels:T.maxApprovalLevels,maxParticipants:T.maxParticipants,allowSpectators:T.allowSpectators,maxSpectators:T.maxSpectators}})]})}function bk(t){return e.jsx(gk,{children:e.jsx(fk,{...t})})}const jk=[{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 yk(){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 vk({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=yk(),v=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(P,{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:w=>c(w.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"})]})]}),v&&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(w=>e.jsx(X,{value:w,children:w},w))})]}),v&&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:jk.map(w=>e.jsx(X,{value:w.value,children:w.label},w.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:l,onValueChange:w=>g(w),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(P,{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(fl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(bl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}const Nk=[{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 wk(){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 Ck({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=wk(),v=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(P,{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:w=>d(w.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"})]})]}),v&&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(w=>e.jsx(X,{value:w,children:w},w))})]}),v&&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:Nk.map(w=>e.jsx(X,{value:w.value,children:w.label},w.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:l,onValueChange:w=>f(w),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(P,{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(fl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(bl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function Sk({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:v="all",onForm16FinancialYearChange:w,onForm16QuarterChange:A,onSearchChange:C,onStatusChange:E,onPriorityChange:D,onTemplateTypeChange:T,onDepartmentChange:N,onSlaComplianceChange:_,onInitiatorChange:I,onApproverChange:B,onApproverTypeChange:k,onDateRangeChange:M,onCustomStartDateChange:L,onCustomEndDateChange:F,onShowCustomDatePickerChange:S,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(P,{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:R=>C(R.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:E,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:w??(()=>{}),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:v,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:N,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(R=>e.jsx(X,{value:R,children:R},R))]})]}),e.jsxs(He,{value:i,onValueChange:_,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(P,{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:R=>f.handleSearch(R.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(R=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(R),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:R.displayName||R.email}),R.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:R.email})]})},R.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:R=>k(R),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(P,{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:R=>b.handleSearch(R.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(R=>e.jsx("button",{type:"button",onClick:()=>b.handleSelect(R),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:R.displayName||R.email}),R.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:R.email})]})},R.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:R=>M(R),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:S,children:[e.jsx(ra,{asChild:!0,children:e.jsxs(P,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ft,{className:"w-4 h-4"}),m&&p?`${tt(m,"MMM d, yyyy")} - ${tt(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:R=>{const H=R?new Date(R):void 0;H?(L==null||L(H),p&&H>p&&(F==null||F(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:R=>{const H=R?new Date(R):void 0;H?(F==null||F(H),m&&H<m&&(L==null||L(H))):F==null||F(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(P,{size:"sm",onClick:G,disabled:!m||!p,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply Range"}),e.jsx(P,{size:"sm",variant:"outline",onClick:()=>{S==null||S(!1),L==null||L(void 0),F==null||F(void 0),M("month")},children:"Cancel"})]})]})})]})]})]})})})}function Ak({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,C,E,D,T,N,_,I,B;if(!ni(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=rf(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=nf(s,a),v=lf(y),w={name:((A=s.initiator)==null?void 0:A.name)||((C=s.initiator)==null?void 0:C.displayName)||((E=s.initiator)==null?void 0:E.email)||"Unknown",role:((D=s.initiator)==null?void 0:D.role)||((T=s.initiator)==null?void 0:T.designation)||"Initiator",department:((N=s.initiator)==null?void 0:N.department)||s.department||"",email:((_=s.initiator)==null?void 0:_.email)||"N/A",phone:((I=s.initiator)==null?void 0:I.phone)||((B=s.initiator)==null?void 0:B.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(q5,{activityInfo:j.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(ek,{dealerInfo:j.dealerInfo}),v.showProposalDetails&&j.proposalDetails&&e.jsx(sk,{proposalDetails:j.proposalDetails}),e.jsx(ak,{initiatorInfo:w}),(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 ",w.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(P,{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(ui,{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(P,{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 Tk({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(v){console.error("Failed to approve request:",v),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(v){console.error("Failed to reject request:",v),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:v=>m(v.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(P,{variant:"outline",onClick:y,disabled:p,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{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(P,{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 kk({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"}):"",v=(n==null?void 0:n.creditNoteAmount)||0,w=(n==null?void 0:n.transactionNo)||"",A=(n==null?void 0:n.tdsAmount)||0,C=(n==null?void 0:n.creditAmount)||0,E=(n==null?void 0:n.status)||"PENDING",D=(n==null?void 0:n.items)||[],T=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",N=(i==null?void 0:i.dealerCode)||"RE-JP-009",_=l||"Activity",I=o||"RE-REQ-2024-CM-101",B=d?bs(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",k=(()=>{var S,G;if(D.length>1){const U=(S=D[0])==null?void 0:S.transactionNo,$=(G=D[D.length-1])==null?void 0:G.transactionNo;return U&&$&&U!==$?`${U} - ${$}`:U||w||"N/A"}return w||"N/A"})(),M=async()=>{if(a)try{u(!0),await a(),W.success("Credit note downloaded successfully")}catch(S){console.error("Failed to download credit note:",S),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(S){console.error("Failed to send credit note to dealer:",S),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")},F=S=>`₹${S.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"}),E==="APPROVED"?"Approved":E==="ISSUED"?"Issued":E==="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(Eo,{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:F(v)})]}),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:F(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:F(C)})]})]}),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((S,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:S.slNo}),e.jsx("td",{className:"px-4 py-2.5 font-medium text-slate-900 font-mono text-[11px]",children:S.transactionNo||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:S.hsnCd||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-right font-medium text-slate-700",children:F(S.claimAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-orange-600 font-medium",children:F(S.tdsAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-emerald-700 font-bold",children:F(S.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(gl,{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:N})]}),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:_})]})]})]}),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:I})]}),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(P,{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(P,{variant:"outline",onClick:M,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(P,{onClick:L,disabled:p||h,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(ap,{className:"w-4 h-4 mr-2"}),h?"Sending...":"Send to Dealer"]})]})})]})]})})}var uh=1,Dk=.9,Rk=.8,Fk=.17,ho=.1,po=.999,Ik=.9999,Pk=.99,Ek=/[\\\/_+.#"@\[\(\{&]/,_k=/[\\\/_+.#"@\[\(\{&]/g,Mk=/[\s-]/,xf=/[\s-]/g;function ic(t,s,a,r,n,i,l){if(i===s.length)return n===t.length?uh:Pk;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=ic(t,s,a,r,d+1,i+1,l),p>m&&(d===n?p*=uh:Ek.test(t.charAt(d-1))?(p*=Rk,h=t.slice(n,d-1).match(_k),h&&n>0&&(p*=Math.pow(po,h.length))):Mk.test(t.charAt(d-1))?(p*=Dk,g=t.slice(n,d-1).match(xf),g&&n>0&&(p*=Math.pow(po,g.length))):(p*=Fk,n>0&&(p*=Math.pow(po,d-n))),t.charAt(d)!==s.charAt(i)&&(p*=Ik)),(p<ho&&a.charAt(d-1)===r.charAt(i+1)||r.charAt(i+1)===r.charAt(i)&&a.charAt(d-1)!==r.charAt(i))&&(u=ic(t,s,a,r,d+1,i+2,l),u*ho>p&&(p=u*ho)),p>m&&(m=p),d=a.indexOf(c,d+1);return l[o]=m,m}function xh(t){return t.toLowerCase().replace(xf," ")}function Lk(t,s,a){return t=a&&a.length>0?`${t+" "+a.join(" ")}`:t,ic(t,s,xh(t),xh(s),0,0,{})}var _n='[cmdk-group=""]',go='[cmdk-group-items=""]',Ok='[cmdk-group-heading=""]',hf='[cmdk-item=""]',hh=`${hf}:not([aria-disabled="true"])`,lc="cmdk-item-select",qr="data-value",$k=(t,s,a)=>Lk(t,s,a),pf=x.createContext(void 0),yi=()=>x.useContext(pf),gf=x.createContext(void 0),Cd=()=>x.useContext(gf),ff=x.createContext(void 0),bf=x.forwardRef((t,s)=>{let a=en(()=>{var R,H;return{search:"",value:(H=(R=t.value)!=null?R:t.defaultValue)!=null?H:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=en(()=>new Set),n=en(()=>new Map),i=en(()=>new Map),l=en(()=>new Set),o=jf(t),{label:c,children:d,value:m,onValueChange:p,filter:u,shouldFilter:h,loop:g,disablePointerSelection:f=!1,vimBindings:b=!0,...j}=t,y=on(),v=on(),w=on(),A=x.useRef(null),C=Xk();Vr(()=>{if(m!==void 0){let R=m.trim();a.current.value=R,E.emit()}},[m]),Vr(()=>{C(6,B)},[]);let E=x.useMemo(()=>({subscribe:R=>(l.current.add(R),()=>l.current.delete(R)),snapshot:()=>a.current,setState:(R,H,K)=>{var z,O,V,Q;if(!Object.is(a.current[R],H)){if(a.current[R]=H,R==="search")I(),N(),C(1,_);else if(R==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let q=document.getElementById(w);q?q.focus():(z=document.getElementById(y))==null||z.focus()}if(C(7,()=>{var q;a.current.selectedItemId=(q=k())==null?void 0:q.id,E.emit()}),K||C(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}}E.emit()}},emit:()=>{l.current.forEach(R=>R())}}),[]),D=x.useMemo(()=>({value:(R,H,K)=>{var z;H!==((z=i.current.get(R))==null?void 0:z.value)&&(i.current.set(R,{value:H,keywords:K}),a.current.filtered.items.set(R,T(H,K)),C(2,()=>{N(),E.emit()}))},item:(R,H)=>(r.current.add(R),H&&(n.current.has(H)?n.current.get(H).add(R):n.current.set(H,new Set([R]))),C(3,()=>{I(),N(),a.current.value||_(),E.emit()}),()=>{i.current.delete(R),r.current.delete(R),a.current.filtered.items.delete(R);let K=k();C(4,()=>{I(),(K==null?void 0:K.getAttribute("id"))===R&&_(),E.emit()})}),group:R=>(n.current.has(R)||n.current.set(R,new Set),()=>{i.current.delete(R),n.current.delete(R)}),filter:()=>o.current.shouldFilter,label:c||t["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:y,inputId:w,labelId:v,listInnerRef:A}),[]);function T(R,H){var K,z;let O=(z=(K=o.current)==null?void 0:K.filter)!=null?z:$k;return R?O(R,a.current.search,H):0}function N(){if(!a.current.search||o.current.shouldFilter===!1)return;let R=a.current.filtered.items,H=[];a.current.filtered.groups.forEach(z=>{let O=n.current.get(z),V=0;O.forEach(Q=>{let q=R.get(Q);V=Math.max(q,V)}),H.push([z,V])});let K=A.current;M().sort((z,O)=>{var V,Q;let q=z.getAttribute("id"),ee=O.getAttribute("id");return((V=R.get(ee))!=null?V:0)-((Q=R.get(q))!=null?Q:0)}).forEach(z=>{let O=z.closest(go);O?O.appendChild(z.parentElement===O?z:z.closest(`${go} > *`)):K.appendChild(z.parentElement===K?z:z.closest(`${go} > *`))}),H.sort((z,O)=>O[1]-z[1]).forEach(z=>{var O;let V=(O=A.current)==null?void 0:O.querySelector(`${_n}[${qr}="${encodeURIComponent(z[0])}"]`);V==null||V.parentElement.appendChild(V)})}function _(){let R=M().find(K=>K.getAttribute("aria-disabled")!=="true"),H=R==null?void 0:R.getAttribute(qr);E.setState("value",H||void 0)}function I(){var R,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=(R=i.current.get(V))==null?void 0:R.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 R,H,K;let z=k();z&&(((R=z.parentElement)==null?void 0:R.firstChild)===z&&((K=(H=z.closest(_n))==null?void 0:H.querySelector(Ok))==null||K.scrollIntoView({block:"nearest"})),z.scrollIntoView({block:"nearest"}))}function k(){var R;return(R=A.current)==null?void 0:R.querySelector(`${hf}[aria-selected="true"]`)}function M(){var R;return Array.from(((R=A.current)==null?void 0:R.querySelectorAll(hh))||[])}function L(R){let H=M()[R];H&&E.setState("value",H.getAttribute(qr))}function F(R){var H;let K=k(),z=M(),O=z.findIndex(Q=>Q===K),V=z[O+R];(H=o.current)!=null&&H.loop&&(V=O+R<0?z[z.length-1]:O+R===z.length?z[0]:z[O+R]),V&&E.setState("value",V.getAttribute(qr))}function S(R){let H=k(),K=H==null?void 0:H.closest(_n),z;for(;K&&!z;)K=R>0?Qk(K,_n):Kk(K,_n),z=K==null?void 0:K.querySelector(hh);z?E.setState("value",z.getAttribute(qr)):F(R)}let G=()=>L(M().length-1),U=R=>{R.preventDefault(),R.metaKey?G():R.altKey?S(1):F(1)},$=R=>{R.preventDefault(),R.metaKey?L(0):R.altKey?S(-1):F(-1)};return x.createElement(pr.div,{ref:s,tabIndex:-1,...j,"cmdk-root":"",onKeyDown:R=>{var H;(H=j.onKeyDown)==null||H.call(j,R);let K=R.nativeEvent.isComposing||R.keyCode===229;if(!(R.defaultPrevented||K))switch(R.key){case"n":case"j":{b&&R.ctrlKey&&U(R);break}case"ArrowDown":{U(R);break}case"p":case"k":{b&&R.ctrlKey&&$(R);break}case"ArrowUp":{$(R);break}case"Home":{R.preventDefault(),L(0);break}case"End":{R.preventDefault(),G();break}case"Enter":{R.preventDefault();let z=k();if(z){let O=new Event(lc);z.dispatchEvent(O)}}}}},x.createElement("label",{"cmdk-label":"",htmlFor:D.inputId,id:D.labelId,style:Jk},c),Pl(t,R=>x.createElement(gf.Provider,{value:E},x.createElement(pf.Provider,{value:D},R))))}),Uk=x.forwardRef((t,s)=>{var a,r;let n=on(),i=x.useRef(null),l=x.useContext(ff),o=yi(),c=jf(t),d=(r=(a=c.current)==null?void 0:a.forceMount)!=null?r:l==null?void 0:l.forceMount;Vr(()=>{if(!d)return o.item(n,l==null?void 0:l.id)},[d]);let m=yf(n,i,[t.value,t.children,i],t.keywords),p=Cd(),u=hr(C=>C.value&&C.value===m.current),h=hr(C=>d||o.filter()===!1?!0:C.search?C.filtered.items.get(n)>0:!0);x.useEffect(()=>{let C=i.current;if(!(!C||t.disabled))return C.addEventListener(lc,g),()=>C.removeEventListener(lc,g)},[h,t.onSelect,t.disabled]);function g(){var C,E;f(),(E=(C=c.current).onSelect)==null||E.call(C,m.current)}function f(){p.setState("value",m.current,!0)}if(!h)return null;let{disabled:b,value:j,onSelect:y,forceMount:v,keywords:w,...A}=t;return x.createElement(pr.div,{ref:Kn(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)}),Bk=x.forwardRef((t,s)=>{let{heading:a,children:r,forceMount:n,...i}=t,l=on(),o=x.useRef(null),c=x.useRef(null),d=on(),m=yi(),p=hr(h=>n||m.filter()===!1?!0:h.search?h.filtered.groups.has(l):!0);Vr(()=>m.group(l),[]),yf(l,o,[t.value,t.heading,c]);let u=x.useMemo(()=>({id:l,forceMount:n}),[n]);return x.createElement(pr.div,{ref:Kn(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),Pl(t,h=>x.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":a?d:void 0},x.createElement(ff.Provider,{value:u},h))))}),Vk=x.forwardRef((t,s)=>{let{alwaysRender:a,...r}=t,n=x.useRef(null),i=hr(l=>!l.search);return!a&&!i?null:x.createElement(pr.div,{ref:Kn(n,s),...r,"cmdk-separator":"",role:"separator"})}),zk=x.forwardRef((t,s)=>{let{onValueChange:a,...r}=t,n=t.value!=null,i=Cd(),l=hr(d=>d.search),o=hr(d=>d.selectedItemId),c=yi();return x.useEffect(()=>{t.value!=null&&i.setState("search",t.value)},[t.value]),x.createElement(pr.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)}})}),Hk=x.forwardRef((t,s)=>{let{children:a,label:r="Suggestions",...n}=t,i=x.useRef(null),l=x.useRef(null),o=hr(d=>d.selectedItemId),c=yi();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(pr.div,{ref:Kn(i,s),...n,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},Pl(t,d=>x.createElement("div",{ref:Kn(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),Gk=x.forwardRef((t,s)=>{let{open:a,onOpenChange:r,overlayClassName:n,contentClassName:i,container:l,...o}=t;return x.createElement($h,{open:a,onOpenChange:r},x.createElement(Oh,{container:l},x.createElement(cc,{"cmdk-overlay":"",className:n}),x.createElement(dc,{"aria-label":t.label,"cmdk-dialog":"",className:i},x.createElement(bf,{ref:s,...o}))))}),Wk=x.forwardRef((t,s)=>hr(a=>a.filtered.count===0)?x.createElement(pr.div,{ref:s,...t,"cmdk-empty":"",role:"presentation"}):null),Yk=x.forwardRef((t,s)=>{let{progress:a,children:r,label:n="Loading...",...i}=t;return x.createElement(pr.div,{ref:s,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":100,"aria-label":n},Pl(t,l=>x.createElement("div",{"aria-hidden":!0},l)))}),An=Object.assign(bf,{List:Hk,Item:Uk,Input:zk,Group:Bk,Separator:Vk,Dialog:Gk,Empty:Wk,Loading:Yk});function Qk(t,s){let a=t.nextElementSibling;for(;a;){if(a.matches(s))return a;a=a.nextElementSibling}}function Kk(t,s){let a=t.previousElementSibling;for(;a;){if(a.matches(s))return a;a=a.previousElementSibling}}function jf(t){let s=x.useRef(t);return Vr(()=>{s.current=t}),s}var Vr=typeof window>"u"?x.useEffect:x.useLayoutEffect;function en(t){let s=x.useRef();return s.current===void 0&&(s.current=t()),s}function hr(t){let s=Cd(),a=()=>t(s.snapshot());return x.useSyncExternalStore(s.subscribe,a,a)}function yf(t,s,a,r=[]){let n=x.useRef(),i=yi();return Vr(()=>{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(qr,o),n.current=o}),n}var Xk=()=>{let[t,s]=x.useState(),a=en(()=>new Map);return Vr(()=>{a.current.forEach(r=>r()),a.current=new Map},[t]),(r,n)=>{a.current.set(r,n),s({})}};function Zk(t){let s=t.type;return typeof s=="function"?s(t.props):"render"in s?s.render(t.props):t}function Pl({asChild:t,children:s},a){return t&&x.isValidElement(s)?x.cloneElement(Zk(s),{ref:s.ref},a(s.props.children)):a(s)}var Jk={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function qk({className:t,...s}){return e.jsx(An,{"data-slot":"command",className:Le("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",t),...s})}function e4({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(An.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 t4({className:t,...s}){return e.jsx(An.List,{"data-slot":"command-list",className:Le("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",t),...s})}function s4({...t}){return e.jsx(An.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...t})}function a4({className:t,...s}){return e.jsx(An.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 r4({className:t,...s}){return e.jsx(An.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 vf(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 n4(t){var a;const s=await ve.post("/hsn-sac",t);return((a=s.data)==null?void 0:a.data)||s.data}async function i4(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 l4(t){await ve.delete(`/hsn-sac/${t}`)}async function o4(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 Nf({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 vf(!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(P,{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(Fj,{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(qk,{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(e4,{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(t4,{className:"max-h-[350px] scrollbar-thin scrollbar-thumb-slate-200",children:[e.jsx(s4,{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(a4,{className:"p-1.5",children:m.map(u=>e.jsxs(r4,{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:""}},c4={"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"},d4="33",m4=new Set(["04","25","26","31","35","38"]),wf=t=>{if(!t||t.length<2)return null;const s=t.substring(0,2);return c4[s]?s:null},u4=t=>t?m4.has(t):!1,x4=t=>t?t!==d4:!1,Cf=t=>{if(!t)return{isIGST:!1,isCGST:!0,isSGST:!0,isUTGST:!1};if(x4(t))return{isIGST:!0,isCGST:!1,isSGST:!1,isUTGST:!1};const a=u4(t);return{isIGST:!1,isCGST:!0,isSGST:!a,isUTGST:a}};function h4({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=wf(n);return Cf(ne)},[n]),f=x.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),[b,j]=x.useState([]),[y,v]=x.useState([]),[w,A]=x.useState([]),[C,E]=x.useState([]),[D,T]=x.useState(null),[N,_]=x.useState(""),[I,B]=x.useState(!1),[k,M]=x.useState(null),L=x.useRef(null),F=x.useRef(null),S=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);M({file:ne,url:ge})},R=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,at=je+ie+Se+qe,gt=Oe+at;return{cgstRate:ge.cgstRate,cgstAmt:je,sgstRate:ge.sgstRate,sgstAmt:ie,utgstRate:ge.utgstRate,utgstAmt:Se,igstRate:ge.igstRate,igstAmt:qe,gstAmt:at,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=w.length>0,Oe=N.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,w,N,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 at=Oe.cgstRate,gt=Oe.sgstRate,It=Oe.utgstRate,oe=Oe.igstRate;if(ge==="cgstRate"){if(!g.isCGST)return Oe;at=parseFloat(ke)||0,g.isUTGST?(It=at,gt=0):(gt=at,It=0),oe=0}else if(ge==="sgstRate"){if(!g.isSGST)return Oe;gt=parseFloat(ke)||0,at=gt,It=0,oe=0}else if(ge==="utgstRate"){if(!g.isUTGST)return Oe;It=parseFloat(ke)||0,at=It,gt=0,oe=0}else if(ge==="igstRate"){if(!g.isIGST)return Oe;oe=parseFloat(ke)||0,at=0,gt=0,It=0}else if(ge==="gstRate"){const me=parseFloat(ke)||0;g.isIGST?(oe=me,at=0,gt=0,It=0):(at=me/2,g.isUTGST?(It=me/2,gt=0):(gt=me/2,It=0),oe=0)}const Me=K(Se,{cgstRate:at,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 at,gt;const Se="."+((at=ie.name.split(".").pop())==null?void 0:at.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&&v([...y,...ke]),L.current&&(L.current.value="")}},te=ne=>{v(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([...w,...ke]),F.current&&(F.current.value="")}},_e=ne=>{A(w.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 at,gt;const Se="."+((at=ie.name.split(".").pop())==null?void 0:at.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&&E([...C,...ke]),S.current&&(S.current.value="")}},Ue=ne=>{E(C.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()),at=((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(at)){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:w,invoicesReceipts:C.length>0?C:void 0,attendanceSheet:D||void 0,completionDescription:N}),le(),s()}catch(Oe){console.error("Failed to submit completion documents:",Oe),vd(Oe)||W.error("Failed to submit completion documents. Please try again.")}finally{B(!1)}},le=()=>{k!=null&&k.url&&URL.revokeObjectURL(k.url),M(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}]),v([]),A([]),E([]),T(null),_(""),L.current&&(L.current.value=""),F.current&&(F.current.value=""),S.current&&(S.current.value=""),G.current&&(G.current.value="")},ye=()=>{I||(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(P,{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(Nf,{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(P,{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(P,{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(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>R(ne),title:"Download file",children:e.jsx(Tt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{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(Pi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Photos *"]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload photos from the completed activity (event photos, installations, etc.)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${w.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:F,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:w.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:[w.length," photo",w.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-green-600",children:"Click to add more photos"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Pi,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload photos (JPG, PNG - multiple files allowed)"})]})})]}),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 Photos (",w.length,"):"]}),w.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(Pi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-green-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:ne.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[U(ne)&&e.jsx(P,{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(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>R(ne),title:"Download photo",children:e.jsx(Tt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{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 ${C.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:S,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:C.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:[C.length," document",C.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)"})]})})]}),C.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 (",C.length,"):"]}),C.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(P,{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(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>R(ne),title:"Download file",children:e.jsx(Tt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{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(P,{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(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>R(D),title:"Download file",children:e.jsx(Tt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{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:N,onChange:ne=>_(ne.target.value),className:"min-h-[100px] sm:min-h-[120px] text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[N.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(P,{variant:"outline",onClick:ye,disabled:I,className:"border-2",children:"Cancel"}),e.jsx(P,{onClick:De,disabled:I||!z,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:I?"Submitting...":"Submit Documents"})]})]})}),k&&e.jsx(xt,{open:!!k,onOpenChange:()=>{k!=null&&k.url&&URL.revokeObjectURL(k.url),M(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(P,{variant:"outline",size:"sm",onClick:()=>R(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(P,{onClick:()=>R(k.file),className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",k.file.name]})]})})]})})})]})}function p4({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=wf(n);return Cf(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}},[v,w]=x.useState("date"),[A,C]=x.useState(""),[E,D]=x.useState(""),[T,N]=x.useState([]),[_,I]=x.useState(""),[B,k]=x.useState(!1),[M,L]=x.useState(null),[F,S]=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)},R=le=>$(le.name);x.useEffect(()=>()=>{M!=null&&M.fileUrl&&M.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(M.fileUrl)},[M]);const H=le=>{if(!R(le)){W.error("Preview is only available for images and PDF files");return}M!=null&&M.fileUrl&&M.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(M.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=Nn(ae);else if(ne=le.storageUrl||le.documentUrl||"",ne&&!ne.startsWith("http")){const ge="http://localhost:5000",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&&(C(o.expectedCompletionDate.split("T")[0]),w("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}]),C(""),I(""))},[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=v==="date"?A!=="":E!==""&&parseInt(E)>0,he=_.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,v,A,E,_,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&&N(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,at=ne.igstRate;if(ye==="cgstRate"){if(!g.isCGST)return ne;ie=parseFloat(ae)||0,g.isUTGST?(qe=ie,Se=0):(Se=ie,qe=0),at=0}else if(ye==="sgstRate"){if(!g.isSGST)return ne;Se=parseFloat(ae)||0,ie=Se,qe=0,at=0}else if(ye==="utgstRate"){if(!g.isUTGST)return ne;qe=parseFloat(ae)||0,ie=qe,Se=0,at=0}else if(ye==="igstRate"){if(!g.isIGST)return ne;at=parseFloat(ae)||0,ie=0,Se=0,qe=0}else if(ye==="gstRate"){const It=parseFloat(ae)||0;g.isIGST?(at=It,ie=0,Se=0,qe=0):(ie=It/2,g.isUTGST?(qe=It/2,Se=0):(Se=It/2,qe=0),at=0)}const gt=y(Oe,{cgstRate:ie,sgstRate:Se,igstRate:at,utgstRate:qe},je);return{...ge,amount:Oe,quantity:je,...gt}}return ge}return ne}))},_e=le=>{N(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(v==="days"&&(parseInt(E)<=0||isNaN(parseInt(E)))){W.error("Please enter a valid number of days greater than 0");return}let ye=A||"";if(v==="days"&&E){const ae=parseInt(E),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:v,expectedCompletionDays:v==="days"?parseInt(E):0,otherDocuments:T,dealerComments:_}),Ue(),s()}catch(ae){console.error("Failed to submit proposal:",ae),vd(ae)||W.error("Failed to submit proposal. Please try again.")}finally{k(!1)}},Ue=()=>{M!=null&&M.fileUrl&&M.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(M.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}]),w("date"),C(""),D(""),N([]),I(""),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:()=>S(!F),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(P,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:F?e.jsx(fc,{className:"w-4 h-4"}):e.jsx(ms,{className:"w-4 h-4"})})]}),F&&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(Ur,{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="http://localhost:5000",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:[R(u)&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>H(u),className:"h-7 text-[10px]",children:"Preview"}),e.jsx(P,{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(P,{type:"button",onClick:()=>w("date"),className:v==="date"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Date"}),e.jsx(P,{type:"button",onClick:()=>w("days"),className:v==="days"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Days"})]}),v==="date"?e.jsx(ta,{value:A||null,onChange:le=>C(le||""),minDate:De,placeholderText:"dd/mm/yyyy",className:"w-full"}):e.jsx(Re,{type:"number",placeholder:"Enter number of days",min:"1",value:E,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(P,{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(P,{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(Nf,{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:[R(le)&&e.jsx(P,{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(P,{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(P,{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:_,onChange:le=>I(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(P,{variant:"outline",onClick:Pe,disabled:B,className:"border-2",children:"Cancel"}),e.jsx(P,{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"})]})]}),M&&e.jsx(Wr,{fileName:M.fileName||"",fileType:M.fileType||"",fileUrl:M.fileUrl||"",fileSize:M.fileSize||0,attachmentId:M.documentId||"",onDownload:Ms,open:!!M,onClose:()=>L(null)})]})}function g4({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,v=500,w=x.useMemo(()=>(m==="reject"||j.trim().length>0)&&u.trim().length>0,[m,j,u]),A=async()=>{if(!w){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()),C(),s()}catch(D){console.error(`Failed to ${m} request:`,D),W.error(`Failed to ${m} request. Please try again.`)}finally{f(!1)}},C=()=>{p("approve"),h("")},E=()=>{g||(C(),s())};return e.jsx(xt,{open:t,onOpenChange:E,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(P,{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(P,{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<=v&&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,"/",v]})]})]})]})]})}),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(P,{variant:"outline",onClick:E,disabled:g,className:"text-sm lg:text-base",children:"Cancel"}),e.jsx(P,{onClick:A,disabled:!w||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 f4({isOpen:t,onClose:s,onPush:a,onReQuotation:r,completionDetails:n,ioDetails:i,completionDocuments:l,requestTitle:o,requestNumber:c,taxationType:d}){var k,M;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),v=p.length,w=500,A=x.useMemo(()=>n!=null&&n.totalClosedExpenses?n.totalClosedExpenses:n!=null&&n.closedExpenses&&Array.isArray(n.closedExpenses)?n.closedExpenses.reduce((L,F)=>{const S=typeof F=="object"&&F.amount||0,G=typeof F=="object"&&F.gstAmt||0,U=F.totalAmt||S+G;return L+(Number(U)||0)},0):0,[n]),C=L=>{if(!L)return"—";try{return new Date(L).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return L}},E=L=>`₹${L.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,D=L=>{if(!L.name)return!1;const F=L.name.toLowerCase();return F.endsWith(".pdf")||F.endsWith(".jpg")||F.endsWith(".jpeg")||F.endsWith(".png")||F.endsWith(".gif")||F.endsWith(".webp")},T=async L=>{if(!L.id){W.error("Document preview not available - document ID missing");return}y(!0);try{const F=Nn(L.id),S=L.name.toLowerCase(),G=S.endsWith(".pdf"),U=S.match(/\.(jpg|jpeg|png|gif|webp)$/i),$=!0,R=$?null:localStorage.getItem("accessToken"),K=await fetch(F,{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(F){console.error("Failed to load document preview:",F),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 N=async()=>{if(!p.trim()){W.error("Please provide comments before proceeding");return}try{g(!0),await a(p.trim()),_(),s()}catch(L){console.error("Failed to generate e-invoice:",L),W.error("Failed to generate e-invoice. Please try again.")}finally{g(!1)}},_=()=>{u("")},I=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()),_(),s()}catch(L){console.error("Failed to request re-quotation:",L)}finally{g(!1)}},B=()=>{h||(_(),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:C(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:E(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:E(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,F)=>{const S=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||S+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 ${F+1}`}),e.jsx("span",{className:"font-bold text-gray-900",children:E($)})]}),e.jsxs("div",{className:"sm:hidden flex justify-between w-full text-xs text-gray-500",children:[e.jsxs("span",{children:["Base: ",E(S)]}),!m&&e.jsxs("span",{children:["GST: ",G,"% (",E(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 ${F+1}`})}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:E(S)}),!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:E(U)})]}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right font-semibold text-gray-900",children:E($)})]},F)})}),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:E(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,F)=>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(S){console.error("Failed to download document:",S),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"})})]})]},F))})]}),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,F)=>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(S){console.error("Failed to download document:",S),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"})})]})]},F))})]}),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,F)=>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(S){console.error("Failed to download document:",S),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"})})]})]},F))})]}),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(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-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 F=L.target.value;F.length<=w&&u(F)},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:[v,"/",w]})]})]})]})}),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(P,{variant:"outline",onClick:B,disabled:h,children:"Cancel"}),r&&e.jsxs(P,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:I,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(P,{onClick:N,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(P,{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)||(M=f.type)!=null&&M.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(P,{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 b4({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(gl,{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(P,{variant:"outline",onClick:s,className:"h-9",children:[e.jsx(yt,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function j4({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),[v,w]=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(($,R)=>{const H=typeof R=="object"&&R.amount||0,K=typeof R=="object"&&R.quantity||1,z=H*K,O=typeof R=="object"&&R.gstAmt||0,V=R.totalAmt||z+O;return $+(Number(V)||0)},0):0},[i]),C=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(($,R)=>{const H=typeof R=="object"&&R.amount||0,K=typeof R=="object"&&R.quantity||1;return $+Number(H)*Number(K)},0):0},[i]),E=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((R,H)=>{const K=Number(H.ioBlockedAmount||H.io_blocked_amount||0);return R+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=E>=C-.01,T=Math.max(0,C-E),[N,_]=x.useState(null),I=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 R=U.id||U.documentId||"";if(!R&&!$){W.error("Document preview not available");return}if($&&!$.startsWith("http")&&!$.startsWith("blob:")){const H="http://localhost:5000",K=H.endsWith("/")?H.slice(0,-1):H,z=$.startsWith("/")?$:`/${$}`;$=`${K}${z}`}_({name:U.name||"Document",url:$||(R?Nn(R):""),type:(U.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:R})};x.useEffect(()=>()=>{N!=null&&N.url&&N.url.startsWith("blob:")&&window.URL.revokeObjectURL(N.url)},[N]);const M=async()=>{if(!h.trim()){W.error("Please provide approval comments");return}try{b(!0),y("approve"),await a(h),S(),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),S(),s()}catch(U){console.error("Failed to reject proposal:",U),W.error("Failed to reject proposal. Please try again.")}finally{b(!1),y(null)}},F=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),S(),s()}catch(U){console.error("Failed to request revision:",U),W.error("Failed to request revision. Please try again.")}finally{b(!1),y(null)}},S=()=>{g(""),y(null)},G=()=>{f||(S(),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:()=>w(!v),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(P,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:v?e.jsx(fc,{className:"w-4 h-4"}):e.jsx(ms,{className:"w-4 h-4"})})]}),v&&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(Ur,{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 R=>{if(R)await Ms(R);else{let H=U.storageUrl||U.documentUrl;if(H&&!H.startsWith("http")){const K="http://localhost:5000",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 ",I(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(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-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(($,R)=>{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)||R)})})]}),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?I(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(P,{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(P,{onClick:F,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(P,{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(P,{onClick:M,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:E>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."})]})]})]}),N&&e.jsx(Wr,{fileName:N.name,fileType:N.type||"",fileUrl:N.url,fileSize:N.size,attachmentId:N.id,onDownload:Ms,open:!!N,onClose:()=>_(null)})]}):null}function y4({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=Nn(f);else if(j=h.storageUrl||h.documentUrl||"",j&&!j.startsWith("http")){const y="http://localhost:5000",v=y.endsWith("/")?y.slice(0,-1):y,w=j.startsWith("/")?j:`/${j}`;j=`${v}${w}`}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(Ur,{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="http://localhost:5000",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(Ur,{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="http://localhost:5000",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(Xh,{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(P,{onClick:s,children:"Close"})})]})}),i&&e.jsx(Wr,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:Ms,open:!!i,onClose:()=>l(null)})]})}async function v4(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 N4(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 w4(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 C4(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 S4(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 Sf(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 A4(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 T4(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 k4(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 D4(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 Jr=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}}},R4=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"})}},F4=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"}},I4=(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",P4=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 E4({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i,isSpectator:l=!1}){var yr,vr,er,Pa,tr,Qt,As,la,Nr,wr,Sa,sr,Rt,xs,Xs,xa,Xr,Aa,ar,Tn,kn,Dn,Td,kd,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;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),[v,w]=x.useState(!1),[A,C]=x.useState(null),[E,D]=x.useState(!1),[T,N]=x.useState(null),[_,I]=x.useState([]),[B,k]=x.useState(!1),[M,L]=x.useState(new Set),[F,S]=x.useState(null),[G,U]=x.useState(null),[$,R]=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 H1(t.id||t.requestId)||[]].sort((Ce,xe)=>new Date(xe.createdAt).getTime()-new Date(Ce.createdAt).getTime());I($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(!_||_.length===0||!Y)return{current:null,previous:null};const xe=[..._.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=((yr=s==null?void 0:s.email)==null?void 0:yr.toLowerCase())||"",je=((vr=t==null?void 0:t.dealerEmail)==null?void 0:vr.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(),at=qe&&Oe===qe,gt=((wr=(Nr=t==null?void 0:t.initiator)==null?void 0:Nr.email)==null?void 0:wr.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),rt=((Qe==null?void 0:Qe.approverEmail)||"").toLowerCase(),Ke=rt&&Oe===rt,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 Vn(Y.proposalDocument,xe,"APPROVAL");for(const pe of Y.otherDocuments)await Vn(pe,xe,"SUPPORTING");const Ne=Y.costBreakup.reduce((pe,Ie)=>pe+(Ie.totalAmt||Ie.amount||0),0);await w4(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 Un(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 Dr(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 Dr(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 Dr(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 Sf(xe,{ioNumber:Y.ioNumber}),await Un(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 C4(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 Vn(pe,xe,"SUPPORTING");Y.attendanceSheet&&await Vn(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 A4(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 Dr(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}},[fr,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 D4(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"})}},Yr=async()=>{try{const Y=t.id||t.requestId;if(!Y){W.error("Request ID not found");return}const Ce=await fetch(`http://localhost:5000/api/v1/dealer-claims/${Y}/e-invoice/csv`,{headers:{Authorization:`Bearer ${nt.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")}},Qr=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),R(!0);const Ce=await fetch(`http://localhost:5000/api/v1/dealer-claims/${Y}/e-invoice/pdf`,{headers:{Authorization:`Bearer ${nt.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"),R(!1)}finally{K(!1)}},br=()=>{R(!1),G&&(window.URL.revokeObjectURL(G),U(null))},Kr=()=>{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",jr=((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=((Xr=t==null?void 0:t.claimDetails)==null?void 0:Xr.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 ${I4(Y.status,pe)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${P4(Y.status)}`,children:R4(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:F4(Y.status),children:Y.status.toLowerCase()}),Y.emailTemplateUrl&&Y.status==="approved"&&e.jsx(P,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>{C({stepNumber:Y.step,stepName:Y.title}),w(!0)},children:e.jsx(va,{className:"w-3.5 h-3.5 text-blue-600"})}),Y.step===7&&Y.einvoiceUrl&&Ie&&e.jsx(P,{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(P,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-amber-100",title:"Preview Invoice",onClick:Qr,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(P,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-emerald-100",title:"Export CSV",onClick:Yr,children:e.jsx(rp,{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(P,{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(P,{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(P,{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(M);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(lp,{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"]})]}),M.has(Y.step)?e.jsx(cl,{className:"w-4 h-4"}):e.jsx(bn,{className:"w-4 h-4"})]}),M.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:Jr(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:()=>S({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:()=>S({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(Ki,{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?Jr(Y.ioDetails.organizedAt):Y.approvedAt?Jr(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"," ",Jr(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(P,{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(P,{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 og(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 Wf=((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(Wf)}};return e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(P,{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(P,{variant:"outline",className:"border-blue-500 text-blue-600 hover:bg-blue-50",onClick:()=>At("REOPEN"),children:[e.jsx(ep,{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||at))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(P,{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(P,{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(P,{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(P,{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(P,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{N({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(P,{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 Un(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(P,{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 Dr(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 ",Jr(Y.approvedAt)]})]})]})},$e)})})]})]}),e.jsx(p4,{isOpen:o,onClose:()=>c(!1),onSubmit:Hs,dealerName:Ja,dealerGSTIN:jr,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:(Tn=_==null?void 0:_.find(Y=>Y.snapshotType==="PROPOSAL"))==null?void 0:Tn.snapshotData,documentPolicy:i,taxationType:(kn=t==null?void 0:t.claimDetails)==null?void 0:kn.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(j4,{isOpen:d,onClose:()=>{m(!1)},onApprove:is,onReject:vt,onRequestRevision:pt,proposalData:fr,dealerName:Ja,activityName:qa,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const Y=(_==null?void 0:_.filter($e=>$e.snapshotType==="PROPOSAL"))||[];return Y.length>1?Y[1].snapshotData:null})(),taxationType:(Dn=t==null?void 0:t.claimDetails)==null?void 0:Dn.taxationType}),e.jsx(g4,{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:((Td=t==null?void 0:t.internalOrder)==null?void 0:Td.ioNumber)||((kd=t==null?void 0:t.internalOrder)==null?void 0:kd.io_number)||((Dd=t==null?void 0:t.internal_order)==null?void 0:Dd.ioNumber)||((Rd=t==null?void 0:t.internal_order)==null?void 0:Rd.io_number)||void 0,preFilledBlockedAmount:((Fd=t==null?void 0:t.internalOrder)==null?void 0:Fd.ioBlockedAmount)||((Id=t==null?void 0:t.internalOrder)==null?void 0:Id.io_blocked_amount)||((Pd=t==null?void 0:t.internal_order)==null?void 0:Pd.ioBlockedAmount)||((Ed=t==null?void 0:t.internal_order)==null?void 0:Ed.io_blocked_amount)||void 0,preFilledRemainingBalance:((_d=t==null?void 0:t.internalOrder)==null?void 0:_d.ioRemainingBalance)||((Md=t==null?void 0:t.internalOrder)==null?void 0:Md.io_remaining_balance)||((Ld=t==null?void 0:t.internal_order)==null?void 0:Ld.ioRemainingBalance)||((Od=t==null?void 0:t.internal_order)==null?void 0:Od.io_remaining_balance)||void 0,taxationType:($d=t==null?void 0:t.claimDetails)==null?void 0:$d.taxationType}),e.jsx(h4,{isOpen:h,onClose:()=>g(!1),onSubmit:as,dealerName:Ja,dealerGSTIN:jr,activityName:qa,defaultGstRate:(Ud=t==null?void 0:t.claimDetails)==null?void 0:Ud.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i,taxationType:(Bd=t==null?void 0:t.claimDetails)==null?void 0:Bd.taxationType}),e.jsx(f4,{isOpen:f,onClose:()=>b(!1),onPush:za,completionDetails:{activityCompletionDate:((Vd=t==null?void 0:t.completionDetails)==null?void 0:Vd.activityCompletionDate)||((zd=t==null?void 0:t.completionDetails)==null?void 0:zd.activity_completion_date),numberOfParticipants:((Hd=t==null?void 0:t.completionDetails)==null?void 0:Hd.numberOfParticipants)||((Gd=t==null?void 0:t.completionDetails)==null?void 0:Gd.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((Wd=t==null?void 0:t.completionDetails)==null?void 0:Wd.closedExpenses)||((Yd=t==null?void 0:t.completionDetails)==null?void 0:Yd.closed_expenses),totalClosedExpenses:((Qd=t==null?void 0:t.budgetTracking)==null?void 0:Qd.closedExpenses)||((Kd=t==null?void 0:t.budgetTracking)==null?void 0:Kd.closed_expenses)||((Xd=t==null?void 0:t.completionDetails)==null?void 0:Xd.totalClosedExpenses)||((Zd=t==null?void 0:t.completionDetails)==null?void 0:Zd.total_closed_expenses),completionDescription:((Jd=t==null?void 0:t.completionDetails)==null?void 0:Jd.completionDescription)||((qd=t==null?void 0:t.completionDetails)==null?void 0:qd.completion_description)},ioDetails:{ioNumber:((em=t==null?void 0:t.internalOrder)==null?void 0:em.ioNumber)||((tm=t==null?void 0:t.internalOrder)==null?void 0:tm.io_number)||((sm=t==null?void 0:t.internal_order)==null?void 0:sm.ioNumber)||((am=t==null?void 0:t.internal_order)==null?void 0:am.io_number),blockedAmount:((rm=t==null?void 0:t.internalOrder)==null?void 0:rm.ioBlockedAmount)||((nm=t==null?void 0:t.internalOrder)==null?void 0:nm.io_blocked_amount)||((im=t==null?void 0:t.internal_order)==null?void 0:im.ioBlockedAmount)||((lm=t==null?void 0:t.internal_order)==null?void 0:lm.io_blocked_amount),availableBalance:((om=t==null?void 0:t.internalOrder)==null?void 0:om.ioAvailableBalance)||((cm=t==null?void 0:t.internalOrder)==null?void 0:cm.io_available_balance)||((dm=t==null?void 0:t.internal_order)==null?void 0:dm.ioAvailableBalance)||((mm=t==null?void 0:t.internal_order)==null?void 0:mm.io_available_balance),remainingBalance:((um=t==null?void 0:t.internalOrder)==null?void 0:um.ioRemainingBalance)||((xm=t==null?void 0:t.internalOrder)==null?void 0:xm.io_remaining_balance)||((hm=t==null?void 0:t.internal_order)==null?void 0:hm.ioRemainingBalance)||((pm=t==null?void 0:t.internal_order)==null?void 0:pm.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:(gm=t==null?void 0:t.claimDetails)==null?void 0:gm.taxationType,onReQuotation:Pt}),e.jsx(kk,{isOpen:j,onClose:()=>y(!1),taxationType:(fm=t==null?void 0:t.claimDetails)==null?void 0:fm.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 T4(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:((bm=t==null?void 0:t.creditNote)==null?void 0:bm.creditNoteNumber)||((jm=t==null?void 0:t.creditNote)==null?void 0:jm.credit_note_number)||((vm=(ym=t==null?void 0:t.claimDetails)==null?void 0:ym.creditNote)==null?void 0:vm.creditNoteNumber)||((Nm=t==null?void 0:t.claimDetails)==null?void 0:Nm.creditNoteNumber)||((wm=t==null?void 0:t.claimDetails)==null?void 0:wm.credit_note_number),creditNoteDate:((Cm=t==null?void 0:t.creditNote)==null?void 0:Cm.creditNoteDate)||((Sm=t==null?void 0:t.creditNote)==null?void 0:Sm.credit_note_date)||((Tm=(Am=t==null?void 0:t.claimDetails)==null?void 0:Am.creditNote)==null?void 0:Tm.creditNoteDate)||((km=t==null?void 0:t.claimDetails)==null?void 0:km.creditNoteDate)||((Dm=t==null?void 0:t.claimDetails)==null?void 0:Dm.credit_note_date),creditNoteAmount:(Rm=t==null?void 0:t.creditNote)!=null&&Rm.creditNoteAmount?Number((Fm=t==null?void 0:t.creditNote)==null?void 0:Fm.creditNoteAmount):(Im=t==null?void 0:t.creditNote)!=null&&Im.credit_note_amount?Number((Pm=t==null?void 0:t.creditNote)==null?void 0:Pm.credit_note_amount):(_m=(Em=t==null?void 0:t.claimDetails)==null?void 0:Em.creditNote)!=null&&_m.creditNoteAmount?Number((Lm=(Mm=t==null?void 0:t.claimDetails)==null?void 0:Mm.creditNote)==null?void 0:Lm.creditNoteAmount):(Om=t==null?void 0:t.claimDetails)!=null&&Om.creditNoteAmount?Number(($m=t==null?void 0:t.claimDetails)==null?void 0:$m.creditNoteAmount):(Um=t==null?void 0:t.claimDetails)!=null&&Um.credit_note_amount?Number((Bm=t==null?void 0:t.claimDetails)==null?void 0:Bm.credit_note_amount):void 0,transactionNo:((Vm=t==null?void 0:t.creditNote)==null?void 0:Vm.transactionNo)||((zm=t==null?void 0:t.creditNote)==null?void 0:zm.transaction_no),tdsAmount:((Hm=t==null?void 0:t.creditNote)==null?void 0:Hm.tdsAmount)||((Gm=t==null?void 0:t.creditNote)==null?void 0:Gm.tds_amount),creditAmount:((Wm=t==null?void 0:t.creditNote)==null?void 0:Wm.creditAmount)||((Ym=t==null?void 0:t.creditNote)==null?void 0:Ym.credit_amount),items:((Qm=t==null?void 0:t.creditNote)==null?void 0:Qm.items)||[],status:((Km=t==null?void 0:t.creditNote)==null?void 0:Km.status)||((Zm=(Xm=t==null?void 0:t.claimDetails)==null?void 0:Xm.creditNote)==null?void 0:Zm.status)||((Jm=t==null?void 0:t.creditNote)!=null&&Jm.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((qm=t==null?void 0:t.claimDetails)==null?void 0:qm.dealerName)||((eu=t==null?void 0:t.claimDetails)==null?void 0:eu.dealer_name),dealerCode:((tu=t==null?void 0:t.claimDetails)==null?void 0:tu.dealerCode)||((su=t==null?void 0:t.claimDetails)==null?void 0:su.dealer_code),dealerEmail:((au=t==null?void 0:t.claimDetails)==null?void 0:au.dealerEmail)||((ru=t==null?void 0:t.claimDetails)==null?void 0:ru.dealer_email)},activityName:((nu=t==null?void 0:t.claimDetails)==null?void 0:nu.activityName)||((iu=t==null?void 0:t.claimDetails)==null?void 0:iu.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(b4,{isOpen:v,onClose:()=>{w(!1),C(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(Tk,{isOpen:E,onClose:()=>{D(!1),N(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 Un(xe,Ne,Y),W.success("Request approved successfully"),q(),D(!1),N(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 Dr(xe,Ne,"Request rejected",Y),W.success("Request rejected successfully"),q(),D(!1),N(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}),_&&_.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(P,{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:_.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:Jr(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(P,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-small flex items-center gap-1",onClick:()=>S({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(P,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-medium flex items-center gap-1",onClick:()=>S({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(y4,{isOpen:!!F,onClose:()=>S(null),snapshot:F==null?void 0:F.data,type:(F==null?void 0:F.type)||"PROPOSAL",title:F==null?void 0:F.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:br}),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(P,{variant:"outline",size:"sm",onClick:Kr,className:"gap-1.5 text-xs",children:[e.jsx(Tt,{className:"w-3.5 h-3.5"}),"Download"]}),e.jsx(P,{variant:"ghost",size:"icon",onClick:br,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 _4({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((M,L)=>{const F=typeof L=="object"&&L.amount||0,S=typeof L=="object"&&L.quantity||1;return M+Number(F)*Number(S)},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),[v,w]=x.useState(null),[A,C]=x.useState(""),[E,D]=x.useState([]),[T,N]=x.useState(!1);x.useEffect(()=>{if(u.length>0){const B=u.map(k=>{const M=k.organizer||null,L=(M==null?void 0:M.displayName)||(M==null?void 0:M.display_name)||(M==null?void 0:M.name)||(M!=null&&M.firstName&&(M!=null&&M.lastName)?`${M.firstName} ${M.lastName}`.trim():null)||(M==null?void 0:M.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 _=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 M=await S4(i,f.trim());if(M.isValid&&M.availableBalance>0){w(M.availableBalance);const L=E.reduce((S,G)=>S+G.blockedAmount,0),F=Math.max(0,d-L);F>0?C(String(F.toFixed(2))):d>0&&L===0?C(String(d.toFixed(2))):C(String(M.availableBalance.toFixed(2))),W.success(`IO fetched from SAP. Available balance: ₹${M.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)}else W.error("Invalid IO number or no available balance found"),w(null),C("")}catch(M){console.error("Failed to fetch IO budget:",M);const L=((k=(B=M==null?void 0:M.response)==null?void 0:B.data)==null?void 0:k.message)||(M==null?void 0:M.message)||"Failed to validate IO number or fetch budget from SAP";W.error(L),w(null)}finally{y(!1)}},I=async()=>{var F,S;if(!f.trim()||v===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>v){W.error("Amount to block exceeds available IO budget");return}const L=E.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}}N(!0);try{const G=parseFloat(v.toFixed(2)),U=parseFloat((G-k).toFixed(2)),$={ioNumber:f.trim(),ioAvailableBalance:G,ioBlockedAmount:k,ioRemainingBalance:U};await Sf(i,$);const R=await N4(i),H=(R==null?void 0:R.internalOrder)||(R==null?void 0:R.internal_order);if(H){const K=Number(H.ioBlockedAmount||H.io_blocked_amount||k),z=Number(H.ioRemainingBalance||H.io_remaining_balance||0),O=v-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:v,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:v,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]),C(""),w(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=((S=(F=G==null?void 0:G.response)==null?void 0:F.data)==null?void 0:S.message)||(G==null?void 0:G.message)||"Failed to block IO budget in SAP";W.error(U)}finally{N(!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||E.length>0&&!g||r,className:"flex-1"}),e.jsxs(P,{onClick:_,disabled:!f.trim()||j||E.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"]})]})]}),!v&&E.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.']})}),v!==null&&(E.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:["₹",v.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}C(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(P,{onClick:I,disabled:T||!A||parseFloat(A)<=0||parseFloat(A)>v||d>0&&Math.abs(E.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:E.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-E.reduce((B,k)=>B+k.blockedAmount,0)).toLocaleString("en-IN",{minimumFractionDigits:2}),"."]})]})]})}),E.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:["₹",E.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 M4(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 L4(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 O4({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}=Y0(),[h,g]=x.useState(!1),[f,b]=x.useState(""),[j,y]=x.useState(24),[v,w]=x.useState("hours"),[A,C]=x.useState(3),[E,D]=x.useState([]),[T,N]=x.useState(!1),[_,I]=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@undefined":"system@undefined",_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 M=(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."})}},F=(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))}},S=(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),_&&_.email.toLowerCase()!==O.toLowerCase()&&I(null),B.current&&clearTimeout(B.current),!O||!O.startsWith("@")||O.length<2){D([]),N(!1);return}N(!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{N(!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),I(O),D([]),N(!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=v==="days"?30:720;if((v==="days"?Q*24:Q)>720){W.error(`TAT cannot exceed ${q} ${v==="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&&(_==null?void 0:_.userId)&&ye.userId===_.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(!_||_.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:v,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:_.email,name:_.displayName||[_.firstName,_.lastName].filter(Boolean).join(" "),userId:_.userId,level:Pe,tat:j,tatType:v,isAdditional:!0,insertAfterLevel:A,stepName:`Additional Approver - ${_.displayName||_.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),w("hours"),C(3),I(null),D([]),g(!1)},R=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(zr,{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(P,{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(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(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||M(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=>F(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=>S(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(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(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=>C(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:v==="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:v,onValueChange:O=>w(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-",v==="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(pl,{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||E.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..."}):E.length>0?e.jsx("ul",{className:"divide-y",children:E.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(P,{type:"button",variant:"outline",onClick:()=>{g(!1),b(""),y(24),w("hours"),C(3),I(null),D([])},className:"flex-1",children:"Cancel"}),e.jsxs(P,{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 fo=[{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"}],bo=["Claim Details","Approver Selection","Review & Submit"];function $4({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}),[v,w]=x.useState({open:!1,violations:[]}),[A,C]=x.useState([]),[E,D]=x.useState(!0);x.useEffect(()=>{(async()=>{try{D(!0);const R=await YT();C(R)}catch(R){console.error("Failed to load activity types:",R),W.error("Failed to load activity types. Please refresh the page.")}finally{D(!1)}})()},[]),x.useEffect(()=>{(async()=>{var R;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:((R=O.ALLOW_ADD_SPECTATOR)==null?void 0:R.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,N]=x.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",dealerItemGroup:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),_=bo.length,I=$=>{if(u($),h.current&&clearTimeout(h.current),!$||$.trim().length<2){c([]),m(!1);return}m(!0),h.current=setTimeout(async()=>{try{const R=await L4($);if(R){const H={dealerId:R.dealer||R.dealer_code||$,dealerCode:R.dealer||R.dealer_code||$,dealerName:R["dealer name"]||R.dealer_name||"Unknown Dealer",displayName:R["dealer name"]||R.dealer_name||"Unknown Dealer",email:R["dealer email"]||"",phone:R["dealer phone"]||"",city:R["re city"]||R.city||"",state:R["re state code"]||R.state||"",isLoggedIn:!0,parentCode:R.parentcode||null,itemGroup:R["item group"]||null};c([H])}else c([])}catch(R){console.error("Error searching external dealer:",R),c([])}finally{m(!1)}},300)},B=($,R)=>{N(H=>{const K={...H,[$]:R};if($==="periodStartDate")R&&K.periodEndDate&&R>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"&&R&&K.periodStartDate&&R<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===R);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 "${R}" is missing creditPostingOn configuration.`)}return K})},k=$=>{N(R=>({...R,...$}))},M=()=>{switch(r){case 1:return T.activityName&&T.activityType&&T.dealerCode&&T.dealerName&&T.activityDate&&T.location&&T.requestDescription;case 2:const R=(T.approvers||[]).find(H=>H.originalStepLevel===3||!H.originalStepLevel&&H.level===3&&!H.isAdditional);return(R==null?void 0:R.email)&&(R==null?void 0:R.userId)&&(R==null?void 0:R.tat);case 3:return!0;default:return!1}},L=()=>{if(r<_){if(!M()){if(r===2){const R=(T.approvers||[]).find(K=>K.originalStepLevel===3||!K.originalStepLevel&&K.level===3&&!K.isAdditional),H=[];(!(R!=null&&R.email)||!(R!=null&&R.userId)||!(R!=null&&R.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)}},F=()=>{r>1&&n(r-1)},S=async $=>{l(!0);try{const R=await M4($.dealerCode);if(!R.isLoggedIn){W.error(`Dealer "${R.dealerName||R.displayName}" (${R.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=(R.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 ${R.itemGroup||"N/A"}`,duration:6e3}),u(""),c([]),l(!1);return}}}k({dealerCode:R.dealerCode,dealerName:R.dealerName||R.displayName,dealerEmail:R.email||"",dealerPhone:R.phone||"",dealerAddress:"",dealerItemGroup:R.itemGroup||""}),u(R.dealerName||R.displayName),c([]),W.success(`Dealer "${R.dealerName||R.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 R=[...T.approvers||[]].sort((V,Q)=>V.level-Q.level),H=new Map,K=[];if(R.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,R);return}const z=R.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:E,children:[e.jsx(We,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(Ge,{placeholder:E?"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)):I($.target.value)},onFocus:()=>{p&&p.length>=2&&I(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:()=>S($),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(P,{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?tt(T.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(na,{className:"w-auto p-0",align:"start",children:e.jsx(_i,{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(ui,{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(P,{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?tt(T.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(na,{className:"w-auto p-0",align:"start",children:e.jsx(_i,{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(P,{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?tt(T.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(na,{className:"w-auto p-0",align:"start",children:e.jsx(_i,{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: ",tt(T.periodStartDate,"d MMM yyyy")," - ",tt(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(O4,{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:$=>w({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(gl,{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(R=>{var H,K;return!((H=R.email)!=null&&H.includes("system@"))&&!((K=R.email)!=null&&K.includes("finance@"))}).sort((R,H)=>R.level-H.level).map(R=>{const H=Number(R.tat||0),z=(R.tatType||"hours")==="days"?H*24:H;let O="Unknown",V="";if(R.isAdditional){O=R.stepName||"Additional Approver";const Q=fo.find(q=>q.level===R.insertAfterLevel);V=R.stepName||`Additional Approver (after "${(Q==null?void 0:Q.name)||"Unknown"}")`}else{const Q=R.originalStepLevel?fo.find(q=>q.level===R.originalStepLevel):fo.find(q=>q.level===R.level&&!q.isAuto);O=(Q==null?void 0:Q.name)||"Unknown",V=O}return e.jsx("div",{className:`p-3 rounded-lg border ${R.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}),R.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:R.name||R.email||"Not selected"}),R.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:R.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"})]})]})},`${R.level}-${R.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?tt(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(bc,{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?tt(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?tt(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(zr,{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(P,{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 ",_,": ",e.jsx("span",{className:"hidden sm:inline",children:bo[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(ia,{value:r/_*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:bo.map(($,R)=>e.jsx("span",{className:`text-xs sm:text-sm ${R+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:R+1},R))})]})]}),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(Tl,{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(P,{variant:"outline",onClick:F,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<_?e.jsxs(P,{onClick:L,className:`gap-2 w-full sm:w-auto order-1 sm:order-2 ${M()?"":"opacity-50 cursor-pointer hover:opacity-60"}`,children:["Next",e.jsx(js,{className:"w-4 h-4"})]}):e.jsx(P,{onClick:G,disabled:!M()||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(fi,{open:v.open,onClose:()=>w({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}const{DocumentsTab:U4,ActivityTab:B4,WorkNotesTab:V4,SummaryTab:z4,RequestDetailHeader:H4,QuickActionsSidebar:G4,RequestDetailModals:W4}=of;let Y4=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(P,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(P,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function Q4({requestId:t,onBack:s,dynamicRequests:a=[]}){var Qt,As,la,Nr,wr,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),[v,w]=x.useState(!1),[A,C]=x.useState(!1),[E,D]=x.useState(!1),[T,N]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[_,I]=x.useState({open:!1,violations:[]}),{user:B}=us(),{request:k,apiRequest:M,loading:L,refreshing:F,refreshDetails:S,currentApprovalLevel:G,isSpectator:U,isInitiator:$,existingParticipants:R,accessDenied:H}=yd(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"||(M==null?void 0:M.workflowType)==="CLAIM_MANAGEMENT"||(k==null?void 0:k.templateType)==="claim-management")&&!V&&($||O),{mergedMessages:ee,unreadWorkNotes:te,workNoteAttachments:ue,setWorkNoteAttachments:_e}=Q0(n,M,o,B),{uploadingDocument:Ze,triggerFileInput:Ue,previewDocument:Pe,setPreviewDocument:De,documentPolicy:le,documentError:ye,setDocumentError:ae}=K0(M,S),[he,ne]=x.useState(null),ge=he||G,{showApproveModal:ke,setShowApproveModal:Oe,showRejectModal:je,setShowRejectModal:ie,showAddApproverModal:Se,setShowAddApproverModal:qe,showAddSpectatorModal:at,setShowAddSpectatorModal:gt,showSkipApproverModal:It,setShowSkipApproverModal:oe,showActionStatusModal:Me,setShowActionStatusModal:me,skipApproverData:Xe,setSkipApproverData:Qe,actionStatus:rt,setActionStatus:Ke,handleApproveConfirm:lt,handleRejectConfirm:et,handleAddApprover:ut,handleSkipApprover:Hs,handleAddSpectator:is}=Z0(n,ge,S),vt=async Rt=>{await lt(Rt),ne(null)},pt=async Rt=>{await et(Rt),ne(null)},Pt=((k==null?void 0:k.status)||(M==null?void 0:M.status)||"").toLowerCase(),Ss=(Pt==="approved"||Pt==="rejected")&&$,{conclusionRemark:as,setConclusionRemark:za,conclusionLoading:Ha,conclusionSubmitting:fr,aiGenerated:wa,handleGenerateConclusion:Lt,handleFinalizeConclusion:Ca,generationAttempts:Us,generationFailed:Yr,maxAttemptsReached:Qr}=X0(k,n,$,S,s,Ke,me);x.useEffect(()=>{(async()=>{var xs;try{const Xs=await ua("SYSTEM_SETTINGS"),xa=await ua("WORKFLOW_SHARING"),Xr=[...Xs,...xa],Aa={};Xr.forEach(ar=>{Aa[ar.configKey]=ar.configValue}),N({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 br=()=>{S()},Kr=()=>{w(!0)},Ja=()=>{C(!0)},jr=async()=>{await S()},qa=()=>{D(!0)},yr=async()=>{await S()},vr=async()=>{await S()},er=async()=>{if(!(M!=null&&M.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||!(M!=null&&M.requestId)){g(null),u(null);return}try{b(!0);const xs=await af(M.requestId);if(xs!=null&&xs.summaryId){u(xs.summaryId);try{const Xs=await Nd(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,M==null?void 0:M.requestId]),x.useEffect(()=>{if(!K||!(M!=null&&M.requestId))return;const Rt=Br();if(!Rt)return;Sc(Rt,K);const xs=Xs=>{var ar,Tn,kn,Dn;const xa=Xs==null?void 0:Xs.notification;if(!xa)return;const Xr=xa.requestId||xa.request_id,Aa=((ar=xa.metadata)==null?void 0:ar.requestNumber)||((Tn=xa.metadata)==null?void 0:Tn.request_number);Xr!==M.requestId&&Aa!==n&&Aa!==M.requestNumber||((kn=xa.metadata)!=null&&kn.creditNoteNumber||(Dn=xa.metadata)!=null&&Dn.credit_note_number)&&S()};return Rt.on("notification:new",xs),()=>{Rt.off("notification:new",xs)}},[K,M==null?void 0:M.requestId,n,S]);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&&!M?e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(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(np,{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(P,{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(P,{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(H4,{request:k,refreshing:F,onBack:s||(()=>window.history.back()),onRefresh:br,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(bi,{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(ji,{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(ip,{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(jc,{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(Ak,{request:k,apiRequest:M,currentUserId:K,isInitiator:$,needsClosure:Ss,conclusionRemark:as,setConclusionRemark:za,conclusionLoading:Ha,conclusionSubmitting:fr,aiGenerated:wa,handleGenerateConclusion:Lt,handleFinalizeConclusion:Ca,generationAttempts:Us,generationFailed:Yr,maxAttemptsReached:Qr})}),Pa&&e.jsx(Ut,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(z4,{summary:h,loading:f,onShare:er,isInitiator:$})}),e.jsx(Ut,{value:"workflow",className:"mt-0",children:e.jsx(E4,{request:k,user:B,isInitiator:$,isSpectator:U,onSkipApprover:Rt=>{if(!Rt.levelId){alert("Level ID not available");return}Qe(Rt),oe(!0)},onRefresh:S,documentPolicy:le})}),q&&e.jsx(Ut,{value:"io",className:"mt-0",children:e.jsx(_4,{request:k,apiRequest:M,onRefresh:S,isSpectator:U})}),e.jsx(Ut,{value:"documents",className:"mt-0",children:e.jsx(U4,{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(B4,{request:k})}),e.jsx(Ut,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(V4,{requestId:n,requestTitle:k.title,mergedMessages:ee,setWorkNoteAttachments:_e,isInitiator:$,isSpectator:U,currentLevels:tr,onAddApprover:ut,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Rt=>I({open:!0,violations:Rt})})})]}),o!=="worknotes"&&e.jsx(G4,{request:k,isInitiator:$,isSpectator:U,currentApprovalLevel:G,onAddApprover:()=>qe(!0),onAddSpectator:()=>gt(!0),onApprove:()=>Oe(!0),onReject:()=>ie(!0),onPause:Kr,onResume:Ja,onRetrigger:qa,summaryId:p,refreshTrigger:j,pausedByUserId:(wr=(Nr=k==null?void 0:k.pauseInfo)==null?void 0:Nr.pausedBy)==null?void 0:wr.userId,currentUserId:K,apiRequest:M,hideApproveReject:V})]})]})]})}),d&&p&&e.jsx(cf,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(k==null?void 0:k.title)||"N/A",onSuccess:()=>{S(),y(Rt=>Rt+1)}}),v&&(M==null?void 0:M.requestId)&&e.jsx(df,{isOpen:v,onClose:()=>w(!1),requestId:M.requestId,levelId:(G==null?void 0:G.levelId)||null,onSuccess:yr}),A&&(M==null?void 0:M.requestId)&&e.jsx(mf,{isOpen:A,onClose:()=>C(!1),requestId:M.requestId,onSuccess:jr}),E&&(M==null?void 0:M.requestId)&&e.jsx(uf,{isOpen:E,onClose:()=>D(!1),requestId:M.requestId,approverName:(sr=(Sa=k==null?void 0:k.pauseInfo)==null?void 0:Sa.pausedBy)==null?void 0:sr.name,onSuccess:vr}),e.jsx(W4,{showApproveModal:ke,showRejectModal:je,showAddApproverModal:Se,showAddSpectatorModal:at,showSkipApproverModal:It,showActionStatusModal:Me,previewDocument:Pe,documentError:ye,request:k,skipApproverData:Xe,actionStatus:rt,existingParticipants:R,currentLevels:tr,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Rt=>I({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(fi,{open:_.open,onClose:()=>I({open:!1,violations:[]}),violations:_.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(P,{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(P,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function K4(t){return e.jsx(Y4,{children:e.jsx(Q4,{...t})})}function X4({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(I=!1)=>{try{I?i(!0):r(!0);const B=await k4(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=(I,B=!1)=>{if(I==null||isNaN(I))return"₹0";const k=typeof I=="string"?parseFloat(I):Number(I);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=I=>I.toLocaleString("en-IN"),v=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),w=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),A=x.useMemo(()=>{const I=c.reduce((B,k)=>B+k.raised,0);return I===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/I*100).toFixed(0)}))},[c]),C=x.useMemo(()=>c.map(I=>({name:I.activityType.length>15?I.activityType.substring(0,15)+"...":I.activityType,fullName:I.activityType,Raised:I.raised,Approved:I.approved,Rejected:I.rejected,Pending:I.pending})),[c]),E=x.useMemo(()=>c.map(I=>({name:I.activityType.length>15?I.activityType.substring(0,15)+"...":I.activityType,fullName:I.activityType,Raised:I.raisedValue,Approved:I.approvedValue,Credited:I.creditedValue})),[c]),D=["#166534","#15803d","#16a34a","#22c55e","#4ade80","#86efac","#bbf7d0"],T=x.useMemo(()=>c.length===0?null:c.reduce((I,B)=>B.approvalRate>((I==null?void 0:I.approvalRate)||0)?B:I),[c]),N=x.useMemo(()=>c.length===0?null:c.reduce((I,B)=>B.raisedValue>((I==null?void 0:I.raisedValue)||0)?B:I),[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(P,{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(Po,{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(P,{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(P,{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(P,{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(Xi,{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:[v(),"% 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(Ij,{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(Pj,{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:[w(),"% 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(Po,{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(cn,{width:"100%",height:300,children:e.jsxs(Bh,{children:[e.jsx(Vh,{data:A,cx:"50%",cy:"50%",labelLine:!1,label:({name:I,percentage:B})=>`${I}: ${B}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:A.map((I,B)=>e.jsx(zh,{fill:D[B%D.length]},`cell-${B}`))}),e.jsx(dn,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:A.slice(0,3).map((I,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:I.name}),e.jsx("p",{className:"text-sm text-gray-900",children:y(I.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(Xi,{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(cn,{width:"100%",height:300,children:e.jsxs(Ro,{data:C,children:[e.jsx(Hi,{strokeDasharray:"3 3"}),e.jsx(Gi,{dataKey:"name"}),e.jsx(Wi,{}),e.jsx(dn,{}),e.jsx(Yi,{}),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(cn,{width:"100%",height:350,children:e.jsxs(Ro,{data:E,children:[e.jsx(Hi,{strokeDasharray:"3 3"}),e.jsx(Gi,{dataKey:"name"}),e.jsx(Wi,{tickFormatter:I=>j(I)}),e.jsx(dn,{formatter:I=>j(I),labelFormatter:I=>I}),e.jsx(Yi,{}),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((I,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:I.activityType}),e.jsxs(re,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[I.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(I.raised)," (",j(I.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(I.approved)," (",j(I.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(I.rejected)," (",j(I.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(I.pending)," (",j(I.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(I.credited)," (",j(I.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(I.pendingCredit)," (",j(I.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:[I.creditRate.toFixed(1),"%"]})]}),e.jsx(ia,{value:I.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:(N==null?void 0:N.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-blue-600",children:[N?j(N.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(ml,{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:[w(),"%"]}),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(qh,{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 Z4({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(P,{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(P,{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(fl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(bl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function J4({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(P,{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(P,{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(fl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(bl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function q4({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:v,onApplyCustomDate:w,onClearFilters:A,hasActiveFilters:C,...E}){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"}),C&&e.jsx(re,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),C&&e.jsxs(P,{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(P,{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(P,{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:v,children:[e.jsx(ra,{asChild:!0,children:e.jsxs(P,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ft,{className:"w-4 h-4"}),l&&o?`${tt(l,"MMM d, yyyy")} - ${tt(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(P,{size:"sm",onClick:w,disabled:!l||!o,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(P,{size:"sm",variant:"outline",onClick:()=>{v==null||v(!1),j==null||j(void 0),y==null||y(void 0),b("month")},children:"Cancel"})]})]})})]})]})]})})})}function e6(t){switch(t){case"DEALER_CLAIM":return K4;case"CUSTOM":default:return bk}}function t6(t){switch(t){case"DEALER":return Z4;case"STANDARD":default:return vk}}function s6(t){switch(t){case"DEALER":return J4;case"STANDARD":default:return Ck}}function a6(t){switch(t){case"DEALER":return q4;case"STANDARD":default:return Sk}}const r6=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"}}},n6=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 i6({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=k1(),g=x.useMemo(()=>{try{const T=nt.getUserData();return $c(T)}catch(T){return console.error("[OpenRequests] Error getting user filter type:",T),"STANDARD"}},[]),f=x.useMemo(()=>t6(g),[g]),b=g==="DEALER",j=T=>{const N={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 N.templateType==="FORM_16"&&(h.form16FinancialYear&&(N.financialYear=h.form16FinancialYear),h.form16Quarter&&(N.quarter=h.form16Quarter)),N},y=x.useCallback(async(T=1,N)=>{try{T===1&&(n(!0),a([]));const _=await Ks.listOpenForMe({page:T,limit:p,search:N==null?void 0:N.search,status:N==null?void 0:N.status,priority:N==null?void 0:N.priority,templateType:N==null?void 0:N.templateType,financialYear:N==null?void 0:N.financialYear,quarter:N==null?void 0:N.quarter,sortBy:N==null?void 0:N.sortBy,sortOrder:N==null?void 0:N.sortOrder}),I=Array.isArray(_==null?void 0:_.data)?_.data:[],B=_==null?void 0:_.pagination;B&&(h.setCurrentPage(B.page||1),c(B.totalPages||1),m(B.total||0));const k=I.map(M=>{var F,S,G,U;const L=M.submittedAt||M.submitted_at||M.createdAt||M.created_at;return{id:M.requestNumber||M.request_number||M.requestId,requestId:M.requestId,displayId:M.requestNumber||M.request_number||M.requestId,title:M.title,description:M.description,status:(M.status||"").toString().toLowerCase().replace("_","-"),priority:(M.priority||"").toString().toLowerCase(),initiator:{name:((F=M.initiator)==null?void 0:F.displayName)||((S=M.initiator)==null?void 0:S.email)||"—",avatar:(((G=M.initiator)==null?void 0:G.displayName)||((U=M.initiator)==null?void 0:U.email)||"NA").split(" ").map($=>$[0]).join("").slice(0,2).toUpperCase()},currentApprover:M.currentApprover?{name:M.currentApprover.name||M.currentApprover.email||"—",avatar:(M.currentApprover.name||M.currentApprover.email||"CA").split(" ").map($=>$[0]).join("").slice(0,2).toUpperCase(),sla:M.currentApprover.sla}:void 0,createdAt:L||"—",approvalStep:M.currentLevel?`Step ${M.currentLevel} of ${M.totalLevels||"?"}`:void 0,department:M.department,currentLevelSLA:M.currentLevelSLA,templateType:M.templateType||M.template_type,form16Submission:M.form16Submission??null}});a(k)}finally{n(!1),l(!1)}},[p,h]);u.current=y;const v=x.useCallback(()=>{l(!0),y(h.currentPage,j(!0))},[h.currentPage,y]),w=x.useCallback(T=>{T>=1&&T<=o&&(h.setCurrentPage(T),y(T,j(!0)))},[o,h,y]),A=()=>{const T=[];let _=Math.max(1,h.currentPage-Math.floor(2.5)),I=Math.min(o,_+5-1);I-_<4&&(_=Math.max(1,I-5+1));for(let B=_;B<=I;B++)T.push(B);return T},C=x.useRef(!1);x.useEffect(()=>{if(!C.current){C.current=!0;const T=h.currentPage||1;y(T,j(!0))}},[]);const E=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(!C.current)return;const T=E.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 _=setTimeout(()=>{h.setCurrentPage(1),y(1,j(!0)),E.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(_)},[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(P,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:v,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 N=r6(T.priority),_=(T.templateType||T.template_type||"").toString().toUpperCase()==="FORM_16",I=T.form16Submission,B=I==null?void 0:I.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}:n6(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 ${N.color} border shadow-sm`,children:e.jsx(N.icon,{className:`w-5 h-5 ${N.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:T.displayId||T.id}),e.jsxs(re,{variant:"outline",className:`${M.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(M.icon,{className:"w-3.5 h-3.5 mr-1"}),M.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:`${N.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)||"",F=(L==null?void 0:L.toUpperCase())||"";let S="Non-Templatized",G="bg-purple-100 !text-purple-600 border-purple-200";return F==="DEALER CLAIM"?(S="Dealer Claim",G="bg-blue-100 !text-blue-700 border-blue-200"):F==="FORM_16"?(S="Form 16",G="bg-emerald-100 !text-emerald-700 border-emerald-200"):F==="TEMPLATE"&&(S="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:S})})()]}),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"),F=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"}:F>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:F>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:F>=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(lr,{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: ",F,"% ",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:F,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(P,{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(P,{variant:"outline",size:"sm",onClick:()=>w(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(P,{variant:"outline",size:"sm",onClick:()=>w(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),A().map(T=>e.jsx(P,{variant:T===h.currentPage?"default":"outline",size:"sm",onClick:()=>w(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(P,{variant:"outline",size:"sm",onClick:()=>w(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(P,{variant:"outline",size:"sm",onClick:()=>w(h.currentPage+1),disabled:h.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(js,{className:"h-4 w-4"})})]})]})})})]})}function l6({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(P,{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 o6(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 c6(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 d6({request:t,onViewRequest:s}){var l;const a=o6(t.priority),r=c6(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 m6({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(d6,{request:r,onViewRequest:a},r.id))})}function u6({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(P,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function x6(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 h6({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=x6(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(P,{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(P,{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(P,{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(P,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(P,{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 p6(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 g6(t){return t.map(p6)}function f6({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=g6(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 b6={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},Af=jn({name:"closedRequests",initialState:b6,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:j6,setStatusFilter:y6,setPriorityFilter:v6,setTemplateTypeFilter:N6,setForm16FinancialYear:w6,setForm16Quarter:C6,setSortBy:S6,setSortOrder:A6,setCurrentPage:T6,clearFilters:k6}=Af.actions;function D6({onFiltersChange:t,debounceMs:s=500}={}){const a=oi(),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}=vn(N=>N.closedRequests),g=x.useCallback(N=>a(j6(N)),[a]),f=x.useCallback(N=>a(y6(N)),[a]),b=x.useCallback(N=>a(v6(N)),[a]),j=x.useCallback(N=>a(N6(N)),[a]),y=x.useCallback(N=>a(w6(N)),[a]),v=x.useCallback(N=>a(C6(N)),[a]),w=x.useCallback(N=>a(S6(N)),[a]),A=x.useCallback(N=>a(A6(N)),[a]),C=x.useCallback(N=>a(T6(N)),[a]),E=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 N=setTimeout(()=>{t&&t(E())},i?s:0);return r.current=N,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,p,u,t,E,s]);const D=x.useCallback(()=>{a(k6())},[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:v,setSortBy:w,setSortOrder:A,setCurrentPage:C,clearFilters:D,activeFiltersCount:T,getFilters:E}}function R6({onViewRequest:t}){const s=f6({itemsPerPage:10}),a=x.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=D6(),n=x.useMemo(()=>{try{const u=nt.getUserData();return $c(u)}catch(u){return console.error("[ClosedRequests] Error getting user filter type:",u),"STANDARD"}},[]),i=x.useMemo(()=>s6(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(l6,{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(m6,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(u6,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(h6,{pagination:s.pagination,onPageChange:m})]})}function F6(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 I6(t){return F6(t)?"DEALER_CLAIM":"CUSTOM"}function P6(t,s){return`/request/${t}`}class E6 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(P,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(P,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function _6({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=Va().requestId||t||"",{user:i}=us(),{apiRequest:l,loading:o}=yd(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=I6(l),d=e6(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function M6(t){return e.jsx(E6,{children:e.jsx(_6,{...t})})}function L6({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(v=1)=>{try{i(!0);const w=await Z5({page:v,limit:g});r(w.data||[]),p(w.pagination.totalPages||1),h(w.pagination.total||0),d(w.pagination.page||1)}catch(w){console.error("Failed to fetch shared summaries:",w),W.error("Failed to load shared summaries")}finally{i(!1)}},[]);x.useEffect(()=>{f(1)},[f]);const b=async v=>{try{await sf(v),r(w=>w.map(A=>A.sharedSummaryId===v?{...A,isRead:!0,viewedAt:new Date().toISOString()}:A)),t?t(v):s(`/shared-summaries/${v}`)}catch(w){console.error("Failed to mark as viewed:",w),t?t(v):s(`/shared-summaries/${v}`)}},j=v=>{v>=1&&v<=m&&f(v)},y=a.filter(v=>{var A,C,E,D;if(!l)return!0;const w=l.toLowerCase();return((A=v.title)==null?void 0:A.toLowerCase().includes(w))||((C=v.requestNumber)==null?void 0:C.toLowerCase().includes(w))||((E=v.initiatorName)==null?void 0:E.toLowerCase().includes(w))||((D=v.sharedByName)==null?void 0:D.toLowerCase().includes(w))});return e.jsx("div",{className:"min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden",children:e.jsxs("div",{className:"max-w-7xl mx-auto w-full",children:[e.jsxs("div",{className:"mb-4 sm:mb-6",children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900 mb-1 sm:mb-2",children:"Shared Summaries"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600",children:"View summaries of closed requests shared with you"})]}),e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs("div",{className:"relative",children:[e.jsx(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:v=>o(v.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(v=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${v.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>b(v.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:[v.isRead?e.jsx(Ej,{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:v.title}),!v.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:v.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:v.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:v.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: ",tt(new Date(v.sharedAt),"MMM dd, yyyy HH:mm")]})]}),v.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: ",tt(new Date(v.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(P,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:w=>{w.stopPropagation(),b(v.sharedSummaryId)},children:"View"})]})})},v.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(P,{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(P,{variant:"outline",size:"sm",onClick:()=>j(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function O6(){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 sf(t)}catch(h){console.warn("Failed to mark as viewed:",h)}const u=await Nd(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(P,{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:tt(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:tt(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(P,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function $6(){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(tf,{requestId:t||""})})})}function Tf({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 U6({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:dr,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:jl,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:yl,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 B6({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 V6(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 z6(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:jl,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Je,iconColor:"text-gray-600"}}}const H6=t=>{if(!t)return"";let s=t.replace(/<(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|tfoot|ul|video)[^>]*>/gi," ");return s=s.replace(/<br\s*\/?>/gi," "),s=s.replace(/<[^>]*>/g,""),s=s.replace(/\s+/g," ").trim(),s=s.replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"),s};function G6({request:t,index:s,onViewRequest:a}){var o;const r=z6(t.status),n=V6(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(dr,{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:H6(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 W6({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(G6,{request:l,index:o,onViewRequest:i},l.id))})}function Y6(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 kf(t){return Array.isArray(t)?t.map(Y6):[]}function Q6({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=kf(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 K6={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},Df=jn({name:"myRequests",initialState:K6,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:X6,setStatusFilter:Z6,setPriorityFilter:J6,setTemplateTypeFilter:q6,setCurrentPage:eD,clearFilters:tD}=Df.actions;function sD({onFiltersChange:t,debounceMs:s=500}={}){const a=oi(),r=x.useRef(null),n=x.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d}=vn(j=>j.myRequests),m=x.useCallback(j=>a(X6(j)),[a]),p=x.useCallback(j=>a(Z6(j)),[a]),u=x.useCallback(j=>a(J6(j)),[a]),h=x.useCallback(j=>a(q6(j)),[a]),g=x.useCallback(j=>a(eD(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(tD())},[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 aD({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=us(),r=Q6({itemsPerPage:10}),n=x.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=sD(),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 v=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(v)},[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=kf(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(Tf,{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(U6,{stats:f,onStatusFilter:j=>{i.setStatusFilter(j)}}),e.jsx(B6,{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(W6,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(Gr,{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 Rf({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(Tf,{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(P,{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 Ff({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:dr,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:yl,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 rD=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"}}},ph=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:jl,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:Je,iconColor:"text-gray-600"}}},nD=t=>{if(!t)return"";let s=t.replace(/<(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|tfoot|ul|video)[^>]*>/gi," ");return s=s.replace(/<br\s*\/?>/gi," "),s=s.replace(/<[^>]*>/g,""),s=s.replace(/\s+/g," ").trim(),s=s.replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"),s};function iD(t){return t==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function lD({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:ph(t.status).icon,label:i}:ph(t.status),c=rD(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(dr,{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:nD(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?iD(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 If({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(lD,{request:n,index:i,onViewRequest:r},n.id))})}const oD={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},Pf=jn({name:"requests",initialState:oD,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:cD,setStatusFilter:dD,setPriorityFilter:mD,setTemplateTypeFilter:uD,setRequestTypeFilter:xD,setForm16FinancialYear:hD,setForm16Quarter:pD,setSlaComplianceFilter:gD,setDepartmentFilter:fD,setInitiatorFilter:bD,setApproverFilter:jD,setApproverFilterType:yD,setDateRange:gh,setCustomStartDate:jo,setCustomEndDate:yo,setShowCustomDatePicker:Ti,setCurrentPage:vD,clearFilters:ND}=Pf.actions;function Ef(){const t=oi(),{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}=vn(z=>z.requests),y=x.useCallback(z=>t(cD(z)),[t]),v=x.useCallback(z=>t(dD(z)),[t]),w=x.useCallback(z=>t(mD(z)),[t]),A=x.useCallback(z=>t(uD(z)),[t]),C=x.useCallback(z=>t(xD(z)),[t]),E=x.useCallback(z=>t(hD(z)),[t]),D=x.useCallback(z=>t(pD(z)),[t]),T=x.useCallback(z=>t(gD(z)),[t]),N=x.useCallback(z=>t(fD(z)),[t]),_=x.useCallback(z=>t(bD(z)),[t]),I=x.useCallback(z=>t(jD(z)),[t]),B=x.useCallback(z=>t(yD(z)),[t]),k=x.useCallback(z=>t(gh(z)),[t]),M=x.useCallback(z=>t(jo(z)),[t]),L=x.useCallback(z=>t(yo(z)),[t]),F=x.useCallback(z=>t(Ti(z)),[t]),S=x.useCallback(z=>t(vD(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(ND())},[t]),$=x.useCallback(z=>{const O=z;t(gh(O)),O!=="custom"?(t(jo(void 0)),t(yo(void 0)),t(Ti(!1))):t(Ti(!0))},[t]),R=x.useCallback(()=>{g&&f&&(g>f&&(t(jo(f)),t(yo(g))),t(Ti(!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:v,setPriorityFilter:w,setTemplateTypeFilter:A,setRequestTypeFilter:C,setForm16FinancialYear:E,setForm16Quarter:D,setSlaComplianceFilter:T,setDepartmentFilter:N,setInitiatorFilter:_,setApproverFilter:I,setApproverFilterType:B,setDateRange:k,setCustomStartDate:M,setCustomEndDate:L,setShowCustomDatePicker:F,setCurrentPage:S,getFilters:G,clearFilters:U,handleDateRangeChange:$,handleApplyCustomDate:R}}function rl({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 w=((y=(await da.searchUsers(j.trim(),10,a)).data)==null?void 0:y.data)||[];l(w),c(w.length>0)}catch(v){console.error("Search API failed:",v),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 wD(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((v,w)=>{const A=v.levelNumber||v.level_number||0;return(w.levelNumber||w.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 _f(t){return Array.isArray(t)?t.map(wD):[]}function CD(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 Mf={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(il,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(Mf);var SD=Mf.exports;const Lf=ll(SD);var Of={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(il,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(Of);var AD=Of.exports;const $f=ll(AD);rs.extend($f);rs.extend(Lf);function TD(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,v;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const w=(r.status||"").toString().toUpperCase();if(!(w==="APPROVED"||w==="REJECTED"||w==="CLOSED"))return!1;const C=((c=r.currentLevelSLA)==null?void 0:c.status)||((m=(d=r.currentApprover)==null?void 0:d.sla)==null?void 0:m.status)||((p=r.sla)==null?void 0:p.status)||((h=(u=r.summary)==null?void 0:u.sla)==null?void 0:h.status);return C?C!=="breached"&&C.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)||((v=(y=r.summary)==null?void 0:y.sla)==null?void 0:v.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(Lf);rs.extend($f);function kD(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return tt(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function Uf(t,s){const a=TD(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var y,v,w,A,C;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),p=((y=c.initiator)==null?void 0:y.displayName)||((v=c.initiator)==null?void 0:v.email)||c.initiatorName||"N/A",u=c.department||((w=c.initiator)==null?void 0:w.department)||"N/A",h=((A=c.currentApprover)==null?void 0:A.displayName)||((C=c.currentApprover)==null?void 0:C.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",f=kD(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 DD({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 RD(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 FD({onViewRequest:t}){const{user:s}=us(),a=vn(U=>U.dashboard.viewAsUser),r=x.useMemo(()=>Nl(s),[s]),n=x.useMemo(()=>r&&!a,[r,a]),i=Ef(),[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,v]=x.useState(1),[w,A]=x.useState(0),[C]=x.useState(10),E=rl({filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter,source:"local"}),D=rl({filterValue:i.approverFilter,onFilterChange:i.setApproverFilter,source:"local"}),T=x.useCallback(async(U,$,R,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()),R&&(O.endDate=R.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,R?R.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]),N=x.useCallback(async()=>{try{j(!0);const U=await Ot.getDepartments();f(U)}catch{}finally{j(!1)}},[]),_=x.useRef(i),I=x.useRef(T);x.useEffect(()=>{_.current=i,I.current=T},[i,T]),x.useEffect(()=>{const U=new URLSearchParams(window.location.search),$=U.get("approver"),R=U.get("approverType"),H=U.get("slaCompliance"),K=U.get("dateRange"),z=U.get("startDate"),O=U.get("endDate");$&&i.setApproverFilter($),(R==="current"||R==="any")&&i.setApproverFilterType(R),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 $=_.current.getFilters(),R=await DD({page:U,itemsPerPage:C,filters:$,isOrgLevel:n});o(R.data),i.setCurrentPage(R.pagination.page),v(R.pagination.totalPages),A(R.pagination.total)}catch{o([])}finally{d(!1)}},[C,n]),k=x.useCallback(async()=>{try{p(!0);const U=await RD(n);await Uf(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(()=>{N()},[N]),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},R=i.dateRange||"all";I.current(R,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 M=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=M.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 R=setTimeout(()=>{i.setCurrentPage(1),B(1),M.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(R)},[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 F=x.useCallback(U=>{U>=1&&U<=y&&(i.setCurrentPage(U),B(U))},[y,B,i]),S=x.useMemo(()=>_f(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}:CD([],n,u,!1,w,S),[n,u,w,S]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(Rf,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:k}),e.jsx(Ff,{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(P,{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:E.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:E.selectedUser.displayName||E.selectedUser.email}),e.jsx(P,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:E.handleClear,children:e.jsx(yt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{placeholder:"Search initiator...",value:E.searchQuery,onChange:U=>E.handleSearch(U.target.value),onFocus:()=>{E.searchResults.length>0&&E.setShowResults(!0)},onBlur:()=>setTimeout(()=>E.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),E.showResults&&E.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:E.searchResults.map(U=>e.jsx("button",{type:"button",onClick:()=>E.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(P,{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(P,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ft,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${tt(i.customStartDate,"MMM d, yyyy")} - ${tt(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(P,{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(P,{size:"sm",variant:"outline",onClick:()=>{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})})]})})]})]})]})]})})}),e.jsx(If,{requests:S,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(Gr,{currentPage:i.currentPage||1,totalPages:y,totalRecords:w,itemsPerPage:C,onPageChange:F,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function ID({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 fh=100;async function PD(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:fh,...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===fh}}return s}function ED({onViewRequest:t}){const s=Ef(),a=x.useMemo(()=>{try{const K=nt.getUserData();return $c(K)}catch(K){return console.error("[UserAllRequests] Error getting user filter type:",K),"STANDARD"}},[]),r=x.useMemo(()=>a6(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),[v,w]=x.useState(!1),[A,C]=x.useState(1),[E,D]=x.useState(0),[T]=x.useState(10),N=rl({filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter,source:"local"}),_=rl({filterValue:s.approverFilter,onFilterChange:s.setApproverFilter,source:"local"}),I=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"&&Dc().then(K=>w(!!(K.canViewForm16Submission||K.canView26AS))).catch(()=>w(!1))},[a]);const k=x.useRef(s),M=x.useRef(I),L=x.useRef(i);x.useEffect(()=>{k.current=s,M.current=I,L.current=i},[s,I,i]);const F=x.useCallback(async(K=1)=>{try{K===1&&(m(!0),c([]));const z=L.current(),O=await ID({page:K,itemsPerPage:T,filters:z});c(O.data),s.setCurrentPage(O.pagination.page),C(O.pagination.totalPages),D(O.pagination.total)}catch{c([])}finally{m(!1)}},[T,s]),S=x.useCallback(async()=>{try{u(!0);const K=i(),z=await PD(K);await Uf(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";M.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;F(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),F(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),F(K))},[A,F,s]),R=x.useMemo(()=>_f(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=R.filter(q=>{const ee=(q.status||"").toString().toLowerCase();return ee==="pending"||ee==="in-progress"}).length,z=R.filter(q=>(q.status||"").toString().toLowerCase()==="paused").length,O=R.filter(q=>(q.status||"").toString().toLowerCase()==="approved").length,V=R.filter(q=>(q.status||"").toString().toLowerCase()==="rejected").length,Q=R.filter(q=>(q.status||"").toString().toLowerCase()==="closed").length;return{total:E>0?E:R.length,pending:K,paused:z,approved:O,rejected:V,draft:0,closed:Q}},[h,E,R]);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(Rf,{isOrgLevel:!1,isAdmin:!1,loading:d,exporting:p,onExport:S}),e.jsx(Ff,{stats:H,onStatusFilter:K=>{s.setStatusFilter(K)}}),e.jsx(r,{requestTypeFilter:s.requestTypeFilter,onRequestTypeChange:K=>s.setRequestTypeFilter(K),showForm16Filter:v,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:N,approverSearch:_,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(If,{requests:R,loading:d,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(Gr,{currentPage:s.currentPage||1,totalPages:A,totalRecords:E,itemsPerPage:T,onPageChange:$,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function _D(){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(P,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(ws,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function MD({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(P,{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 LD({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(yc,{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 OD({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"?o1(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(yl,{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(_j,{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(Xi,{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 $D({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:v}){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(P,{variant:"ghost",size:"sm",onClick:v,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:w=>m(w.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(P,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(ft,{className:"w-4 h-4"}),c&&d?`${tt(c,"MMM d")} - ${tt(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?tt(c,"yyyy-MM-dd"):"",onChange:w=>{const A=w.target.value?new Date(w.target.value):void 0;A?(b(A),d&&A>d&&j(A)):b(void 0)},max:tt(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?tt(d,"yyyy-MM-dd"):"",onChange:w=>{const A=w.target.value?new Date(w.target.value):void 0;A?(j(A),c&&A<c&&b(A)):j(void 0)},min:c?tt(c,"yyyy-MM-dd"):void 0,max:tt(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(P,{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(P,{size:"sm",variant:"outline",onClick:()=>{f(!1),b(i),j(l),(!i||!l)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const UD=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"}}},BD=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"}}},VD=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 zD(t){if(!t)return"N/A";try{return tt(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function HD(t){if(!t)return"N/A";try{return tt(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function nl(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=P6(s);n(l)}function GD({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=UD(d.priority),p=BD(d.status),u=VD(d.slaStatus||""),h=m.icon,g=p.icon;return e.jsx(Z,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{nl({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: ",zD(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: ",HD(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(yc,{className:"w-3 h-3"}),Xt(d.levelElapsedHours)," / ",Xt(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(P,{variant:"ghost",size:"sm",onClick:f=>{f.stopPropagation(),nl({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(Gr,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function WD(){const[t]=mp(),[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),[v,w]=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),w(void 0),b(!1)},[]),C=x.useCallback(D=>{const T=D;m(T),T!=="custom"?(u(void 0),g(void 0),y(void 0),w(void 0),b(!1)):(y(p),w(h),b(!0))},[p,h]),E=x.useCallback(()=>{if(j&&v){if(j>v){const D=j;u(v),g(D),y(v),w(D)}else u(j),g(v);b(!1)}},[j,v]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:d,customStartDate:p,customEndDate:h,showCustomDatePicker:f,tempCustomStartDate:j,tempCustomEndDate:v,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:u,setCustomEndDate:g,setShowCustomDatePicker:b,setTempCustomStartDate:y,setTempCustomEndDate:w,clearFilters:A,handleDateRangeChange:C,handleApplyCustomDate:E}}function YD({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),[v,w]=x.useState(1),[A,C]=x.useState(1),[E,D]=x.useState(0),T=x.useRef(!0),N=x.useCallback(async()=>{if(t)try{const k=s==="all"?void 0:s,M=await Ot.getSingleApproverStats(t,k,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);u(M)}catch(k){console.error("[ApproverPerformance] Failed to fetch approver stats:",k),u(null)}},[t,s,a,r,i,l]),_=x.useCallback(async(k=1)=>{if(!t){b(!1);return}try{b(!0);const M=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(M.requests),D(M.pagination.totalRecords),C(M.pagination.totalPages),w(M.pagination.currentPage),g(M.requests)}catch(M){console.error("Failed to fetch requests:",M)}finally{b(!1),y(!1)}},[t,s,a,r,n,i,l,o,c]);x.useEffect(()=>{T.current&&(T.current=!1,N(),_(1))},[]),x.useEffect(()=>{T.current||N()},[s,a,r,i,l]),x.useEffect(()=>{T.current||_(1)},[s,a,r,n,i,l,o]);const I=x.useCallback(()=>{y(!0),N(),_(1)},[N,_]),B=x.useCallback(k=>{_(k)},[_]);return{requests:d,approverStats:p,allFilteredRequests:h,loading:f,refreshing:j,currentPage:v,totalPages:A,totalRecords:E,handleRefresh:I,handlePageChange:B}}const bh=10;function QD(){const[t]=mp(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=WD(),n=YD({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:bh});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(MD,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(LD,{approverStats:n.approverStats}),n.approverStats&&e.jsx(OD,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx($D,{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(GD,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:bh,onPageChange:n.handlePageChange})]}):e.jsx(_D,{})}function KD(){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(Cl,{src:(t==null?void 0:t.picture)||""}),e.jsx(ds,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),kr(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:[kr(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"]}),Rn(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(ii,{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(mu,{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(pc,{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(mu,{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:kr(t)||Rn(t)?"default":"secondary",className:kr(t)?"bg-yellow-400 text-slate-900":Rn(t)?"bg-blue-400 text-slate-900":"",children:kr(t)?"Administrator":Rn(t)?"Management":"User"}),(kr(t)||Rn(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 ki="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",XD="http://localhost:5000";function vo(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 ZD(){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 JD(t){if(ki.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:vo(ki)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:vo(ki)})}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:vo(ki)})}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(`${XD}/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 qD(){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 ZD()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await JD(s)}catch(a){throw a}}function oc({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(Hb,{"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(Gb,{"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(Wb,{"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(Yb,{"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 eR({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 N,_;try{n(!0),c(null);const I=await Fl();a(I)}catch(I){c(((_=(N=I.response)==null?void 0:N.data)==null?void 0:_.error)||"Failed to load configurations")}finally{n(!1)}},g=async N=>{var _,I;try{l(N.configKey),c(null);const B=d[N.configKey]??N.configValue;if(N.validationRules){const k=parseFloat(B);if(N.valueType==="NUMBER"){if(N.validationRules.min!==void 0&&k<N.validationRules.min)throw new Error(`Value must be at least ${N.validationRules.min}`);if(N.validationRules.max!==void 0&&k>N.validationRules.max)throw new Error(`Value must be at most ${N.validationRules.max}`)}}await Gs(N.configKey,B),a(k=>k.map(M=>M.configKey===N.configKey?{...M,configValue:B}:M)),m(k=>{const M={...k};return delete M[N.configKey],M}),u(`${N.displayName} updated successfully`),setTimeout(()=>u(null),3e3),t&&t()}catch(B){c(B.message||((I=(_=B.response)==null?void 0:_.data)==null?void 0:I.error)||"Failed to save configuration")}finally{l(null)}},f=async N=>{var _,I;if(confirm(`Reset "${N.displayName}" to default value?`))try{l(N.configKey),c(null),await UT(N.configKey),a(B=>B.map(k=>k.configKey===N.configKey?{...k,configValue:k.defaultValue||""}:k)),m(B=>{const k={...B};return delete k[N.configKey],k}),u(`${N.displayName} reset to default`),setTimeout(()=>u(null),3e3)}catch(B){c(((I=(_=B.response)==null?void 0:_.data)==null?void 0:I.error)||"Failed to reset configuration")}finally{l(null)}},b=(N,_)=>{m(I=>({...I,[N]:_}))},j=N=>d[N.configKey]??N.configValue,y=N=>d[N.configKey]!==void 0&&d[N.configKey]!==N.configValue,v=N=>{var B,k,M,L;const _=j(N),I=i===N.configKey;if(!N.isEditable)return e.jsxs("div",{className:"p-3 bg-slate-100 border border-slate-200 rounded-md",children:[e.jsx("p",{className:"text-sm text-slate-700 font-mono",children:N.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Je,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(N.uiComponent||N.valueType.toLowerCase()){case"toggle":return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${_==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${_==="true"?"text-green-700":"text-slate-600"}`,children:_==="true"?"Enabled":"Disabled"})]}),e.jsx(os,{checked:_==="true",onCheckedChange:U=>b(N.configKey,U?"true":"false"),disabled:I})]});case"slider":const F=parseInt(_)||0,S=((B=N.validationRules)==null?void 0:B.min)||0,G=((k=N.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:[F,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",S,"-",G]})]}),e.jsx(oc,{value:[F],min:S,max:G,step:1,onValueChange:([U])=>{U!==void 0&&b(N.configKey,U.toString())},disabled:I,className:"w-full"})]});case"number":return e.jsx(Re,{type:"number",value:_,onChange:U=>b(N.configKey,U.target.value),disabled:I,min:(M=N.validationRules)==null?void 0:M.min,max:(L=N.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:_,onChange:U=>b(N.configKey,U.target.value),disabled:I,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},w=N=>{switch(N){case"TAT_SETTINGS":return e.jsx(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(ul,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(fn,{className:"w-5 h-5"});default:return e.jsx(cr,{className:"w-5 h-5"})}},A=["DASHBOARD_LAYOUT"],C=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],E=s.filter(N=>!A.includes(N.configCategory)&&!C.includes(N.configKey)),D=E.reduce((N,_)=>(N[_.configCategory]||(N[_.configCategory]=[]),N[_.configCategory].push(_),N),{});if(Object.keys(D).forEach(N=>{const _=D[N];_&&_.sort((I,B)=>I.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(E.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(cr,{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(P,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(bi,{defaultValue:T[0],className:"w-full",children:[e.jsx(ji,{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(N=>e.jsx($t,{value:N,className:"flex-1 min-w-[120px] text-[10px] xs:text-xs sm:text-sm font-medium py-2 sm:py-2.5 px-2 sm:px-3 rounded-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-slate-900 transition-all",children:e.jsx("span",{className:"truncate block",children:N.replace(/_/g," ")})},N))}),T.map(N=>{var _,I,B;return e.jsx(Ut,{value:N,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:w(N)})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-slate-900",children:N.replace(/_/g," ")}),e.jsxs(we,{className:"text-sm",children:[((_=D[N])==null?void 0:_.length)||0," setting",(((I=D[N])==null?void 0:I.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(J,{className:"space-y-6",children:(B=D[N])==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})]})]})}),v(k),k.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(P,{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(P,{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(sp,{className:"w-4 h-4"}),"Reset to Default"]})]})]},k.configKey))})]})},N)})]})]})}function tR(){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 N,_;try{r(!0),p(null);const I=await zT(n);s(I)}catch(I){p(((_=(N=I.response)==null?void 0:N.data)==null?void 0:_.error)||"Failed to load holidays")}finally{r(!1)}},j=()=>{f({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),o(!0)},y=N=>{f({holidayDate:N.holidayDate,holidayName:N.holidayName,description:N.description||"",holidayType:N.holidayType,isRecurring:N.isRecurring}),d(N),o(!0)},v=()=>{if(c)return;const N=new Date;return N.setDate(N.getDate()+1),N.toISOString().split("T")[0]},w=async()=>{var N,_;try{if(p(null),!g.holidayDate||!g.holidayName){p("Holiday date and name are required");return}c?(await GT(c.holidayId,g),W.success("Holiday updated successfully")):(await HT(g),W.success("Holiday created successfully")),await b(),o(!1),setTimeout(()=>h(null),3e3)}catch(I){p(((_=(N=I.response)==null?void 0:N.data)==null?void 0:_.error)||"Failed to save holiday")}},A=async N=>{var _,I;if(confirm(`Delete "${N.holidayName}"?`))try{p(null),await WT(N.holidayId),W.success("Holiday deleted successfully"),await b()}catch(B){const k=((I=(_=B.response)==null?void 0:_.data)==null?void 0:I.error)||"Failed to delete holiday";p(k),W.error(k)}},C=N=>{switch(N){case"NATIONAL":return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300";case"REGIONAL":return"bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-800 border-blue-300";case"ORGANIZATIONAL":return"bg-gradient-to-r from-purple-50 to-violet-50 text-purple-800 border-purple-300";case"OPTIONAL":return"bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-300";default:return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300"}},E=Array.from({length:5},(N,_)=>new Date().getFullYear()-1+_),D=t.reduce((N,_)=>{const I=new Date(_.holidayDate).toLocaleString("default",{month:"long"});return N[I]||(N[I]=[]),N[I].push(_),N},{}),T=Object.keys(D).sort((N,_)=>{const I=new Date(Date.parse(N+" 1, 2000")).getMonth(),B=new Date(Date.parse(_+" 1, 2000")).getMonth();return I-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(P,{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:N=>i(parseInt(N)),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:E.map(N=>e.jsx(X,{value:N.toString(),children:N},N))})]}),e.jsxs(P,{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(P,{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(N=>{var _,I,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:[N," ",n]}),e.jsxs(we,{className:"text-xs sm:text-sm",children:[((_=D[N])==null?void 0:_.length)||0," holiday",(((I=D[N])==null?void 0:I.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[N])==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:`${C(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:cg(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(P,{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(Zn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(P,{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(Hr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},k.holidayId))})]},N)})}),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:N=>f({...g,holidayDate:N.target.value}),min:v(),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:N=>f({...g,holidayName:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(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:N=>f({...g,description:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(He,{value:g.holidayType,onValueChange:N=>f({...g,holidayType:N}),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:N=>f({...g,isRecurring:N.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(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(P,{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(P,{onClick:w,disabled:!g.holidayDate||!g.holidayName,className:"h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(ft,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function sR(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function aR(){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,v]=x.useState({admins:0,management:0,users:0}),[w,A]=x.useState("ELEVATED"),[C,E]=x.useState(1),[D,T]=x.useState(1),[N,_]=x.useState(0),I=10,B=x.useRef(null),k=x.useRef(null),M=x.useCallback(sR(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),M(V)},F=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")}},S=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=C)=>{var V,Q,q,ee,te,ue;j(!0);try{const _e=await da.getUsersByRole(w,O,I),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&&(E(Ue.currentPage),T(Ue.totalPages),_(Ue.totalUsers)),Pe&&v({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)||[];v({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()},[w]);const $=O=>{A(O),E(1)},R=O=>{G(O)},H=O=>{A(O),E(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(tn,{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(Mj,{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 ${w==="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:w==="ADMIN"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-xl shadow-md",children:e.jsx(tn,{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 ${w==="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:w==="MANAGEMENT"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-blue-400 to-blue-500 rounded-xl shadow-md",children:e.jsx(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 ${w==="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:w==="USER"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-gray-400 to-gray-500 rounded-xl shadow-md",children:e.jsx(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:()=>F(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(P,{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(tn,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(P,{onClick:S,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 (",N," ",w!=="ALL"&&w!=="ELEVATED"?w.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(He,{value:w,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(tn,{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:w==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2","data-testid":"users-list",children:g.map(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 ",(C-1)*I+1," to ",Math.min(C*I,N)," of ",N," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(P,{variant:"outline",size:"sm",onClick:()=>R(C-1),disabled:C===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,D)},(O,V)=>{let Q;return D<=5||C<=3?Q=V+1:C>=D-2?Q=D-4+V:Q=C-2+V,e.jsx(P,{variant:C===Q?"default":"outline",size:"sm",onClick:()=>R(Q),className:`w-9 h-9 p-0 ${C===Q?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${Q}-button`,children:Q},Q)})}),e.jsx(P,{variant:"outline",size:"sm",onClick:()=>R(C+1),disabled:C===D,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function rR(){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,C;try{r(!0),d(null);const E=await QT(!1);s(E)}catch(E){const D=((C=(A=E.response)==null?void 0:A.data)==null?void 0:C.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,C;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 E={title:u.title.trim(),itemCode:u.itemCode.trim()||null,taxationType:u.taxationType.trim(),sapRefNo:u.sapRefNo.trim(),creditPostingOn:u.creditPostingOn.trim()};l?(await XT(l.activityTypeId,E),W.success("Activity type updated successfully")):(await KT(E),W.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>p(null),3e3)}catch(E){const D=((C=(A=E.response)==null?void 0:A.data)==null?void 0:C.error)||"Failed to save activity type";d(D),W.error(D)}},y=async A=>{var C,E;if(confirm(`Delete "${A.title}"? This will deactivate the activity type.`))try{d(null),await ZT(A.activityTypeId),W.success("Activity type deleted successfully"),await g()}catch(D){const T=((E=(C=D.response)==null?void 0:C.data)==null?void 0:E.error)||"Failed to delete activity type";d(T),W.error(T)}},v=t.filter(A=>A.isActive!==!1&&A.isActive!==void 0),w=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(P,{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(P,{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"})}):v.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(P,{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:[v.length," active type",v.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:v.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(P,{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(Zn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(P,{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(Hr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},A.activityTypeId))})]}),w.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:[w.length," inactive type",w.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:w.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(P,{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(Zn,{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(P,{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(P,{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 st({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 nR(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function jh({emails:t,onAdd:s,onRemove:a,placeholder:r}){const[n,i]=x.useState(""),l=()=>{const o=n.trim().toLowerCase();if(o){if(!nR(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(P,{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(st,{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(st,{children:[e.jsx(be,{className:"font-medium",children:o}),e.jsx(be,{className:"text-right",children:e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>a(o),className:"text-destructive hover:text-destructive",children:e.jsx(Hr,{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 yh(t,s){return{enabled:t,template:s}}const No=()=>({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 havent already."});function iR(){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(No()),[g,f]=x.useState(!0),[b,j]=x.useState(0),[y,v]=x.useState(yh(!0,"Form 16 submitted successfully. Credit note: [CreditNoteRef].")),[w,A]=x.useState(yh(!0,"Form 16 submission was unsuccessful. Issue: [Issue]. Please review.")),[C,E]=x.useState(!0),[D,T]=x.useState(0),[N,_]=x.useState(7),[I,B]=x.useState(0),[k,M]=x.useState(24),[L,F]=x.useState("09:00"),[S,G]=x.useState("Dear [Name], please submit Form 16A for the pending period. Due: [DueDate]."),[U,$]=x.useState(!0),[R,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 BT().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??No().templateRe,templateDealers:_e.templateDealers??No().templateDealers})}f(ue.reminder26AsUploadEnabled??!0),j(typeof ue.reminder26AsUploadAfterQuarterEndDays=="number"?ue.reminder26AsUploadAfterQuarterEndDays:0),ue.notificationForm16SuccessCreditNote&&v(ue.notificationForm16SuccessCreditNote),ue.notificationForm16Unsuccessful&&A(ue.notificationForm16Unsuccessful),E(ue.alertSubmitForm16Enabled??!0),T(typeof ue.alertSubmitForm16AfterQuarterEndDays=="number"?ue.alertSubmitForm16AfterQuarterEndDays:0),_(typeof ue.alertSubmitForm16EveryDays=="number"?ue.alertSubmitForm16EveryDays:7),B(ue.alertSubmitForm16FrequencyDays??0),M(ue.alertSubmitForm16FrequencyHours??24),F(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 VT({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:w,alertSubmitForm16Enabled:C,alertSubmitForm16AfterQuarterEndDays:Math.max(0,Math.min(365,D)),alertSubmitForm16EveryDays:Math.max(1,Math.min(365,N)),alertSubmitForm16FrequencyDays:Math.max(0,Math.min(365,I)),alertSubmitForm16FrequencyHours:Math.max(0,Math.min(168,k)),alertSubmitForm16RunAtTime:L??"",alertSubmitForm16Template:S,reminderNotificationEnabled:U,reminderFrequencyDays:Math.max(0,Math.min(365,R)),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,w==null?void 0:w.enabled,C,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(uu,{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(jh,{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(uu,{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(jh,{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:N,onChange:te=>_(parseInt(te.target.value||"7",10)||7),className:"w-24"})]})]})]}),e.jsx(os,{checked:C,onCheckedChange:E})]}),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=>v(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:w.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(P,{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:R,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(P,{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 lR(){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(""),[v,w]=x.useState(""),[A,C]=x.useState({code:"",type:"HSN",gstRate:"",description:"",isActive:!0});x.useEffect(()=>{const B=setTimeout(()=>{w(j),p(1)},500);return()=>clearTimeout(B)},[j]),x.useEffect(()=>{E()},[m,v]);const E=async()=>{var B,k;try{r(!0),d(null);const M=await vf(!1,m,b,v);s(M.codes),h(M.pagination.totalPages),f(M.pagination.totalRecords)}catch(M){const L=((k=(B=M.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=()=>{C({code:"",type:"HSN",gstRate:"",description:"",isActive:!0}),o(null),i(!0)},T=B=>{var k;C({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)},N=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:M,message:L}=ba(A.code,A.type==="SAC");if(!M){d(L),W.error(L);return}const F={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 i4(l.id,F),W.success(`${A.type} code updated successfully`)):(await n4(F),W.success(`${A.type} code created successfully`)),await E(),i(!1)}catch(M){const L=((k=(B=M.response)==null?void 0:B.data)==null?void 0:k.error)||"Failed to save code";d(L),W.error(L)}},_=async B=>{var k,M;if(confirm(`Delete ${B.type} code "${B.code}"?`))try{d(null),await l4(B.id),W.success("Code deleted successfully"),await E()}catch(L){const F=((M=(k=L.response)==null?void 0:k.data)==null?void 0:M.error)||"Failed to delete code";d(F),W.error(F)}},I=async B=>{try{await o4(B),await E(),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(P,{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(Eo,{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(P,{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:v?e.jsx(Lj,{className:"w-10 h-10 text-slate-400"}):e.jsx(Eo,{className:"w-10 h-10 text-slate-400"})}),e.jsx("p",{className:"text-slate-700 font-medium text-lg",children:v?`No results for "${v}"`:"No HSN/SAC codes found"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:v?"Try a different search term":"Add codes to use in dealer claims"}),v?e.jsx(P,{onClick:()=>y(""),variant:"outline",children:"Clear Search"}):e.jsxs(P,{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(oR,{code:B,onEdit:()=>T(B),onDelete:()=>_(B),onToggle:()=>I(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(P,{variant:"outline",size:"sm",onClick:()=>p(B=>Math.max(1,B-1)),disabled:m===1,className:"gap-1 h-9",children:[e.jsx(hn,{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 M=k+1;return u<=7||M===1||M===u||M>=m-1&&M<=m+1?e.jsx(P,{variant:m===M?"default":"outline",size:"sm",onClick:()=>p(M),className:`w-9 h-9 p-0 ${m===M?"bg-slate-800":"text-slate-600"}`,children:M},M):M===m-2&&M>1||M===m+2&&M<u?e.jsx("span",{className:"px-1 text-slate-400",children:"..."},M):null})}),e.jsxs(P,{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=>C({...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=>C({...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=>C({...A,description:B.target.value})})]})]}),e.jsxs(Dt,{children:[e.jsx(P,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(P,{onClick:N,className:"bg-re-green hover:bg-re-green/90 text-white",children:l?"Update Code":"Create Code"})]})]})})]})}function oR({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(Oj,{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(P,{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(Zn,{className:"w-4 h-4"})}),e.jsx(P,{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(Hr,{className:"w-4 h-4"})})]}),e.jsx(P,{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 cR({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(P,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const dR=async()=>(await ve.get("/user/preferences/notifications")).data.data,mR=async t=>(await ve.put("/user/preferences/notifications",t)).data.data;function uR({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 dR();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},v=await mR(y);r(v),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(cr,{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 xR(){const t=Cs(),{user:s}=us(),a=kr(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),[v,w]=x.useState(!1),[A,C]=x.useState(!1);x.useEffect(()=>{E()},[]);const E=async()=>{try{b(!0);const T=await Rv();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 qD(),l(!0),c("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),n(!0),await E()}catch(T){console.error("[Settings] Error enabling notifications:",T),l(!1);const N=(T==null?void 0:T.message)||"Unknown error occurred";c(N.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":N.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":N.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${N}`),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(cr,{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(bi,{defaultValue:"user",className:"w-full",children:[e.jsxs(ji,{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(cr,{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(op,{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(P,{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(lr,{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(P,{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(lr,{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(xu,{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(P,{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(aR,{})}),e.jsx(Ut,{value:"system",className:"mt-0",children:e.jsx(eR,{})}),e.jsx(Ut,{value:"holidays",className:"mt-0",children:e.jsx(tR,{})}),e.jsx(Ut,{value:"templates",className:"mt-0",children:v?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(P,{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-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(iR,{})]}):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(P,{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(rR,{})]}):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(P,{variant:"ghost",size:"sm",onClick:()=>C(!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(lR,{})]}):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:()=>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-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:()=>C(!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(P,{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(lr,{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(P,{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(lr,{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(xu,{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(P,{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(cR,{open:r,onClose:()=>n(!1),success:i,message:o}),e.jsx(uR,{open:p,onClose:()=>u(!1)})]})}const hR=Ac("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 pR({className:t,variant:s,...a}){return e.jsx("div",{"data-slot":"alert",role:"alert",className:Le(hR({variant:s}),t),...a})}function gR({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 fR({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 bR(){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)}},v=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)}},w=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")}},C=()=>{m&&(navigator.clipboard.writeText(m),f(!0),setTimeout(()=>f(!1),2e3),W.success("Token copied to clipboard"))},E=()=>{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(P,{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(cp,{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(st,{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(st,{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?tt(new Date(D.lastUsedAt),"MMM d, yyyy"):"Never"}),e.jsx(be,{className:"text-gray-500 text-sm",children:D.expiresAt?tt(new Date(D.expiresAt),"MMM d, yyyy"):"No Expiry"}),e.jsx(be,{className:"text-right",children:e.jsxs(P,{variant:"ghost",size:"sm",onClick:()=>w(D),className:"text-red-600 hover:text-red-700 hover:bg-red-50",children:[e.jsx(Hr,{className:"w-4 h-4"}),e.jsx("span",{className:"sr-only",children:"Revoke"})]})})]},D.id))})]})}),e.jsx(xt,{open:n,onOpenChange:D=>!D&&E(),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(pR,{className:"bg-green-50 border-green-200",children:[e.jsx($a,{className:"h-4 w-4 text-green-600"}),e.jsx(gR,{className:"text-green-800",children:"Token Generated Successfully"}),e.jsx(fR,{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(P,{size:"icon",variant:"ghost",className:"absolute top-1 right-1 text-gray-400 hover:text-white hover:bg-slate-800",onClick:C,children:g?e.jsx($a,{className:"w-4 h-4 text-green-500"}):e.jsx($j,{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 N=parseInt(T);!isNaN(N)&&N>=1&&d(N)}}})]})]}),e.jsx(Dt,{children:m?e.jsx(P,{onClick:E,children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(P,{variant:"outline",onClick:E,children:"Cancel"}),e.jsx(P,{onClick:v,disabled:!l.trim()||u,children:u?"Generating...":"Generate Token"})]})})]})}),e.jsx(Dp,{open:!!b,onOpenChange:D=>!D&&j(null),children:e.jsxs(kc,{children:[e.jsxs(Fp,{children:[e.jsx(Pp,{children:"Revoke API Token"}),e.jsxs(Ep,{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(Ip,{children:[e.jsx(Mp,{children:"Cancel"}),e.jsx(_p,{onClick:A,className:"bg-red-600 hover:bg-red-700 text-white",children:"Revoke Token"})]})]})})]})}function jR(){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(P,{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(lr,{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(cp,{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(bR,{})})]})]})]})}function yR({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,N=p==="unread")=>{var _,I;try{n(T===1);const B=await or.list({page:T,limit:f,unreadOnly:N}),k=((_=B.data)==null?void 0:_.notifications)||[],M=((I=B.data)==null?void 0:I.pagination)||{},L=M.total||0,F=M.totalPages||1;a(k),m(L),c(F),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 N;try{if(T.isRead||(await or.markAsRead(T.notificationId),a(_=>_.map(I=>I.notificationId===T.notificationId?{...I,isRead:!0}:I))),T.actionUrl&&t){const _=(N=T.metadata)==null?void 0:N.requestNumber;if(_){let I=`request/${_}`;(T.notificationType==="mention"||T.notificationType==="comment"||T.notificationType==="worknote")&&(I+="?tab=worknotes"),T.notificationType==="document_added"&&(I+="?tab=documents"),t(I)}}}catch(_){console.error("[Notifications] Error handling notification click:",_)}},y=async()=>{try{g(!0),await or.markAllAsRead(),await b(i,p==="unread")}catch(T){console.error("[Notifications] Error marking all as read:",T),g(!1)}},v=async T=>{try{await or.delete(T),a(N=>N.filter(_=>_.notificationId!==T)),m(N=>N-1)}catch(N){console.error("[Notifications] Error deleting notification:",N)}},w=()=>{g(!0),b(i,p==="unread")},A=T=>{T<1||T>o||(l(T),b(T,p==="unread"))},C=T=>{const N="w-6 h-6";switch(T){case"mention":case"comment":return e.jsx(Ys,{className:`${N} text-blue-600`});case"worknote":return e.jsx(Fe,{className:`${N} text-purple-600`});case"document_added":return e.jsx(Fe,{className:`${N} text-teal-600`});case"assignment":return e.jsx(hl,{className:`${N} text-indigo-600`});case"approval":return e.jsx(Be,{className:`${N} text-green-600`});case"rejection":return e.jsx(St,{className:`${N} text-red-600`});case"tat_alert":return e.jsx(it,{className:`${N} text-orange-600`});case"tat_breach":return e.jsx(Je,{className:`${N} text-red-600`});case"tat_breach_initiator":return e.jsx(ss,{className:`${N} text-amber-600`});default:return e.jsx(_s,{className:`${N} text-gray-600`})}},E=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(P,{variant:"outline",size:"sm",onClick:w,disabled:h,className:"gap-2",children:[e.jsx(Et,{className:`w-4 h-4 ${h?"animate-spin":""}`}),"Refresh"]}),D>0&&e.jsxs(P,{variant:"outline",size:"sm",onClick:y,disabled:h,className:"gap-2",children:[e.jsx(Uj,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{variant:p==="all"?"default":"outline",size:"sm",onClick:()=>{u("all"),l(1)},children:"All Notifications"}),e.jsxs(P,{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 N;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:C(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 ${E(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:[Hh(new Date(T.createdAt),{addSuffix:!0}),((N=T.metadata)==null?void 0:N.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",T.metadata.requestNumber]})]}),e.jsx(P,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:_=>{_.stopPropagation(),v(T.notificationId)},children:e.jsx(Hr,{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(P,{variant:"outline",size:"sm",onClick:()=>A(i-1),disabled:i===1,children:[e.jsx(hn,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,o)},(T,N)=>{let _;return o<=5||i<=3?_=N+1:i>=o-2?_=o-4+N:_=i-2+N,e.jsx(P,{variant:i===_?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>A(_),children:_},_)})}),e.jsxs(P,{variant:"outline",size:"sm",onClick:()=>A(i+1),disabled:i===o,children:["Next",e.jsx(Ka,{className:"w-4 h-4"})]})]})]})]})}function vR({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(P,{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 Sd({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?`${tt(s,"d MMM yyyy")} - ${tt(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(P,{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(P,{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(P,{size:"sm",variant:"outline",onClick:p,"data-testid":`${u}-cancel-button`,children:"Cancel"})]})]})})]})]})}function NR(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 Bf(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 Vf(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 wR(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function CR({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:v,onViewRequest:w}){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(P,{variant:"outline",size:"sm",className:"gap-2",onClick:v,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(Sd,{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:()=>w(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:C=>{C.stopPropagation(),w(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:Bf(A.priority),"data-testid":`lifecycle-priority-${A.id}`,children:A.priority}),e.jsx(re,{className:Vf(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(P,{variant:"ghost",size:"sm",onClick:()=>w(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(P,{variant:"outline",size:"sm",onClick:()=>y(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(P,{variant:"outline",size:"sm",onClick:()=>y(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function SR({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:v,onCategoryChange:w,onSeverityChange:A,onClearFilters:C,onPageChange:E,onExport:D,onViewRequest:T}){const N=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(lp,{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(P,{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(Sd,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:g,onShowCustomDatePickerChange:f,onStartDateChange:b,onEndDateChange:j,onApply:y,onCancel:v,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:w,"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"})]})]})]}),N&&e.jsx(P,{variant:"ghost",size:"sm",onClick:C,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(st,{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((_,I)=>e.jsxs(st,{className:"hover:bg-gray-50","data-testid":`activity-row-${I}`,children:[e.jsx(be,{className:"text-xs font-medium",children:_.timestamp}),e.jsx(be,{className:"text-sm",children:_.user}),e.jsx(be,{children:e.jsx(re,{className:NR(_.action),"data-testid":`activity-action-${I}`,children:_.action})}),e.jsx(be,{className:"text-sm text-gray-600",children:_.details}),e.jsx(be,{className:"text-xs font-mono text-gray-500",children:_.ip&&_.ip!=="N/A"?e.jsx("span",{title:_.userAgent||"",children:_.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(be,{children:_.requestId!=="-"&&_.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const B=_.requestId;B&&T(B)},className:"hover:underline","data-testid":`activity-request-link-${I}`,children:e.jsx(re,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:_.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},I))})]}),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(P,{variant:"outline",size:"sm",onClick:()=>E(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(P,{variant:"outline",size:"sm",onClick:()=>E(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function AR({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:v,onEndDateChange:w,onApplyCustomDate:A,onCancelCustomDate:C,onSearchChange:E,onPageChange:D,onExport:T,onViewRequest:N}){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(yc,{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:_=>f(_.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(P,{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(Sd,{dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:p,tempCustomEndDate:u,onDateRangeChange:j,onShowCustomDatePickerChange:y,onStartDateChange:v,onEndDateChange:w,onApply:A,onCancel:C,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:_=>E(_.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(st,{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(_=>e.jsxs(st,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${_.id}`,children:[e.jsx(be,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>N(_.requestId||_.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${_.id}`,children:_.id})}),e.jsx(be,{className:"text-sm",children:_.title}),e.jsx(be,{className:"text-sm",children:_.initiator}),e.jsx(be,{className:"text-sm text-gray-600",children:_.startDate}),e.jsx(be,{children:e.jsxs(re,{className:`${wR(_.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${_.id}`,children:[_.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(be,{className:"text-sm",children:_.currentStage}),e.jsx(be,{className:"text-sm",children:_.assignedTo&&_.assignedTo!=="N/A"?_.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:Bf(_.priority),"data-testid":`aging-priority-${_.id}`,children:_.priority})}),e.jsx(be,{children:e.jsx(re,{className:Vf(_.status),"data-testid":`aging-status-${_.id}`,children:_.status})})]},_.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(P,{variant:"outline",size:"sm",onClick:()=>D(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(P,{variant:"outline",size:"sm",onClick:()=>D(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function wo(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(w=>{const A=w;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 w=d;n(p),l(w),m(p),u(w)}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(w=>{w?(m(w),p&&w>p&&u(w)):m(void 0)},[p]),j=x.useCallback(w=>{w?(u(w),d&&w<d&&m(w)):u(void 0)},[d]),y=x.useCallback(()=>r&&i?`${tt(r,"MMM d, yyyy")} - ${tt(i,"MMM d, yyyy")}`:"Select dates",[r,i]),v=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:v}}function TR(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 zf(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 Ir(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 Hf(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 kR=10;function DR({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,kR,t,s,a),y=j.lifecycleData.map(v=>{const w=TR(v.overallTATHours);return{id:v.requestNumber,requestId:v.requestId,title:v.title,priority:v.priority||"medium",status:v.status,initiator:v.initiatorName||"Unknown",initDate:zf(v.submissionDate),currentStage:v.currentStageName||`Level ${v.currentLevel}`,overallTAT:w,currentLevel:v.currentLevel,totalLevels:v.totalLevels,breachCount:v.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 RR=20;function FR({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 v=await Ot.getActivityLogReport(j,RR,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),w=v.activities.map(A=>{const C=Hf(A.type||"",A.details),E=(A.type||"").toLowerCase()==="login"||A.requestId==="00000000-0000-0000-0000-000000000001"||A.requestId==="SYSTEM_LOGIN",D=E?A.details||"User login":A.requestTitle||A.requestNumber||A.details||"N/A";return{timestamp:A.timestamp?zf(A.timestamp):"N/A",user:A.userName||"Unknown",action:C,details:D,ip:A.ipAddress||"N/A",userAgent:A.userAgent||null,requestId:E?"System Login":A.requestNumber||A.requestId||"-",userId:A.userId}});l(w),g({page:v.pagination.currentPage,totalPages:v.pagination.totalPages,totalRecords:v.pagination.totalRecords})}catch(v){console.error("Failed to fetch activity data:",v),u((v==null?void 0:v.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 IR=20;function PR({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 v=y===1&&f.current;try{v?c(!0):m(!0),u(null);const w=parseInt(t,10);if(isNaN(w)||w<1){u("Please enter a valid threshold (minimum 1 day)");return}const A=await Ot.getWorkflowAgingReport(w,y,IR,s,a,r),C=A.agingData.map(E=>({id:E.requestNumber||E.requestId,requestId:E.requestId,title:E.title,initiator:E.initiatorName||"Unknown",startDate:E.submissionDate?new Date(E.submissionDate).toLocaleDateString():"N/A",daysOpen:E.daysOpen,currentStage:E.currentStageName||`Level ${E.currentLevel}`,assignedTo:E.currentApproverName||"N/A",priority:E.priority||"medium",status:E.status||"pending"}));l(C),g({page:A.pagination.currentPage,totalPages:A.pagination.totalPages,totalRecords:A.pagination.totalRecords})}catch(w){console.error("Failed to fetch aging data:",w),u((w==null?void 0:w.message)||"Failed to load aging data")}finally{v?c(!1):m(!1)}v&&(f.current=!1)},[t,s,a,r]),j=x.useMemo(()=>i.filter(y=>{var w,A,C;if(!n)return!0;const v=n.toLowerCase();return((w=y.id)==null?void 0:w.toLowerCase().includes(v))||((A=y.title)==null?void 0:A.toLowerCase().includes(v))||((C=y.initiator)==null?void 0:C.toLowerCase().includes(v))}),[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 ER(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 _R(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?Ir(i.submissionDate):"N/A",c=i.closureDate?Ir(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?Ir(g.levelStartTime):"N/A",b=g.levelEndTime||g.completedAt?Ir(g.levelEndTime||g.completedAt):"N/A",j=g.tatHours||0,y=g.tatDays||(j>0?(j/8).toFixed(2):"0");let v="N/A",w="N/A",A="N/A",C="N/A";if(g.levelStartTime){const D=new Date(g.levelStartTime);if(w=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-D.getTime())/(1e3*60*60)).toFixed(2),j>0){const _=parseFloat(w);A=Math.max(0,j-_).toFixed(2),C=(_/j*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?v=_<=j?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?v=_<=j?"On Track":"At Risk":v="N/A"}}const E=[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(),v,w,A,C];n.push(E.join(","))})}catch(l){console.error(`Failed to fetch details for request ${i.requestNumber}:`,l);const o=i.submissionDate?Ir(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(","))}Ad(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function MR(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=Hf(o.type||"",o.details),m=[o.timestamp?Ir(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(","))}),Ad(l,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function LR(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?Ir(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(","))}),Ad(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function Ad(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 OR(){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 _R(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 MR(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 LR(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 $R({onBack:t}){const s=Cs(),[a,r]=x.useState(""),[n,i]=x.useState("all"),[l,o]=x.useState("all"),c=wo("month"),d=wo("month"),m=wo("month"),p=ER("7"),u=DR({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),h=FR({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:l}),g=PR({threshold:p.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),f=OR(),b=x.useCallback(()=>{t?t():s("/dashboard")},[t,s]),j=x.useCallback(C=>{nl({requestId:C,navigate:s})},[s]),y=x.useCallback(()=>{f.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[f,c]),v=x.useCallback(()=>{f.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,l)},[f,d,n,l]),w=x.useCallback(()=>{const C=parseInt(p.threshold,10);!isNaN(C)&&C>=1&&f.handleExportAging(C,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(vR,{onBack:b}),e.jsx(CR,{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(SR,{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:v,onViewRequest:j}),e.jsx(AR,{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:w,onViewRequest:j})]})})}function Di({className:t,...s}){return e.jsx("div",{"data-slot":"skeleton",className:Le("bg-accent animate-pulse rounded-md",t),...s})}function UR(){const t=Cs(),[s,a]=x.useState(()=>nh()||[]),[r,n]=x.useState(()=>!nh()),[i,l]=x.useState(""),o=async()=>{try{s.length===0&&n(!0);const m=await Il();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(P,{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(Di,{className:"h-6 w-3/4 mb-2"}),e.jsx(Di,{className:"h-4 w-1/2"})]}),e.jsxs(J,{children:[e.jsx(Di,{className:"h-4 w-full mb-2"}),e.jsx(Di,{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(P,{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(P,{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(Bj,{className:"w-4 h-4 mr-2"}),"Edit"]})})]})]},m.id)})})]})}function vh(){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}=W0(),[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 Il()).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(E){console.error("Failed to load template:",E),W.error("Failed to load template details")}finally{l(!1)}})()},[a,s,t]);const f=C=>{const{name:E,value:D}=C.target;g(T=>({...T,[E]:D}))},b=(C,E)=>{g(D=>({...D,[C]:E}))},j=C=>{if(u(C),C.startsWith("@")&&C.slice(1).length>=1){d(C,5);return}m()},y=C=>{if(h.approvers.some(E=>E.userId===C.userId)){W.error("Approver already added");return}g(E=>({...E,approvers:[...E.approvers,{userId:C.userId,name:C.displayName||C.email,email:C.email,level:E.approvers.length+1,tat:24,tatType:"hours"}]})),u(""),m()},v=C=>{const E=[...h.approvers];E.splice(C,1),E.forEach((D,T)=>D.level=T+1),g(D=>({...D,approvers:E}))},w=async C=>{if(C.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 E={...h,approvers:h.approvers.map(D=>({...D,tat:D.tatType==="days"?parseInt(D.tat)*24:parseInt(D.tat)}))};try{n(!0),a&&s?(await f5(s,E),W.success("Template updated successfully")):(await g5(E),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(C=>{const E=parseInt(String(C.tat))||0,D=C.tatType==="days"?7:24;return E>=1&&E<=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(P,{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:w,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:C=>b("priority",C),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((C,E)=>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 ",C.level]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:C.name}),e.jsx("div",{className:"text-sm text-gray-500",children:C.email})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(se,{htmlFor:`tat-${E}`,className:"text-xs whitespace-nowrap",children:"TAT"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Re,{id:`tat-${E}`,type:"number",className:"h-8 w-16 border-gray-200",value:C.tat||"",min:1,max:C.tatType==="days"?7:24,placeholder:C.tatType==="days"?"1":"24",onChange:D=>{if((parseInt(D.target.value)||0)<0)return;const N=[...h.approvers];N[E].tat=D.target.value,g(_=>({..._,approvers:N}))}}),e.jsxs(He,{value:C.tatType||"hours",onValueChange:D=>{const T=[...h.approvers];T[E].tatType=D,T[E].tat=1,g(N=>({...N,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(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>v(E),children:e.jsx(yt,{className:"w-4 h-4 text-gray-500 hover:text-red-600"})})]},E)),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:C=>j(C.target.value),className:"border-gray-200"})}),(c||o.length>0)&&e.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-white border rounded-lg shadow-lg z-10 max-h-60 overflow-y-auto",children:[c&&e.jsx("div",{className:"p-2 text-sm text-gray-500",children:"Searching..."}),o.map(C=>e.jsxs("div",{className:"p-2 hover:bg-gray-50 cursor-pointer flex items-center gap-3",onClick:()=>y(C),children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{children:(C.displayName||"U").substring(0,2)})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:C.displayName}),e.jsx("div",{className:"text-xs text-gray-500",children:C.email})]})]},C.userId))]})]}),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 C=h.approvers.reduce((D,T)=>{const N=Number(T.tat||0);return(T.tatType||"hours")==="days"?D+N:D+N/24},0)||0,E=Math.ceil(C);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[E," ",E===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((C,E)=>{const D=Number(C.tat||0),N=(C.tatType||"hours")==="days"?D*24:D;return D?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",E+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[N," ",N===1?"hour":"hours"]})]})},E):null})}),(()=>{const C=h.approvers.reduce((D,T)=>{const N=Number(T.tat||0);return(T.tatType||"hours")==="days"?D+N*24:D+N},0)||0,E=Math.ceil(C/8);return C===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[C,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children:E}),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(P,{type:"button",variant:"outline",onClick:()=>t("/admin/templates"),children:"Cancel"}),e.jsx(P,{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 BR({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(ui,{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(P,{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(P,{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(Wr,{fileName:l.file.name,fileType:l.file.type,fileUrl:l.url,fileSize:l.file.size,open:!!l,onClose:p})]})}function VR({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 zR(){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 v=(await Il()).find(w=>w.id===t);if(v){const w={id:v.id,name:v.name,description:v.description,category:v.category,icon:Fe,estimatedTime:v.estimatedTime,commonApprovers:v.approvers.map(A=>A.name),workflowApprovers:v.approvers,suggestedSLA:v.suggestedSLA,priority:v.priority,fields:v.fields||{}};c(w),g({title:w.name,description:w.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(w=>({email:w.email,name:w.name,tat:w.tat,tatType:"hours"})),spectators:[],ccList:[]},v=await Oc(y,p);v&&v.id&&await lg(v.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(P,{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(P,{variant:"outline",onClick:()=>s("/dashboard"),children:"Cancel Request"})]}),e.jsx(G0,{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(BR,{template:o,formData:h,setFormData:g,documents:p,setDocuments:u}):e.jsx(VR,{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(P,{variant:"outline",onClick:()=>d===1?s("/new-request"):m(1),disabled:i,children:d===1?"Cancel":"Back to Details"}),e.jsx(P,{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(P,{variant:"outline",onClick:()=>s("/dashboard"),children:"Go to Dashboard"}),e.jsx(P,{onClick:()=>s("/new-request"),children:"Browse Templates"})]})]})})}function HR({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 GR({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 WR=["CSV","Excel","PDF","JSON"];function YR({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:WR.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(wd,{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 QR({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 KR(){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(HR,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(Jt,{}),e.jsx(GR,{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(YR,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(QR,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(P,{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 XR=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"}},ZR=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function JR({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(st,{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(st,{children:e.jsx(be,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(st,{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:ZR(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:XR(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(P,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx(jl,{className:"w-4 h-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(Vj,{className:"w-4 h-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(Hr,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function qR({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 eF(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function tF(){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,v]=x.useState(!1),[w,A]=x.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[C,E]=x.useState("ELEVATED"),[D,T]=x.useState(1),[N,_]=x.useState(1),[I,B]=x.useState(0),k=10,M=x.useRef(null),L=x.useCallback(eF(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),[]),F=q=>{const ee=q.target.value;s(ee),L(ee)},S=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 S(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 R(),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;v(!0);try{const Pe=await da.getUsersByRole(C,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),_(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{v(!1)}},R=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),R()},[C]);const H=q=>{E(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 R()}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=>{M.current&&!M.current.contains(ee.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",q),()=>{document.removeEventListener("mousedown",q)}},[a]);const Q={total:w.total,active:w.active,inactive:w.inactive,admins:w.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(qR,{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(P,{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:M,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:F,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(P,{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(tn,{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 (",I," ",C!=="ALL"&&C!=="ELEVATED"?C.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(He,{value:C,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 (",w.admins+w.management,")"]})]})}),e.jsx(X,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tn,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",w.admins,")"]})]})}),e.jsx(X,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",w.management,")"]})]})}),e.jsx(X,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",w.users,")"]})]})}),e.jsx(X,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",w.admins+w.management+w.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:C==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(JR,{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}),N>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t mt-4",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(D-1)*k+1," to ",Math.min(D*k,I)," of ",I," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(P,{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,N)},(q,ee)=>{let te;return N<=5||D<=3?te=ee+1:D>=N-2?te=N-4+ee:te=D-2+ee,e.jsx(P,{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(P,{variant:"outline",size:"sm",onClick:()=>K(D+1),disabled:D===N,children:"Next"})]})]})]})})]})]})}function sF({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(ml,{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 aF({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(oc,{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(oc,{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 Mn=[{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 rF({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:Mn.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:Mn.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=Mn.find(p=>p.value===a))==null?void 0:c.label} only`:` ${(d=Mn.find(p=>p.value===a))==null?void 0:d.label} to ${(m=Mn.find(p=>p.value===r))==null?void 0:m.label}`]})})]})]})}function nF(){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 Fl("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(sF,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx(Jt,{}),e.jsx(rF,{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(aF,{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(P,{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 iF({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 lF({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 oF({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 cF(){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(iF,{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(lF,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(oF,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(P,{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 dF({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(yl,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const mF=[{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 uF({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(jc,{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:mF.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 xF(){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 Fl("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(dF,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx(Jt,{}),e.jsx(uF,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:d=>c({allowedFileTypes:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(P,{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 hF(){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 pF=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],gF=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 fF({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:gF(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:pF.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(wd,{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 bF(){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(hF,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(fF,{role:i,kpis:t[i]||{},onKPIToggle:(l,o)=>r(i,l,o)},i))}),e.jsxs(P,{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 jF({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(dp,{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 yF({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(ul,{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 vF({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(op,{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 NF(){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 Fl("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(ul,{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(jF,{aiEnabled:n.aiEnabled,onAiEnabledChange:d=>c({aiEnabled:d})}),e.jsx(Jt,{}),e.jsx(yF,{aiRemarkGeneration:n.aiRemarkGeneration,onRemarkGenerationChange:d=>c({aiRemarkGeneration:d})}),e.jsx(Jt,{}),e.jsx(vF,{maxRemarkChars:n.maxRemarkChars,onMaxRemarkCharsChange:d=>c({maxRemarkChars:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(P,{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 Nh=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function wF({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:Nh.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:Nh.map(n=>e.jsx(X,{value:n,children:n},n))})]})]})]})}function CF({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 SF(){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(wF,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(Jt,{}),e.jsx(CF,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(P,{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 AF(){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(P,{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(bi,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(ji,{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(Xi,{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(zj,{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(dp,{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(fn,{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(Hj,{className:"w-3 h-3"}):e.jsx(Gj,{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(KR,{})}),e.jsx(Ut,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(tF,{})}),e.jsx(Ut,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(nF,{})}),e.jsx(Ut,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(cF,{})}),e.jsx(Ut,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(xF,{})}),e.jsx(Ut,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(bF,{})}),e.jsx(Ut,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(NF,{})}),e.jsx(Ut,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(SF,{})})]})]})}function TF(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 Co(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}const So={totalCreditNotes:0,totalAmount:0,activeDealersCount:0};function kF(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function DF(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 RF(){const[t,s]=x.useState([]),[a,r]=x.useState(So),[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 v=await $p(y);s(v.creditNotes),r(v.summary??So)}catch(v){console.error("[Form16CreditNotes] Failed to fetch:",v),W.error(v instanceof Error?v.message:"Failed to load credit notes"),s([]),r(So)}finally{i(!1)}},[]);x.useEffect(()=>{g()},[g]);const f=x.useCallback(async(y,v)=>{var w;d(!0),p(!0),h(null);try{const A=await Rc(y),C=(v||`credit-note-${y}`).trim()+".csv",E=kF(A.sapResponse),D=t.find(_=>Number(_.id)===Number(y)),T=Co((D==null?void 0:D.amount)??null),N=DF((D==null?void 0:D.issueDate)??null);h({fileName:C,row:E,meta:{amountText:T,issuedAtText:N},downloadUrl:A.url||null})}catch(A){const C=((w=A==null?void 0:A.response)==null?void 0:w.status)===409?"The credit note is being generated, wait.":A instanceof Error?A.message:"Failed to load SAP response";W.error(String(C)),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(v=>{var w;return v.creditNoteNumber&&v.creditNoteNumber.toLowerCase().includes(y)||v.dealerName&&v.dealerName.toLowerCase().includes(y)||v.dealerCode&&v.dealerCode.toLowerCase().includes(y)||((w=v.submission)==null?void 0:w.form16aNumber)&&v.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(vl,{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(P,{variant:"outline",onClick:()=>d(!1),children:"Close"}),e.jsxs(P,{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?"...":Co(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(st,{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(st,{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(st,{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 v,w,A;return e.jsxs(st,{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:((v=y.submission)==null?void 0:v.form16aNumber)??""}),e.jsx(be,{children:Co(y.amount)}),e.jsx(be,{children:TF(y.issueDate)}),e.jsx(be,{children:e.jsx(re,{className:((w=y.status)==null?void 0:w.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(P,{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(P,{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 Ao(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 To(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function FF(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function IF(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 PF(){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 N=s?parseInt(s,10):NaN;if(Number.isNaN(N)){i(!1);return}let _=!1;return Du(N).then(I=>{_||r(I)}).catch(I=>{_||(W.error(I instanceof Error?I.message:"Failed to load credit note"),t("/form16/credit-notes"))}).finally(()=>{_||i(!1)}),()=>{_=!0}},[s,t]);const b=()=>{W.info("Resend to dealer integration pending")},j=async()=>{var _;const N=s?parseInt(s,10):NaN;if(!Number.isNaN(N)){o(!0);try{const I=await Du(N);r(I),(_=I.creditNote)!=null&&_.sapResponseAvailable?W.success("Credit note is available to download."):W.info("Credit note is being generated. Please wait.")}catch(I){W.error(I instanceof Error?I.message:"Failed to pull credit note")}finally{o(!1)}}},y=async()=>{var _;const N=s?parseInt(s,10):NaN;if(!Number.isNaN(N))try{d(!0),p(!0),h(null),f(null);const I=await Rc(N),B=FF(I.sapResponse);h(B),f(I.url||null)}catch(I){const B=((_=I==null?void 0:I.response)==null?void 0:_.status)===409?"The credit note is being generated, wait.":I instanceof Error?I.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:v,dealerName:w,dealerEmail:A,dealerContact:C,dealerCreditNotes:E}=a,D=v.creditNoteNumber?v.creditNoteNumber.startsWith("CN")?v.creditNoteNumber:`CN #${v.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:N=>{d(N),N||(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:To(v.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(vl,{className:"w-4 h-4"})," Issued Date"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:IF(v.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(P,{variant:"outline",onClick:()=>d(!1),children:"Close"}),e.jsxs(P,{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(P,{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(P,{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:v.status??"Issued"})]}),e.jsxs("p",{className:"text-sm text-gray-500",children:["Issued on ",Ao(v.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:To(v.amount)})]})]}),e.jsx("div",{className:"flex justify-end gap-2 mt-4",children:v.sapResponseAvailable?e.jsxs(P,{variant:"outline",size:"sm",onClick:y,children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),"Download Credit Note"]}):e.jsxs(P,{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:w||""})]}),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=v.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:C||""})]})]})]})}),e.jsxs(Z,{children:[e.jsxs(ce,{children:[e.jsx(de,{children:"Dealer Transaction History"}),e.jsxs(we,{children:["All credit notes issued to ",w||"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(st,{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:E.length===0?e.jsx(st,{children:e.jsx(be,{colSpan:7,className:"text-center py-8 text-gray-500",children:"No other credit notes for this dealer"})}):E.map(N=>{var _,I;return e.jsxs(st,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(be,{children:Ao(N.submittedDate)}),e.jsx(be,{children:N.form16aNumber??""}),e.jsx(be,{children:To(N.amount)}),e.jsx(be,{children:e.jsx(re,{className:"bg-green-100 text-green-800 border-green-200",children:"Yes"})}),e.jsx(be,{children:N.creditNoteNumber?N.creditNoteNumber.startsWith("CN")?N.creditNoteNumber:`CN #${N.creditNoteNumber}`:""}),e.jsx(be,{children:Ao(N.issueDate)}),e.jsx(be,{children:e.jsx(re,{className:((_=N.status)==null?void 0:_.toLowerCase())==="withdrawn"?"bg-red-50 text-red-700 border-red-200":"bg-green-100 text-green-800 border-green-200",children:((I=N.status)==null?void 0:I.toLowerCase())==="withdrawn"?"Withdrawn":"Completed"})})]},N.id)})})]})})})]})]})]})}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 ko(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}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 MF(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}const Do={totalDebitNotes:0,totalAmount:0,impactedDealersCount:0};function LF(){const[t,s]=x.useState([]),[a,r]=x.useState(Do),[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 C=>{try{i(!0);const E=await Up(C);s(E.debitNotes),r(E.summary??Do)}catch(E){console.error("[Form16DebitNotes] Failed to fetch:",E),W.error(E instanceof Error?E.message:"Failed to load debit notes"),s([]),r(Do)}finally{i(!1)}},[]);x.useEffect(()=>{y()},[y]);const v=x.useMemo(()=>{if(!l.trim())return t;const C=l.trim().toLowerCase();return t.filter(E=>E.debitNoteNumber&&E.debitNoteNumber.toLowerCase().includes(C)||E.creditNoteNumber&&E.creditNoteNumber.toLowerCase().includes(C)||E.dealerName&&E.dealerName.toLowerCase().includes(C)||E.dealerCode&&E.dealerCode.toLowerCase().includes(C)||E.form16aNumber&&E.form16aNumber.toLowerCase().includes(C))},[t,l]),w=x.useCallback(async C=>{var E;d(!0),p(!0),h(null),f({amountText:ko(C.amount),issuedAtText:_F(C.issueDate)});try{const D=await Bp(Number(C.id));h(MF(D.sapResponse))}catch(D){const T=((E=D==null?void 0:D.response)==null?void 0:E.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 C;j(!0),W.loading("Pulling SAP responses...",{id:"pull-debit"});try{const E=await ve.post("/form16/sap/pull");await y();const D=(C=E.data)==null?void 0:C.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:C=>{d(C),C||(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(vl,{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(P,{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?"...":ko(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:C=>o(C.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(st,{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(st,{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..."})]})}):v.length===0?e.jsx(st,{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."})]})}):v.map(C=>{var E,D;return e.jsxs(st,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(be,{className:"font-medium",children:C.debitNoteNumber??""}),e.jsx(be,{className:"font-medium",children:C.creditNoteNumber??""}),e.jsx(be,{children:C.dealerName??C.dealerCode??""}),e.jsx(be,{children:C.form16aNumber??""}),e.jsx(be,{children:ko(C.amount)}),e.jsx(be,{children:EF(C.issueDate)}),e.jsx(be,{children:e.jsx(re,{className:((E=C.status)==null?void 0:E.toLowerCase())==="issued"||((D=C.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:C.status??""})}),e.jsx(be,{className:"text-right",children:e.jsx("div",{className:"flex items-center justify-end gap-2",children:C.sapResponseAvailable?e.jsxs(P,{variant:"outline",size:"sm",onClick:()=>w(C),children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"View"]}):e.jsxs(P,{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"]})})})]},C.id)})})]})})})]})]})]})}function OF(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 $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 wh(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function UF(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function BF(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 VF(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 zF(){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,v]=await Promise.all([$p(),Up()]),w=[...y.creditNotes.map(BF),...v.debitNotes.map(VF)].sort((A,C)=>{const E=A.issueDate?new Date(A.issueDate).getTime():0;return(C.issueDate?new Date(C.issueDate).getTime():0)-E});o(w)}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(v=>v.searchText.includes(y))},[l,n]),b=x.useCallback(async y=>{d(!0),p(!0),h(null);try{const v=y.type==="credit"?await Rc(y.id):await Bp(y.id);h({type:y.type,referenceNumber:y.referenceNumber,amountText:wh(y.amount),issuedAtText:$F(y.issueDate),row:UF(v.sapResponse)})}catch(v){const w=v instanceof Error?v.message:"Failed to load SAP response";W.error(w),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(vl,{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(P,{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(P,{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(st,{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(st,{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(st,{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(st,{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(Wj,{className:"w-4 h-4"}):e.jsx(Yj,{className:"w-4 h-4"}),e.jsxs("span",{children:[y.type==="credit"?"+ ":"- ",wh(y.amount)]})]})}),e.jsx(be,{children:OF(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(P,{variant:"outline",size:"sm",onClick:()=>b(y),children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"View"]}):e.jsxs(P,{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 HF({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 Ri=10;function GF(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 WF(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 YF(){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),[v,w]=x.useState(!1),[A,C]=x.useState(""),[E,D]=x.useState(""),[T,N]=x.useState(null),[_,I]=x.useState(!1);x.useEffect(()=>{let z=!1;return zp().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/Ri)),k=i>0,M=i<B-1,L=Math.max(0,Math.min(i-4,B-9)),F=Math.min(B-1,L+8),S=Array.from({length:F-L+1},(z,O)=>L+O),G=s.slice(i*Ri,(i+1)*Ri),U=x.useCallback(()=>{if(!p)return;const z=URL.createObjectURL(p);N(z),I(!0)},[p]),$=x.useCallback(()=>{I(!1),T&&(URL.revokeObjectURL(T),N(null))},[T]),R=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 _v(z);b(O.extractedData),y(O.ocrProvider||null),C(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=(E||((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}w(!0);try{const te=await Mv({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{w(!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(P,{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(HF,{state:h==="extracting"?"extracting":h==="error"?"error":h==="success"?"success":"idle",onFileSelect:R,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(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{u(null),b(null),y(null),C(""),D(""),c(""),m(""),g("idle"),$()},disabled:h==="extracting",children:"Remove"})]}),p&&e.jsxs(P,{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(st,{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(st,{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(st,{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(st,{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:GF(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(P,{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>Ri&&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(P,{variant:"outline",size:"sm",disabled:!k,onClick:()=>l(z=>z-1),children:[e.jsx(hn,{className:"w-4 h-4"}),"Previous"]}),S.map(z=>e.jsx(P,{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(P,{variant:"outline",size:"sm",disabled:!M,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(zr,{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 23 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:WF(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=>C(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:E,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(P,{type:"button",variant:"outline",onClick:()=>t(-1),disabled:v,children:"Cancel"}),e.jsxs(P,{type:"button",className:"bg-re-green hover:bg-re-green/90",onClick:H,disabled:!o||!d||v,children:[v?e.jsx(ze,{className:"w-4 h-4 animate-spin mr-2"}):null,"Submit Form 16A"]})]})]}):null})]}),e.jsx(xt,{open:_,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 QF={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 KF({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 ${QF[t]}`,children:[a&&e.jsx(r,{className:"h-4 w-4 shrink-0"}),s]})}function XF({step:t,label:s,state:a,isLast:r}){const n=a==="completed"?ps:a==="failed"?St:gc,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 ZF({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(KF,{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(Qj,{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(XF,{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(P,{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(P,{onClick:o,className:"bg-teal-600 hover:bg-teal-700",children:"View Request"}),l&&(d||u||h)&&e.jsx(P,{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(P,{onClick:i,variant:"outline",children:"Back to My Requests"})]})})]})})})})}const Ln="form16_submission_result";function JF(){const t=Cs(),a=Jj().state,r=(()=>{try{const d=sessionStorage.getItem(Ln);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(Ln,JSON.stringify(n))},[i,n]);const l=x.useCallback(()=>{sessionStorage.removeItem(Ln),t("/my-requests",{replace:!0})},[t]),o=x.useCallback(()=>{sessionStorage.removeItem(Ln),t("/form16/submit",{replace:!0})},[t]),c=x.useCallback(()=>{n!=null&&n.requestNumber&&(sessionStorage.removeItem(Ln),t(`/request/${n.requestNumber}`,{replace:!0}))},[t,n==null?void 0:n.requestNumber]);return i?e.jsx(ZF,{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 On=50,Fi=10,qF=["Q1","Q2","Q3","Q4"],eI=[{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 Ch(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 Ii(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function tI(){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 sI(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 aI(){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),[v,w]=x.useState([]),[A,C]=x.useState(0),[E,D]=x.useState({totalRecords:0,booked:0,notBooked:0,pending:0,totalTaxDeducted:0}),[T,N]=x.useState(!0),[_,I]=x.useState(0),[B,k]=x.useState([]),[M,L]=x.useState(0),[F,S]=x.useState(0),[G,U]=x.useState(!1),$=tI(),R=x.useCallback(async(ae=0)=>{try{U(!0);const{history:he,total:ne}=await Ov({limit:Fi,offset:ae*Fi});k(he),L(ne),S(ae)}catch(he){console.error("[Form16_26AS] upload history",he),k([]),L(0),S(0)}finally{U(!1)}},[]),H=x.useCallback(async(ae=0)=>{try{N(!0);const he={limit:On,offset:ae*On};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 Lv(he);w(ne.entries),C(ne.total),D(ne.summary),I(ae)}catch(he){console.error("[Form16_26AS]",he),W.error(he instanceof Error?he.message:"Failed to load 26AS entries"),w([]),C(0),D({totalRecords:0,booked:0,notBooked:0,pending:0,totalTaxDeducted:0})}finally{N(!1)}},[a.assessmentYear,a.quarter,a.section,a.tanNumber,a.deductor,a.status]);x.useEffect(()=>{H(0)},[H]),x.useEffect(()=>{R(0)},[R]),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 Uv(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),R(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/On)),q=_>0,ee=_<Q-1,te=Math.max(0,Math.min(_-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(M/Fi)),Ue=F>0,Pe=F<Ze-1,De=Math.max(0,Math.min(F-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(P,{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(P,{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(cl,{className:"w-4 h-4"}):e.jsx(bn,{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(P,{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(P,{variant:"outline",onClick:()=>{c(!1),b(null),j.current&&(j.current.value="")},disabled:d,children:"Cancel"}),e.jsx(P,{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",M>0?` (${M} 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(st,{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(st,{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(st,{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(st,{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&&M>Fi&&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 ",F+1," of ",Ze," (",M," uploads)"]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-wrap justify-center",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:!Ue,onClick:()=>R(F-1),children:[e.jsx(hn,{className:"w-4 h-4"}),"Previous"]}),ye.map(ae=>e.jsx(P,{variant:ae===F?"default":"outline",size:"sm",className:ae===F?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>R(ae),children:ae+1},ae)),e.jsxs(P,{variant:"outline",size:"sm",disabled:!Pe,onClick:()=>R(F+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(P,{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"}),qF.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"}),eI.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:E.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:E.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:E.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:E.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:Ii(E.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 ${v.length} of ${A} records`:`Complete list of TDS deduction records (${A} total)`})]}),e.jsxs(P,{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(st,{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(st,{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..."})]})})}):v.length===0?e.jsx(st,{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(P,{variant:"outline",size:"sm",onClick:O,className:"mt-2",children:"Clear Filters"})]})}):v.map((ae,he)=>e.jsxs(st,{className:"hover:bg-gray-50",children:[e.jsx(be,{className:"text-center text-sm text-gray-900",children:_*On+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:Ii(ae.amountPaid??0)}),e.jsx(be,{className:"text-right text-sm text-gray-900",children:Ii(ae.taxDeducted)}),e.jsx(be,{className:"text-right text-sm text-gray-900",children:Ii(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:Ch(ae.transactionDate)}),e.jsx(be,{children:sI(ae.statusOltas)}),e.jsx(be,{className:"text-sm text-gray-700",children:Ch(ae.dateOfBooking)})]},ae.id))})]})}),!T&&A>On&&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 ",_+1," of ",Q," (",A," records)"]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-wrap justify-center",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:!q,onClick:()=>H(_-1),children:[e.jsx(hn,{className:"w-4 h-4"}),"Previous"]}),_e.map(ae=>e.jsx(P,{variant:ae===_?"default":"outline",size:"sm",className:ae===_?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>H(ae),children:ae+1},ae)),e.jsxs(P,{variant:"outline",size:"sm",disabled:!ee,onClick:()=>H(_+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 Sh={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 Ah({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(st,{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 rI(){const[t,s]=x.useState(Sh),[a,r]=x.useState(!0);return x.useEffect(()=>{let n=!0;return(async()=>{try{r(!0);const i=await Iv();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(Sh)}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(st,{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(st,{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(st,{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(Ah,{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(st,{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(st,{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(st,{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(Ah,{rows:t.zoneWise})]})})]})})})]})]})})}function Th(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 nI=[{value:"2024-25",label:"2024-25"},{value:"2023-24",label:"2023-24"},{value:"2022-23",label:"2022-23"},{value:"",label:"All Years"}];function iI(){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 Bv(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 Vv({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:nI.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(st,{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(st,{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(st,{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(st,{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(ii,{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:Th(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(zn,{children:e.jsxs(Mi,{children:[e.jsx(Li,{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:Th(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(Oi,{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(P,{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 lI(){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 C=!1;return(async()=>{l(!0);try{const[E,D]=await Promise.all([zp(),zv({status:"pending,failed,completed"})]);C||(a(Array.isArray(E)?E:[]),n(Array.isArray(D)?D:[]))}catch{C||(W.error("Failed to load pending submissions"),a([]),n([]))}finally{C||l(!1)}})(),()=>{C=!0}},[]);const p=s.filter(C=>!(d.financialYear!=="all"&&C.financial_year!==d.financialYear||d.quarter!=="all"&&C.quarter!==d.quarter)),u=p.length,h=p.filter(C=>(C.days_overdue??0)>0).length,g=p.filter(C=>(C.days_remaining??0)>0).length,f=()=>m({financialYear:"all",quarter:"all"}),b=d.financialYear!=="all"||d.quarter!=="all",j=C=>{if(!C)return"—";try{return new Date(C).toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}catch{return C}},y=C=>C==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(C),v=C=>{const E=(C||"").toLowerCase();return E==="completed"?"bg-emerald-50 text-emerald-700 border-emerald-200":E==="balance mismatch"||E==="failed"?"bg-red-50 text-red-700 border-red-200":E==="resubmission needed"||E==="duplicate"||E==="duplicate submission"?"bg-amber-50 text-amber-700 border-amber-200":"bg-slate-50 text-slate-600 border-slate-200"},w=C=>{t("/form16/submit")},A=[...new Set(s.map(C=>C.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(P,{className:"bg-teal-600 hover:bg-teal-700",onClick:()=>t("/form16/submit"),children:"New Submission"}),e.jsxs(P,{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(C=>C!=="all").length}),o?e.jsx(cl,{className:"w-4 h-4"}):e.jsx(bn,{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(P,{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:C=>m(E=>({...E,financialYear:C})),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(C=>e.jsx(X,{value:C,children:C},C))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Quarter"}),e.jsxs(He,{value:d.quarter,onValueChange:C=>m(E=>({...E,quarter:C})),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(st,{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(st,{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(st,{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(P,{variant:"outline",size:"sm",onClick:f,className:"mt-2",children:"Clear Filters"}),!b&&e.jsx(P,{size:"sm",className:"bg-teal-600 hover:bg-teal-700 mt-2",onClick:()=>t("/form16/submit"),children:"New Submission"})]})})}):p.map(C=>e.jsxs(st,{className:"hover:bg-gray-50",children:[e.jsx(be,{className:"text-sm text-gray-900",children:C.dealer_name??"Your submission"}),e.jsx(be,{children:e.jsxs("span",{className:"text-sm text-gray-900",children:["FY ",C.financial_year]})}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:C.quarter})}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:C.has_submission?"V1":"—"})}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:C.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":C.has_submission?"bg-slate-50 text-slate-600 border-slate-200":"bg-gray-100 text-gray-600 border-gray-200",children:C.latest_submission_status==="failed"?"Failed":C.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(C.twenty_six_as_start_date??C.audit_start_date)})]})}),e.jsx(be,{children:C.days_since_26as_uploaded!=null&&C.days_since_26as_uploaded>=0?e.jsxs("span",{className:"text-sm font-medium text-gray-700",children:["due from ",C.days_since_26as_uploaded," days"]}):e.jsx("span",{className:"text-sm text-gray-500",children:"—"})}),e.jsx(be,{className:"text-right",children:e.jsx(P,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>w(),children:"Submit Now"})})]},`${C.financial_year}|${C.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(st,{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(st,{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(st,{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(C=>e.jsxs(st,{className:"hover:bg-gray-50",children:[e.jsx(be,{className:"font-mono text-sm",children:C.requestId?String(C.requestId).slice(0,8)+"…":"—"}),e.jsxs(be,{children:["FY ",C.financial_year]}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:C.quarter})}),e.jsx(be,{className:"text-right font-medium",children:y(C.total_amount)}),e.jsx(be,{children:C.credit_note_number??"—"}),e.jsx(be,{children:e.jsx(re,{variant:"outline",className:v(C.display_status),children:C.display_status??(C.status==="completed"?"Completed":C.status==="failed"?"Failed":"Under review")})}),e.jsx(be,{className:"text-sm text-gray-600",children:j(C.submitted_date)}),e.jsx(be,{className:"text-right",children:e.jsx(P,{variant:"outline",size:"sm",onClick:()=>t(`/request/${C.requestId}`),children:"View Request"})})]},C.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(C=>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:C.quarter}),e.jsx("p",{className:"text-sm text-gray-600",children:C.financial_year}),C.has_submission&&C.latest_submission_status&&e.jsx(re,{variant:"outline",className:`mt-1 text-xs ${C.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":"bg-slate-50 text-slate-600 border-slate-200"}`,children:C.latest_submission_status==="failed"?"Failed":"Under review"})]}),e.jsx(P,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>t("/form16/submit"),children:"Submit"})]})},`${C.financial_year}|${C.quarter}`))})})]})]})}function oI({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(P,{variant:"outline",onClick:p,disabled:c,children:"Cancel"}),e.jsx(P,{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 cI=(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{}},dI=x.createContext(void 0),mI={setTheme:t=>{},themes:[]},uI=()=>{var t;return(t=x.useContext(dI))!=null?t:mI};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:`(${cI.toString()})(${m})`}})});const xI=({...t})=>{const{theme:s="system"}=uI();return e.jsx(Kj,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function hI({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(pc,{className:"w-4 h-4"}),e.jsx("span",{children:c.department})]})]})]})]}),e.jsx(P,{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(P,{onClick:s,variant:"outline",children:"Close"}):e.jsx(e.Fragment,{children:e.jsx(P,{onClick:s,variant:"outline",disabled:l,children:"Cancel"})})})]})})}function kh({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 Dc();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 pI({onViewRequest:t}){const{user:s}=us();return Nl(s)?e.jsx(FD,{onViewRequest:t}):e.jsx(ED,{onViewRequest:t})}function Dh({onNavigate:t,onNewRequest:s}){const[a,r]=x.useState(!1),[n,i]=x.useState(!0);return x.useEffect(()=>{try{const l=nt.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(X4,{onNavigate:t,onNewRequest:s}):e.jsx(g1,{onNavigate:t,onNewRequest:s})}function gI({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 C=localStorage.getItem("dynamicRequests");if(C)try{const E=JSON.parse(C);i(E)}catch(E){console.error("Error parsing dynamic requests:",E)}},[]),x.useEffect(()=>{n.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(n))},[n]);const g=C=>{if(C==="profile"){s("/profile");return}if(C==="settings"){s("/settings");return}C.startsWith("/")?s(C):s(`/${C}`)},f=(C,E,D,T)=>{o(C),d(E||"Unknown Request"),nl({requestId:C,status:D,request:T,navigate:s})},b=()=>{s(-1)},j=()=>{s("/new-request")},y=C=>{var T,N,_,I,B,k,M,L,F,S,G;if(C.templateType){C.templateType==="claim-management"&&s("/claim-management");return}if(C.backendId){s("/my-requests");return}const D={id:`RE-REQ-2024-${String(n.length+1).padStart(3,"0")}`,title:C.title,description:C.description||"",category:C.category||"General",subcategory:C.subcategory||"",status:"pending",priority:C.priority||"standard",amount:C.budget||"N/A",slaProgress:0,slaRemaining:"5 days",slaEndDate:new Date(Date.now()+5*24*60*60*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),currentStep:1,totalSteps:((T=C.approvers)==null?void 0:T.length)||1,currentApprover:((_=(N=C.approvers)==null?void 0:N[0])==null?void 0:_.name)||((k=(B=(I=C.approvers)==null?void 0:I[0])==null?void 0:B.email)==null?void 0:k.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((M=C.approvers)==null?void 0:M.length)||1}`,template:"custom",initiator:{name:"Current User",role:C.initiatorRole||"Employee",department:C.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:C.department||"General",createdAt:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),updatedAt:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),dueDate:new Date(Date.now()+5*24*60*60*1e3).toISOString(),submittedDate:new Date().toISOString(),estimatedCompletion:new Date(Date.now()+5*24*60*60*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),conclusionRemark:"",approvalFlow:(C.approvers||[]).filter(U=>U).map((U,$)=>{var K;const R=(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:`${R}${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:(C.spectators||[]).filter(U=>U&&(U.name||U.email)).map(U=>{var R;const $=(U==null?void 0:U.name)||((R=U==null?void 0:U.email)==null?void 0:R.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 "${C.title}" created`,user:"Current User",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})},{type:"assignment",action:"Assigned to Approver",details:`Request assigned to ${((F=(L=C.approvers)==null?void 0:L[0])==null?void 0:F.name)||((G=(S=C.approvers)==null?void 0:S[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:C.tags||["custom-request"]};i([...n,D]),s("/my-requests")},v=(C,E)=>new Promise(D=>{setTimeout(()=>{C==="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)}),w=()=>{r(null)},A=async(C,E)=>{var D,T,N,_,I,B,k;try{const M={activityName:C.activityName,activityType:C.activityType,dealerCode:C.dealerCode,dealerName:C.dealerName,dealerEmail:C.dealerEmail||void 0,dealerPhone:C.dealerPhone||void 0,dealerAddress:C.dealerAddress||void 0,activityDate:C.activityDate?new Date(C.activityDate).toISOString():void 0,location:C.location,requestDescription:C.requestDescription,periodStartDate:C.periodStartDate?new Date(C.periodStartDate).toISOString():void 0,periodEndDate:C.periodEndDate?new Date(C.periodEndDate).toISOString():void 0,estimatedBudget:C.estimatedBudget||void 0,approvers:C.approvers||[]},L=await v4(M);if(!L||!L.request)throw new Error("Invalid response from server: Request object not found");const F=L.request;if(!F.requestNumber&&!F.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."}),F.requestNumber?s(`/request/${F.requestNumber}`):F.requestId?s(`/request/${F.requestId}`):s("/my-requests")}catch(M){console.error("[App] Error creating claim request:",M);const L=(D=M==null?void 0:M.response)==null?void 0:D.data,F=(L==null?void 0:L.code)||((T=L==null?void 0:L.error)==null?void 0:T.code);if(F==="NO_MANAGER_FOUND"){h({errorType:"NO_MANAGER_FOUND",message:(L==null?void 0:L.message)||((N=L==null?void 0:L.error)==null?void 0:N.message)||"No reporting manager found. Please ensure your manager is correctly configured in the system.",pendingClaimData:C}),p(!0);return}if(F==="MULTIPLE_MANAGERS_FOUND"){const G=(L==null?void 0:L.managers)||((_=L==null?void 0:L.error)==null?void 0:_.managers)||[];h({errorType:"MULTIPLE_MANAGERS_FOUND",managers:G,message:(L==null?void 0:L.message)||((I=L==null?void 0:L.error)==null?void 0:I.message)||"Multiple managers found. Please select one.",pendingClaimData:C}),p(!0);return}const S=((k=(B=M==null?void 0:M.response)==null?void 0:B.data)==null?void 0:k.message)||(M==null?void 0:M.message)||"Failed to create claim request";W.error("Failed to Submit Claim Request",{description:S})}};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(ey,{children:[e.jsx(kt,{path:"/login/callback",element:e.jsx(kp,{})}),e.jsx(kt,{path:"/",element:e.jsx(zt,{currentPage:"dashboard",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(Dh,{onNavigate:g,onNewRequest:j})})}),e.jsx(kt,{path:"/dashboard",element:e.jsx(zt,{currentPage:"dashboard",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(Dh,{onNavigate:g,onNewRequest:j})})}),e.jsxs(kt,{element:e.jsx(zt,{currentPage:"admin",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(ty,{})}),children:[e.jsx(kt,{path:"/admin",element:e.jsx(AF,{})}),e.jsx(kt,{path:"/admin/create-template",element:e.jsx(vh,{})}),e.jsx(kt,{path:"/admin/edit-template/:templateId",element:e.jsx(vh,{})}),e.jsx(kt,{path:"/admin/templates",element:e.jsx(UR,{})})]}),e.jsx(kt,{path:"/create-admin-request/:templateId",element:e.jsx(zR,{})}),e.jsx(kt,{path:"/open-requests",element:e.jsx(zt,{currentPage:"open-requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(i6,{onViewRequest:f})})}),e.jsx(kt,{path:"/closed-requests",element:e.jsx(zt,{currentPage:"closed-requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(R6,{onViewRequest:f})})}),e.jsx(kt,{path:"/shared-summaries",element:e.jsx(zt,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(L6,{})})}),e.jsx(kt,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(zt,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(O6,{})})}),e.jsx(kt,{path:"/form16/credit-notes",element:e.jsx(zt,{currentPage:"form16-credit-notes",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(RF,{})})}),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(PF,{})})}),e.jsx(kt,{path:"/form16/debit-notes",element:e.jsx(zt,{currentPage:"form16-debit-notes",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(LF,{})})}),e.jsx(kt,{path:"/form16/transactions",element:e.jsx(zt,{currentPage:"form16-transactions",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(zF,{})})}),e.jsx(kt,{path:"/form16/submit",element:e.jsx(zt,{currentPage:"form16-submit",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(YF,{})})}),e.jsx(kt,{path:"/form16/submit/result",element:e.jsx(zt,{currentPage:"form16-submit",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(JF,{})})}),e.jsx(kt,{path:"/form16/dashboard",element:e.jsx(zt,{currentPage:"form16-dashboard",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(kh,{children:e.jsx(rI,{})})})}),e.jsx(kt,{path:"/form16/26as",element:e.jsx(zt,{currentPage:"form16-26as",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(kh,{children:e.jsx(aI,{})})})}),e.jsx(kt,{path:"/form16/pending-submissions",element:e.jsx(zt,{currentPage:"form16-pending-submissions",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(lI,{})})}),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(iI,{})})}),e.jsx(kt,{path:"/my-requests",element:e.jsx(zt,{currentPage:"my-requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(aD,{onViewRequest:f,dynamicRequests:n})})}),e.jsx(kt,{path:"/requests",element:e.jsx(zt,{currentPage:"requests",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(pI,{onViewRequest:f})})}),e.jsx(kt,{path:"/approver-performance",element:e.jsx(zt,{currentPage:"approver-performance",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(QD,{})})}),e.jsx(kt,{path:"/request/:requestId",element:e.jsx(zt,{currentPage:"request-detail",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(M6,{requestId:"",onBack:b,dynamicRequests:n})})}),e.jsx(kt,{path:"/work-notes/:requestId",element:e.jsx($6,{})}),e.jsx(kt,{path:"/new-request",element:e.jsx(oh,{onBack:b,onSubmit:y})}),e.jsx(kt,{path:"/edit-request/:requestId",element:e.jsx(oh,{onBack:b,onSubmit:y,requestId:void 0,isEditMode:!0})}),e.jsx(kt,{path:"/claim-management",element:e.jsx($4,{onBack:b,onSubmit:A})}),e.jsx(kt,{path:"/profile",element:e.jsx(zt,{currentPage:"profile",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(KD,{})})}),e.jsx(kt,{path:"/settings",element:e.jsx(zt,{currentPage:"settings",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(xR,{})})}),e.jsx(kt,{path:"/settings/security",element:e.jsx(zt,{currentPage:"settings",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(jR,{})})}),e.jsx(kt,{path:"/notifications",element:e.jsx(zt,{currentPage:"notifications",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx(yR,{onNavigate:g})})}),e.jsx(kt,{path:"/detailed-reports",element:e.jsx(zt,{currentPage:"detailed-reports",onNavigate:g,onNewRequest:j,onLogout:t,children:e.jsx($R,{})})})]}),e.jsx(xI,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),e.jsx(hI,{open:m,onClose:()=>{p(!1),h(null)},onSelect:async C=>{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(oI,{isOpen:!!a,onClose:w,action:a,requestId:l,requestTitle:c,onSubmit:v})]})}function fI(t){const{onLogout:s}=t||{};return e.jsx(qj,{children:e.jsx(gI,{onLogout:s})})}function bI(){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(Av,{}):e.jsx(kp,{}):s&&nt.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(fI,{onLogout:c}),i&&e.jsx(kv,{isOpen:i,onClose:()=>l(!1)})]}):e.jsx(Sv,{})}const zi=()=>{try{return!0}catch{return!1}},jI=()=>{if(zi())return null;try{return localStorage.getItem("token")}catch{return null}},yI={user:null,token:jI(),isAuthenticated:!1,isLoading:!1,error:null},Gf=jn({name:"auth",initialState:yI,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,!zi())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,!zi())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!zi())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:PI,loginSuccess:EI,loginFailure:_I,logout:MI,clearError:LI,updateUser:OI}=Gf.actions,vI=Zj({reducer:{auth:Gf.reducer,dashboard:Hp.reducer,requests:Pf.reducer,myRequests:Df.reducer,openRequests:sg.reducer,closedRequests:Af.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});_o.createRoot(document.getElementById("root")).render(e.jsx(Xb.StrictMode,{children:e.jsx(vy,{store:vI,children:e.jsx(Wy,{children:e.jsx(bI,{})})})}));export{ve as a};