Re_Backend/build/assets/index-DoaotahL.js
2026-04-17 20:06:06 +05:30

65 lines
1.7 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-CFo0PF7I.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-DbXFJHwt.js"])))=>i.map(i=>d[i]);
var Rb=Object.defineProperty;var Ib=(t,s,a)=>s in t?Rb(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Zl=(t,s,a)=>Ib(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as cp,R as dp,I as mp,F as up,a as Fb,T as Pb,P as Eb,C as _b,b as Mb,O as xp,c as hp,d as Lb,e as Ob,f as $b,D as Ub,g as Bb,A as zb,h as Vb,i as Wb,k as Hb,l as Gb,m as Yb,n as Qb,V as Kb,o as Xb,p as Jb,q as Zb,r as qb,s as ej,t as tj,u as sj,v as aj,w as rj,x as nj,y as ij,z as lj,B as oj,E as cj,G as dj,H as mj,J as uj,K as xj,L as hj,M as pj,N as gj,Q as Ec,U as _c,W as fj,X as pp,Y as gp,Z as fp,_ as bp,$ as bj,a0 as jj,a1 as yj,a2 as vj,a3 as Nj,a4 as wj,a5 as Cj,a6 as Sj,a7 as Aj,a8 as gn,a9 as yr,aa as ai,ab as Tj,ac as kj,ad as Dj,ae as Rj}from"./radix-vendor-CLtqm-Ae.js";import{a as Ij,r as u,d as jp,e as fn,B as Jo,C as il,X as ll,Y as ol,T as bn,L as cl,f as $a,P as yp,g as vp,h as Np,i as Fj,j as Pu,k as Cl,l as Sl,b as xa}from"./charts-vendor-CmYZJIYl.js";import{a as fi,f as wp,s as ha,e as Mc,b as Eu,c as Pj,d as Va,g as ri,i as Lc,h as Cp,j as sa,k as da,l as ql,m as Za,n as Ej,o as Zo,p as _j,q as st,r as qo,t as Mj,u as Lj,v as Oj,w as $j,x as eo,y as _u,z as Uj,A as Sp,B as Ap,C as Oc,D as $c,E as Bj,F as zj,G as Tp,H as rn,I as to,J as Vj,K as Wj,L as Hj}from"./utils-vendor-BTBPSQfW.js";import{u as Q,A as ys,S as bs,C as Ze,a as ps,L as ze,X as vt,H as Mu,b as ec,U as Wt,F as Ee,c as Ve,d as Sn,R as Et,e as Qr,f as Wa,P as is,g as Gj,h as Yj,B as Os,i as hr,j as so,k as Uc,l as Ha,m as Al,n as Nn,o as bt,p as Ga,q as _t,I as Jr,T as ts,r as it,s as Ma,t as Qj,v as ss,M as Qs,w as Tl,x as zt,y as tc,D as kt,Z as kl,z as qt,E as Kj,G as Xj,J as Jj,K as Zj,N as qj,O as ey,Q as ty,V as sy,W as ay,Y as kp,_ as ry,$ as ny,a0 as Dp,a1 as Ca,a2 as bi,a3 as pr,a4 as dl,a5 as Lu,a6 as Pi,a7 as ml,a8 as Rp,a9 as At,aa as iy,ab as Ks,ac as Bc,ad as Cs,ae as Dl,af as Ip,ag as wt,ah as ly,ai as oy,aj as Fp,ak as Rl,al as Pp,am as cy,an as zc,ao as vs,ap as Pa,aq as Ep,ar as Il,as as Fl,at as Jt,au as dy,av as my,aw as _p,ax as Mp,ay as Qi,az as ur,aA as Vc,aB as Pl,aC as ni,aD as Lp,aE as Op,aF as Wc,aG as El,aH as _l,aI as sc,aJ as uy,aK as zs,aL as $p,aM as ul,aN as xy,aO as hy,aP as py,aQ as Ml,aR as Ll,aS as Hc,aT as gy,aU as Ou,aV as La,aW as vr,aX as fy,aY as cn,aZ as $u,a_ as by,a$ as jy,b0 as Up,b1 as Uu,b2 as Bp,b3 as yy,b4 as vy,b5 as Ny,b6 as wy,b7 as zp,b8 as Cy,b9 as Sy,ba as Ay,bb as Ol,bc as Ty,bd as ky,be as Dy,bf as Ry}from"./ui-vendor-DgwXkk2Y.js";import{l as Iy}from"./socket-vendor-TjCxX7sJ.js";import{c as An,a as Fy}from"./redux-vendor-tbZCm13o.js";import{u as gs,a as Aa,b as Vp,c as $l,L as ii,B as Py,R as Ey,d as ot,O as _y,N as dr}from"./router-vendor-DbXFJHwt.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 ac={},Bu=Ij;ac.createRoot=Bu.createRoot,ac.hydrateRoot=Bu.hydrateRoot;var Wp={exports:{}},Hp={};var ji=u;function My(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var Ly=typeof Object.is=="function"?Object.is:My,Oy=ji.useSyncExternalStore,$y=ji.useRef,Uy=ji.useEffect,By=ji.useMemo,zy=ji.useDebugValue;Hp.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=$y(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=By(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,Ly(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,x=a===void 0?null:a;return[function(){return c(s())},x===null?void 0:function(){return c(x())}]},[s,a,r,n]);var o=Oy(t,i[0],i[1]);return Uy(function(){l.hasValue=!0,l.value=o},[o]),zy(o),o};Wp.exports=Hp;var Vy=Wp.exports;function Wy(t){t()}function Hy(){let t=null,s=null;return{clear(){t=null,s=null},notify(){Wy(()=>{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 zu={notify(){},get:()=>[]};function Gy(t,s){let a,r=zu,n=0,i=!1;function l(f){m();const b=r.subscribe(f);let y=!1;return()=>{y||(y=!0,b(),p())}}function o(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=Hy())}function p(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=zu)}function x(){i||(i=!0,m())}function h(){i&&(i=!1,p())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:x,tryUnsubscribe:h,getListeners:()=>r};return g}var Yy=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Qy=Yy(),Ky=()=>typeof navigator<"u"&&navigator.product==="ReactNative",Xy=Ky(),Jy=()=>Qy||Xy?u.useLayoutEffect:u.useEffect,Zy=Jy(),ao=Symbol.for("react-redux-context"),ro=typeof globalThis<"u"?globalThis:{};function qy(){if(!u.createContext)return{};const t=ro[ao]??(ro[ao]=new Map);let s=t.get(u.createContext);return s||(s=u.createContext(null),t.set(u.createContext,s)),s}var gr=qy();function ev(t){const{children:s,context:a,serverState:r,store:n}=t,i=u.useMemo(()=>{const c=Gy(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=u.useMemo(()=>n.getState(),[n]);Zy(()=>{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||gr;return u.createElement(o.Provider,{value:i},s)}var tv=ev;function Gc(t=gr){return function(){return u.useContext(t)}}var Gp=Gc();function Yp(t=gr){const s=t===gr?Gp:Gc(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var sv=Yp();function av(t=gr){const s=t===gr?sv:Yp(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var rv=av(),nv=(t,s)=>t===s;function iv(t=gr){const s=t===gr?Gp:Gc(t),a=(r,n={})=>{const{equalityFn:i=nv}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;u.useRef(!0);const m=u.useCallback({[r.name](x){return r(x)}}[r.name],[r]),p=Vy.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return u.useDebugValue(p),p};return Object.assign(a,{withTypes:()=>a}),a}var lv=iv(),rc=function(t,s){return rc=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])},rc(t,s)};function ov(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");rc(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var xl=function(){return xl=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},xl.apply(this,arguments)};var Lr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Yc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Qc(t,s){return t(s={exports:{}},s.exports),s.exports}var Pr=Qc(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()}});Yc(Pr);var cv=Yc(Qc(function(t,s){var a=Lr&&Lr.__awaiter||function(m,p,x,h){return new(x||(x=Promise))(function(g,f){function b(v){try{j(h.next(v))}catch(N){f(N)}}function y(v){try{j(h.throw(v))}catch(N){f(N)}}function j(v){v.done?g(v.value):new x(function(N){N(v.value)}).then(b,y)}j((h=h.apply(m,p||[])).next())})},r=Lr&&Lr.__generator||function(m,p){var x,h,g,f,b={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return f={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function y(j){return function(v){return function(N){if(x)throw new TypeError("Generator is already executing.");for(;b;)try{if(x=1,h&&(g=2&N[0]?h.return:N[0]?h.throw||((g=h.return)&&g.call(h),0):h.next)&&!(g=g.call(h,N[1])).done)return g;switch(h=0,g&&(N=[2&N[0],g.value]),N[0]){case 0:case 1:g=N;break;case 4:return b.label++,{value:N[1],done:!1};case 5:b.label++,h=N[1],N=[0];continue;case 7:N=b.ops.pop(),b.trys.pop();continue;default:if(g=b.trys,!((g=g.length>0&&g[g.length-1])||N[0]!==6&&N[0]!==2)){b=0;continue}if(N[0]===3&&(!g||N[1]>g[0]&&N[1]<g[3])){b.label=N[1];break}if(N[0]===6&&b.label<g[1]){b.label=g[1],g=N;break}if(g&&b.label<g[2]){b.label=g[2],b.ops.push(N);break}g[2]&&b.ops.pop(),b.trys.pop();continue}N=p.call(m,b)}catch(T){N=[6,T],h=0}finally{x=g=0}if(5&N[0])throw N[1];return{value:N[0]?N[1]:void 0,done:!0}}([j,v])}}},n=Lr;Object.defineProperty(s,"__esModule",{value:!0});var i="browser-tabs-lock-key",l={key:function(m){return a(n,void 0,void 0,function(){return r(this,function(p){throw new Error("Unsupported")})})},getItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(p){throw new Error("Unsupported")})})},clear:function(){return a(n,void 0,void 0,function(){return r(this,function(m){return[2,window.localStorage.clear()]})})},removeItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(p){throw new Error("Unsupported")})})},setItem:function(m,p){return a(n,void 0,void 0,function(){return r(this,function(x){throw new Error("Unsupported")})})},keySync:function(m){return window.localStorage.key(m)},getItemSync:function(m){return window.localStorage.getItem(m)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(m){return window.localStorage.removeItem(m)},setItemSync:function(m,p){return window.localStorage.setItem(m,p)}};function o(m){return new Promise(function(p){return setTimeout(p,m)})}function c(m){for(var p="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",x="",h=0;h<m;h++)x+=p[Math.floor(Math.random()*p.length)];return x}var d=function(){function m(p){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+c(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=p,m.waiters===void 0&&(m.waiters=[])}return m.prototype.acquireLock=function(p,x){return x===void 0&&(x=5e3),a(this,void 0,void 0,function(){var h,g,f,b,y,j,v;return r(this,function(N){switch(N.label){case 0:h=Date.now()+c(4),g=Date.now()+x,f=i+"-"+p,b=this.storageHandler===void 0?l:this.storageHandler,N.label=1;case 1:return Date.now()<g?[4,o(30)]:[3,8];case 2:return N.sent(),b.getItemSync(f)!==null?[3,5]:(y=this.id+"-"+p+"-"+h,[4,o(Math.floor(25*Math.random()))]);case 3:return N.sent(),b.setItemSync(f,JSON.stringify({id:this.id,iat:h,timeoutKey:y,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,o(30)];case 4:return N.sent(),(j=b.getItemSync(f))!==null&&(v=JSON.parse(j)).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:N.sent(),N.label=7;case 7:return h=Date.now()+c(4),[3,1];case 8:return[2,!1]}})})},m.prototype.refreshLockWhileAcquired=function(p,x){return a(this,void 0,void 0,function(){var h=this;return r(this,function(g){return setTimeout(function(){return a(h,void 0,void 0,function(){var f,b,y;return r(this,function(j){switch(j.label){case 0:return[4,Pr.default().lock(x)];case 1:return j.sent(),this.acquiredIatSet.has(x)?(f=this.storageHandler===void 0?l:this.storageHandler,(b=f.getItemSync(p))===null?(Pr.default().unlock(x),[2]):((y=JSON.parse(b)).timeRefreshed=Date.now(),f.setItemSync(p,JSON.stringify(y)),Pr.default().unlock(x),this.refreshLockWhileAcquired(p,x),[2])):(Pr.default().unlock(x),[2])}})})},1e3),[2]})})},m.prototype.waitForSomethingToChange=function(p){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,new Promise(function(h){var g=!1,f=Date.now(),b=!1;function y(){if(b||(window.removeEventListener("storage",y),m.removeFromWaiting(y),clearTimeout(j),b=!0),!g){g=!0;var v=50-(Date.now()-f);v>0?setTimeout(h,v):h(null)}}window.addEventListener("storage",y),m.addToWaiting(y);var j=setTimeout(y,Math.max(0,p-Date.now()))})];case 1:return x.sent(),[2]}})})},m.addToWaiting=function(p){this.removeFromWaiting(p),m.waiters!==void 0&&m.waiters.push(p)},m.removeFromWaiting=function(p){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(x){return x!==p}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(p){return p()})},m.prototype.releaseLock=function(p){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,this.releaseLock__private__(p)];case 1:return[2,x.sent()]}})})},m.prototype.releaseLock__private__=function(p){return a(this,void 0,void 0,function(){var x,h,g,f;return r(this,function(b){switch(b.label){case 0:return x=this.storageHandler===void 0?l:this.storageHandler,h=i+"-"+p,(g=x.getItemSync(h))===null?[2]:(f=JSON.parse(g)).id!==this.id?[3,2]:[4,Pr.default().lock(f.iat)];case 1:b.sent(),this.acquiredIatSet.delete(f.iat),x.removeItemSync(h),Pr.default().unlock(f.iat),m.notifyWaiters(),b.label=2;case 2:return[2]}})})},m.lockCorrector=function(p){for(var x=Date.now()-5e3,h=p,g=[],f=0;;){var b=h.keySync(f);if(b===null)break;g.push(b),f++}for(var y=!1,j=0;j<g.length;j++){var v=g[j];if(v.includes(i)){var N=h.getItemSync(v);if(N!==null){var T=JSON.parse(N);(T.timeRefreshed===void 0&&T.timeAcquired<x||T.timeRefreshed!==void 0&&T.timeRefreshed<x)&&(h.removeItemSync(v),y=!0)}}}y&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var $r=Qc(function(t,s){var a=Lr&&Lr.__assign||function(){return a=Object.assign||function(c){for(var d,m=1,p=arguments.length;m<p;m++)for(var x in d=arguments[m])Object.prototype.hasOwnProperty.call(d,x)&&(c[x]=d[x]);return c},a.apply(this,arguments)};function r(c,d){if(!d)return"";var m="; "+c;return d===!0?m:m+"="+d}function n(c,d,m){return encodeURIComponent(c).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(d).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(p){if(typeof p.expires=="number"){var x=new Date;x.setMilliseconds(x.getMilliseconds()+864e5*p.expires),p.expires=x}return r("Expires",p.expires?p.expires.toUTCString():"")+r("Domain",p.domain)+r("Path",p.path)+r("Secure",p.secure)+r("SameSite",p.sameSite)}(m)}function i(c){for(var d={},m=c?c.split("; "):[],p=/(%[\dA-F]{2})+/gi,x=0;x<m.length;x++){var h=m[x].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}))}});Yc($r),$r.encode,$r.parse,$r.getAll;$r.get;$r.set;$r.remove;var Vu;(function(t){t.Code="code",t.ConnectCode="connect_code"})(Vu||(Vu={}));var Wu;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(Wu||(Wu={}));new cv;var dv={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Zs=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},mv=xl(xl({},dv),{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}),uv=u.createContext(mv);(function(t){ov(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 xv=function(t){return t===void 0&&(t=uv),u.useContext(t)};const no="idToken",io="userData",hv=()=>!0;class nt{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(no,s)}static getIdToken(){return sessionStorage.getItem(no)}static setUserData(s){localStorage.setItem(io,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(io);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(io),sessionStorage.removeItem(no)}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 hv()}static setAuthError(s){s?sessionStorage.setItem("__auth_error__",s):sessionStorage.removeItem("__auth_error__")}static getAuthError(){return sessionStorage.getItem("__auth_error__")}}function Ei(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}}function nc(){const t="https://reflow-uat.royalenfield.com/".trim(),s="".trim(),a="".trim();if(typeof window>"u")return`${t.replace(/\/$/,"")||""}/login/callback`;const r=t.replace(/\/$/,""),n=window.location.hostname,i=/^(localhost|127\.0\.0\.1)$/i.test(n);return i&&a?a:s||(i?`${window.location.origin}/login/callback`:/localhost|127\.0\.0\.1/i.test(t)?`${window.location.origin}/login/callback`:`${(t||r).replace(/\/$/,"")}/login/callback`)}const ic="https://ssodev.rebridge.co.in/realms/RE",Qp="REFLOW",Kc=`${window.location.origin}/login/callback`;function pv(){const t=ic.trim(),s=Qp.trim();if(!t||!t.startsWith("http")){const l="Dealer login is not configured: VITE_TANFLOW_BASE_URL is missing or invalid. Set it in .env (e.g. VITE_TANFLOW_BASE_URL=https://your-tanflow-server).";throw console.error("🚪 Tanflow login:",l),new Error(l)}if(!s){const l="Dealer login is not configured: VITE_TANFLOW_CLIENT_ID is missing. Set it in .env (e.g. VITE_TANFLOW_CLIENT_ID=your-client-id).";throw console.error("🚪 Tanflow login:",l),new Error(l)}const a=new URLSearchParams(window.location.search),r=a.has("logout")||a.has("tanflow_logged_out");r&&(sessionStorage.removeItem("tanflow_logged_out"),sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),console.log("🚪 Cleared logout flags before initiating Tanflow login"));const n=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","tanflow"),sessionStorage.setItem("tanflow_auth_state",n);let i=`${t}/protocol/openid-connect/auth?client_id=${encodeURIComponent(s)}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(Kc)}&state=${n}`;r&&(i+="&prompt=login",console.log("🚪 Adding prompt=login to force re-authentication after logout")),console.log("🚪 Initiating Tanflow login",{isAfterLogout:r,hasPrompt:r}),window.location.href=i}async function gv(t,s){var r,n,i;const a="https://reflow-uat.royalenfield.com/api/v1";try{const l=await fi.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:Kc,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),o=((r=l.data)==null?void 0:r.data)||l.data;return o.accessToken&&nt.setAccessToken(o.accessToken),o.refreshToken&&nt.setRefreshToken(o.refreshToken),o.idToken&&nt.setIdToken(o.idToken),o.user&&nt.setUserData(o.user),o}catch(l){throw console.error("❌ Tanflow token exchange failed:",{message:l.message,response:(n=l.response)==null?void 0:n.data,status:(i=l.response)==null?void 0:i.status}),l}}function Kp(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=Kc,a=new URL(`${ic}/protocol/openid-connect/logout`);a.searchParams.set("client_id",Qp),a.searchParams.set("id_token_hint",t),a.searchParams.set("post_logout_redirect_uri",s);const r=a.toString();console.log("🚪 Tanflow logout initiated",{hasIdToken:!!t,idTokenPrefix:t?t.substring(0,20)+"...":"none",postLogoutRedirectUri:s,logoutUrlBase:`${ic}/protocol/openid-connect/logout`,finalLogoutUrl:r.replace(t.substring(0,20),"***")}),sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),console.log("🚪 Redirecting to Tanflow logout endpoint..."),window.location.href=r}function Xp(t){const s="https://dev-830839.oktapreview.com",a=nc();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 Hu="https://reflow-uat.royalenfield.com/api/v1".trim(),fv=typeof window<"u"&&/^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname),Xc=(!fv&&/localhost:5000/i.test(Hu)?"":Hu.replace(/\/$/,""))||"/api/v1",Se=fi.create({baseURL:Xc,headers:{"Content-Type":"application/json"},withCredentials:!0});Se.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));Se.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"),Q.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?Kp(l):Xp(l||void 0)},1e3),Promise.reject(t)}if(!s._retry){s._retry=!0;const l=!0;try{const o=nt.getRefreshToken(),c=await fi.post(`${Xc}/auth/refresh`,l?{}:{refreshToken:o},{withCredentials:!0}),m=(c.data.data||c.data).accessToken;return Se(s)}catch(o){return nt.clearAll(),window.location.href="/",Promise.reject(o)}}}return Promise.reject(t)});async function bv(t,s){var a,r;try{const n=await Se.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 jv(){var r;const t={},a=(await Se.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 Yn(){const s=(await Se.get("/auth/me")).data;return s.data||s}async function yv(){var t,s;try{await fi.post(`${Xc}/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 Rr=null;function vv(){const t="https://reflow-uat.royalenfield.com/api/v1";if(String(t).trim())return String(t).replace(/\/api\/v1\/?$/,"").replace(/\/$/,"");const s="https://reflow-uat.royalenfield.com/";return String(s).trim()?String(s).replace(/\/$/,""):""}function Kr(t){const s=vv();return Rr||(Rr=Iy(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),Rr.on("connect",()=>{}),Rr.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),Rr.on("disconnect",a=>{}),Rr)}function lc(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function Jp(t,s){t.emit("leave:request",s)}function Jc(t,s){t.emit("join:user",{userId:s})}const Nv=/^(localhost|127\.0\.0\.1)$/i;function wv(){return typeof window>"u"?"":window.location.hostname||""}function Zp(){return Nv.test(wv())}function Ln(){return!Zp()}function lr(t){return String(t||"").trim()}function Cv(t){const s=(t||"").toLowerCase();return s.includes("uat")||s.includes("dev")}function qp(){const t=typeof window<"u"?window.location.hostname:"",s=Zp(),a=!s&&Cv(t),r=lr("https://dev-830839.oktapreview.com"),n=lr("0oa2jgzvrpdwx2iqd0h8"),i=lr(void 0),l=lr(void 0),o=lr(void 0),c=lr(void 0),d=lr(void 0),m=lr(void 0);return s?{domain:i||r,clientId:l||n}:a?{domain:o||r,clientId:c||n}:{domain:d||r,clientId:m||n}}const eg=u.createContext(void 0);function Sv({children:t}){const[s,a]=u.useState(!1),[r,n]=u.useState(!0),[i,l]=u.useState(null),[o,c]=u.useState(null),[d,m]=u.useState(!1);u.useEffect(()=>{const v=sessionStorage.getItem("__logout_in_progress__"),N=sessionStorage.getItem("__force_logout__");if(v==="true"||N==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),nt.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(I){console.error("Error clearing storage:",I)}a(!1),l(null),n(!1),c(null);return}const T=new URLSearchParams(window.location.search),A=T.has("code"),k=sessionStorage.getItem("__logout_type__");if((T.has("logout")||T.has("okta_logged_out")||T.has("tanflow_logged_out")||k)&&!A){console.log("🚪 Logout parameter detected in URL, clearing all tokens and backend session"),yv().catch(I=>console.warn("🚪 Final backend logout cleanup failed:",I)),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(I){console.warn("Could not set force reauth flag:",I)}window.history.replaceState({},document.title,"/");return}if(window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback")return;const F=nt.getAccessToken(),w=nt.getRefreshToken(),L=nt.getUserData(),_=F||w||L;if(Ln())d?n(!1):h();else{if(!_){a(!1),l(null),n(!1);return}d?n(!1):h()}},[d]),u.useEffect(()=>{if(!s)return;const v=Ln(),N=async()=>{if(v)try{await y()}catch(k){console.error("Silent refresh failed:",k)}else{const k=nt.getAccessToken();if(k&&Ei(k,5))try{await y()}catch(D){console.error("Silent refresh failed:",D)}}},T=v?10*60*1e3:5*60*1e3,A=setInterval(N,T);return()=>clearInterval(A)},[s]),u.useEffect(()=>{if(!s||!(i!=null&&i.userId))return;const v=Kr();Jc(v,i.userId);const N=T=>{console.log("📡 [Socket] Session superseded event received:",T),nt.setAuthError("SESSION_SUPERSEDED"),Q.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(()=>{f()},1e3)};return v.on("SESSION_SUPERSEDED",N),()=>{v.off("SESSION_SUPERSEDED",N)}},[s,i==null?void 0:i.userId]);const p=u.useRef(!1),x=u.useRef(null);u.useEffect(()=>{if(p.current||window.location.pathname!=="/login/callback")return;(async()=>{var L,_,W,I;const N=new URLSearchParams(window.location.search);if(sessionStorage.getItem("auth_provider")==="tanflow")return;const A=sessionStorage.getItem("__logout_type__");if((N.has("logout")||N.has("tanflow_logged_out")||N.has("okta_logged_out")||A)&&!N.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const $=new URLSearchParams;(N.has("tanflow_logged_out")||A==="tanflow")&&$.set("tanflow_logged_out","true"),(N.has("okta_logged_out")||A==="okta")&&$.set("okta_logged_out","true"),N.has("logout")&&$.set("logout",N.get("logout")||Date.now().toString());const M=$.toString()?`/?${$.toString()}`:"/?logout="+Date.now();window.location.replace(M);return}p.current=!0;const D=N.get("code"),F=N.get("error");if(window.history.replaceState({},document.title,"/login/callback"),F){c(new Error(`Authentication error: ${F}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!D){n(!1),sessionStorage.removeItem("auth_provider");return}const w=sessionStorage.getItem("__okta_auth_code_consumed__");if(w&&w===D){c(new Error("Authorization code already used. Please login again.")),n(!1),sessionStorage.removeItem("auth_provider");return}if(x.current!==D){x.current=D,sessionStorage.setItem("__okta_auth_code_consumed__",D);try{n(!0),a(!1),c(null);const $=nc(),M=await bv(D,$);l(M.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch($){console.error("❌ Token exchange error in AuthContext:",$);const M=String(((_=(L=$==null?void 0:$.response)==null?void 0:L.data)==null?void 0:_.error)||"").toUpperCase(),R=String(((I=(W=$==null?void 0:$.response)==null?void 0:W.data)==null?void 0:I.message)||($==null?void 0:$.message)||"").toLowerCase();if(M==="RELOGIN_REQUIRED"||R.includes("invalid or has expired")||R.includes("invalid_grant")||R.includes("authorization code already used")){a(!1),l(null),c(new Error("Login session expired. Please sign in again.")),sessionStorage.removeItem("auth_provider"),window.location.replace("/?relogin_required=1");return}c($),a(!1),l(null),sessionStorage.removeItem("auth_provider"),p.current=!1}finally{n(!1)}}})()},[]);const h=async()=>{var N;if(d){n(!1);return}const v=Ln();try{if(n(!0),v){const k=nt.getUserData();try{const D=await Yn();l(D),nt.setUserData(D),a(!0)}catch(D){if(((N=D==null?void 0:D.response)==null?void 0:N.status)===401)try{await y();const F=await Yn();l(F),nt.setUserData(F),a(!0)}catch{nt.clearAll(),a(!1),l(null)}else D!=null&&D.isConnectionError?k?(l(k),a(!0)):(a(!1),l(null)):(nt.clearAll(),a(!1),l(null))}return}const T=nt.getAccessToken(),A=nt.getUserData();if(!T){a(!1),l(null),n(!1);return}if(Ei(T))try{await y();const k=nt.getAccessToken();if(k&&!Ei(k)){const D=nt.getUserData();if(D)l(D),a(!0);else try{const F=await Yn();l(F),nt.setUserData(F),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(A)l(A),a(!0);else try{const k=await Yn();l(k),nt.setUserData(k),a(!0)}catch{nt.clearAll(),a(!1),l(null)}}catch(T){console.error("Error checking auth status:",T),c(T),nt.clearAll(),a(!1),l(null)}finally{n(!1)}},g=async()=>{try{c(null);const{domain:v,clientId:N}=qp();if(!v||!N)throw new Error("Missing Okta configuration (VITE_OKTA_DOMAIN / VITE_OKTA_CLIENT_ID). Set them and rebuild the frontend.");const T=nc(),A="code",k="openid profile email",D=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const F=new URLSearchParams(window.location.search),w=F.has("logout")||F.has("okta_logged_out")||F.has("tanflow_logged_out"),L=sessionStorage.getItem("__force_reauth_after_logout__")==="true",_=w||L;let W=`${v}/oauth2/default/v1/authorize?client_id=${N}&redirect_uri=${encodeURIComponent(T)}&response_type=${A}&scope=${encodeURIComponent(k)}&state=${D}`;_&&(W+="&prompt=login",sessionStorage.removeItem("__force_reauth_after_logout__")),window.location.href=W}catch(v){throw c(v),v}},f=async()=>{try{const v=nt.getIdToken(),N=sessionStorage.getItem("auth_provider")||(v&&v.includes("tanflow")?"tanflow":null)||"okta";sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),l(null),c(null),n(!0);const T=sessionStorage.getItem("__logout_in_progress__"),A=sessionStorage.getItem("__force_logout__"),k=sessionStorage.getItem("auth_provider");if(nt.clearAll(),T&&sessionStorage.setItem("__logout_in_progress__",T),A&&sessionStorage.setItem("__force_logout__",A),v&&nt.setIdToken(v),k&&sessionStorage.setItem("auth_provider",k),await new Promise(D=>setTimeout(D,100)),N==="tanflow"&&v){console.log("🚪 Initiating Tanflow logout...");try{Kp(v);return}catch(D){console.error("🚪 Tanflow logout error:",D)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),Xp(v||void 0)}catch(v){console.error("🚪 Logout error:",v);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const T=`${"https://reflow-uat.royalenfield.com/".trim().replace(/\/$/,"")}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(T)}catch{window.location.replace("/?logout="+Date.now())}}},b=async()=>{if(Ln()){if(s)return"cookie-based-auth";try{return await y(),s?"cookie-based-auth":null}catch{return null}}const N=nt.getAccessToken();if(N&&!Ei(N))return N;try{return await y(),nt.getAccessToken()}catch{return null}},y=async()=>{const v=Ln();try{const N=await jv();if(v||N)return;throw new Error("Failed to refresh token")}catch(N){throw nt.clearAll(),a(!1),l(null),N}},j={isAuthenticated:s,isLoading:r,user:i,error:o,login:g,logout:f,getAccessTokenSilently:b,refreshTokenSilently:y};return e.jsx(eg.Provider,{value:j,children:t})}function Av({children:t}){return e.jsx(Sv,{children:t})}function us(){const t=u.useContext(eg);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Er(t){return(t==null?void 0:t.role)==="ADMIN"}function On(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function Ul(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Gu=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,Yu=jp,Zc=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return Yu(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,l=Object.keys(n).map(d=>{const m=a==null?void 0:a[d],p=i==null?void 0:i[d];if(m===null)return null;const x=Gu(m)||Gu(p);return n[d][x]}),o=a&&Object.entries(a).reduce((d,m)=>{let[p,x]=m;return x===void 0||(d[p]=x),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:p,className:x,...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,x]:d},[]);return Yu(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},qc="-",Tv=t=>{const s=Dv(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(qc);return o[0]===""&&o.length!==1&&o.shift(),tg(o,s)||kv(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},tg=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?tg(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(qc);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Qu=/^\[(.+)\]$/,kv=t=>{if(Qu.test(t)){const s=Qu.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Dv=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Iv(Object.entries(t.classGroups),a).forEach(([i,l])=>{oc(l,r,i,s)}),r},oc=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:Ku(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Rv(n)){oc(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{oc(l,Ku(s,i),a,r)})})},Ku=(t,s)=>{let a=t;return s.split(qc).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Rv=t=>t.isThemeGetter,Iv=(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,Fv=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)}}},sg="!",Pv=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 y=o[b];if(d===0){if(y===n&&(r||o.slice(b,b+i)===s)){c.push(o.slice(m,b)),m=b+i;continue}if(y==="/"){p=b;continue}}y==="["?d++:y==="]"&&d--}const x=c.length===0?o:o.substring(m),h=x.startsWith(sg),g=h?x.substring(1):x,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},_v=t=>({cache:Fv(t.cacheSize),parseClassName:Pv(t),...Tv(t)}),Mv=/\s+/,Lv=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(Mv);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:p,baseClassName:x,maybePostfixModifierPosition:h}=a(d);let g=!!h,f=r(g?x.substring(0,h):x);if(!f){if(!g){o=d+(o.length>0?" "+o:o);continue}if(f=r(x),!f){o=d+(o.length>0?" "+o:o);continue}g=!1}const b=Ev(m).join(":"),y=p?b+sg:b,j=y+f;if(i.includes(j))continue;i.push(j);const v=n(f,g);for(let N=0;N<v.length;++N){const T=v[N];i.push(y+T)}o=d+(o.length>0?" "+o:o)}return o};function Ov(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=ag(s))&&(r&&(r+=" "),r+=a);return r}const ag=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=ag(t[r]))&&(a&&(a+=" "),a+=s);return a};function $v(t,...s){let a,r,n,i=l;function l(c){const d=s.reduce((m,p)=>p(m),t());return a=_v(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=Lv(c,a);return n(c,m),m}return function(){return i(Ov.apply(null,arguments))}}const Kt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},rg=/^\[(?:([a-z-]+):)?(.+)\]$/i,Uv=/^\d+\/\d+$/,Bv=new Set(["px","full","screen"]),zv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Vv=/\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$/,Wv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Hv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Gv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ka=t=>jn(t)||Bv.has(t)||Uv.test(t),or=t=>Tn(t,"length",eN),jn=t=>!!t&&!Number.isNaN(Number(t)),lo=t=>Tn(t,"number",jn),$n=t=>!!t&&Number.isInteger(Number(t)),Yv=t=>t.endsWith("%")&&jn(t.slice(0,-1)),yt=t=>rg.test(t),cr=t=>zv.test(t),Qv=new Set(["length","size","percentage"]),Kv=t=>Tn(t,Qv,ng),Xv=t=>Tn(t,"position",ng),Jv=new Set(["image","url"]),Zv=t=>Tn(t,Jv,sN),qv=t=>Tn(t,"",tN),Un=()=>!0,Tn=(t,s,a)=>{const r=rg.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},eN=t=>Vv.test(t)&&!Wv.test(t),ng=()=>!1,tN=t=>Hv.test(t),sN=t=>Gv.test(t),aN=()=>{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"),x=Kt("gap"),h=Kt("gradientColorStops"),g=Kt("gradientColorStopPositions"),f=Kt("inset"),b=Kt("margin"),y=Kt("opacity"),j=Kt("padding"),v=Kt("saturate"),N=Kt("scale"),T=Kt("sepia"),A=Kt("skew"),k=Kt("space"),D=Kt("translate"),F=()=>["auto","contain","none"],w=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto",yt,s],_=()=>[yt,s],W=()=>["",Ka,or],I=()=>["auto",jn,yt],$=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],M=()=>["solid","dashed","dotted","double","none"],R=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],C=()=>["start","end","center","between","around","evenly","stretch"],H=()=>["","0",yt],z=()=>["auto","avoid","all","avoid-page","page","left","right","column"],P=()=>[jn,yt];return{cacheSize:500,separator:":",theme:{colors:[Un],spacing:[Ka,or],blur:["none","",cr,yt],brightness:P(),borderColor:[t],borderRadius:["none","","full",cr,yt],borderSpacing:_(),borderWidth:W(),contrast:P(),grayscale:H(),hueRotate:P(),invert:H(),gap:_(),gradientColorStops:[t],gradientColorStopPositions:[Yv,or],inset:L(),margin:L(),opacity:P(),padding:_(),saturate:P(),scale:P(),sepia:H(),skew:P(),space:_(),translate:_()},classGroups:{aspect:[{aspect:["auto","square","video",yt]}],container:["container"],columns:[{columns:[cr]}],"break-after":[{"break-after":z()}],"break-before":[{"break-before":z()}],"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:[...$(),yt]}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],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",$n,yt]}],basis:[{basis:L()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",yt]}],grow:[{grow:H()}],shrink:[{shrink:H()}],order:[{order:["first","last","none",$n,yt]}],"grid-cols":[{"grid-cols":[Un]}],"col-start-end":[{col:["auto",{span:["full",$n,yt]},yt]}],"col-start":[{"col-start":I()}],"col-end":[{"col-end":I()}],"grid-rows":[{"grid-rows":[Un]}],"row-start-end":[{row:["auto",{span:[$n,yt]},yt]}],"row-start":[{"row-start":I()}],"row-end":[{"row-end":I()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",yt]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",yt]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...C()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...C(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...C(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[j]}],px:[{px:[j]}],py:[{py:[j]}],ps:[{ps:[j]}],pe:[{pe:[j]}],pt:[{pt:[j]}],pr:[{pr:[j]}],pb:[{pb:[j]}],pl:[{pl:[j]}],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":[k]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[k]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",yt,s]}],"min-w":[{"min-w":[yt,s,"min","max","fit"]}],"max-w":[{"max-w":[yt,s,"none","full","min","max","fit","prose",{screen:[cr]},cr]}],h:[{h:[yt,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[yt,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[yt,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[yt,s,"auto","min","max","fit"]}],"font-size":[{text:["base",cr,or]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",lo]}],"font-family":[{font:[Un]}],"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",yt]}],"line-clamp":[{"line-clamp":["none",jn,lo]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Ka,yt]}],"list-image":[{"list-image":["none",yt]}],"list-style-type":[{list:["none","disc","decimal",yt]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...M(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Ka,or]}],"underline-offset":[{"underline-offset":["auto",Ka,yt]}],"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:_()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",yt]}],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",yt]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...$(),Xv]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Kv]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Zv]}],"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":[y]}],"border-style":[{border:[...M(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[y]}],"divide-style":[{divide:M()}],"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:["",...M()]}],"outline-offset":[{"outline-offset":[Ka,yt]}],"outline-w":[{outline:[Ka,or]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[Ka,or]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",cr,qv]}],"shadow-color":[{shadow:[Un]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...R(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":R()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",cr,yt]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[v]}],sepia:[{sepia:[T]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[v]}],"backdrop-sepia":[{"backdrop-sepia":[T]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",yt]}],duration:[{duration:P()}],ease:[{ease:["linear","in","out","in-out",yt]}],delay:[{delay:P()}],animate:[{animate:["none","spin","ping","pulse","bounce",yt]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[N]}],"scale-x":[{"scale-x":[N]}],"scale-y":[{"scale-y":[N]}],rotate:[{rotate:[$n,yt]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[A]}],"skew-y":[{"skew-y":[A]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",yt]}],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",yt]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":_()}],"scroll-mx":[{"scroll-mx":_()}],"scroll-my":[{"scroll-my":_()}],"scroll-ms":[{"scroll-ms":_()}],"scroll-me":[{"scroll-me":_()}],"scroll-mt":[{"scroll-mt":_()}],"scroll-mr":[{"scroll-mr":_()}],"scroll-mb":[{"scroll-mb":_()}],"scroll-ml":[{"scroll-ml":_()}],"scroll-p":[{"scroll-p":_()}],"scroll-px":[{"scroll-px":_()}],"scroll-py":[{"scroll-py":_()}],"scroll-ps":[{"scroll-ps":_()}],"scroll-pe":[{"scroll-pe":_()}],"scroll-pt":[{"scroll-pt":_()}],"scroll-pr":[{"scroll-pr":_()}],"scroll-pb":[{"scroll-pb":_()}],"scroll-pl":[{"scroll-pl":_()}],"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",yt]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Ka,or,lo]}],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"]}}},rN=$v(aN);function $e(...t){return rN(jp(t))}const li=Zc("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"}}),O=u.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?cp:"button";return e.jsx(l,{"data-slot":"button",className:$e(li({variant:s,size:a,className:t})),ref:i,...n})});O.displayName="Button";function Z({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:$e("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function de({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:$e("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",t),...s})}function ue({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:$e("leading-none",t),...s})}function Te({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:$e("text-muted-foreground",t),...s})}function ee({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:$e("px-6 [&:last-child]:pb-6",t),...s})}const Bl="/assets/Re_Logo-By51taPS.png",Xu="/assets/landing_page_image-ClTD-4qZ.jpg";function nN(){var g,f;const{login:t,isLoading:s,error:a}=us(),{domain:r,clientId:n}=qp(),i=!!(r&&n),[l,o]=u.useState(!1),[c,d]=u.useState(null),[m,p]=u.useState(!1);u.useEffect(()=>{const b=new Image;b.src=Xu,b.onload=()=>p(!0),b.complete&&p(!0)},[]);const x=async()=>{const b=sessionStorage.getItem("__force_reauth_after_logout__");localStorage.clear(),sessionStorage.clear(),b&&sessionStorage.setItem("__force_reauth_after_logout__",b);try{sessionStorage.setItem("auth_provider","okta"),await t()}catch(y){console.error("OKTA LOGIN ERROR",y)}},h=()=>{d(null),localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("auth_provider","tanflow"),o(!0);try{pv()}catch(b){const y=b instanceof Error?b.message:"Dealer login failed. Check console for details.";console.error("TANFLOW LOGIN ERROR",b),d(y),o(!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:m?`url(${Xu})`:"none",backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},children:[!m&&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(de,{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:Bl,alt:"Royal Enfield",className:"h-9 w-auto max-w-[180px] object-contain mb-2"}),e.jsx("p",{className:"text-sm text-gray-400",children:"Approval Portal"})]})}),e.jsxs(ee,{className:"space-y-5 pb-8 px-8",children:[a&&e.jsxs("div",{className:"bg-red-900/40 border border-red-700 text-red-200 px-4 py-3 rounded-lg text-sm",children:[e.jsx("p",{className:"font-medium",children:"Authentication Error"}),e.jsx("p",{children:a.message}),(((g=a.message)==null?void 0:g.includes("401"))||((f=a.message)==null?void 0:f.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."]})]}),c&&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:c})]}),e.jsx(O,{onClick:x,disabled:s||l||!i,className:"w-full h-12 bg-re-red hover:bg-re-red/90 text-white font-semibold text-base border-0 disabled:opacity-50 disabled:pointer-events-none",size:"lg",title:i?void 0:"Set VITE_OKTA_DOMAIN and VITE_OKTA_CLIENT_ID, then rebuild",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(ys,{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(O,{onClick:h,disabled:s||l,className:"w-full h-12 bg-blue-600 hover:bg-blue-700 text-white font-semibold text-base border-0",size:"lg",children:l?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(bs,{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 ig(){const{isAuthenticated:t,isLoading:s,error:a,user:r,login:n}=us(),[i,l]=u.useState("exchanging");u.useEffect(()=>{if(a){l("error");return}if(s){const d=new URLSearchParams(window.location.search).get("code");l(d&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&l("complete")},[t,s,a,r]);const o=()=>{switch(i){case"exchanging":return"Exchanging authorization code...";case"fetching":return"Fetching your profile...";case"complete":return"Authentication successful!";case"error":return"Authentication failed";default:return"Completing authentication..."}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"}),e.jsxs("div",{className:"relative z-10 text-center px-4 max-w-md w-full",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Bl,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:i==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(Ze,{className:"w-16 h-16 text-red-500"})}),e.jsx(Ze,{className:"w-16 h-16 text-red-500 relative"})]}):i==="complete"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(ps,{className:"w-16 h-16 text-green-500"})}),e.jsx(ps,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(ze,{className:"w-16 h-16 animate-spin text-re-red"}),e.jsx("div",{className:"absolute inset-0 border-4 rounded-full border-re-red/20"}),e.jsx("div",{className:"absolute inset-0 border-4 border-transparent border-t-re-red rounded-full animate-spin"})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-white mb-2",children:i==="complete"?"Welcome Back!":i==="error"?"Authentication Error":"Authenticating"}),e.jsx("p",{className:"text-slate-300 text-sm",children:o()})]}),i!=="error"&&e.jsxs("div",{className:"space-y-3 mb-6",children:[e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${i==="exchanging"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${i==="exchanging"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Validating credentials"})]}),e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${i==="fetching"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${i==="fetching"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Loading your profile"})]}),i==="complete"&&e.jsxs("div",{className:"flex items-center gap-3 text-sm transition-all duration-500 text-white",children:[e.jsx("div",{className:"w-2 h-2 rounded-full transition-all duration-500 bg-green-500"}),e.jsx("span",{children:"Setting up your session"})]})]}),i==="error"&&a&&e.jsxs("div",{className:"mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx("p",{className:"text-red-400 text-sm",children:a.message||"An error occurred during authentication"}),e.jsx("button",{onClick:async()=>{try{await n()}catch{window.location.href="/"}},className:"mt-4 text-sm text-red-400 hover:text-red-300 underline",children:"Retry Login"})]}),i!=="error"&&i!=="complete"&&e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"h-1.5 bg-slate-700/50 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-re-red rounded-full animate-pulse",style:{animation:"progress 2s ease-in-out infinite"}})}),e.jsx("style",{children:`
@keyframes progress {
0%, 100% { width: 20%; }
50% { width: 80%; }
}
`})]})]}),e.jsx("p",{className:"mt-6 text-slate-500 text-xs",children:i==="complete"?"Loading dashboard...":"Please wait while we secure your session"})]}),e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute top-1/4 left-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-1/4 right-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse delay-1000"})]})]})}function iN(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=us(),[n,i]=u.useState("exchanging"),[l,o]=u.useState(""),c=u.useRef(!1);u.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]),u.useEffect(()=>{if(c.current||window.location.pathname!=="/login/callback")return;const m=new URLSearchParams(window.location.search),p=m.get("code"),x=m.get("error");if(!p&&!x){console.log("🚪 Logout redirect detected: no code, no error - redirecting to home immediately"),c.current=!0;const f=new URLSearchParams;f.set("tanflow_logged_out","true"),f.set("logout",Date.now().toString());const b=`/?${f.toString()}`;console.log("🚪 Redirecting to:",b),window.location.replace(b);return}if(sessionStorage.getItem("auth_provider")!=="tanflow")return;(async()=>{c.current=!0;const f=new URLSearchParams(window.location.search),b=f.get("code"),y=f.get("state"),j=f.get("error");if(window.history.replaceState({},document.title,"/login/callback"),j){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}const v=sessionStorage.getItem("tanflow_auth_state");if(y&&y!==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 N=await gv(b,y||"");sessionStorage.removeItem("tanflow_auth_state"),i("fetching");const T=N.user||await Yn();if(T)nt.setUserData(T),i("complete"),setTimeout(()=>{window.history.replaceState({},document.title,"/"),window.location.href="/"},1e3);else throw new Error("User data not received")}catch(N){console.error("Tanflow callback error:",N),i("error"),o(N.message||"Authentication failed"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state")}})()},[]);const d=()=>{switch(n){case"exchanging":return"Exchanging authorization code...";case"fetching":return"Fetching your profile...";case"complete":return"Authentication successful!";case"error":return"Authentication failed";default:return"Completing authentication..."}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"}),e.jsxs("div",{className:"relative z-10 text-center px-4 max-w-md w-full",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Bl,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:n==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(Ze,{className:"w-16 h-16 text-red-500"})}),e.jsx(Ze,{className:"w-16 h-16 text-red-500 relative"})]}):n==="complete"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(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 lN=Zc("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 oe({className:t,variant:s,asChild:a=!1,...r}){const n=a?cp:"span";return e.jsx(n,{"data-slot":"badge",className:$e(lN({variant:s}),t),...r})}function oN({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=xv();return u.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(de,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Authentication Debug Information"}),e.jsx(O,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(vt,{className:"h-4 w-4"})})]})}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold",children:"Status:"}),e.jsx(oe,{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 ds=u.forwardRef(({className:t,...s},a)=>e.jsx(dp,{ref:a,"data-slot":"avatar",className:$e("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));ds.displayName=dp.displayName;const zl=u.forwardRef(({className:t,...s},a)=>e.jsx(mp,{ref:a,"data-slot":"avatar-image",className:$e("aspect-square size-full",t),...s}));zl.displayName=mp.displayName;const ms=u.forwardRef(({className:t,...s},a)=>e.jsx(up,{ref:a,"data-slot":"avatar-fallback",className:$e("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));ms.displayName=up.displayName;function Ju({...t}){return e.jsx(Fb,{"data-slot":"dropdown-menu",...t})}function Zu({...t}){return e.jsx(Pb,{"data-slot":"dropdown-menu-trigger",...t})}function qu({className:t,sideOffset:s=4,...a}){return e.jsx(Eb,{children:e.jsx(_b,{"data-slot":"dropdown-menu-content",sideOffset:s,className:$e("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",t),...a})})}function oo({className:t,inset:s,variant:a="default",...r}){return e.jsx(Mb,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:$e("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r})}function lg({...t}){return e.jsx(Ob,{"data-slot":"alert-dialog",...t})}function cN({...t}){return e.jsx(Lb,{"data-slot":"alert-dialog-portal",...t})}const og=u.forwardRef(({className:t,...s},a)=>e.jsx(xp,{"data-slot":"alert-dialog-overlay",className:$e("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...s,ref:a}));og.displayName=xp.displayName;const ed=u.forwardRef(({className:t,...s},a)=>e.jsxs(cN,{children:[e.jsx(og,{}),e.jsx(hp,{"data-slot":"alert-dialog-content",ref:a,className:$e("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...s})]}));ed.displayName=hp.displayName;function cg({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:$e("flex flex-col gap-2 text-center sm:text-left",t),...s})}function dg({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:$e("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function mg({className:t,...s}){return e.jsx($b,{"data-slot":"alert-dialog-title",className:$e("text-lg font-semibold",t),...s})}function ug({className:t,...s}){return e.jsx(Ub,{"data-slot":"alert-dialog-description",className:$e("text-muted-foreground text-sm",t),...s})}function xg({className:t,...s}){return e.jsx(zb,{className:$e(li(),t),...s})}function hg({className:t,...s}){return e.jsx(Bb,{className:$e(li({variant:"outline"}),t),...s})}const xr={async list(t){return(await Se.get("/notifications",{params:t})).data},async getUnreadCount(){return(await Se.get("/notifications/unread-count")).data},async markAsRead(t){return(await Se.patch(`/notifications/${t}/read`)).data},async markAllAsRead(){return(await Se.post("/notifications/mark-all-read")).data},async delete(t){return(await Se.delete(`/notifications/${t}`)).data}},dN=async()=>(await Se.get("/notifications/subscriptions")).data.data.subscriptions,ex="https://reflow-uat.royalenfield.com/api/v1".trim(),mN=typeof window<"u"&&/^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname),pg=(!mN&&/localhost:5000/i.test(ex)?"":ex.replace(/\/$/,""))||"/api/v1";async function gg(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(`${pg}${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 td(){var a;const t=await Se.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 uN(){const{data:t}=await Se.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 fg(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 Se.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 bg(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 Se.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 jg(t){const{data:s}=await Se.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 sd(t){const{data:s}=await Se.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 yg(t){const{data:s}=await Se.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 xN(t){await Se.post(`/form16/requests/${encodeURIComponent(t)}/cancel-submission`)}async function hN(t){await Se.post(`/form16/requests/${encodeURIComponent(t)}/resubmission-needed`)}async function tx(t){const{data:s}=await Se.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 pN(t){const s=new FormData;s.append("document",t);const a=await gg("/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 gN(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 gg("/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 fN(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 Se.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 bN(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 Se.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 jN=5*60*1e3;function yN(t,s){return new Promise((a,r)=>{const n=new FormData;n.append("file",t);const i=new XMLHttpRequest,l=`${pg}/form16/26as/upload`,o=nt.getAccessToken(),c=setTimeout(()=>{i.abort(),r(new Error("Upload timed out. Try a smaller file or try again."))},jN);i.upload.addEventListener("progress",d=>{if(d.lengthComputable&&d.total>0){const m=Math.min(100,Math.round(d.loaded/d.total*100));s==null||s(m)}else s==null||s(0)}),i.addEventListener("load",()=>{clearTimeout(c),s==null||s(100);const d=i.getResponseHeader("content-type"),m=d==null?void 0:d.includes("application/json"),p=i.responseText;let x;try{x=m?JSON.parse(p):{message:p||"Request failed"}}catch{x={message:p||"Invalid response"}}if(i.status>=200&&i.status<300){const h=x.data??x;a({imported:(h==null?void 0:h.imported)??0,errors:Array.isArray(h==null?void 0:h.errors)?h.errors:[]})}else r(new Error(x.message||`Request failed ${i.status}`))}),i.addEventListener("error",()=>{clearTimeout(c),r(new Error("Network error during upload"))}),i.addEventListener("abort",()=>{clearTimeout(c),r(new Error("Upload was cancelled or timed out"))}),i.open("POST",l),o&&i.setRequestHeader("Authorization",`Bearer ${o}`),i.withCredentials=!0,i.send(n)})}async function vN(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 Se.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 NN(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 Se.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 wN(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 Se.get(r),i=(n==null?void 0:n.data)??n;return Array.isArray(i)?i:[]}async function vg(){const{data:t}=await Se.get("/form16/dealer/pending-quarters"),s=(t==null?void 0:t.data)??t;return Array.isArray(s)?s:[]}async function Ng(){var r;const t=await Se.get("/cpc-csd/permissions"),s=((r=t.data)==null?void 0:r.data)??t.data;return{canViewCpcCsd:!!((s==null?void 0:s.canViewCpcCsd)??(s==null?void 0:s.canViewCpcCdc))}}function Lt({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,l]=u.useState(!1),[o,c]=u.useState(()=>(s==null?void 0:s.startsWith("form16"))??!1),[d,m]=u.useState(()=>(s==null?void 0:s.startsWith("cpc-csd"))||(s==null?void 0:s.startsWith("cpc-cdc"))||!1),[p,x]=u.useState(!1),[h,g]=u.useState([]),[f,b]=u.useState(0),[y,j]=u.useState(!1),[v,N]=u.useState(null),[T,A]=u.useState(null),{user:k}=us(),D=u.useMemo(()=>{try{const U=nt.getUserData();return(U==null?void 0:U.jobTitle)==="Dealer"}catch(U){return console.error("[PageLayout] Error checking dealer status:",U),!1}},[]),F=(k==null?void 0:k.role)==="ADMIN",w=()=>{var U,Y;try{if(k!=null&&k.displayName&&typeof k.displayName=="string"){const B=k.displayName.split(" ").filter(Boolean);return B.length>=2?`${((U=B[0])==null?void 0:U[0])||""}${((Y=B[B.length-1])==null?void 0:Y[0])||""}`.toUpperCase():k.displayName.substring(0,2).toUpperCase()}return k!=null&&k.email&&typeof k.email=="string"?k.email.substring(0,2).toUpperCase():"U"}catch(B){return console.error("[PageLayout] Error getting user initials:",B),"U"}},L=u.useMemo(()=>{const U=[{id:"dashboard",label:"Dashboard",icon:Mu},{id:"requests",label:"All Requests",icon:ec,adminOnly:!1}];return D||U.push({id:"my-requests",label:"My Requests",icon:Wt}),U.push({id:"open-requests",label:"Open Requests",icon:Ee},{id:"closed-requests",label:"Closed Requests",icon:Ve},{id:"shared-summaries",label:"Shared Summary",icon:Sn}),U},[D,F]);u.useEffect(()=>{if(!(k!=null&&k.userId)){N(null);return}let U=!0;return td().then(Y=>{U&&N(Y)}).catch(Y=>{U&&(N({canViewForm16Submission:!1,canView26AS:!1}),console.warn("[PageLayout] Form 16 permissions could not be loaded Form 16 menu will be hidden.",Y))}),()=>{U=!1}},[k==null?void 0:k.userId]),u.useEffect(()=>{if(!(k!=null&&k.userId)){A(null);return}let U=!0;return Ng().then(Y=>{U&&A(Y)}).catch(Y=>{U&&(A({canViewCpcCsd:!1}),console.warn("[PageLayout] CPC-CSD permissions could not be loaded CPC-CSD menu will be hidden.",Y))}),()=>{U=!1}},[k==null?void 0:k.userId]);const _=!!v&&(D?!!v.canViewForm16Submission:!!v.canView26AS),W=!!(v!=null&&v.canViewForm16Submission),I=!!(v!=null&&v.canView26AS),$=!!(T!=null&&T.canViewCpcCsd),M=s==="form16-credit-notes"||s==="form16-debit-notes"||s==="form16-transactions"||s==="form16-submit"||s==="form16-pending-submissions"||s==="form16-dashboard"||s==="form16-26as"||s==="form16-non-submitted-dealers",R=o||M,C=!!(s!=null&&s.startsWith("cpc-csd"))||!!(s!=null&&s.startsWith("cpc-cdc")),H=d||C,z=()=>{l(!i)},P=async U=>{var Y;try{if(U.isRead||(await xr.markAsRead(U.notificationId),g(B=>B.map(E=>E.notificationId===U.notificationId?{...E,isRead:!0}:E)),b(B=>Math.max(0,B-1))),U.actionUrl&&a){const B=(Y=U.metadata)==null?void 0:Y.requestNumber;if(B){let E=`request/${B}`;(U.notificationType==="mention"||U.notificationType==="comment"||U.notificationType==="worknote")&&(E+="?tab=worknotes"),a(E)}}j(!1)}catch(B){console.error("[PageLayout] Error handling notification click:",B)}},S=async()=>{try{await xr.markAllAsRead(),g(U=>U.map(Y=>({...Y,isRead:!0}))),b(0)}catch(U){console.error("[PageLayout] Error marking all as read:",U)}};return u.useEffect(()=>{const U=k==null?void 0:k.userId;if(!U)return;let Y=!0;(async()=>{var V,G;try{const J=await xr.list({page:1,limit:4,unreadOnly:!1});if(!Y)return;const q=((V=J.data)==null?void 0:V.notifications)||[];g(q),b(((G=J.data)==null?void 0:G.unreadCount)||0)}catch(J){console.error("[PageLayout] Failed to fetch notifications:",J)}})();const E=Kr();if(E){Jc(E,U);const V=G=>{Y&&(g(J=>[G.notification,...J].slice(0,4)),b(J=>J+1))};return E.on("notification:new",V),()=>{Y=!1,E.off("notification:new",V)}}return()=>{Y=!1}},[k]),u.useEffect(()=>{const U=()=>{window.innerWidth>=768?l(!0):l(!1)};return U(),window.addEventListener("resize",U),()=>window.removeEventListener("resize",U)},[]),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:Bl,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:[L.filter(U=>!U.adminOnly||(k==null?void 0:k.role)==="ADMIN").map(U=>e.jsxs("button",{onClick:()=>{a==null||a(U.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===U.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(U.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:U.label})]},U.id)),_&&e.jsxs("div",{className:"pt-2 border-t border-gray-800",children:[e.jsxs("button",{type:"button",onClick:()=>c(!R),className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${M?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(Et,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate flex-1 text-left",children:"Form 16"}),R?e.jsx(Qr,{className:"w-4 h-4 shrink-0"}):e.jsx(Wa,{className:"w-4 h-4 shrink-0"})]}),R&&e.jsx("div",{className:"mt-1 ml-4 pl-2 border-l border-gray-700 space-y-0.5",children:D?e.jsx(e.Fragment,{children:W&&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(Ee,{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(Ee,{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(Et,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Credit Notes"})]})]})}):e.jsxs(e.Fragment,{children:[I&&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(Ee,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Form16A Dashboard"})]}),I&&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(Ee,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"26AS Management"})]}),W&&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(Et,{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(Et,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Transactions"})]})]})]})})]}),$&&e.jsxs("div",{className:"pt-2 border-t border-gray-800",children:[e.jsxs("button",{type:"button",onClick:()=>m(!H),className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${C?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(Et,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate flex-1 text-left",children:"CPC-CSD"}),H?e.jsx(Qr,{className:"w-4 h-4 shrink-0"}):e.jsx(Wa,{className:"w-4 h-4 shrink-0"})]}),H&&e.jsxs("div",{className:"mt-1 ml-4 pl-2 border-l border-gray-700 space-y-0.5",children:[e.jsxs("button",{type:"button",onClick:()=>{a==null||a("/cpc-csd/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==="cpc-csd-dashboard"?"bg-re-green/80 text-white font-medium":"text-gray-400 hover:bg-gray-800 hover:text-white"}`,children:[e.jsx(Mu,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Dashboard"})]}),e.jsxs("button",{type:"button",onClick:()=>{a==null||a("/cpc-csd/history"),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==="cpc-csd-history"?"bg-re-green/80 text-white font-medium":"text-gray-400 hover:bg-gray-800 hover:text-white"}`,children:[e.jsx(ec,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"All Submissions"})]}),e.jsxs("button",{type:"button",onClick:()=>{a==null||a("/cpc-csd/rejected"),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==="cpc-csd-rejected"?"bg-re-green/80 text-white font-medium":"text-gray-400 hover:bg-gray-800 hover:text-white"}`,children:[e.jsx(Ze,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Rejected Docs"})]})]})]})]}),!D&&e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(O,{onClick:r,className:"w-full bg-re-green hover:bg-re-green/90 text-white text-sm font-medium",size:"sm",children:[e.jsx(is,{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(O,{variant:"ghost",size:"icon",onClick:z,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(Gj,{className:"w-5 h-5 text-gray-600"}):e.jsx(Yj,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[!D&&e.jsxs(O,{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(is,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(Ju,{open:y,onOpenChange:j,children:[e.jsx(Zu,{asChild:!0,children:e.jsxs(O,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(Os,{className:"w-5 h-5"}),f>0&&e.jsx(oe,{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:f>9?"9+":f})]})}),e.jsxs(qu,{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"}),f>0&&e.jsx(O,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:U=>{U.stopPropagation(),S()},children:"Mark all as read"})]}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:h.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(Os,{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:h.map(U=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${U.isRead?"":"bg-blue-50"}`,onClick:()=>P(U),children:e.jsxs("div",{className:"flex gap-2",children:[!U.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 ${U.isRead?"font-medium":"font-semibold"}`,children:U.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:U.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:wp(new Date(U.createdAt),{addSuffix:!0})})]})]})},U.notificationId))})}),h.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(O,{variant:"ghost",className:"w-full text-sm text-blue-600 hover:text-blue-700",onClick:()=>{j(!1),a==null||a("notifications")},children:"View all notifications"})})]})]}),e.jsxs(Ju,{children:[e.jsx(Zu,{asChild:!0,children:e.jsxs(ds,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(zl,{src:(k==null?void 0:k.picture)||""}),e.jsx(ms,{className:"bg-re-green text-white text-sm",children:w()})]})}),e.jsxs(qu,{align:"end",children:[e.jsxs(oo,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(Wt,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(oo,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(hr,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(oo,{onClick:()=>x(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(so,{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(lg,{open:p,onOpenChange:x,children:e.jsxs(ed,{children:[e.jsxs(cg,{children:[e.jsxs(mg,{className:"flex items-center gap-2",children:[e.jsx(so,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(ug,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(dg,{children:[e.jsx(hg,{onClick:()=>x(!1),children:"Cancel"}),e.jsxs(xg,{onClick:async()=>{if(x(!1),n)try{await n()}catch(U){console.error("🔴 Error calling onLogout:",U)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(so,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const yi=()=>rv(),kn=lv,CN=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},SN={viewAsUser:CN()},wg=An({name:"dashboard",initialState:SN,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:AN}=wg.actions;function TN(){const[t,s]=u.useState("all"),[a,r]=u.useState(void 0),[n,i]=u.useState(void 0),[l,o]=u.useState(!1),c=u.useCallback(p=>{const x=p;s(x),x!=="custom"?(r(void 0),i(void 0),o(!1)):o(!0)},[]),d=u.useCallback(p=>{if(a&&n){if(a>n){const x=a;r(n),i(x),p(n,x)}else p(a,n);o(!1)}},[a,n]),m=u.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 kN(){const[t,s]=u.useState({page:1,totalPages:1,totalRecords:0}),[a,r]=u.useState({page:1,totalPages:1,totalRecords:0}),[n,i]=u.useState({page:1,totalPages:1,totalRecords:0}),[l,o]=u.useState({page:1,totalPages:1,totalRecords:0}),c=u.useCallback((b,y,j)=>{s({page:b,totalPages:y,totalRecords:j})},[]),d=u.useCallback((b,y,j)=>{r({page:b,totalPages:y,totalRecords:j})},[]),m=u.useCallback((b,y,j)=>{i({page:b,totalPages:y,totalRecords:j})},[]),p=u.useCallback((b,y,j)=>{o({page:b,totalPages:y,totalRecords:j})},[]),x=u.useCallback((b,y)=>{b>=1&&b<=t.totalPages&&(s(j=>({...j,page:b})),y(b))},[t.totalPages]),h=u.useCallback((b,y)=>{b>=1&&b<=a.totalPages&&(r(j=>({...j,page:b})),y(b))},[a.totalPages]),g=u.useCallback((b,y)=>{b>=1&&b<=n.totalPages&&(i(j=>({...j,page:b})),y(b))},[n.totalPages]),f=u.useCallback((b,y)=>{b>=1&&b<=l.totalPages&&(o(j=>({...j,page:b})),y(b))},[l.totalPages]);return{activity:t,critical:a,deadlines:n,approver:l,updateActivityPagination:c,updateCriticalPagination:d,updateDeadlinesPagination:m,updateApproverPagination:p,handleActivityPageChange:x,handleCriticalPageChange:h,handleDeadlinesPageChange:g,handleApproverPageChange:f}}class DN{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 Se.get("/dashboard/kpis",{params:i})).data.data}catch(i){throw console.error("Failed to fetch KPIs:",i),i}}async getRequestStats(s,a,r,n,i,l,o,c,d,m,p,x,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),x&&x!=="all"&&(g.slaCompliance=x),h&&(g.viewAsUser="true"),(await Se.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 Se.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 Se.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 Se.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 Se.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 Se.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 Se.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 Se.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 Se.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 Se.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 Se.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 Se.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 Se.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 Se.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 Se.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 Se.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 Se.get("/dashboard/stats/single-approver",{params:o})).data.data}catch(o){throw console.error("Failed to fetch single approver stats:",o),o}}async getRequestsByApprover(s,a=1,r=50,n,i,l,o,c,d,m){try{const p={approverId:s,page:a,limit:r};n&&(p.dateRange=n),n==="custom"&&i&&l&&(p.startDate=i.toISOString(),p.endDate=l.toISOString()),o&&(p.status=o),c&&(p.priority=c),d&&(p.slaCompliance=d),m&&(p.search=m);const x=await Se.get("/dashboard/requests/by-approver",{params:p});return{requests:x.data.data,pagination:x.data.pagination}}catch(p){throw console.error("Failed to fetch requests by approver:",p),p}}}const $t=new DN;function RN({isAdmin:t,viewAsUser:s=!1,userId:a,dateRange:r,customStartDate:n,customEndDate:i,onPaginationUpdate:l}){const[o,c]=u.useState(null),[d,m]=u.useState([]),[p,x]=u.useState([]),[h,g]=u.useState([]),[f,b]=u.useState([]),[y,j]=u.useState([]),[v,N]=u.useState(null),[T,A]=u.useState([]),[k,D]=u.useState(!0),[F,w]=u.useState(!1),L=u.useRef(l);L.current=l;const _=u.useCallback(async(R=!1)=>{try{R?w(!0):D(!0);const C=[$t.getKPIs(r,n,i,s),$t.getRecentActivity(1,10,s),$t.getCriticalRequests(1,10,s),$t.getUpcomingDeadlines(1,10,s)],H=!t&&a?$t.getRequestStats(r,n==null?void 0:n.toISOString(),i==null?void 0:i.toISOString(),void 0,void 0,void 0,void 0,a,void 0,void 0,void 0,void 0,s):null,z=t?[$t.getDepartmentStats(r,n,i),$t.getPriorityDistribution(r,n,i),$t.getAIRemarkUtilization(r,n,i),$t.getApproverPerformance(r,1,10,n,i)]:[],[P,S,U]=await Promise.all([Promise.all(C),H,Promise.all(z)]),Y=P[0],B=P[1],E=P[2],V=P[3];if(!t&&S&&(Y.requestVolume=S),c(Y),m(B.activities),L.current.activity(B.pagination.currentPage,B.pagination.totalPages,B.pagination.totalRecords),x(E.criticalRequests),L.current.critical(E.pagination.currentPage,E.pagination.totalPages,E.pagination.totalRecords),j(V.deadlines),L.current.deadlines(V.pagination.currentPage,V.pagination.totalPages,V.pagination.totalRecords),t&&U.length>=4){const G=U[0],J=U[1],q=U[2],se=U[3];g(G),b(J),N(q),A(se.performance),L.current.approver(se.pagination.currentPage,se.pagination.totalPages,se.pagination.totalRecords)}else t||(g([]),b([]),N(null),A([]))}catch(C){console.error("Failed to fetch dashboard data:",C)}finally{D(!1),w(!1)}},[t,s,a,r,n,i]),W=u.useCallback(async(R=1)=>{try{const C=await $t.getRecentActivity(R,10,s);m(C.activities),L.current.activity(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch recent activities:",C)}},[s]),I=u.useCallback(async(R=1)=>{try{const C=await $t.getCriticalRequests(R,10,s);x(C.criticalRequests),L.current.critical(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch critical requests:",C)}},[s]),$=u.useCallback(async(R=1)=>{try{const C=await $t.getUpcomingDeadlines(R,10,s);j(C.deadlines),L.current.deadlines(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch upcoming deadlines:",C)}},[s]),M=u.useCallback(async(R=1)=>{try{const C=await $t.getApproverPerformance(r,R,10,n,i);A(C.performance),L.current.approver(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch approver performance:",C)}},[r,n,i]);return{kpis:o,recentActivity:d,criticalRequests:p,departmentStats:h,priorityDistribution:f,upcomingDeadlines:y,aiRemarkUtilization:v,approverPerformance:T,loading:k,refreshing:F,fetchDashboardData:_,fetchRecentActivities:W,fetchCriticalRequests:I,fetchUpcomingDeadlines:$,fetchApproverPerformance:M}}const Xa={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 IN{constructor(){Zl(this,"config",null);Zl(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 Se.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...Xa,...r,workingHours:{...Xa.workingHours,...r.workingHours},tat:{...Xa.tat,...r.tat},upload:{...Xa.upload,...r.upload},workflow:{...Xa.workflow,...r.workflow},workNotes:{...Xa.workNotes,...r.workNotes},features:{...Xa.features,...r.features},ui:{...Xa.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),Xa}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const FN=new IN;let PN=9,EN=18,_N=1,MN=5,sx=!1;async function LN(){if(!sx)try{const t=await FN.getConfig();PN=t.workingHours.START_HOUR,EN=t.workingHours.END_HOUR,_N=t.workingHours.START_DAY,MN=t.workingHours.END_DAY,sx=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}LN().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 ON(t,s,a){const r=[];let n=1,i=!0;const l=100;for(;i&&n<=l;){const x=await $t.getApproverPerformance(t,n,100,s,a);x.performance&&x.performance.length>0?(r.push(...x.performance),n++,i=n<=x.pagination.totalPages):i=!1}const o=[["Approver Name","Total Approved","TAT Compliance (%)","Avg Response Time","Pending Count"].join(",")];r.forEach(x=>{const h=[`"${(x.approverName||"Unknown").replace(/"/g,'""')}"`,x.totalApproved||0,x.tatCompliancePercent||0,Xt(x.avgResponseHours),x.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 $N(t,s,a){const r=await $t.getDepartmentStats(t,s,a),n=[["Department","Total Requests","Approved","Rejected","In Progress","Approval Rate (%)"].join(",")];r.forEach(d=>{const m=[`"${(d.department||"Unknown").replace(/"/g,'""')}"`,d.totalRequests||0,d.approved||0,d.rejected||0,d.inProgress||0,d.approvalRate||0];n.push(m.join(","))});const i=n.join(`
`),l=new Blob([i],{type:"text/csv;charset=utf-8;"}),o=document.createElement("a"),c=URL.createObjectURL(l);o.setAttribute("href",c),o.setAttribute("download",`department-workflow-summary-${new Date().toISOString().split("T")[0]}.csv`),o.style.visibility="hidden",document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(c)}function UN(){const[t,s]=u.useState(!1),[a,r]=u.useState(!1),n=u.useCallback(async(l,o,c)=>{try{s(!0),await $N(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=u.useCallback(async(l,o,c)=>{try{r(!0),await ON(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 cs({className:t,...s}){return e.jsx(Vb,{"data-slot":"switch",className:$e("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-switch-background focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(Wb,{"data-slot":"switch-thumb",className:$e("bg-card dark:data-[state=unchecked]:bg-card-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}function re({className:t,...s}){return e.jsx(Hb,{"data-slot":"label",className:$e("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",t),...s})}function BN({isAdmin:t,effectiveIsAdmin:s,viewAsUser:a,onToggleView:r,quickActions:n,userDisplayName:i,userEmail:l}){const o=i||(l==null?void 0:l.split("@")[0])||"User";return e.jsxs(Z,{className:"relative overflow-hidden shadow-xl border-0","data-testid":"dashboard-hero",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsxs(ee,{className:"relative z-10 p-4 sm:p-6 lg:p-12",children:[t&&e.jsx("div",{className:"absolute top-4 right-4 sm:top-6 sm:right-6 z-20","data-testid":"view-toggle",children:e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 p-1.5 sm:p-2 bg-white/10 backdrop-blur-sm rounded-lg border border-white/20 shadow-lg",children:[e.jsxs("div",{className:`flex items-center gap-1 sm:gap-1.5 px-1.5 sm:px-2 py-0.5 sm:py-1 rounded transition-all cursor-pointer ${a?"opacity-60 hover:opacity-80":"bg-red-600/20 border border-red-600/50"}`,onClick:()=>r(!1),children:[e.jsx(Uc,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(re,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-gray-300":"text-red-600"}`,children:"Org"})]}),e.jsx(cs,{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(Wt,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(re,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-red-600":"text-gray-300"}`,children:"Personal"})]})]})}),e.jsx("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 sm:gap-6",children:e.jsxs("div",{className:`text-white w-full lg:w-auto ${t?"pt-12 sm:pt-0":""}`,children:[e.jsx("div",{className:"flex items-center gap-3 sm:gap-4 mb-4 sm:mb-6",children:e.jsxs("div",{className:"pr-2 sm:pr-0",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl lg:text-4xl font-bold mb-1 sm:mb-2 text-white","data-testid":"hero-title",children:["Welcome, ",o,"!"]}),e.jsx("p",{className:"text-sm sm:text-lg lg:text-xl text-gray-200","data-testid":"hero-subtitle",children:s?"Organization-wide analytics and insights":"Track your requests and approvals"})]})}),e.jsx("div",{className:"flex flex-wrap gap-2 sm:gap-4 mt-4 sm:mt-8","data-testid":"quick-actions",children:n.map((c,d)=>e.jsxs(O,{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(Gb,{"data-slot":"select",...t})}function Ge({...t}){return e.jsx(Kb,{"data-slot":"select-value",...t})}function Ye({className:t,size:s="default",children:a,...r}){return e.jsxs(Yb,{"data-slot":"select-trigger","data-size":s,className:$e("border-gray-400 data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground bg-white text-gray-900 flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap transition-all outline-none disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4","hover:border-gray-500","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...r,children:[a,e.jsx(Qb,{asChild:!0,children:e.jsx(Qr,{className:"size-4 opacity-50"})})]})}function Qe({className:t,children:s,position:a="popper",...r}){return e.jsx(Xb,{children:e.jsxs(Jb,{"data-slot":"select-content",className:$e("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",a==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:a,...r,children:[e.jsx(zN,{}),e.jsx(Zb,{className:$e("p-1",a==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:s}),e.jsx(VN,{})]})})}function X({className:t,children:s,...a}){return e.jsxs(qb,{"data-slot":"select-item",className:$e("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...a,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(ej,{children:e.jsx(Ha,{className:"size-4"})})}),e.jsx(tj,{children:s})]})}function zN({className:t,...s}){return e.jsx(sj,{"data-slot":"select-scroll-up-button",className:$e("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Al,{className:"size-4"})})}function VN({className:t,...s}){return e.jsx(aj,{"data-slot":"select-scroll-down-button",className:$e("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Qr,{className:"size-4"})})}function Zt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(rj,{"data-slot":"separator-root",decorative:a,orientation:s,className:$e("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",t),...r})}function na({...t}){return e.jsx(nj,{"data-slot":"popover",...t})}function ia({...t}){return e.jsx(ij,{"data-slot":"popover-trigger",...t})}function la({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(lj,{children:e.jsx(oj,{"data-slot":"popover-content",align:s,sideOffset:a,className:$e("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",t),...r})})}var dt=function(){return dt=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},dt.apply(this,arguments)};function WN(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 Cg(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 vi(t){return t.mode==="multiple"}function Ni(t){return t.mode==="range"}function Vl(t){return t.mode==="single"}var HN={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 GN(t,s){return st(t,"LLLL y",s)}function YN(t,s){return st(t,"d",s)}function QN(t,s){return st(t,"LLLL",s)}function KN(t){return"".concat(t)}function XN(t,s){return st(t,"cccccc",s)}function JN(t,s){return st(t,"yyyy",s)}var ZN=Object.freeze({__proto__:null,formatCaption:GN,formatDay:YN,formatMonthCaption:QN,formatWeekNumber:KN,formatWeekdayName:XN,formatYearCaption:JN}),qN=function(t,s,a){return st(t,"do MMMM (EEEE)",a)},ew=function(){return"Month: "},tw=function(){return"Go to next month"},sw=function(){return"Go to previous month"},aw=function(t,s){return st(t,"cccc",s)},rw=function(t){return"Week n. ".concat(t)},nw=function(){return"Year: "},iw=Object.freeze({__proto__:null,labelDay:qN,labelMonthDropdown:ew,labelNext:tw,labelPrevious:sw,labelWeekNumber:rw,labelWeekday:aw,labelYearDropdown:nw});function lw(){var t="buttons",s=HN,a=Pj,r={},n={},i=1,l={},o=new Date;return{captionLayout:t,classNames:s,formatters:ZN,labels:iw,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:l,today:o,mode:"default"}}function ow(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,l=t.toDate;return r?i=ha(r):s&&(i=new Date(s,0,1)),n?l=Mc(n):a&&(l=new Date(a,11,31)),{fromDate:i?Eu(i):void 0,toDate:l?Eu(l):void 0}}var Sg=u.createContext(void 0);function cw(t){var s,a=t.initialProps,r=lw(),n=ow(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;(Vl(a)||vi(a)||Ni(a))&&(c=a.onSelect);var d=dt(dt(dt({},r),a),{captionLayout:o,classNames:dt(dt({},r.classNames),a.classNames),components:dt({},a.components),formatters:dt(dt({},r.formatters),a.formatters),fromDate:i,labels:dt(dt({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:dt(dt({},r.modifiers),a.modifiers),modifiersClassNames:dt(dt({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:dt(dt({},r.styles),a.styles),toDate:l});return e.jsx(Sg.Provider,{value:d,children:t.children})}function Yt(){var t=u.useContext(Sg);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function Ag(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 dw(t){return e.jsx("svg",dt({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 Tg(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:dw;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 mw(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($j(r,n))for(var x=ha(r),h=r.getMonth();h<=n.getMonth();h++)p.push(eo(x,h));else for(var x=ha(new Date),h=0;h<=11;h++)p.push(eo(x,h));var g=function(b){var y=Number(b.target.value),j=eo(ha(t.displayMonth),y);t.onChange(j)},f=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Tg;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 uw(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,x=[];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++)x.push(_u(Uj(new Date),f));var b=function(j){var v=_u(ha(a),Number(j.target.value));t.onChange(v)},y=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Tg;return e.jsx(y,{name:"years","aria-label":p(),className:c.dropdown_year,style:o.dropdown_year,onChange:b,value:a.getFullYear(),caption:m(a,{locale:l}),children:x.map(function(j){return e.jsx("option",{value:j.getFullYear(),children:m(j,{locale:l})},j.getFullYear())})})}function xw(t,s){var a=u.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function hw(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&&ri(i,n)<0){var d=-1*(c-1);n=Va(i,d)}return l&&ri(n,l)<0&&(n=l),ha(n)}function pw(){var t=Yt(),s=hw(t),a=xw(s,t.month),r=a[0],n=a[1],i=function(l){var o;if(!t.disableNavigation){var c=ha(l);n(c),(o=t.onMonthChange)===null||o===void 0||o.call(t,c)}};return[r,i]}function gw(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=ha(t),i=ha(Va(n,r)),l=ri(i,n),o=[],c=0;c<l;c++){var d=Va(n,c);o.push(d)}return a&&(o=o.reverse()),o}function fw(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=ha(t);if(!a)return Va(o,l);var c=ri(a,t);if(!(c<i))return Va(o,l)}}function bw(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=ha(t);if(!a)return Va(o,-l);var c=ri(o,a);if(!(c<=0))return Va(o,-l)}}var kg=u.createContext(void 0);function jw(t){var s=Yt(),a=pw(),r=a[0],n=a[1],i=gw(r,s),l=fw(r,s),o=bw(r,s),c=function(p){return i.some(function(x){return Lc(p,x)})},d=function(p,x){c(p)||(x&&Cp(p,x)?n(Va(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(kg.Provider,{value:m,children:t.children})}function wi(){var t=u.useContext(kg);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function ax(t){var s,a=Yt(),r=a.classNames,n=a.styles,i=a.components,l=wi().goToMonth,o=function(m){l(Va(m,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:Ag,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(mw,{onChange:o,displayMonth:t.displayMonth}),e.jsx(uw,{onChange:o,displayMonth:t.displayMonth})]})}function yw(t){return e.jsx("svg",dt({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 vw(t){return e.jsx("svg",dt({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 hl=u.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=dt(dt({},n.button_reset),n.button);return t.style&&Object.assign(o,t.style),e.jsx("button",dt({},t,{ref:s,type:"button",className:l,style:o}))});function Nw(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 x=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:vw,y=(a=p==null?void 0:p.IconLeft)!==null&&a!==void 0?a:yw;return e.jsxs("div",{className:l.nav,style:o.nav,children:[!t.hidePrevious&&e.jsx(hl,{name:"previous-month","aria-label":x,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(y,{className:l.nav_icon,style:o.nav_icon})}),!t.hideNext&&e.jsx(hl,{name:"next-month","aria-label":g,className:f,style:o.nav_button_next,disabled:!t.nextMonth,onClick:t.onNextClick,children:n==="rtl"?e.jsx(y,{className:l.nav_icon,style:o.nav_icon}):e.jsx(b,{className:l.nav_icon,style:o.nav_icon})})]})}function rx(t){var s=Yt().numberOfMonths,a=wi(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,l=a.displayMonths,o=l.findIndex(function(g){return Lc(t.displayMonth,g)}),c=o===0,d=o===l.length-1,m=s>1&&(c||!d),p=s>1&&(d||!c),x=function(){r&&i(r)},h=function(){n&&i(n)};return e.jsx(Nw,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:p,nextMonth:n,previousMonth:r,onPreviousClick:x,onNextClick:h})}function ww(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:Ag,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):l==="dropdown"?d=e.jsx(ax,{displayMonth:t.displayMonth,id:t.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(ax,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(rx,{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(rx,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function Cw(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 Sw(t,s,a){for(var r=a?Oc(new Date):$c(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var l=da(r,i);n.push(l)}return n}function Aw(){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=Sw(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 Tw(){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:Aw;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function kw(t){var s=Yt(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var ad=u.createContext(void 0);function Dw(t){if(!vi(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(ad.Provider,{value:s,children:t.children})}return e.jsx(Rw,{initialProps:t.initialProps,children:t.children})}function Rw(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,l=function(d,m,p){var x,h;(x=s.onDayClick)===null||x===void 0||x.call(s,d,m,p);var g=!!(m.selected&&n&&(r==null?void 0:r.length)===n);if(!g){var f=!!(!m.selected&&i&&(r==null?void 0:r.length)===i);if(!f){var b=r?Cg([],r):[];if(m.selected){var y=b.findIndex(function(j){return sa(d,j)});b.splice(y,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(x){return sa(x,d)});return!!(m&&!p)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(ad.Provider,{value:c,children:a})}function rd(){var t=u.useContext(ad);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function Iw(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?sa(n,t)&&sa(r,t)?void 0:sa(n,t)?{from:n,to:void 0}:sa(r,t)?void 0:qo(r,t)?{from:t,to:n}:{from:r,to:t}:n?qo(t,n)?{from:n,to:t}:{from:t,to:n}:r?Cp(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var nd=u.createContext(void 0);function Fw(t){if(!Ni(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(nd.Provider,{value:s,children:t.children})}return e.jsx(Pw,{initialProps:t.initialProps,children:t.children})}function Pw(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,y;(b=s.onDayClick)===null||b===void 0||b.call(s,h,g,f);var j=Iw(h,r);(y=s.onSelect)===null||y===void 0||y.call(s,j,h,g,f)},m={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(m.range_start=[i],l?(m.range_end=[l],sa(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:ql(i,o-1),before:da(i,o-1)}),i&&l&&m.disabled.push({after:i,before:da(i,o-1)}),!i&&l&&m.disabled.push({after:ql(l,o-1),before:da(l,o-1)})),c){if(i&&!l&&(m.disabled.push({before:da(i,-c+1)}),m.disabled.push({after:da(i,c-1)})),i&&l){var p=Za(l,i)+1,x=c-p;m.disabled.push({before:ql(i,x)}),m.disabled.push({after:da(l,x)})}!i&&l&&(m.disabled.push({before:da(l,-c+1)}),m.disabled.push({after:da(l,c-1)}))}return e.jsx(nd.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function id(){var t=u.useContext(nd);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function Ki(t){return Array.isArray(t)?Cg([],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]=Ki(n)}),s}var Ea;(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"})(Ea||(Ea={}));var _w=Ea.Selected,Ja=Ea.Disabled,Mw=Ea.Hidden,Lw=Ea.Today,co=Ea.RangeEnd,mo=Ea.RangeMiddle,uo=Ea.RangeStart,Ow=Ea.Outside;function $w(t,s,a){var r,n=(r={},r[_w]=Ki(t.selected),r[Ja]=Ki(t.disabled),r[Mw]=Ki(t.hidden),r[Lw]=[t.today],r[co]=[],r[mo]=[],r[uo]=[],r[Ow]=[],r);return t.fromDate&&n[Ja].push({before:t.fromDate}),t.toDate&&n[Ja].push({after:t.toDate}),vi(t)?n[Ja]=n[Ja].concat(s.modifiers[Ja]):Ni(t)&&(n[Ja]=n[Ja].concat(a.modifiers[Ja]),n[uo]=a.modifiers[uo],n[mo]=a.modifiers[mo],n[co]=a.modifiers[co]),n}var Dg=u.createContext(void 0);function Uw(t){var s=Yt(),a=rd(),r=id(),n=$w(s,a,r),i=Ew(s.modifiers),l=dt(dt({},n),i);return e.jsx(Dg.Provider,{value:l,children:t.children})}function Rg(){var t=u.useContext(Dg);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function Bw(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function zw(t){return!!(t&&typeof t=="object"&&"from"in t)}function Vw(t){return!!(t&&typeof t=="object"&&"after"in t)}function Ww(t){return!!(t&&typeof t=="object"&&"before"in t)}function Hw(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function Gw(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=Za(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var l=Za(t,r)>=0&&Za(n,t)>=0;return l}return n?sa(n,t):r?sa(r,t):!1}function Yw(t){return Tp(t)}function Qw(t){return Array.isArray(t)&&t.every(Tp)}function Kw(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(Yw(a))return sa(t,a);if(Qw(a))return a.includes(t);if(zw(a))return Gw(t,a);if(Hw(a))return a.dayOfWeek.includes(t.getDay());if(Bw(a)){var r=Za(a.before,t),n=Za(a.after,t),i=r>0,l=n<0,o=qo(a.before,a.after);return o?l&&i:i||l}return Vw(a)?Za(t,a.after)>0:Ww(a)?Za(a.before,t)>0:typeof a=="function"?a(t):!1})}function ld(t,s,a){var r=Object.keys(s).reduce(function(i,l){var o=s[l];return Kw(t,o)&&i.push(l),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!Lc(t,a)&&(n.outside=!0),n}function Xw(t,s){for(var a=ha(t[0]),r=Mc(t[t.length-1]),n,i,l=a;l<=r;){var o=ld(l,s),c=!o.disabled&&!o.hidden;if(!c){l=da(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),n||(n=l),l=da(l,1)}return i||n}var Jw=365;function Ig(t,s){var a=s.moveBy,r=s.direction,n=s.context,i=s.modifiers,l=s.retry,o=l===void 0?{count:0,lastFocused:t}:l,c=n.weekStartsOn,d=n.fromDate,m=n.toDate,p=n.locale,x={day:da,week:Zo,month:Va,year:Mj,startOfWeek:function(b){return n.ISOWeek?Oc(b):$c(b,{locale:p,weekStartsOn:c})},endOfWeek:function(b){return n.ISOWeek?Sp(b):Ap(b,{locale:p,weekStartsOn:c})}},h=x[a](t,r==="after"?1:-1);r==="before"&&d?h=Lj([d,h]):r==="after"&&m&&(h=Oj([m,h]));var g=!0;if(i){var f=ld(h,i);g=!f.disabled&&!f.hidden}return g?h:o.count>Jw?o.lastFocused:Ig(h,{moveBy:a,direction:r,context:n,modifiers:i,retry:dt(dt({},o),{count:o.count+1})})}var Fg=u.createContext(void 0);function Zw(t){var s=wi(),a=Rg(),r=u.useState(),n=r[0],i=r[1],l=u.useState(),o=l[0],c=l[1],d=Xw(s.displayMonths,a),m=n??(o&&s.isDateDisplayed(o))?o:d,p=function(){c(n),i(void 0)},x=function(b){i(b)},h=Yt(),g=function(b,y){if(n){var j=Ig(n,{moveBy:b,direction:y,context:h,modifiers:a});sa(n,j)||(s.goToDate(j,n),x(j))}},f={focusedDay:n,focusTarget:m,blur:p,focus:x,focusDayAfter:function(){return g("day","after")},focusDayBefore:function(){return g("day","before")},focusWeekAfter:function(){return g("week","after")},focusWeekBefore:function(){return g("week","before")},focusMonthBefore:function(){return g("month","before")},focusMonthAfter:function(){return g("month","after")},focusYearBefore:function(){return g("year","before")},focusYearAfter:function(){return g("year","after")},focusStartOfWeek:function(){return g("startOfWeek","before")},focusEndOfWeek:function(){return g("endOfWeek","after")}};return e.jsx(Fg.Provider,{value:f,children:t.children})}function od(){var t=u.useContext(Fg);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function qw(t,s){var a=Rg(),r=ld(t,a,s);return r}var cd=u.createContext(void 0);function e1(t){if(!Vl(t.initialProps)){var s={selected:void 0};return e.jsx(cd.Provider,{value:s,children:t.children})}return e.jsx(t1,{initialProps:t.initialProps,children:t.children})}function t1(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(cd.Provider,{value:n,children:a})}function Pg(){var t=u.useContext(cd);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function s1(t,s){var a=Yt(),r=Pg(),n=rd(),i=id(),l=od(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,m=l.focusWeekBefore,p=l.blur,x=l.focus,h=l.focusMonthBefore,g=l.focusMonthAfter,f=l.focusYearBefore,b=l.focusYearAfter,y=l.focusStartOfWeek,j=l.focusEndOfWeek,v=function(R){var C,H,z,P;Vl(a)?(C=r.onDayClick)===null||C===void 0||C.call(r,t,s,R):vi(a)?(H=n.onDayClick)===null||H===void 0||H.call(n,t,s,R):Ni(a)?(z=i.onDayClick)===null||z===void 0||z.call(i,t,s,R):(P=a.onDayClick)===null||P===void 0||P.call(a,t,s,R)},N=function(R){var C;x(t),(C=a.onDayFocus)===null||C===void 0||C.call(a,t,s,R)},T=function(R){var C;p(),(C=a.onDayBlur)===null||C===void 0||C.call(a,t,s,R)},A=function(R){var C;(C=a.onDayMouseEnter)===null||C===void 0||C.call(a,t,s,R)},k=function(R){var C;(C=a.onDayMouseLeave)===null||C===void 0||C.call(a,t,s,R)},D=function(R){var C;(C=a.onDayPointerEnter)===null||C===void 0||C.call(a,t,s,R)},F=function(R){var C;(C=a.onDayPointerLeave)===null||C===void 0||C.call(a,t,s,R)},w=function(R){var C;(C=a.onDayTouchCancel)===null||C===void 0||C.call(a,t,s,R)},L=function(R){var C;(C=a.onDayTouchEnd)===null||C===void 0||C.call(a,t,s,R)},_=function(R){var C;(C=a.onDayTouchMove)===null||C===void 0||C.call(a,t,s,R)},W=function(R){var C;(C=a.onDayTouchStart)===null||C===void 0||C.call(a,t,s,R)},I=function(R){var C;(C=a.onDayKeyUp)===null||C===void 0||C.call(a,t,s,R)},$=function(R){var C;switch(R.key){case"ArrowLeft":R.preventDefault(),R.stopPropagation(),a.dir==="rtl"?o():c();break;case"ArrowRight":R.preventDefault(),R.stopPropagation(),a.dir==="rtl"?c():o();break;case"ArrowDown":R.preventDefault(),R.stopPropagation(),d();break;case"ArrowUp":R.preventDefault(),R.stopPropagation(),m();break;case"PageUp":R.preventDefault(),R.stopPropagation(),R.shiftKey?f():h();break;case"PageDown":R.preventDefault(),R.stopPropagation(),R.shiftKey?b():g();break;case"Home":R.preventDefault(),R.stopPropagation(),y();break;case"End":R.preventDefault(),R.stopPropagation(),j();break}(C=a.onDayKeyDown)===null||C===void 0||C.call(a,t,s,R)},M={onClick:v,onFocus:N,onBlur:T,onKeyDown:$,onKeyUp:I,onMouseEnter:A,onMouseLeave:k,onPointerEnter:D,onPointerLeave:F,onTouchCancel:w,onTouchEnd:L,onTouchMove:_,onTouchStart:W};return M}function a1(){var t=Yt(),s=Pg(),a=rd(),r=id(),n=Vl(t)?s.selected:vi(t)?a.selected:Ni(t)?r.selected:void 0;return n}function r1(t){return Object.values(Ea).includes(t)}function n1(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(r1(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function i1(t,s){var a=dt({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=dt(dt({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function l1(t,s,a){var r,n,i,l=Yt(),o=od(),c=qw(t,s),d=s1(t,c),m=a1(),p=!!(l.onDayClick||l.mode!=="default");u.useEffect(function(){var A;c.outside||o.focusedDay&&p&&sa(o.focusedDay,t)&&((A=a.current)===null||A===void 0||A.focus())},[o.focusedDay,t,a,p,c.outside]);var x=n1(l,c).join(" "),h=i1(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:kw,b=e.jsx(f,{date:t,displayMonth:s,activeModifiers:c}),y={style:h,className:x,children:b,role:"gridcell"},j=o.focusTarget&&sa(o.focusTarget,t)&&!c.outside,v=o.focusedDay&&sa(o.focusedDay,t),N=dt(dt(dt({},y),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=v||j?0:-1,r)),d),T={isButton:p,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:N,divProps:y};return T}function o1(t){var s=u.useRef(null),a=l1(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(hl,dt({name:"day",ref:s},a.buttonProps)):e.jsx("div",dt({},a.divProps))}function c1(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}),x=function(h){n(s,a,h)};return e.jsx(hl,{name:"week-number","aria-label":p,className:l.weeknumber,style:i.weeknumber,onClick:x,children:m})}function d1(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:o1,d=(a=o==null?void 0:o.WeekNumber)!==null&&a!==void 0?a:c1,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})},_j(p))})]})}function nx(t,s,a){for(var r=a!=null&&a.ISOWeek?Sp(s):Ap(s,a),n=a!=null&&a.ISOWeek?Oc(t):$c(t,a),i=Za(r,n),l=[],o=0;o<=i;o++)l.push(da(n,o));var c=l.reduce(function(d,m){var p=a!=null&&a.ISOWeek?Bj(m):zj(m,a),x=d.find(function(h){return h.weekNumber===p});return x?(x.dates.push(m),d):(d.push({weekNumber:p,dates:[m]}),d)},[]);return c}function m1(t,s){var a=nx(ha(t),Mc(t),s);if(s!=null&&s.useFixedWeeks){var r=Ej(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],l=Zo(i,6-r),o=nx(Zo(i,1),l,s);a.push.apply(a,o)}}return a}function u1(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,x=n.firstWeekContainsDate,h=n.ISOWeek,g=m1(t.displayMonth,{useFixedWeeks:!!d,ISOWeek:h,locale:i,weekStartsOn:p,firstWeekContainsDate:x}),f=(s=m==null?void 0:m.Head)!==null&&s!==void 0?s:Tw,b=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:d1,y=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:Cw;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(j){return e.jsx(b,{displayMonth:t.displayMonth,dates:j.dates,weekNumber:j.weekNumber},j.weekNumber)})}),e.jsx(y,{displayMonth:t.displayMonth})]})}function x1(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var h1=x1()?u.useLayoutEffect:u.useEffect,xo=!1,p1=0;function ix(){return"react-day-picker-".concat(++p1)}function g1(t){var s,a=t??(xo?ix():null),r=u.useState(a),n=r[0],i=r[1];return h1(function(){n===null&&i(ix())},[]),u.useEffect(function(){xo===!1&&(xo=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function f1(t){var s,a,r=Yt(),n=r.dir,i=r.classNames,l=r.styles,o=r.components,c=wi().displayMonths,d=g1(r.id?"".concat(r.id,"-").concat(t.displayIndex):void 0),m=r.id?"".concat(r.id,"-grid-").concat(t.displayIndex):void 0,p=[i.month],x=l.month,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),x=dt(dt({},x),l.caption_start)),g&&(p.push(i.caption_end),x=dt(dt({},x),l.caption_end)),f&&(p.push(i.caption_between),x=dt(dt({},x),l.caption_between));var b=(a=o==null?void 0:o.Caption)!==null&&a!==void 0?a:ww;return e.jsxs("div",{className:p.join(" "),style:x,children:[e.jsx(b,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(u1,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function b1(t){var s=Yt(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function j1(t){var s,a,r=t.initialProps,n=Yt(),i=od(),l=wi(),o=u.useState(!1),c=o[0],d=o[1];u.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=dt(dt({},n.styles.root),n.style),x=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,f){var b;return dt(dt({},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:b1;return e.jsx("div",dt({className:m.join(" "),style:p,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},x,{children:e.jsx(h,{children:l.displayMonths.map(function(g,f){return e.jsx(f1,{displayIndex:f,displayMonth:g},f)})})}))}function y1(t){var s=t.children,a=WN(t,["children"]);return e.jsx(cw,{initialProps:a,children:e.jsx(jw,{children:e.jsx(e1,{initialProps:a,children:e.jsx(Dw,{initialProps:a,children:e.jsx(Fw,{initialProps:a,children:e.jsx(Uw,{children:e.jsx(Zw,{children:s})})})})})})})}function v1(t){return e.jsx(y1,dt({},t,{children:e.jsx(j1,{initialProps:t})}))}function Xi({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(v1,{showOutsideDays:a,className:$e("p-3",t),classNames:{months:"flex flex-col sm:flex-row gap-2",month:"flex flex-col gap-4",caption:"flex justify-center pt-1 relative items-center w-full",caption_label:"text-sm font-medium",nav:"flex items-center gap-1",nav_button:$e(li({variant:"outline"}),"size-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-x-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:$e("relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-range-end)]:rounded-r-md",r.mode==="range"?"[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md":"[&:has([aria-selected])]:rounded-md"),day:$e(li({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(Nn,{className:$e("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(Wa,{className:$e("size-4",n),...i})},...r})}function aa({value:t,onChange:s,minDate:a,maxDate:r,placeholderText:n="dd/mm/yyyy",disabled:i=!1,className:l,wrapperClassName:o,error:c=!1,displayFormat:d="dd/MM/yyyy",id:m}){const[p,x]=u.useState(!1),h=u.useMemo(()=>{if(t){if(t instanceof Date)return rn(t)?t:void 0;if(typeof t=="string")try{const y=to(t,"yyyy-MM-dd",new Date);return rn(y)?y:void 0}catch{return}}},[t]),g=u.useMemo(()=>{if(a){if(a instanceof Date)return rn(a)?a:void 0;if(typeof a=="string"){const y=to(a,"yyyy-MM-dd",new Date);return rn(y)?y:void 0}}},[a]),f=u.useMemo(()=>{if(r){if(r instanceof Date)return rn(r)?r:void 0;if(typeof r=="string"){const y=to(r,"yyyy-MM-dd",new Date);return rn(y)?y:void 0}}},[r]),b=y=>{if(x(!1),!!s){if(!y){s(null);return}s(st(y,"yyyy-MM-dd"))}};return e.jsx("div",{className:$e("relative",o),children:e.jsxs(na,{open:p,onOpenChange:x,children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{id:m,disabled:i,variant:"outline",className:$e("w-full justify-start text-left font-normal",!h&&"text-muted-foreground",c&&"border-destructive ring-destructive/20",l),children:[e.jsx(bt,{className:"mr-2 h-4 w-4"}),h?st(h,d):e.jsx("span",{children:n})]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(Xi,{mode:"single",selected:h,onSelect:b,disabled:y=>!!(g&&y<g||f&&y>f),initialFocus:!0})})]})})}function N1({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,showCustomDatePicker:n,refreshing:i,onDateRangeChange:l,onCustomStartDateChange:o,onCustomEndDateChange:c,onShowCustomDatePickerChange:d,onApplyCustomDate:m,onResetCustomDates:p,onRefresh:x}){return e.jsx(Z,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(oe,{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(bt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:s,onValueChange:l,"data-testid":"date-range-select",children:[e.jsx(Ye,{className:"w-[140px]",children:e.jsx(Ge,{placeholder:"Select period"})}),e.jsxs(Qe,{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(na,{open:n,onOpenChange:d,children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(bt,{className:"w-4 h-4"}),a&&r?`${st(a,"MMM d, yyyy")} - ${st(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(la,{className:"w-auto p-4",align:"start",sideOffset:8,"data-testid":"custom-date-picker",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(aa,{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(re,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(aa,{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(O,{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(O,{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(bt,{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(Ye,{className:"w-[140px]",children:e.jsx(Ge,{placeholder:"Select period"})}),e.jsxs(Qe,{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(na,{open:n,onOpenChange:d,children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(bt,{className:"w-4 h-4"}),a&&r?`${st(a,"MMM d, yyyy")} - ${st(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(la,{className:"w-auto p-4",align:"start",sideOffset:8,"data-testid":"custom-date-picker",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date-user",className:"text-sm font-medium",children:"Start Date"}),e.jsx(aa,{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(re,{htmlFor:"end-date-user",className:"text-sm font-medium",children:"End Date"}),e.jsx(aa,{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(O,{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(O,{size:"sm",variant:"outline",onClick:p,"data-testid":"cancel-custom-date-user",children:"Cancel"})]})]})})]})]}),e.jsx(Zt,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(O,{variant:"outline",size:"sm",onClick:x,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx(_t,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function Ur({title:t,value:s,icon:a,iconBgColor:r,iconColor:n,subtitle:i,children:l,testId:o="kpi-card",onClick:c,onJustifyClick:d,showJustifyButton:m=!1}){const p=x=>{x.stopPropagation(),d==null||d()};return e.jsxs(Z,{className:"hover:shadow-lg transition-all duration-200 shadow-md cursor-pointer h-full flex flex-col",onClick:c,"data-testid":o,children:[e.jsxs(de,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ue,{className:"text-sm font-medium text-muted-foreground","data-testid":`${o}-title`,children:t}),e.jsxs("div",{className:"flex items-center gap-2",children:[m&&d&&e.jsx("button",{type:"button",onClick: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(Jr,{className:"h-4 w-4"})}),e.jsx("div",{className:`p-1.5 sm:p-2 rounded-lg ${r}`,"data-testid":`${o}-icon-wrapper`,children:e.jsx(a,{className:`h-4 w-4 sm:h-4 sm:w-4 ${n}`,"data-testid":`${o}-icon`})})]})]}),e.jsxs(ee,{className:"flex flex-col flex-1 py-3",children:[e.jsx("div",{className:"text-xl sm:text-2xl font-bold text-gray-900 mb-2","data-testid":`${o}-value`,children:s}),i&&e.jsx("div",{className:"text-xs text-muted-foreground mb-2","data-testid":`${o}-subtitle`,children:i}),l&&e.jsx("div",{className:"flex-1 flex flex-col","data-testid":`${o}-children`,children:l})]})]})}function 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 oa({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(cj,{"data-slot":"progress",className:$e("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(dj,{"data-slot":"progress-indicator",className:$e("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function w1({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(Ur,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Ee,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(Ur,{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(oa,{value:(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0,className:"h-2 mb-2","data-testid":"sla-progress-bar"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(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(Ur,{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 C1({kpis:t,criticalRequests:s,dateRange:a,customStartDate:r,customEndDate:n,onKPIClick:i,onNavigate:l,userId:o,userDisplayName:c}){const d=()=>({dateRange:a,startDate:r,endDate:n}),m=()=>{if(!o)return;const x=new URLSearchParams;x.set("approverId",o),x.set("approverName",c||"My Performance"),x.set("dateRange",a),a==="custom"&&r&&n&&(x.set("startDate",r.toISOString()),x.set("endDate",n.toISOString())),l==null||l(`/approver-performance?${x.toString()}`)},p=t&&t.requestVolume.totalRequests>0?t.requestVolume.approvedRequests/t.requestVolume.totalRequests*100:0;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 items-stretch","data-testid":"user-kpi-cards",children:[e.jsx(Ur,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Ee,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:x=>{x.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:x=>{x.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:x=>{x.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:x=>{x.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:x=>{x.stopPropagation(),i({...d(),status:"closed"})}})]})}),e.jsx(Ur,{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:x=>{x.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:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}})]})}),e.jsx(Ur,{title:"Critical Alerts",value:s.length,icon:Ma,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(x=>x.breachCount>0).length,bgColor:"bg-orange-50",textColor:"text-red-600",testId:"stat-user-breached",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests"})}}),e.jsx(Ds,{label:"Warning",value:s.filter(x=>x.breachCount===0).length,bgColor:"bg-yellow-50",textColor:"text-orange-600",testId:"stat-user-warning",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests"})}})]})}),e.jsx(Ur,{title:"Success Rate",value:`${p.toFixed(0)}%`,icon:Ve,iconBgColor:"bg-green-50",iconColor:"text-green-600",subtitle:`of ${(t==null?void 0:t.requestVolume.totalRequests)||0} requests approved`,testId:"kpi-success-rate",children:e.jsxs("div",{className:"space-y-4 mt-3 flex flex-col flex-1",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(oa,{value: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 S1=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)))},A1=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 T1({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=S1(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(Qj,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(oe,{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(oe,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:A1(t)})]}),e.jsxs("div",{className:"space-y-1 sm:space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs text-gray-600",children:[e.jsx("span",{children:"TAT Used"}),e.jsxs("span",{className:"font-medium","data-testid":`${a}-progress-percentage`,children:[r,"%"]})]}),e.jsx(oa,{value:r,className:`h-1.5 sm:h-2 ${r>=80?"[&>div]:bg-red-600":r>=50?"[&>div]:bg-orange-500":"[&>div]:bg-green-600"}`,"data-testid":`${a}-progress-bar`})]})]})}function k1(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 D1(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function R1(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 I1(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 Eg(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 F1({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(de,{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(Ma,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(Te,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(oe,{variant:"destructive",className:`font-semibold text-xs sm:text-sm ${a.totalRecords>0?"animate-pulse":""}`,"data-testid":"critical-count-badge",children:a.totalRecords})]})}),e.jsx(ee,{className:`overflow-y-auto flex-1 p-4 ${a.totalPages>1?"max-h-[calc(100%-140px)]":"max-h-[calc(100%-80px)]"}`,children:e.jsx("div",{className:"space-y-3 sm:space-y-4",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-critical-alerts",children:[e.jsx(Ve,{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(T1,{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(O,{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(ys,{className:"h-3 w-3 rotate-180"})}),Eg(a.page,a.totalPages,3).map(i=>e.jsx(O,{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(O,{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(ys,{className:"h-3 w-3"})})]})]})})]})}const P1=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=Vj(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=Wj(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=Hj(s,a);return`${i} day${i>1?"s":""} ago`},_1=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()},M1=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(Ve,{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(Qs,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(Ma,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(Ee,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(Tl,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(zt,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function L1({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(ds,{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(zl,{src:""}),e.jsx(ms,{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:M1(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(oe,{variant:"outline",className:`text-xs ${P1(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:_1(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(ys,{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 O1({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(de,{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(zt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(ue,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(Te,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(O,{variant:"ghost",size:"sm",className:"text-blue-600 hover:bg-blue-50 font-medium flex-shrink-0 h-8 sm:h-9 px-2 sm:px-3 sm:min-w-[100px]",onClick:i,disabled:r,"data-testid":"activity-refresh-button",children:[e.jsx(_t,{className:`w-3 h-3 sm:w-4 sm:h-4 ${r?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline ml-2 sm:w-[60px] sm:text-center",children:r?"Refreshing...":"Refresh"})]})]})}),e.jsx(ee,{className:`overflow-y-auto flex-1 p-4 ${a.totalPages>1?"max-h-[calc(100%-140px)]":"max-h-[calc(100%-80px)]"}`,children:e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-recent-activity",children:[e.jsx(zt,{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(L1,{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(O,{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(ys,{className:"h-3 w-3 rotate-180"})}),Eg(a.page,a.totalPages,3).map(m=>e.jsx(O,{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(O,{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(ys,{className:"h-3 w-3"})})]})]})})]})}function $1({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(de,{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(zt,{className:"h-4 w-4 text-blue-600"})}),e.jsx(ue,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl sm:text-3xl font-bold text-blue-600",children:s.length}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"levels"})]}),e.jsx(Zt,{}),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(de,{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(Qs,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ue,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center p-2 bg-indigo-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-indigo-600",children:t.engagement.workNotesAdded})]}),e.jsxs("div",{className:"text-center p-2 bg-purple-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Files"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-purple-600",children:t.engagement.attachmentsUploaded})]})]}),e.jsx(Zt,{}),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(de,{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(tc,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2 self-start sm:self-auto",onClick:()=>d(n,i,l),disabled:o,"data-testid":"export-dept-stats-button",children:[e.jsx(kt,{className:`w-3 h-3 sm:w-4 sm:h-4 ${o?"animate-pulse":""}`}),e.jsx("span",{className:"text-xs sm:text-sm",children:o?"Exporting...":"Export"})]})]})}),e.jsx(ee,{children:e.jsx(fn,{width:"100%",height:400,children:e.jsxs(Jo,{data:r,children:[e.jsx(il,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ll,{dataKey:"department",stroke:"#999",tick:p=>{const{x,y:h,payload:g}=p;return e.jsx("g",{transform:`translate(${x},${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(ol,{stroke:"#999",tick:{fontSize:11}}),e.jsx(bn,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(cl,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx($a,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx($a,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx($a,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function U1({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(de,{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(Qs,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ue,{className:"text-sm",children:"My Activity"})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center p-3 bg-indigo-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Work Notes"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold text-indigo-600",children:t.engagement.workNotesAdded})]}),e.jsxs("div",{className:"text-center p-3 bg-purple-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Attachments"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold text-purple-600",children:t.engagement.attachmentsUploaded})]})]})})})]}),e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(de,{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(ue,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-baseline gap-2",children:e.jsx("span",{className:"text-2xl sm:text-3xl font-bold text-purple-600",children:Xt(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(Zt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function B1({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(de,{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(ue,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"grid grid-cols-2 gap-4 mb-6",children:t.map((a,r)=>{const n=Number(a.avgCycleTimeHours)||0,i=a.priority==="express",l=i?"bg-red-50":"bg-blue-50",o=i?"bg-red-500":"bg-blue-500";return e.jsxs("div",{className:`${l} p-4 rounded-lg`,"data-testid":`priority-card-${a.priority}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`w-3 h-3 ${o} rounded-full`}),e.jsx("span",{className:"text-sm text-gray-600 capitalize",children:a.priority})]}),e.jsx("div",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-1",children:a.totalCount}),e.jsxs("div",{className:"text-xs text-gray-500",children:["Avg: ",Xt(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(fn,{width:"100%",height:300,children:e.jsxs(yp,{children:[e.jsx(vp,{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(Np,{fill:a.priority==="express"?"#ef4444":"#3b82f6",className:"cursor-pointer"},`cell-${r}`))}),e.jsx(bn,{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 Zr({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(ee,{className:"p-4",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("div",{className:"text-sm sm:text-base font-medium text-gray-700","data-testid":`${o}-info`,children:i?`Loading ${l}...`:r===0?`No ${l} found`:r===1?`Showing 1 ${l.slice(0,-1)}`:d===m?`Showing ${d} of ${r} ${l}`:`Showing ${d} to ${m} of ${r} ${l}`})})})}):e.jsx(Z,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-sm sm:text-base font-medium text-gray-700","data-testid":`${o}-info`,children:["Showing ",d," to ",m," of ",r," ",l]}),e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${o}-controls`,children:[e.jsx(O,{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(ys,{className:"h-4 w-4 rotate-180"})}),t>3&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx(O,{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(O,{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(O,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${o}-page-${s}`,children:s})]}),e.jsx(O,{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(ys,{className:"h-4 w-4"})})]})]})})})}function z1(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${st(s,"MMM d, yyyy")} - ${st(a,"MMM d, yyyy")}`:{all:"(All Time)",today:`${r} Today`,week:`${r} This Week`,month:`${r} This Month`,quarter:`${r} This Quarter`,year:`${r} This Year`,last30days:`${r} Last 30 Days`,custom:`${r} Custom Range`}[t]||`${r} Selected Period`}function V1(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${st(s,"MMM d, yyyy")} to ${st(a,"MMM d, yyyy")}`:{all:"All historical data",today:"Today's data",week:"This week data",month:"This month data",quarter:"This quarter data",year:"This year data",last30days:"Last 30 days data",custom:"Custom date range"}[t]||"Filtered data"}function W1({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(de,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-red-50 p-2 sm:p-3 rounded-lg",children:e.jsx(ss,{className:"h-5 w-5 sm:h-6 sm:w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs(Te,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",V1(a,r,n)]})]})]}),e.jsxs(oe,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[s.totalRecords," ",s.totalRecords===1?"Breach":"Breaches"]})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"overflow-x-auto -mx-4 sm:mx-0",children:e.jsxs("table",{className:"w-full min-w-[1000px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 bg-gray-50",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Request ID"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[250px]",children:"Title"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Department"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Approver"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Level"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[140px]",children:"Breach Time"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[300px]",children:"Reason"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Priority"})]})}),e.jsx("tbody",{children:t.map((d,m)=>{const p=d.breachTime||0;return e.jsxs("tr",{className:"border-b border-gray-100 hover:bg-gray-50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-blue-600 cursor-pointer hover:underline",onClick:()=>o==null?void 0:o(`request/${d.requestNumber}`),"data-testid":`breach-request-${d.requestNumber}`,children:d.requestNumber}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-900 w-[250px]",children:e.jsx("p",{className:"break-words leading-relaxed",children:d.title})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{d.department&&d.department!=="Unknown"&&l({...c(),department:d.department})},children:d.department||"Unknown"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.approverId?e.jsx("span",{className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{if(o){const x=new URLSearchParams;x.set("approver",d.approverId),x.set("approverType","current"),x.set("slaCompliance","breached"),a&&x.set("dateRange",a),r&&x.set("startDate",r.toISOString()),n&&x.set("endDate",n.toISOString()),o(`requests?${x.toString()}`)}},title:"Click to view all requests for this approver",children:d.approver||"N/A"}):d.approver||"N/A"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.currentLevel&&d.totalLevels?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/",d.totalLevels]}):d.currentLevel?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/—"]}):e.jsx("span",{className:"text-gray-400",children:"—"})}),e.jsx("td",{className:"py-3 px-4 w-[140px]",children:e.jsx("span",{className:"bg-red-500 text-white px-2 py-1 rounded text-xs font-medium whitespace-nowrap",children:R1(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(oe,{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(Zr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function H1({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(de,{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(bt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(ee,{children:[e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.map((i,l)=>{const o=Number(i.tatPercentageUsed)||0,c=Number(i.elapsedHours)||0,d=Number(i.remainingHours)||0;return e.jsxs("div",{className:"p-3 sm:p-4 border rounded-lg hover:shadow-md transition-all cursor-pointer",onClick:()=>n==null?void 0:n(`request/${i.requestNumber}`),"data-testid":`deadline-item-${i.requestNumber}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-xs sm:text-sm",children:i.requestNumber}),e.jsx(oe,{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(oe,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:["Level ",i.levelNumber||"?","/",i.totalLevels||"?"]}),e.jsx("span",{className:"truncate",children:i.approverName})]})]}),e.jsxs("div",{className:"text-right flex-shrink-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"TAT Used"}),e.jsxs("p",{className:`text-base sm:text-lg font-bold ${o>=80?"text-red-600":o>=50?"text-orange-600":"text-green-600"}`,children:[o.toFixed(0),"%"]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(oa,{value:o,className:`h-1.5 sm:h-2 ${o>=80?"bg-red-100":o>=50?"bg-orange-100":"bg-green-100"}`}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[Xt(c)," elapsed"]}),e.jsxs("span",{children:[Xt(d)," left"]})]})]})]},l)})}),e.jsx("div",{className:"mt-4",children:e.jsx(Zr,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function G1({aiRemarkUtilization:t}){return t?e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(de,{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(kl,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(ee,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4 mb-6",children:[e.jsxs("div",{className:"bg-purple-50 p-4 rounded-lg text-center","data-testid":"ai-total-usage",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Total Usage"}),e.jsx("div",{className:"text-2xl font-bold text-gray-900",children:t.totalUsage})]}),e.jsxs("div",{className:"bg-pink-50 p-4 rounded-lg text-center","data-testid":"ai-total-edits",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Total Edits"}),e.jsx("div",{className:"text-2xl font-bold text-gray-900",children:t.totalEdits})]}),e.jsxs("div",{className:"bg-purple-50 p-4 rounded-lg text-center","data-testid":"ai-edit-rate",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Edit Rate"}),e.jsxs("div",{className:"text-2xl font-bold text-gray-900",children:[t.editRate,"%"]})]})]}),t.monthlyTrends&&t.monthlyTrends.length>0&&e.jsx(fn,{width:"100%",height:250,children:e.jsxs(Fj,{data:t.monthlyTrends,children:[e.jsx(il,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ll,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(ol,{stroke:"#999",tick:{fontSize:11}}),e.jsx(bn,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(cl,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Pu,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(Pu,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function Y1({approverPerformance:t,pagination:s,dateRange:a,customStartDate:r,customEndDate:n,loading:i,exportingApproverPerformance:l,onPageChange:o,onExport:c,onNavigate:d}){return t.length===0?null:e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(de,{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(ue,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(O,{onClick:()=>c(a,r,n),disabled:l||i,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-approver-performance-button",children:l?e.jsxs(e.Fragment,{children:[e.jsx(_t,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"space-y-3",children:t.map((m,p)=>{const x=m.tatCompliancePercent;return e.jsxs("div",{className:"border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{const 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 ${I1(x)} flex-shrink-0`,children:[x,"% TAT"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"Avg Response"}),e.jsx("div",{className:"text-sm font-medium text-gray-900",children: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(Zr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:o,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function Q1(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 K1(t,s,a,r){const n=[];return r||n.push({label:"New Request",icon:Ee,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:hr,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:zt,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),n}function X1({onNavigate:t,onNewRequest:s}){const{user:a}=us(),r=yi(),n=kn(Re=>Re.dashboard.viewAsUser),i=u.useMemo(()=>Ul(a),[a]),l=i&&!n,o=u.useCallback(Re=>{r(AN(Re))},[r]),c=TN(),{dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:x,handleDateRangeChange:h,handleApplyCustomDate:g,resetCustomDates:f,setCustomStartDate:b,setCustomEndDate:y,setShowCustomDatePicker:j}=c,v=kN(),{activity:N,critical:T,deadlines:A,approver:k,updateActivityPagination:D,updateCriticalPagination:F,updateDeadlinesPagination:w,updateApproverPagination:L,handleActivityPageChange:_,handleCriticalPageChange:W,handleDeadlinesPageChange:I,handleApproverPageChange:$}=v,M=RN({isAdmin:l,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:p,onPaginationUpdate:{activity:D,critical:F,deadlines:w,approver:L}}),{kpis:R,recentActivity:C,criticalRequests:H,departmentStats:z,priorityDistribution:P,upcomingDeadlines:S,aiRemarkUtilization:U,approverPerformance:Y,loading:B,refreshing:E,fetchDashboardData:V,fetchRecentActivities:G,fetchCriticalRequests:J,fetchUpcomingDeadlines:q,fetchApproverPerformance:se}=M,ne=UN(),{exportingDeptStats:te,exportingApproverPerformance:ge,handleExportDepartmentStats:we,handleExportApproverPerformance:fe}=ne,ke=u.useMemo(()=>k1(H),[H]),le=u.useMemo(()=>D1(S),[S]),Ne=u.useCallback(()=>{V(!0)},[d,m,p,V]),ae=u.useCallback(()=>{g(()=>{m&&p&&V(!1)})},[m,p,g,V]),he=u.useCallback(Re=>{_(Re,G)},[_,G]),ie=u.useCallback(Re=>{W(Re,J)},[W,J]),je=u.useCallback(Re=>{I(Re,q)},[I,q]),Fe=u.useCallback(Re=>{$(Re,()=>se(Re))},[$,se]);u.useEffect(()=>{d==="custom"?m&&p&&V(!1):V(!1)},[d,m,p,n]);const Ue=u.useMemo(()=>{try{const Re=nt.getUserData();return(Re==null?void 0:Re.jobTitle)==="Dealer"}catch(Re){return console.error("[Dashboard] Error checking dealer status:",Re),!1}},[]),Ce=u.useMemo(()=>K1(i,s,t,Ue),[i,s,t,Ue]),ce=u.useCallback(Re=>{const qe=Q1(Re);t==null||t(qe)},[t]);return B?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(_t,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto p-3 sm:p-4","data-testid":"dashboard",children:[e.jsx(BN,{isAdmin:i,effectiveIsAdmin:l,viewAsUser:n,onToggleView:o,quickActions:Ce,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(N1,{isAdmin:l,dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:x,refreshing:E,onDateRangeChange:h,onCustomStartDateChange:b,onCustomEndDateChange:y,onShowCustomDatePickerChange:j,onApplyCustomDate:ae,onResetCustomDates:f,onRefresh:Ne}),l?e.jsx(w1,{kpis:R,priorityDistribution:P,dateRange:d,customStartDate:m,customEndDate:p,onKPIClick:ce}):e.jsx(C1,{kpis:R,criticalRequests:H,dateRange:d,customStartDate:m,customEndDate:p,onKPIClick:ce,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(F1,{isAdmin:l,breachedRequests:ke,pagination:T,onPageChange:ie,onNavigate:t}),e.jsx(O1,{isAdmin:l,recentActivity:C,pagination:N,refreshing:E,onPageChange:he,onRefresh:Ne,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),l&&R&&e.jsx($1,{kpis:R,upcomingDeadlines:S,criticalRequests:H,departmentStats:z,dateRange:d,customStartDate:m,customEndDate:p,exportingDeptStats:te,onKPIClick:ce,onExportDepartmentStats:we}),!l&&R&&e.jsx(U1,{kpis:R}),l&&P.length>0&&e.jsx(B1,{priorityDistribution:P,onNavigate:t}),l&&ke.length>0&&e.jsx(W1,{breachedRequests:ke,pagination:T,dateRange:d,customStartDate:m,customEndDate:p,onPageChange:ie,onKPIClick:ce,onNavigate:t}),le.length>0&&e.jsx(H1,{isAdmin:l,upcomingDeadlines:le,pagination:A,onPageChange:je,onNavigate:t}),l&&U&&e.jsx(G1,{aiRemarkUtilization:U}),l&&Y.length>0&&e.jsx(Y1,{approverPerformance:Y,pagination:k,dateRange:d,customStartDate:m,customEndDate:p,loading:B,exportingApproverPerformance:ge,onPageChange:Fe,onExport:fe,onNavigate:t})]})}const J1={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},_g=An({name:"openRequests",initialState:J1,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:Z1,setStatusFilter:q1,setPriorityFilter:eC,setTemplateTypeFilter:tC,setForm16FinancialYear:sC,setForm16Quarter:aC,setSortBy:rC,setSortOrder:nC,setCurrentPage:iC,clearFilters:lC}=_g.actions;function oC(){const t=yi(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,form16FinancialYear:i,form16Quarter:l,sortBy:o,sortOrder:c,currentPage:d}=kn(T=>T.openRequests),m=u.useCallback(T=>t(Z1(T)),[t]),p=u.useCallback(T=>t(q1(T)),[t]),x=u.useCallback(T=>t(eC(T)),[t]),h=u.useCallback(T=>t(tC(T)),[t]),g=u.useCallback(T=>t(sC(T)),[t]),f=u.useCallback(T=>t(aC(T)),[t]),b=u.useCallback(T=>t(rC(T)),[t]),y=u.useCallback(T=>t(nC(T)),[t]),j=u.useCallback(T=>t(iC(T)),[t]),v=u.useCallback(()=>t(lC()),[t]),N=[s,r!=="all"?r:null,a!=="all"?a:null,n!=="all"?n:null,n==="FORM_16"&&i?"fy":null,n==="FORM_16"&&l?"q":null].filter(Boolean).length;return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,form16FinancialYear:i,form16Quarter:l,sortBy:o,sortOrder:c,currentPage:d,setSearchTerm:m,setStatusFilter:p,setPriorityFilter:x,setTemplateTypeFilter:h,setForm16FinancialYear:g,setForm16Quarter:f,setSortBy:b,setSortOrder:y,setCurrentPage:j,clearFilters:v,activeFiltersCount:N}}function ho(){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 cC(t){var o;const s=t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",a=Array.from({length:t.approverCount||1},(c,d)=>{const m=d,p=t.approvers[m]||{},x=m+1,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 ${x}`;return{levelNumber:x,levelName:`Level ${x}`,approverId:ho(),approverEmail:f,approverName:b,tatHours:g>0?g:24,isFinalApprover:x===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:ho(),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:ho(),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 Se.post("/workflows",n),l=((o=i.data)==null?void 0:o.data)||i.data;return{id:l.id||l.workflowId||""}}async function dd(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 Se.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 dC(t={}){var y;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,department:d,initiator:m,approver:p,slaCompliance:x,dateRange:h,startDate:g,endDate:f}=t,b=await Se.get("/workflows",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,department:d,initiator:m,approver:p,slaCompliance:x,dateRange:h,startDate:g,endDate:f}});return((y=b.data)==null?void 0:y.data)||b.data}async function mC(t={}){var j,v,N,T,A;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,department:d,initiator:m,approver:p,approverType:x,slaCompliance:h,dateRange:g,startDate:f,endDate:b}=t,y=await Se.get("/workflows/participant-requests",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,financialYear:o,quarter:c,department:d,initiator:m,approver:p,approverType:x,slaCompliance:h,dateRange:g,startDate:f,endDate:b}});return{data:((v=(j=y.data)==null?void 0:j.data)==null?void 0:v.data)||((N=y.data)==null?void 0:N.data)||[],pagination:((A=(T=y.data)==null?void 0:T.data)==null?void 0:A.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function uC(t={}){var g,f,b,y,j;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:l,initiator:o,approver:c,slaCompliance:d,dateRange:m,startDate:p,endDate:x}=t,h=await Se.get("/workflows/my",{params:{page:s,limit:a,search:r,status:n,priority:i,department:l,initiator:o,approver:c,slaCompliance:d,dateRange:m,startDate:p,endDate:x}});return{data:((f=(g=h.data)==null?void 0:g.data)==null?void 0:f.data)||((b=h.data)==null?void 0:b.data)||[],pagination:((j=(y=h.data)==null?void 0:y.data)==null?void 0:j.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function xC(t={}){var h,g,f,b,y;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:c,dateRange:d,startDate:m,endDate:p}=t,x=await Se.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=x.data)==null?void 0:h.data)==null?void 0:g.data)||((f=x.data)==null?void 0:f.data)||[],pagination:((y=(b=x.data)==null?void 0:b.data)==null?void 0:y.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function hC(t={}){var x,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 Se.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=(x=p.data)==null?void 0:x.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 pC(t={}){var x,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 Se.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=(x=p.data)==null?void 0:x.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 Ms(t,s){var r;const a=await Se.get(`/workflows/${t}/details`);return((r=a.data)==null?void 0:r.data)||a.data}async function yn(t){var a;const s=await Se.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function Mg(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 Se.post(`/workflows/${t}/work-notes`,r,{headers:{"Content-Type":"multipart/form-data"}});return((i=n.data)==null?void 0:i.data)||n.data}async function Lg(t,s,a,r){var i;const n=await Se.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 gC(t,s,a){var n;const r=await Se.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function Og(t,s){var r;const a=await Se.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function fC(t,s,a,r){var i;const n=await Se.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function bC(t,s){var r;const a=await Se.post(`/workflows/${t}/resume`,{notes:s});return((r=a.data)==null?void 0:r.data)||a.data}async function jC(t){var a;const s=await Se.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function lx(t){var a;const s=await Se.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function yC(t){return`https://reflow-uat.royalenfield.com//api/v1/workflows/work-notes/attachments/${t}/preview`}function Dn(t){return`https://reflow-uat.royalenfield.com//api/v1/workflows/documents/${t}/preview`}function $g(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 $s(t){const a=`https://reflow-uat.royalenfield.com//api/v1/workflows/documents/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const p=await i.text();throw new Error(`Download failed: ${i.status} - ${p}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=$g(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 ox(t){const a=`https://reflow-uat.royalenfield.com//api/v1/workflows/work-notes/attachments/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const p=await i.text();throw new Error(`Download failed: ${i.status} - ${p}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=$g(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 Xs={createWorkflowFromForm:cC,createWorkflowMultipart:dd,listWorkflows:dC,listParticipantRequests:mC,listMyWorkflows:uC,listMyInitiatedWorkflows:xC,listOpenForMe:hC,listClosedByMe:pC,submitWorkflow:Ug,getWorkflowDetails:Ms,getWorkNotes:yn,createWorkNoteMultipart:Mg,handleInitiatorAction:Bg};async function Ug(t){var a;const s=await Se.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function vC(t,s){var r;const a=await Se.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function NC(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 Se.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((o=l.data)==null?void 0:o.data)||l.data}async function Qn(t,s,a){var n;const r=await Se.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function _r(t,s,a,r){var i;const n=await Se.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 wC(t,s){const a=await Se.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}async function Bg(t,s,a){var n;const r=await Se.post(`/workflows/${t}/initiator-action`,{action:s,...a});return((n=r.data)==null?void 0:n.data)||r.data}async function CC(t){var a;return((a=(await Se.get(`/workflows/${t}/history`)).data)==null?void 0:a.data)||[]}function js(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 zg(t){return js(t,{includeTime:!1,format:"short"})}function _a(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 SC(t){return t?t.jobTitle==="Dealer"||t.jobTitle==="DEALER":!1}function md(t){return SC(t)?"DEALER":"STANDARD"}function Ua(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 _i=[{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 Ci({value:t,onChange:s,placeholder:a="Enter text...",className:r,minHeight:n="120px",...i}){const l=u.useRef(null),[o,c]=u.useState(!1),[d,m]=u.useState(new Set),[p,x]=u.useState(!1),[h,g]=u.useState(null),[f,b]=u.useState("#FFEB3B"),[y,j]=u.useState(!1),[v,N]=u.useState(null),[T,A]=u.useState("#000000");u.useEffect(()=>{l.current&&l.current.innerHTML!==t&&l.current.innerHTML!==t&&(l.current.innerHTML=Ua(t||""))},[t]);const k=u.useCallback(R=>(R=R.replace(/<!--[\s\S]*?-->/g,""),R=R.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),R=R.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),R=R.replace(/<meta[^>]*>/gi,""),R=R.replace(/\s*class="Mso[^"]*"/gi,""),R=R.replace(/\s*class="mso[^"]*"/gi,""),R=R.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),R=R.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),R=R.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),R=R.replace(/<\/?o:p[^>]*>/gi,""),R=R.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),R=R.replace(/<v:[^>]*\/>/gi,""),R=R.replace(/<p[^>]*>\s*<\/p>/gi,""),R=R.replace(/<div[^>]*>\s*<\/div>/gi,""),R=R.replace(/\s+/g," "),R=R.trim(),R),[]),D=u.useCallback(R=>{R.preventDefault();const C=R.clipboardData;let H=C.getData("text/html")||C.getData("text/plain");if((H.includes("<!--")||H.includes("<style")||H.includes("MsoNormal"))&&(H=k(H)),!l.current)return;const z=window.getSelection();if(!z||z.rangeCount===0)return;const P=z.getRangeAt(0);P.deleteContents();const S=document.createElement("div");S.innerHTML=H;const U=document.createDocumentFragment();Array.from(S.childNodes).forEach(Y=>{if(Y.nodeType===Node.ELEMENT_NODE){const B=Y;if(B.tagName==="UL"||B.tagName==="OL"){const E=B.cloneNode(!0);E.removeAttribute("style"),E.removeAttribute("class"),E.querySelectorAll("li").forEach(V=>{V.removeAttribute("style"),V.removeAttribute("class");const G=V.textContent||"";G.trim()&&(V.textContent=G.trim())}),U.appendChild(E)}else if(B.tagName==="TABLE"){const E=B.cloneNode(!0);E.removeAttribute("style"),E.removeAttribute("class"),E.querySelectorAll("td, th").forEach(G=>{G.removeAttribute("style"),G.removeAttribute("class")});const V=document.createElement("div");V.className="table-wrapper",V.appendChild(E),U.appendChild(V)}else if(B.tagName==="P"||B.tagName==="DIV"){const E=document.createElement("p"),G=B.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");E.innerHTML=G,E.removeAttribute("style"),E.removeAttribute("class"),U.appendChild(E)}else if(B.tagName==="BR")U.appendChild(B.cloneNode(!0));else{const E=B.textContent||"";if(E.trim()){const V=document.createElement("p");V.textContent=E.trim(),U.appendChild(V)}}}else if(Y.nodeType===Node.TEXT_NODE){const B=Y.textContent||"";if(B.trim()){const E=document.createElement("p");E.textContent=B.trim(),U.appendChild(E)}}}),U.childNodes.length===0&&C.getData("text/plain").split(`
`).forEach(E=>{if(E.trim()){const V=document.createElement("p");V.textContent=E.trim(),U.appendChild(V)}else U.appendChild(document.createElement("br"))}),P.insertNode(U),P.collapse(!1),z.removeAllRanges(),z.addRange(P),l.current&&s(Ua(l.current.innerHTML))},[s,k]),F=u.useCallback(()=>{if(!l.current||!o)return;const R=new Set,C=window.getSelection();if(C&&C.rangeCount>0){const z=C.getRangeAt(0).commonAncestorContainer;let P=null;for(z.nodeType===Node.TEXT_NODE?P=z.parentElement:P=z;P&&P!==l.current;){const S=P.tagName.toLowerCase();(S==="strong"||S==="b")&&R.add("bold"),(S==="em"||S==="i")&&R.add("italic"),S==="u"&&R.add("underline"),S==="h1"&&R.add("h1"),S==="h2"&&R.add("h2"),S==="h3"&&R.add("h3"),S==="ul"&&R.add("ul"),S==="ol"&&R.add("ol");const U=window.getComputedStyle(P);U.textAlign==="center"&&R.add("center"),U.textAlign==="right"&&R.add("right"),U.textAlign==="left"&&R.add("left");const Y=G=>{if(G.startsWith("#"))return G.toUpperCase();const J=G.match(/\d+/g);if(!J||J.length<3)return null;const q=J[0],se=J[1],ne=J[2];if(!q||!se||!ne)return null;const te=parseInt(q).toString(16).padStart(2,"0"),ge=parseInt(se).toString(16).padStart(2,"0"),we=parseInt(ne).toString(16).padStart(2,"0");return`#${te}${ge}${we}`.toUpperCase()},B=U.backgroundColor;if(B&&B!=="rgba(0, 0, 0, 0)"&&B!=="transparent"&&B!=="rgb(255, 255, 255)"&&B!=="#ffffff"&&B!=="#FFFFFF"){R.add("highlight");const G=Y(B);if(G){const J=_i.find(q=>q.value==="transparent"?!1:q.value.toUpperCase()===G);g(J?J.value:G)}}else R.has("highlight")||g(null);const E=U.color,V=Y(E);if(E&&V&&E!=="rgba(0, 0, 0, 0)"&&V!=="#000000"){R.add("textColor");const G=_i.find(J=>J.value==="transparent"?!1:J.value.toUpperCase()===V);N(G?G.value:V)}else R.has("textColor")||N(V==="#000000"||!V?"#000000":null);P=P.parentElement}}m(R)},[o]),w=u.useCallback((R,C)=>{if(!l.current)return;o||l.current.focus();const H=window.getSelection();if(!H||H.rangeCount===0){l.current.focus();return}document.execCommand(R,!1,C),l.current&&s(Ua(l.current.innerHTML)),setTimeout(F,10)},[o,s,F]),L=u.useCallback(R=>{if(!l.current)return;o||l.current.focus();const C=window.getSelection();if(!C||C.rangeCount===0){l.current.focus();return}let H=!1;if(C.rangeCount>0){const S=C.getRangeAt(0).commonAncestorContainer;let U=null;for(S.nodeType===Node.TEXT_NODE?U=S.parentElement:U=S;U&&U!==l.current;){const B=window.getComputedStyle(U).backgroundColor;if(B&&B!=="rgba(0, 0, 0, 0)"&&B!=="transparent"&&B!=="rgb(255, 255, 255)"&&B!=="#ffffff"&&B!=="#FFFFFF"){const V=(G=>{if(G.startsWith("#"))return G.toUpperCase();const J=G.match(/\d+/g);if(!J||J.length<3)return null;const q=J[0],se=J[1],ne=J[2];if(!q||!se||!ne)return null;const te=parseInt(q).toString(16).padStart(2,"0"),ge=parseInt(se).toString(16).padStart(2,"0"),we=parseInt(ne).toString(16).padStart(2,"0");return`#${te}${ge}${we}`.toUpperCase()})(B);if(V&&V===R.toUpperCase()){H=!0;break}}U=U.parentElement}}if(R==="transparent"||H){const P=C.getRangeAt(0);if(P.collapsed)document.execCommand("removeFormat",!1);else{const S=P.extractContents(),U=document.createDocumentFragment(),Y=B=>{if(B.nodeType===Node.TEXT_NODE)return B.cloneNode(!0);if(B.nodeType===Node.ELEMENT_NODE){const E=B,V=document.createElement(E.tagName.toLowerCase());return Array.from(E.attributes).forEach(G=>{G.name!=="style"&&G.name!=="class"&&V.setAttribute(G.name,G.value)}),Array.from(E.childNodes).forEach(G=>{const J=Y(G);J&&V.appendChild(J)}),E.style.backgroundColor&&(V.style.backgroundColor=""),V}return null};Array.from(S.childNodes).forEach(B=>{const E=Y(B);E&&U.appendChild(E)}),P.insertNode(U),document.execCommand("removeFormat",!1)}g(null),b("#FFEB3B")}else if(C.rangeCount>0&&!C.getRangeAt(0).collapsed)document.execCommand("backColor",!1,R),g(R),R!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(R)&&b(R);else return;const z=window.getSelection();z&&z.removeAllRanges(),l.current&&s(Ua(l.current.innerHTML)),x(!1),setTimeout(()=>{l.current&&l.current.focus(),F()},50)},[o,s,F]),_=u.useCallback(R=>{if(!l.current)return;o||l.current.focus();const C=window.getSelection();if(!C||C.rangeCount===0){l.current.focus();return}let H=!1;if(C.rangeCount>0){const P=C.getRangeAt(0).commonAncestorContainer;let S=null;for(P.nodeType===Node.TEXT_NODE?S=P.parentElement:S=P;S&&S!==l.current;){const Y=window.getComputedStyle(S).color;if(Y){const E=(V=>{if(V.startsWith("#"))return V.toUpperCase();const G=V.match(/\d+/g);if(!G||G.length<3)return null;const J=G[0],q=G[1],se=G[2];if(!J||!q||!se)return null;const ne=parseInt(J).toString(16).padStart(2,"0"),te=parseInt(q).toString(16).padStart(2,"0"),ge=parseInt(se).toString(16).padStart(2,"0");return`#${ne}${te}${ge}`.toUpperCase()})(Y);if(R==="#000000"){if(E==="#000000"||!E){H=!0;break}}else if(E&&E===R.toUpperCase()){H=!0;break}}S=S.parentElement}}if(R==="transparent"||R==="default"||H){if(R==="#000000"&&H){j(!1);return}document.execCommand("removeFormat",!1),N(null),A("#000000")}else document.execCommand("foreColor",!1,R),N(R),R!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(R)&&A(R);l.current&&s(Ua(l.current.innerHTML)),j(!1),setTimeout(F,10)},[o,s,F]),W=u.useCallback(()=>{l.current&&s(Ua(l.current.innerHTML)),F()},[s,F]),I=u.useCallback(R=>{if(R.ctrlKey&&R.key==="b"){R.preventDefault(),w("bold");return}if(R.ctrlKey&&R.key==="i"){R.preventDefault(),w("italic");return}if(R.ctrlKey&&R.key==="u"){R.preventDefault(),w("underline");return}},[w]),$=u.useCallback(()=>{c(!0)},[]),M=u.useCallback(()=>{c(!1),l.current&&s(Ua(l.current.innerHTML))},[s]);return u.useEffect(()=>{if(!o)return;const R=()=>{F()};return document.addEventListener("selectionchange",R),()=>{document.removeEventListener("selectionchange",R)}},[o,F]),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(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>w("bold"),title:"Bold (Ctrl+B)",children:e.jsx(Kj,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>w("italic"),title:"Italic (Ctrl+I)",children:e.jsx(Xj,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>w("underline"),title:"Underline (Ctrl+U)",children:e.jsx(Jj,{className:"h-4 w-4"})}),e.jsxs(na,{open:p,onOpenChange:x,children:[e.jsx(ia,{asChild:!0,children:e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("highlight")&&"bg-blue-100 text-blue-700"),title:"Text Highlight",children:e.jsx(Zj,{className:"h-4 w-4"})})}),e.jsx(la,{className:"w-auto p-2",align:"start",onPointerDownOutside:R=>{R.target.closest("[data-popover-content]")&&R.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:R=>R.stopPropagation(),children:[e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:R=>{R.stopPropagation(),x(!1)},title:"Close",children:e.jsx(vt,{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:_i.map(R=>{const C=h===R.value,H=R.value==="transparent";return e.jsxs("button",{type:"button",onClick:z=>{z.preventDefault(),z.stopPropagation(),L(C&&!H?"transparent":R.value)},className:$e("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",R.class,C&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",H&&"border-gray-400 bg-white",!H&&!C&&"border-gray-300"),title:C&&!H?`${R.name} (Click to remove)`:R.name,style:H?{}:{backgroundColor:R.value},children:[H&&e.jsx("span",{className:"text-[10px] text-gray-600 font-bold",children:"×"}),C&&!H&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]},R.value)})}),h&&h!=="transparent"&&e.jsx("div",{className:"mb-2",children:e.jsx(O,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:R=>{R.stopPropagation(),L("transparent")},title:"Remove highlight color",children:"Remove Highlight"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h&&h!=="transparent"?h:f,onChange:R=>{const C=R.target.value;b(C);const H=window.getSelection();H&&H.rangeCount>0&&!H.getRangeAt(0).collapsed&&L(C)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom color"}),e.jsx("input",{type:"text",value:h&&h!=="transparent"?h:f,onChange:R=>{R.stopPropagation();const C=R.target.value;b(C)},onKeyDown:R=>{if(R.stopPropagation(),R.key==="Enter"){R.preventDefault();const C=R.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(C)&&L(C)}},onPaste:R=>{R.stopPropagation();const C=R.clipboardData.getData("text").trim();R.preventDefault(),setTimeout(()=>{if(/^#[0-9A-Fa-f]{6}$/i.test(C)){b(C);const H=window.getSelection();H&&H.rangeCount>0&&!H.getRangeAt(0).collapsed&&L(C)}else{const H=C.match(/^([0-9A-Fa-f]{6})$/);if(H){const z=`#${H[1]}`;b(z);const P=window.getSelection();P&&P.rangeCount>0&&!P.getRangeAt(0).collapsed&&L(z)}}},0)},onClick:R=>{R.stopPropagation()},onFocus:R=>{R.stopPropagation(),R.target.select()},onBlur:R=>{const C=R.target.value.trim();if(/^#[0-9A-Fa-f]{6}$/i.test(C)){const H=window.getSelection();H&&H.rangeCount>0&&!H.getRangeAt(0).collapsed&&L(C)}else b(C===""?h||"#FFEB3B":C)},placeholder:"#FFEB3B",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply). Supports copy-paste.",autoComplete:"off",spellCheck:"false"}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{const R=f.trim();/^#[0-9A-Fa-f]{6}$/i.test(R)?L(R):b(h||"#FFEB3B")},title:"Apply custom color",children:"Apply"})]})]})]})})]}),e.jsxs(na,{open:y,onOpenChange:j,children:[e.jsx(ia,{asChild:!0,children:e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("textColor")&&"bg-blue-100 text-blue-700"),title:"Text Color",children:e.jsx(qj,{className:"h-4 w-4"})})}),e.jsx(la,{className:"w-auto p-2",align:"start",onPointerDownOutside:R=>{R.target.closest("[data-popover-content]")&&R.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:R=>R.stopPropagation(),children:[e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:R=>{R.stopPropagation(),j(!1)},title:"Close",children:e.jsx(vt,{className:"h-4 w-4 text-gray-500"})}),e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-2 pr-6",children:"Text Color"}),e.jsxs("div",{className:"grid grid-cols-6 gap-1.5 pr-1 mb-2",children:[e.jsxs("button",{type:"button",onClick:R=>{R.preventDefault(),R.stopPropagation(),v==="#000000"||!v&&!d.has("textColor")||_("#000000")},className:$e("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center bg-black",(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"})})]}),_i.filter(R=>R.value!=="transparent").map(R=>{const C=v===R.value;return e.jsxs("button",{type:"button",onClick:H=>{H.preventDefault(),H.stopPropagation(),_(C?"#000000":R.value)},className:$e("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center relative",C&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",!C&&"border-gray-300"),title:C?`${R.name} (Click to reset to default)`:R.name,style:{color:R.value,borderColor:C?"#2563eb":R.value},children:[e.jsx("span",{className:"text-xs font-bold",children:"A"}),C&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]},`text-${R.value}`)})]}),v&&v!=="#000000"&&e.jsx("div",{className:"mb-2",children:e.jsx(O,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:R=>{R.stopPropagation(),_("#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||T,onChange:R=>{const C=R.target.value;A(C),_(C)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom text color"}),e.jsx("input",{type:"text",value:v||T,onChange:R=>{const C=R.target.value;A(C)},onKeyDown:R=>{if(R.key==="Enter"){R.preventDefault();const C=R.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(C)&&_(C)}},onBlur:R=>{const C=R.target.value;/^#[0-9A-Fa-f]{6}$/.test(C)?_(C):C===""&&A(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(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>_(T),title:"Apply custom text color",children:"Apply"})]})]})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>w("formatBlock","<h1>"),title:"Heading 1",children:e.jsx(ey,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>w("formatBlock","<h2>"),title:"Heading 2",children:e.jsx(ty,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>w("formatBlock","<h3>"),title:"Heading 3",children:e.jsx(sy,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>w("insertUnorderedList"),title:"Bullet List",children:e.jsx(ec,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>w("insertOrderedList"),title:"Numbered List",children:e.jsx(ay,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>w("justifyLeft"),title:"Align Left",children:e.jsx(kp,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>w("justifyCenter"),title:"Align Center",children:e.jsx(ry,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:$e("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>w("justifyRight"),title:"Align Right",children:e.jsx(ny,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:l,contentEditable:!0,onPaste:D,onInput:W,onFocus:$,onBlur:M,onKeyDown:I,onMouseUp:F,onKeyUp:F,"data-placeholder":a,className:$e("w-full rounded-b-md border-0 px-3 py-2 text-base transition-all outline-none","bg-white text-gray-900","min-h-[120px]","overflow-y-auto","overflow-x-auto","md:overflow-x-visible","md:text-sm","empty:before:content-[attr(data-placeholder)] empty:before:text-muted-foreground empty:before:pointer-events-none","focus-visible:outline-none","[&_ul]:list-disc [&_ul]:ml-6 [&_ul]:my-2 [&_ul]:list-outside","[&_ol]:list-decimal [&_ol]:ml-6 [&_ol]:my-2 [&_ol]:list-outside","[&_li]:my-1 [&_li]:pl-2","[&_.table-wrapper]:overflow-x-auto [&_.table-wrapper]:max-w-full [&_.table-wrapper]:my-2","[&_.table-wrapper_table]:border-collapse [&_.table-wrapper_table]:border [&_.table-wrapper_table]:border-gray-300 [&_.table-wrapper_table]:min-w-full","[&_.table-wrapper_table_td]:border [&_.table-wrapper_table_td]:border-gray-300 [&_.table-wrapper_table_td]:px-3 [&_.table-wrapper_table_td]:py-2 [&_.table-wrapper_table_td]:text-sm [&_.table-wrapper_table_td]:whitespace-nowrap","[&_.table-wrapper_table_th]:border [&_.table-wrapper_table_th]:border-gray-300 [&_.table-wrapper_table_th]:px-3 [&_.table-wrapper_table_th]:py-2 [&_.table-wrapper_table_th]:bg-gray-50 [&_.table-wrapper_table_th]:font-semibold [&_.table-wrapper_table_th]:text-sm [&_.table-wrapper_table_th]:text-left [&_.table-wrapper_table_th]:whitespace-nowrap","[&_.table-wrapper_table_tr:nth-child(even)]:bg-gray-50","[&_table]:border-collapse [&_table]:my-2 [&_table]:border [&_table]:border-gray-300 [&_table]:w-full","[&_table_td]:border [&_table_td]:border-gray-300 [&_table_td]:px-3 [&_table_td]:py-2 [&_table_td]:text-sm","[&_table_th]:border [&_table_th]:border-gray-300 [&_table_th]:px-3 [&_table_th]:py-2 [&_table_th]:bg-gray-50 [&_table_th]:font-semibold [&_table_th]:text-sm [&_table_th]:text-left","[&_table_tr:nth-child(even)]:bg-gray-50","[&_p]:my-1 [&_p]:leading-relaxed","[&_strong]:font-bold","[&_em]:italic","[&_u]:underline","[&_span[style*='background']]:px-0.5 [&_span[style*='background']]:rounded","[&_h1]:text-xl [&_h1]:font-bold [&_h1]:my-2","[&_h2]:text-lg [&_h2]:font-semibold [&_h2]:my-2","[&_h3]:text-base [&_h3]:font-semibold [&_h3]:my-1",r),style:{minHeight:n},...i})]})}function Ls({content:t,className:s}){const a=u.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>`),Ua(r)},[t]);return t?e.jsx("div",{className:$e("text-sm text-gray-700 max-w-none","overflow-x-auto","md:overflow-x-visible","[&_ul]:list-disc [&_ul]:ml-6 [&_ul]:my-2 [&_ul]:list-outside","[&_ol]:list-decimal [&_ol]:ml-6 [&_ol]:my-2 [&_ol]:list-outside","[&_li]:my-1 [&_li]:pl-2","[&_.table-wrapper]:overflow-x-auto [&_.table-wrapper]:max-w-full [&_.table-wrapper]:my-2 [&_.table-wrapper]:-mx-2 [&_.table-wrapper]:px-2","[&_.table-wrapper_table]:border-collapse [&_.table-wrapper_table]:border [&_.table-wrapper_table]:border-gray-300 [&_.table-wrapper_table]:min-w-full","[&_.table-wrapper_table_td]:border [&_.table-wrapper_table_td]:border-gray-300 [&_.table-wrapper_table_td]:px-3 [&_.table-wrapper_table_td]:py-2 [&_.table-wrapper_table_td]:text-sm [&_.table-wrapper_table_td]:whitespace-nowrap","[&_.table-wrapper_table_th]:border [&_.table-wrapper_table_th]:border-gray-300 [&_.table-wrapper_table_th]:px-3 [&_.table-wrapper_table_th]:py-2 [&_.table-wrapper_table_th]:bg-gray-50 [&_.table-wrapper_table_th]:font-semibold [&_.table-wrapper_table_th]:text-sm [&_.table-wrapper_table_th]:text-left [&_.table-wrapper_table_th]:whitespace-nowrap","[&_.table-wrapper_table_tr:nth-child(even)]:bg-gray-50","[&_table]:border-collapse [&_table]:my-2 [&_table]:border [&_table]:border-gray-300","[&_table_td]:border [&_table_td]:border-gray-300 [&_table_td]:px-3 [&_table_td]:py-2 [&_table_td]:text-sm","[&_table_th]:border [&_table_th]:border-gray-300 [&_table_th]:px-3 [&_table_th]:py-2 [&_table_th]:bg-gray-50 [&_table_th]:font-semibold [&_table_th]:text-sm [&_table_th]:text-left","[&_table_tr:nth-child(even)]:bg-gray-50","[&_p]:my-1 [&_p]:leading-relaxed","[&_strong]:font-bold","[&_em]:italic","[&_u]:underline","[&_h1]:text-xl [&_h1]:font-bold [&_h1]:my-2","[&_h2]:text-lg [&_h2]:font-semibold [&_h2]:my-2","[&_h3]:text-base [&_h3]:font-semibold [&_h3]:my-1",s),dangerouslySetInnerHTML:{__html:a}}):null}var Vg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Cl,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",l="second",o="minute",c="hour",d="day",m="week",p="month",x="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+)?$/,y=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,j={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(I){var $=["th","st","nd","rd"],M=I%100;return"["+I+($[(M-20)%10]||$[M]||$[0])+"]"}},v=function(I,$,M){var R=String(I);return!R||R.length>=$?I:""+Array($+1-R.length).join(M)+I},N={s:v,z:function(I){var $=-I.utcOffset(),M=Math.abs($),R=Math.floor(M/60),C=M%60;return($<=0?"+":"-")+v(R,2,"0")+":"+v(C,2,"0")},m:function I($,M){if($.date()<M.date())return-I(M,$);var R=12*(M.year()-$.year())+(M.month()-$.month()),C=$.clone().add(R,p),H=M-C<0,z=$.clone().add(R+(H?-1:1),p);return+(-(R+(M-C)/(H?C-z:z-C))||0)},a:function(I){return I<0?Math.ceil(I)||0:Math.floor(I)},p:function(I){return{M:p,y:h,w:m,d,D:g,h:c,m:o,s:l,ms:i,Q:x}[I]||String(I||"").toLowerCase().replace(/s$/,"")},u:function(I){return I===void 0}},T="en",A={};A[T]=j;var k="$isDayjsObject",D=function(I){return I instanceof _||!(!I||!I[k])},F=function I($,M,R){var C;if(!$)return T;if(typeof $=="string"){var H=$.toLowerCase();A[H]&&(C=H),M&&(A[H]=M,C=H);var z=$.split("-");if(!C&&z.length>1)return I(z[0])}else{var P=$.name;A[P]=$,C=P}return!R&&C&&(T=C),C||!R&&T},w=function(I,$){if(D(I))return I.clone();var M=typeof $=="object"?$:{};return M.date=I,M.args=arguments,new _(M)},L=N;L.l=F,L.i=D,L.w=function(I,$){return w(I,{locale:$.$L,utc:$.$u,x:$.$x,$offset:$.$offset})};var _=function(){function I(M){this.$L=F(M.locale,null,!0),this.parse(M),this.$x=this.$x||M.x||{},this[k]=!0}var $=I.prototype;return $.parse=function(M){this.$d=function(R){var C=R.date,H=R.utc;if(C===null)return new Date(NaN);if(L.u(C))return new Date;if(C instanceof Date)return new Date(C);if(typeof C=="string"&&!/Z$/i.test(C)){var z=C.match(b);if(z){var P=z[2]-1||0,S=(z[7]||"0").substring(0,3);return H?new Date(Date.UTC(z[1],P,z[3]||1,z[4]||0,z[5]||0,z[6]||0,S)):new Date(z[1],P,z[3]||1,z[4]||0,z[5]||0,z[6]||0,S)}}return new Date(C)}(M),this.init()},$.init=function(){var M=this.$d;this.$y=M.getFullYear(),this.$M=M.getMonth(),this.$D=M.getDate(),this.$W=M.getDay(),this.$H=M.getHours(),this.$m=M.getMinutes(),this.$s=M.getSeconds(),this.$ms=M.getMilliseconds()},$.$utils=function(){return L},$.isValid=function(){return this.$d.toString()!==f},$.isSame=function(M,R){var C=w(M);return this.startOf(R)<=C&&C<=this.endOf(R)},$.isAfter=function(M,R){return w(M)<this.startOf(R)},$.isBefore=function(M,R){return this.endOf(R)<w(M)},$.$g=function(M,R,C){return L.u(M)?this[R]:this.set(C,M)},$.unix=function(){return Math.floor(this.valueOf()/1e3)},$.valueOf=function(){return this.$d.getTime()},$.startOf=function(M,R){var C=this,H=!!L.u(R)||R,z=L.p(M),P=function(J,q){var se=L.w(C.$u?Date.UTC(C.$y,q,J):new Date(C.$y,q,J),C);return H?se:se.endOf(d)},S=function(J,q){return L.w(C.toDate()[J].apply(C.toDate("s"),(H?[0,0,0,0]:[23,59,59,999]).slice(q)),C)},U=this.$W,Y=this.$M,B=this.$D,E="set"+(this.$u?"UTC":"");switch(z){case h:return H?P(1,0):P(31,11);case p:return H?P(1,Y):P(0,Y+1);case m:var V=this.$locale().weekStart||0,G=(U<V?U+7:U)-V;return P(H?B-G:B+(6-G),Y);case d:case g:return S(E+"Hours",0);case c:return S(E+"Minutes",1);case o:return S(E+"Seconds",2);case l:return S(E+"Milliseconds",3);default:return this.clone()}},$.endOf=function(M){return this.startOf(M,!1)},$.$set=function(M,R){var C,H=L.p(M),z="set"+(this.$u?"UTC":""),P=(C={},C[d]=z+"Date",C[g]=z+"Date",C[p]=z+"Month",C[h]=z+"FullYear",C[c]=z+"Hours",C[o]=z+"Minutes",C[l]=z+"Seconds",C[i]=z+"Milliseconds",C)[H],S=H===d?this.$D+(R-this.$W):R;if(H===p||H===h){var U=this.clone().set(g,1);U.$d[P](S),U.init(),this.$d=U.set(g,Math.min(this.$D,U.daysInMonth())).$d}else P&&this.$d[P](S);return this.init(),this},$.set=function(M,R){return this.clone().$set(M,R)},$.get=function(M){return this[L.p(M)]()},$.add=function(M,R){var C,H=this;M=Number(M);var z=L.p(R),P=function(Y){var B=w(H);return L.w(B.date(B.date()+Math.round(Y*M)),H)};if(z===p)return this.set(p,this.$M+M);if(z===h)return this.set(h,this.$y+M);if(z===d)return P(1);if(z===m)return P(7);var S=(C={},C[o]=r,C[c]=n,C[l]=a,C)[z]||1,U=this.$d.getTime()+M*S;return L.w(U,this)},$.subtract=function(M,R){return this.add(-1*M,R)},$.format=function(M){var R=this,C=this.$locale();if(!this.isValid())return C.invalidDate||f;var H=M||"YYYY-MM-DDTHH:mm:ssZ",z=L.z(this),P=this.$H,S=this.$m,U=this.$M,Y=C.weekdays,B=C.months,E=C.meridiem,V=function(q,se,ne,te){return q&&(q[se]||q(R,H))||ne[se].slice(0,te)},G=function(q){return L.s(P%12||12,q,"0")},J=E||function(q,se,ne){var te=q<12?"AM":"PM";return ne?te.toLowerCase():te};return H.replace(y,function(q,se){return se||function(ne){switch(ne){case"YY":return String(R.$y).slice(-2);case"YYYY":return L.s(R.$y,4,"0");case"M":return U+1;case"MM":return L.s(U+1,2,"0");case"MMM":return V(C.monthsShort,U,B,3);case"MMMM":return V(B,U);case"D":return R.$D;case"DD":return L.s(R.$D,2,"0");case"d":return String(R.$W);case"dd":return V(C.weekdaysMin,R.$W,Y,2);case"ddd":return V(C.weekdaysShort,R.$W,Y,3);case"dddd":return Y[R.$W];case"H":return String(P);case"HH":return L.s(P,2,"0");case"h":return G(1);case"hh":return G(2);case"a":return J(P,S,!0);case"A":return J(P,S,!1);case"m":return String(S);case"mm":return L.s(S,2,"0");case"s":return String(R.$s);case"ss":return L.s(R.$s,2,"0");case"SSS":return L.s(R.$ms,3,"0");case"Z":return z}return null}(q)||z.replace(":","")})},$.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},$.diff=function(M,R,C){var H,z=this,P=L.p(R),S=w(M),U=(S.utcOffset()-this.utcOffset())*r,Y=this-S,B=function(){return L.m(z,S)};switch(P){case h:H=B()/12;break;case p:H=B();break;case x:H=B()/3;break;case m:H=(Y-U)/6048e5;break;case d:H=(Y-U)/864e5;break;case c:H=Y/n;break;case o:H=Y/r;break;case l:H=Y/a;break;default:H=Y}return C?H:L.a(H)},$.daysInMonth=function(){return this.endOf(p).$D},$.$locale=function(){return A[this.$L]},$.locale=function(M,R){if(!M)return this.$L;var C=this.clone(),H=F(M,R,!0);return H&&(C.$L=H),C},$.clone=function(){return L.w(this.$d,this)},$.toDate=function(){return new Date(this.valueOf())},$.toJSON=function(){return this.isValid()?this.toISOString():null},$.toISOString=function(){return this.$d.toISOString()},$.toString=function(){return this.$d.toUTCString()},I}(),W=_.prototype;return w.prototype=W,[["$ms",i],["$s",l],["$m",o],["$H",c],["$W",d],["$M",p],["$y",h],["$D",g]].forEach(function(I){W[I[1]]=function($){return this.$g($,I[0],I[1])}}),w.extend=function(I,$){return I.$i||(I($,_,w),I.$i=!0),w},w.locale=F,w.isDayjs=D,w.unix=function(I){return w(1e3*I)},w.en=A[T],w.Ls=A,w.p={},w})})(Vg);var AC=Vg.exports;const rs=Sl(AC);var Wg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Cl,function(){return function(a,r,n){a=a||{};var i=r.prototype,l={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function o(d,m,p,x){return i.fromToBase(d,m,p,x)}n.en.relativeTime=l,i.fromToBase=function(d,m,p,x,h){for(var g,f,b,y=p.$locale().relativeTime||l,j=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=j.length,N=0;N<v;N+=1){var T=j[N];T.d&&(g=x?n(d).diff(p,T.d,!0):p.diff(d,T.d,!0));var A=(a.rounding||Math.round)(Math.abs(g));if(b=g>0,A<=T.r||!T.r){A<=1&&N>0&&(T=j[N-1]);var k=y[T.l];h&&(A=h(""+A)),f=typeof k=="string"?k.replace("%d",A):k(A,m,T.l,b);break}}if(m)return f;var D=b?y.future:y.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)}}})})(Wg);var TC=Wg.exports;const kC=Sl(TC);rs.extend(kC);function DC({request:t,isInitiator:s,needsClosure:a,conclusionRemark:r,setConclusionRemark:n,conclusionLoading:i,conclusionSubmitting:l,aiGenerated:o,handleGenerateConclusion:c,handleFinalizeConclusion:d,onPause:m,onResume:p,onRetrigger:x,currentUserIsApprover:h=!1,pausedByUserId:g,currentUserId:f,generationAttempts:b=0,generationFailed:y=!1,maxAttemptsReached:j=!1}){var H,z,P,S,U,Y,B,E;const{user:v}=us(),N=t==null?void 0:t.pauseInfo,T=(N==null?void 0:N.isPaused)||!1,A=(H=N==null?void 0:N.pausedBy)==null?void 0:H.userId,k=(v==null?void 0:v.userId)||"",D=T&&p&&(h||s),F=T&&s&&A&&A!==k&&x,L=((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"),_=t==null?void 0:t.form16Submission,W=L&&(_!=null&&_.ocrExtractedData)&&typeof _.ocrExtractedData=="object"?_.ocrExtractedData:null,I=L&&W&&Object.keys(W).length>0?W:L&&_?{deductorName:_.deductorName,deductor_name:_.deductorName,tanNumber:_.tanNumber,tan_number:_.tanNumber,financialYear:_.financialYear,financial_year:_.financialYear,quarter:_.quarter,form16aNumber:_.form16aNumber,form16a_number:_.form16aNumber,totalAmount:_.totalAmount,total_amount:_.totalAmount,tdsAmount:_.tdsAmount,tds_amount:_.tdsAmount,acknowledgementNumber:_.acknowledgementNumber,acknowledgement_number:_.acknowledgementNumber,dateOfIssue:_.dateOfIssue,date_of_issue:_.dateOfIssue,deduceeName:_.deduceeName,deducee_name:_.deduceeName,deduceePan:_.deduceePan,deducee_pan:_.deduceePan}:null,$=V=>V!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(Number(V)):"",M=V=>V==null||V===""?"":String(V),R=V=>{const G=(V||"").toLowerCase();return G==="completed"?"bg-emerald-100 text-emerald-800 border-emerald-200":G==="duplicate"||G==="duplicate submission"?"bg-amber-100 text-amber-800 border-amber-200":G==="balance mismatch"||G==="failed"?"bg-red-100 text-red-800 border-red-200":G==="resubmission needed"||G==="partial extracted data"?"bg-amber-50 text-amber-700 border-amber-200":"bg-gray-100 text-gray-700 border-gray-200"},C=V=>{const G=((V==null?void 0:V.displayStatus)||"").toLowerCase(),J=((V==null?void 0:V.validationNotes)||"").toLowerCase();return G==="balance mismatch"||G==="failed"&&(J.includes("mismatch")||J.includes("26as")||J.includes("value"))?"Failed - data mismatch with 26AS, submit the form 16 with correct data":G==="duplicate"||G==="duplicate submission"?"Duplicate. A submission for this FY and quarter already exists.":G==="resubmission needed"?(V==null?void 0:V.validationNotes)||"Resubmission needed. Please submit again with correct data.":G==="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:[L&&(_==null?void 0:_.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(oe,{variant:"outline",className:R(_.displayStatus),children:_.displayStatus})]}),C(_)&&e.jsx("p",{className:`text-sm ${(_.displayStatus||"").toLowerCase()==="balance mismatch"||(_.displayStatus||"").toLowerCase()==="failed"?"text-red-700 font-medium":"text-gray-600"}`,children:C(_)})]}),L&&e.jsxs(Z,{"data-testid":"form16-certificate-details",className:"border-emerald-200 bg-emerald-50/30",children:[e.jsxs(de,{className:"pb-3 sm:pb-4",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base text-emerald-800",children:[e.jsx(Ee,{className:"w-4 h-4 sm:w-5 sm:h-5 text-emerald-600"}),"Form 16A Certificate Details"]}),e.jsx(Te,{className:"text-xs text-gray-600",children:"TDS Certificate as per Income Tax Act, 1961"})]}),e.jsx(ee,{className:"space-y-4",children:_?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:_.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:_.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:_.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:_.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:_.quarter?`${_.quarter} (${_.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:"})," ",_.deductorName||""]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TAN:"})," ",_.tanNumber||""]})]})]}),(_.deduceeName||_.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:[_.deduceeName&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Name:"})," ",_.deduceeName]}),_.deduceePan&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"PAN:"})," ",_.deduceePan]}),_.deduceeAddress&&e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("span",{className:"text-gray-500",children:"Address:"})," ",_.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:[_.section&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Section:"})," ",_.section]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Amount Paid:"})," ",$(_.totalAmount??_.amountPaid)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TDS Deducted:"})," ",$(_.tdsAmount)]}),_.dateOfPayment&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Date of Payment:"})," ",_.dateOfPayment]})]})]}),(_.bsrCode||_.challanSerialNo||_.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:[_.bsrCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"BSR Code:"})," ",_.bsrCode]}),_.challanSerialNo&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Challan Serial No.:"})," ",_.challanSerialNo]}),_.dateOfDeposit&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Date of Deposit:"})," ",_.dateOfDeposit]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Amount:"})," ",$(_.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:$(_.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(Ls,{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."})]})})]}),L&&I&&Object.keys(I).length>0&&e.jsxs(Z,{"data-testid":"form16-ocr-extracted-data",className:"border-slate-200 bg-slate-50/50",children:[e.jsxs(de,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base text-slate-800",children:[e.jsx(Dp,{className:"w-4 h-4 text-slate-600"}),"OCR extracted data"]}),e.jsx(Te,{className:"text-xs text-gray-600",children:"Data extracted from the uploaded Form 16A PDF."})]}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm",children:[(I.deductorName??I.deductor_name??I.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:M(I.deductorName??I.deductor_name??I.nameAndAddressOfDeductor)})]}),(I.tanNumber??I.tan_number??I.tanOfDeductor)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"TAN"}),e.jsx("p",{className:"font-medium",children:M(I.tanNumber??I.tan_number??I.tanOfDeductor)})]}),(I.financialYear??I.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:M(I.financialYear??I.financial_year)})]}),I.quarter!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Quarter"}),e.jsx("p",{className:"font-medium",children:M(I.quarter)})]}),(I.form16aNumber??I.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:M(I.form16aNumber??I.form16a_number)})]}),(I.totalAmount??I.total_amount??I.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:$(I.totalAmount??I.total_amount??I.totalAmountPaid)})]}),(I.totalTaxDeducted??I.tdsAmount??I.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:$(I.totalTaxDeducted??I.tdsAmount??I.tds_amount)})]}),(I.natureOfPayment??I.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:M(I.natureOfPayment??I.nature_of_payment)})]}),(I.transactionDate??I.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:M(I.transactionDate??I.transaction_date)})]}),(I.assessmentYear??I.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:M(I.assessmentYear??I.assessment_year)})]}),(I.acknowledgementNumber??I.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:M(I.acknowledgementNumber??I.acknowledgement_number)})]}),(I.dateOfIssue??I.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:M(I.dateOfIssue??I.date_of_issue)})]}),(I.deduceeName??I.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:M(I.deduceeName??I.deducee_name)})]}),(I.deduceePan??I.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:M(I.deduceePan??I.deducee_pan)})]})]})})]}),e.jsxs(Z,{"data-testid":"initiator-card",children:[e.jsx(de,{className:"pb-3 sm:pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Wt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(ee,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(ds,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(ms,{className:"bg-gray-700 text-white font-semibold text-sm",children:((z=t.initiator)==null?void 0:z.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:((P=t.initiator)==null?void 0:P.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((S=t.initiator)==null?void 0:S.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((U=t.initiator)==null?void 0:U.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(Ca,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((Y=t.initiator)==null?void 0:Y.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(bi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((B=t.initiator)==null?void 0:B.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(Z,{"data-testid":"request-details-card",children:[e.jsx(de,{className:"pb-3 sm:pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ee,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(ee,{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs sm:text-sm font-medium text-gray-700 block mb-2",children:"Description"}),e.jsx("div",{className:"bg-gray-50 rounded-lg p-3 sm:p-4 border border-gray-300",children:e.jsx(Ls,{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:js(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:js(t.updatedAt)})]})]})]})]}),T&&N&&e.jsxs(Z,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(de,{className:"pb-3 sm:pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(pr,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(ee,{className:"space-y-3 sm:space-y-4",children:[e.jsx("div",{className:"bg-white rounded-lg p-3 sm:p-4 border border-orange-200",children:e.jsxs("div",{className:"space-y-2 sm:space-y-3",children:[N.pauseReason&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Reason"}),e.jsx(Ls,{content:N.pauseReason,className:"text-sm text-gray-900 mt-1"})]}),N.pausedBy&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused By"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:N.pausedBy.name||N.pausedBy.email})]}),N.pauseResumeDate&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Auto-Resume Date"}),e.jsxs("p",{className:"text-sm text-gray-900 mt-1",children:[js(N.pauseResumeDate),rs(N.pauseResumeDate).isAfter(rs())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",rs(N.pauseResumeDate).fromNow(),")"]})]})]}),N.pausedAt&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused At"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:js(N.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[D&&p&&e.jsxs(O,{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(dl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),F&&x&&e.jsxs(O,{onClick:x,variant:"outline",className:"border-orange-300 text-orange-700 hover:bg-orange-50 text-xs sm:text-sm h-8 sm:h-9",size:"sm",children:[e.jsx(Ze,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Request Resume"]})]})]})]}),t.claimDetails&&e.jsxs(Z,{children:[e.jsx(de,{className:"pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ee,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityName||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Type"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityType||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Location"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.location||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Date"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityDate?zg(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(Ls,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(Z,{children:[e.jsxs(de,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ve,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(Te,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(ee,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Ls,{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 ",js(t.closureDate)]}),e.jsxs("span",{children:["By ",((E=t.initiator)==null?void 0:E.name)||"Initiator"]})]})]})]}),a&&e.jsxs(Z,{"data-testid":"conclusion-remark-card",children:[e.jsx(de,{className:`bg-gradient-to-r border-b ${t.status==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(Ve,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(Te,{className:"mt-1 text-xs sm:text-sm",children:t.status==="rejected"?"This request was rejected. Please review the AI-generated closure remark and finalize it to close this request.":"All approvals are complete. Please review and finalize the conclusion to close this request."})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(O,{variant:"outline",size:"sm",onClick:c,disabled:i||j,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(_t,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),o?"Regenerate":"Generate with AI"]}),o&&!j&&!y&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-b," attempts remaining"]})]})]})}),e.jsx(ee,{className:"pt-4",children:i?e.jsx("div",{className:"flex items-center justify-center py-8","data-testid":"conclusion-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx(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(Ci,{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(O,{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(Ve,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function Jn({delayDuration:t=0,...s}){return e.jsx(mj,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function Ji({...t}){return e.jsx(Jn,{children:e.jsx(uj,{"data-slot":"tooltip",...t})})}function Zi({...t}){return e.jsx(xj,{"data-slot":"tooltip-trigger",...t})}function qi({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(hj,{children:e.jsxs(pj,{"data-slot":"tooltip-content",sideOffset:s,className:$e("bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...r,children:[a,e.jsx(gj,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function ht({...t}){return e.jsx(bp,{"data-slot":"dialog",...t})}function RC({...t}){return e.jsx(fp,{"data-slot":"dialog-portal",...t})}const Hg=u.forwardRef(({className:t,...s},a)=>e.jsx(Ec,{ref:a,"data-slot":"dialog-overlay",className:$e("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...s}));Hg.displayName=Ec.displayName;const mt=u.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(RC,{"data-slot":"dialog-portal",children:[e.jsx(Hg,{}),e.jsxs(_c,{ref:r,"data-slot":"dialog-content",className:$e("bg-white data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...a,children:[s,e.jsxs(fj,{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(vt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));mt.displayName=_c.displayName;const pt=u.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:$e("flex flex-col gap-2 text-center sm:text-left",t),...s}));pt.displayName="DialogHeader";const Dt=u.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:$e("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));Dt.displayName="DialogFooter";const ut=u.forwardRef(({className:t,...s},a)=>e.jsx(pp,{ref:a,"data-slot":"dialog-title",className:$e("text-lg leading-none font-semibold",t),...s}));ut.displayName=pp.displayName;const Mt=u.forwardRef(({className:t,...s},a)=>e.jsx(gp,{ref:a,"data-slot":"dialog-description",className:$e("text-muted-foreground text-sm",t),...s}));Mt.displayName=gp.displayName;function Vs({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:$e("resize-none border-gray-400 placeholder:text-muted-foreground bg-white text-gray-900 flex field-sizing-content min-h-16 w-full rounded-md border px-3 py-2 text-base transition-all outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","hover:border-gray-500","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...s})}const cx=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`},IC=(t,s)=>{if(s)return e.jsx(Ze,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(Ve,{className:"w-4 h-4 sm:w-5 sm:w-5 text-green-600"});case"rejected":return e.jsx(At,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"paused":return e.jsx(Rp,{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 FC({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]=u.useState(!1),[x,h]=u.useState(""),[g,f]=u.useState(!1),b=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";u.useEffect(()=>{m||h("")},[m]);const y=t.status==="pending"||t.status==="in-review",j=t.status==="approved",v=t.status==="rejected",N=t.status==="waiting",T=t.status==="paused",A=Number(t.tatHours||0),k=t.actualHours??0,D=j&&k?Math.max(0,A-k):0,F=A>0?k/A*100:0,w=F>=100,L=(d==null?void 0:d.role)==="ADMIN",_=Ul(d),W=t.approverId===(d==null?void 0:d.userId),I=L||_||W,$=async()=>{var M,R;if(!x.trim()){Q.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}f(!0);try{await wC(t.levelId,x.trim()),p(!1),h(""),Q.success("Breach Reason Updated",{description:"The breach reason has been saved and will appear in the TAT Breach Report.",duration:5e3}),o?await o():setTimeout(()=>{window.location.reload()},1e3)}catch(C){console.error("Error updating breach reason:",C);const H=((R=(M=C==null?void 0:C.response)==null?void 0:M.data)==null?void 0:R.error)||(C==null?void 0:C.message)||"Failed to update breach reason. Please try again.";Q.error("Failed to Update Breach Reason",{description:H,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":y?"border-blue-500 bg-blue-50 shadow-md":j?"border-green-500 bg-green-50":v?"border-red-500 bg-red-50":N?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${c}-${t.step}`,children:[e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 md:gap-4",children:[e.jsx("div",{className:`p-2 sm:p-2.5 md:p-3 rounded-xl flex-shrink-0 ${t.isSkipped?"bg-orange-100":T?"bg-yellow-100":y?"bg-blue-100":j?"bg-green-100":v?"bg-red-100":N?"bg-gray-200":"bg-gray-100"}`,children:IC(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(oe,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":y?"bg-yellow-100 text-yellow-800 border-yellow-200":j?"bg-green-100 text-green-800 border-green-200":v?"bg-red-100 text-red-800 border-red-200":N?"bg-gray-200 text-gray-600 border-gray-300":"bg-gray-100 text-gray-800 border-gray-200"}`,"data-testid":`${c}-status-badge`,children:t.isSkipped?"skipped":t.status}),t.isSkipped&&t.skipReason&&e.jsx(Jn,{delayDuration:200,children:e.jsxs(Ji,{children:[e.jsx(Zi,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:M=>M.stopPropagation(),children:e.jsx(Ze,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(qi,{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(Lu,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),j&&k&&e.jsx(oe,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:cx(k)})]}),e.jsx("p",{className:"text-sm font-semibold text-gray-900","data-testid":`${c}-approver-name`,children:r?e.jsx("span",{className:"text-blue-600",children:"You"}):t.approver}),e.jsx("p",{className:"text-xs text-gray-600","data-testid":`${c}-role`,children:t.role})]}),e.jsxs("div",{className:"text-left sm:text-right flex-shrink-0",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium",children:"Turnaround Time (TAT)"}),e.jsxs("p",{className:"text-lg font-bold text-gray-900","data-testid":`${c}-tat-hours`,children:[A," hours"]})]})]}),j&&k!==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?js(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:cx(k)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const M=Math.min(100,F),R=()=>w?"bg-red-600":F>=75?"bg-orange-500":F>=50?"bg-amber-500":"bg-green-600",C=()=>w?"text-red-600":F>=75?"text-orange-600":F>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(oa,{value:M,className:"h-2 bg-gray-200",indicatorClassName:R(),"data-testid":`${c}-progress-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-semibold ${C()}`,children:[Math.round(M),"% of TAT used"]}),w&&I&&e.jsx(Jn,{children:e.jsxs(Ji,{children:[e.jsx(Zi,{asChild:!0,children:e.jsx(O,{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(Pi,{className:"w-3 h-3"})})}),e.jsx(qi,{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)]})]})]})})()}),w&&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(Pi,{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(Qs,{className:"w-3.5 h-3.5 text-blue-600"}),"Conclusion Remark:"]}),e.jsx("p",{className:"text-sm text-gray-700 italic leading-relaxed",children:t.comment})]})]}),i&&(y||T)&&(a==null?void 0:a.sla)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Due by:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.deadline?_a(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${T?"bg-gray-100 border-gray-300":(a.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(a.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(a.sla.percentageUsed||0)>=50?"bg-amber-50 border-amber-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",T&&"(Paused)"]}),e.jsxs("div",{className:"space-y-2 text-xs mb-3",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time elapsed since assigned:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.elapsedText})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time used:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[a.sla.elapsedText," / ",Xt(A)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const M=a.sla.percentageUsed||0,R=()=>T?"bg-gray-500":M>=100?"bg-red-600":M>=75?"bg-orange-500":M>=50?"bg-amber-500":"bg-green-600",C=()=>T?"text-gray-600":M>=100?"text-red-600":M>=75?"text-orange-600":M>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(oa,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:R(),"data-testid":`${c}-sla-progress`}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`text-xs font-semibold ${C()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&I&&e.jsx(Jn,{children:e.jsxs(Ji,{children:[e.jsx(Zi,{asChild:!0,children:e.jsx(O,{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(Pi,{className:"w-3 h-3"})})}),e.jsx(qi,{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(ml,{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(Pi,{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"]})]})]})]}),N&&e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"bg-gray-100 border border-gray-300 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-gray-600 mb-1 flex items-center gap-1.5",children:[e.jsx(Rp,{className:"w-3.5 h-3.5 text-gray-500"}),"Awaiting Previous Approval"]}),e.jsx("p",{className:"text-sm font-medium text-gray-700",children:"Will be assigned after previous step"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Allocated ",A," hours for approval"]})]})}),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(At,{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(Lu,{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 ",js(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((M,R)=>{var C,H,z,P,S,U;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${M.isBreached?"bg-red-50 border-red-200":(M.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${R}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(M.thresholdPercentage||0)===50&&e.jsx(iy,{className:"w-5 h-5 text-yellow-600"}),(M.thresholdPercentage||0)===75&&e.jsx(ss,{className:"w-5 h-5 text-orange-600"}),(M.thresholdPercentage||0)===100&&e.jsx(ml,{className:"w-5 h-5 text-red-600"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-2 mb-1",children:[e.jsxs("p",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:["Reminder ",R+1," - ",M.thresholdPercentage||0,"% TAT"]}),e.jsx(oe,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${M.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:M.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[M.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(M.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(M.tatHoursElapsed||0)),((C=M.metadata)==null?void 0:C.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(M.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 ${(M.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[Xt(Number(M.tatHoursRemaining||0)),((H=M.metadata)==null?void 0:H.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(M.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:M.expectedCompletionTime?_a(M.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"}),(((z=M.metadata)==null?void 0:z.testMode)||((P=M.metadata)==null?void 0:P.tatTestMode))&&e.jsx(oe,{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: ",M.alertSentAt?js(M.alertSentAt):"N/A"]}),(((S=M.metadata)==null?void 0:S.testMode)||((U=M.metadata)==null?void 0:U.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},R)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[j?"Approved":v?"Rejected":"Actioned"," on ",js(t.timestamp)]}),n&&!T&&(y||t.status==="pending")&&!j&&!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(O,{variant:"outline",size:"sm",className:"w-full border-orange-300 text-orange-700 hover:bg-orange-50 h-9 sm:h-10 text-xs sm:text-sm",onClick:()=>l({levelId:t.levelId,approverName:t.approver,levelNumber:t.step}),"data-testid":`${c}-skip-button`,children:[e.jsx(Ze,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Skip This Approver"]}),e.jsx("p",{className:"text-[10px] sm:text-xs text-gray-500 mt-1 text-center",children:T?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(ht,{open:m,onOpenChange:p,children:e.jsxs(mt,{className:"sm:max-w-[500px]",children:[e.jsxs(pt,{children:[e.jsx(ut,{children:b?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(Mt,{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(Vs,{placeholder:"Enter the reason for the breach...",value:x,onChange:M=>h(M.target.value),className:"min-h-[100px]",maxLength:500}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[x.length,"/500 characters"]})]}),e.jsxs(Dt,{children:[e.jsx(O,{variant:"outline",onClick:()=>{p(!1),h("")},disabled:g,children:"Cancel"}),e.jsx(O,{onClick:$,disabled:!x.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function PC({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(Z,{children:[e.jsx(de,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ks,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(Te,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var 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,x=Math.min(Math.max(1,l),i);return p?e.jsxs(oe,{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(oe,{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(oe,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",x," of ",i," - ",o," completed"]})})()]})}),e.jsx(ee,{children:t.approvalFlow&&t.approvalFlow.length>0?e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.approvalFlow.map((i,l)=>{var 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,x=i.step===p;return e.jsx(FC,{step:i,index:l,approval:o,isCurrentUser:m,isInitiator:a,isCurrentLevel:x,onSkipApprover:r,onRefresh:n,testId:"workflow-step"},l)})}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-workflow-steps",children:"No workflow steps defined"})})]})}function Ir(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(Number(t))}function fa(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 dx="Failed - data mismatch with 26AS, submit the Form 16 with correct data.";function _C(t){const s=(t||"").toLowerCase();return/notnull|violation|sequelize|econnrefused|database|error\./i.test(s)}function mx(t){const s=((t==null?void 0:t.displayStatus)||"").toLowerCase(),a=String((t==null?void 0:t.validationNotes)||"");return s==="balance mismatch"||s==="failed"?_C(a)?dx:a.trim()||dx: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 MC({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(oe,{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:"})," ",Ir(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]})]}),mx(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:mx(s)})]}),e.jsxs(Z,{"data-testid":"form16-certificate-details",className:"border-emerald-200 bg-emerald-50/30",children:[e.jsxs(de,{className:"pb-3 sm:pb-4",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base text-emerald-800",children:[e.jsx(Ee,{className:"w-4 h-4 sm:w-5 sm:h-5 text-emerald-600"}),"Form 16A Certificate Details"]}),e.jsx(Te,{className:"text-xs text-gray-600",children:"TDS Certificate as per Income Tax Act, 1961"})]}),e.jsx(ee,{className:"space-y-4",children:s?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Certificate Number"}),e.jsx("p",{className:"text-sm font-medium",children:s.form16aNumber||""})]}),s.version!=null&&s.version>=2&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Version"}),e.jsxs("p",{className:"text-sm font-medium",children:["Version ",s.version]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Financial Year"}),e.jsx("p",{className:"text-sm font-medium",children:s.financialYear||""})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Acknowledgement Number"}),e.jsx("p",{className:"text-sm font-medium",children:s.acknowledgementNumber||""})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Date of Issue"}),e.jsx("p",{className:"text-sm font-medium",children:s.dateOfIssue||""})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Quarter"}),e.jsx("p",{className:"text-sm font-medium",children:s.quarter?`${s.quarter} (${s.financialYear||""})`:""})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2",children:"Deductor Details"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Name:"})," ",s.deductorName||""]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TAN:"})," ",s.tanNumber||""]})]})]}),(s.deduceeName||s.deduceePan)&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2",children:"Deductee Details (Dealer)"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm",children:[s.deduceeName&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Name:"})," ",s.deduceeName]}),s.deduceePan&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"PAN:"})," ",s.deduceePan]}),s.deduceeAddress&&e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("span",{className:"text-gray-500",children:"Address:"})," ",s.deduceeAddress]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2",children:"TDS Payment Details"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm",children:[s.section&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Section:"})," ",s.section]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Amount Paid:"})," ",Ir(s.totalAmount??s.amountPaid)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TDS Deducted:"})," ",Ir(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:"})," ",Ir(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:Ir(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(Ls,{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(de,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base text-slate-800",children:[e.jsx(Dp,{className:"w-4 h-4 text-slate-600"}),"OCR extracted data"]}),e.jsx(Te,{className:"text-xs text-gray-600",children:"Data extracted from the uploaded Form 16A PDF (shown for all submission outcomes)."})]}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm",children:[(r.deductorName??r.deductor_name??r.nameAndAddressOfDeductor??r.name_and_address_of_deductor)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Deductor name"}),e.jsx("p",{className:"font-medium",children:fa(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:fa(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:fa(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:fa(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:fa(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:Ir(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:Ir(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:fa(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:fa(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:fa(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:fa(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:fa(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:fa(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:fa(r.deduceePan??r.deducee_pan)})]})]})})]}),e.jsxs(Z,{"data-testid":"form16-submission-context",children:[e.jsx(de,{className:"pb-3",children:e.jsxs(ue,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Wt,{className:"w-4 h-4 text-emerald-600"}),"Submitted by"]})}),e.jsxs(ee,{children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ds,{className:"h-10 w-10 rounded-full flex-shrink-0",children:e.jsx(ms,{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(Ca,{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(Ls,{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 LC=[{key:"submit",label:"Dealer submits Form 16",icon:Ee},{key:"ocr",label:"OCR extracts",icon:Ee},{key:"match",label:"Matching with 26AS",icon:_t},{key:"success",label:"Successfully match",icon:Ve},{key:"credit",label:"Credit note generated",icon:Et}];function OC({request:t,requestId:s}){const[a,r]=u.useState(null),[n,i]=u.useState(!0),l=t==null?void 0:t.form16Submission,o=!!l,c=!!a&&a.status!=="withdrawn",d=!!a&&a.status==="withdrawn",m=(l==null?void 0:l.validationStatus)??null,p=m==="failed"||m==="mismatch"||m==="duplicate",x=c||m==="success"||m==="manually_approved";u.useEffect(()=>{if(!s){i(!1);return}let f=!1;return(async()=>{try{const b=await yg(s);f||r(b)}catch{f||r(null)}finally{f||i(!1)}})(),()=>{f=!0}},[s]);const h={submit:!0,ocr:o,match:x,success:x,credit:c||d},g={submit:!1,ocr:!1,match:p,success:p,credit:!1};return e.jsxs("div",{className:"space-y-6","data-testid":"form16-workflow-tab",children:[e.jsxs(Z,{className:"border-emerald-200",children:[e.jsx(de,{className:"pb-2",children:e.jsxs(ue,{className:"text-base flex items-center gap-2 text-emerald-800",children:[e.jsx(_t,{className:"w-4 h-4"}),"Form 16 process"]})}),e.jsx(ee,{className:"space-y-4",children:LC.map(f=>{const b=h[f.key],y=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 ${y?"bg-red-100 text-red-600":b?"bg-emerald-100 text-emerald-700":"bg-gray-100 text-gray-400"}`,children:y?e.jsx(At,{className:"w-4 h-4"}):b?e.jsx(Ve,{className:"w-4 h-4"}):e.jsx(Bc,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${y?"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 ud=u.createContext({});function xd(t){const s=u.useRef(null);return s.current===null&&(s.current=t()),s.current}const hd=typeof window<"u",Gg=hd?u.useLayoutEffect:u.useEffect,Wl=u.createContext(null);function pd(t,s){t.indexOf(s)===-1&&t.push(s)}function gd(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const qa=(t,s,a)=>a>s?s:a<t?t:a;let fd=()=>{};const er={},Yg=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Qg(t){return typeof t=="object"&&t!==null}const Kg=t=>/^0[^.\s]+$/u.test(t);function bd(t){let s;return()=>(s===void 0&&(s=t()),s)}const Na=t=>t,$C=(t,s)=>a=>s(t(a)),Si=(...t)=>t.reduce($C),oi=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class jd{constructor(){this.subscriptions=[]}add(s){return pd(this.subscriptions,s),()=>gd(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 Ba=t=>t*1e3,ya=t=>t/1e3;function Xg(t,s){return s?t*(1e3/s):0}const Jg=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,UC=1e-7,BC=12;function zC(t,s,a,r,n){let i,l,o=0;do l=s+(a-s)/2,i=Jg(l,r,n)-t,i>0?a=l:s=l;while(Math.abs(i)>UC&&++o<BC);return l}function Ai(t,s,a,r){if(t===s&&a===r)return Na;const n=i=>zC(i,0,1,t,a);return i=>i===0||i===1?i:Jg(n(i),s,r)}const Zg=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,qg=t=>s=>1-t(1-s),ef=Ai(.33,1.53,.69,.99),yd=qg(ef),tf=Zg(yd),sf=t=>(t*=2)<1?.5*yd(t):.5*(2-Math.pow(2,-10*(t-1))),vd=t=>1-Math.sin(Math.acos(t)),af=qg(vd),rf=Zg(vd),VC=Ai(.42,0,1,1),WC=Ai(0,0,.58,1),nf=Ai(.42,0,.58,1),HC=t=>Array.isArray(t)&&typeof t[0]!="number",lf=t=>Array.isArray(t)&&typeof t[0]=="number",GC={linear:Na,easeIn:VC,easeInOut:nf,easeOut:WC,circIn:vd,circInOut:rf,circOut:af,backIn:yd,backInOut:tf,backOut:ef,anticipate:sf},YC=t=>typeof t=="string",ux=t=>{if(lf(t)){fd(t.length===4);const[s,a,r,n]=t;return Ai(s,a,r,n)}else if(YC(t))return GC[t];return t},Mi=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function QC(t,s){let a=new Set,r=new Set,n=!1,i=!1;const l=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1};function c(m){l.has(m)&&(d.schedule(m),t()),m(o)}const d={schedule:(m,p=!1,x=!1)=>{const g=x&&n?a:r;return p&&l.add(m),g.has(m)||g.add(m),m},cancel:m=>{r.delete(m),l.delete(m)},process:m=>{if(o=m,n){i=!0;return}n=!0,[a,r]=[r,a],a.forEach(c),a.clear(),n=!1,i&&(i=!1,d.process(m))}};return d}const KC=40;function of(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,l=Mi.reduce((v,N)=>(v[N]=QC(i),v),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:m,update:p,preRender:x,render:h,postRender:g}=l,f=()=>{const v=er.useManualTiming?n.timestamp:performance.now();a=!1,er.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(v-n.timestamp,KC),1)),n.timestamp=v,n.isProcessing=!0,o.process(n),c.process(n),d.process(n),m.process(n),p.process(n),x.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:Mi.reduce((v,N)=>{const T=l[N];return v[N]=(A,k=!1,D=!1)=>(a||b(),T.schedule(A,k,D)),v},{}),cancel:v=>{for(let N=0;N<Mi.length;N++)l[Mi[N]].cancel(v)},state:n,steps:l}}const{schedule:es,cancel:fr,state:_s,steps:po}=of(typeof requestAnimationFrame<"u"?requestAnimationFrame:Na,!0);let el;function XC(){el=void 0}const ra={now:()=>(el===void 0&&ra.set(_s.isProcessing||er.useManualTiming?_s.timestamp:performance.now()),el),set:t=>{el=t,queueMicrotask(XC)}},cf=t=>s=>typeof s=="string"&&s.startsWith(t),Nd=cf("--"),JC=cf("var(--"),wd=t=>JC(t)?ZC.test(t.split("/*")[0].trim()):!1,ZC=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Rn={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},ci={...Rn,transform:t=>qa(0,1,t)},Li={...Rn,default:1},Zn=t=>Math.round(t*1e5)/1e5,Cd=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function qC(t){return t==null}const e2=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Sd=(t,s)=>a=>!!(typeof a=="string"&&e2.test(a)&&a.startsWith(t)||s&&!qC(a)&&Object.prototype.hasOwnProperty.call(a,s)),df=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,l,o]=r.match(Cd);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},t2=t=>qa(0,255,t),go={...Rn,transform:t=>Math.round(t2(t))},Br={test:Sd("rgb","red"),parse:df("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+go.transform(t)+", "+go.transform(s)+", "+go.transform(a)+", "+Zn(ci.transform(r))+")"};function s2(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 cc={test:Sd("#"),parse:s2,transform:Br.transform},Ti=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),mr=Ti("deg"),za=Ti("%"),ct=Ti("px"),a2=Ti("vh"),r2=Ti("vw"),xx={...za,parse:t=>za.parse(t)/100,transform:t=>za.transform(t*100)},dn={test:Sd("hsl","hue"),parse:df("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+za.transform(Zn(s))+", "+za.transform(Zn(a))+", "+Zn(ci.transform(r))+")"},fs={test:t=>Br.test(t)||cc.test(t)||dn.test(t),parse:t=>Br.test(t)?Br.parse(t):dn.test(t)?dn.parse(t):cc.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Br.transform(t):dn.transform(t),getAnimatableNone:t=>{const s=fs.parse(t);return s.alpha=0,fs.transform(s)}},n2=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function i2(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(Cd))==null?void 0:s.length)||0)+(((a=t.match(n2))==null?void 0:a.length)||0)>0}const mf="number",uf="color",l2="var",o2="var(",hx="${}",c2=/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 di(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const o=s.replace(c2,c=>(fs.test(c)?(r.color.push(i),n.push(uf),a.push(fs.parse(c))):c.startsWith(o2)?(r.var.push(i),n.push(l2),a.push(c)):(r.number.push(i),n.push(mf),a.push(parseFloat(c))),++i,hx)).split(hx);return{values:a,split:o,indexes:r,types:n}}function xf(t){return di(t).values}function hf(t){const{split:s,types:a}=di(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===mf?i+=Zn(n[l]):o===uf?i+=fs.transform(n[l]):i+=n[l]}return i}}const d2=t=>typeof t=="number"?0:fs.test(t)?fs.getAnimatableNone(t):t;function m2(t){const s=xf(t);return hf(t)(s.map(d2))}const br={test:i2,parse:xf,createTransformer:hf,getAnimatableNone:m2};function fo(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 u2({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=fo(c,o,t+1/3),i=fo(c,o,t),l=fo(c,o,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function pl(t,s){return a=>a>0?s:t}const ns=(t,s,a)=>t+(s-t)*a,bo=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},x2=[cc,Br,dn],h2=t=>x2.find(s=>s.test(t));function px(t){const s=h2(t);if(!s)return!1;let a=s.parse(t);return s===dn&&(a=u2(a)),a}const gx=(t,s)=>{const a=px(t),r=px(s);if(!a||!r)return pl(t,s);const n={...a};return i=>(n.red=bo(a.red,r.red,i),n.green=bo(a.green,r.green,i),n.blue=bo(a.blue,r.blue,i),n.alpha=ns(a.alpha,r.alpha,i),Br.transform(n))},dc=new Set(["none","hidden"]);function p2(t,s){return dc.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function g2(t,s){return a=>ns(t,s,a)}function Ad(t){return typeof t=="number"?g2:typeof t=="string"?wd(t)?pl:fs.test(t)?gx:j2:Array.isArray(t)?pf:typeof t=="object"?fs.test(t)?gx:f2:pl}function pf(t,s){const a=[...t],r=a.length,n=t.map((i,l)=>Ad(i)(i,s[l]));return i=>{for(let l=0;l<r;l++)a[l]=n[l](i);return a}}function f2(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=Ad(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function b2(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 j2=(t,s)=>{const a=br.createTransformer(s),r=di(t),n=di(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?dc.has(t)&&!n.values.length||dc.has(s)&&!r.values.length?p2(t,s):Si(pf(b2(r,n),n.values),a):pl(t,s)};function gf(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?ns(t,s,a):Ad(t)(t,s)}const y2=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>es.update(s,a),stop:()=>fr(s),now:()=>_s.isProcessing?_s.timestamp:ra.now()}},ff=(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)})`},gl=2e4;function Td(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<gl;)s+=a,r=t.next(s);return s>=gl?1/0:s}function v2(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(Td(r),gl);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:ya(n)}}const N2=5;function bf(t,s,a){const r=Math.max(s-N2,0);return Xg(a-t(r),s-r)}const os={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},jo=.001;function w2({duration:t=os.duration,bounce:s=os.bounce,velocity:a=os.velocity,mass:r=os.mass}){let n,i,l=1-s;l=qa(os.minDamping,os.maxDamping,l),t=qa(os.minDuration,os.maxDuration,ya(t)),l<1?(n=d=>{const m=d*l,p=m*t,x=m-a,h=mc(d,l),g=Math.exp(-p);return jo-x/h*g},i=d=>{const p=d*l*t,x=p*a+a,h=Math.pow(l,2)*Math.pow(d,2)*t,g=Math.exp(-p),f=mc(Math.pow(d,2),l);return(-n(d)+jo>0?-1:1)*((x-h)*g)/f}):(n=d=>{const m=Math.exp(-d*t),p=(d-a)*t+1;return-jo+m*p},i=d=>{const m=Math.exp(-d*t),p=(a-d)*(t*t);return m*p});const o=5/t,c=S2(n,i,o);if(t=Ba(t),isNaN(c))return{stiffness:os.stiffness,damping:os.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:t}}}const C2=12;function S2(t,s,a){let r=a;for(let n=1;n<C2;n++)r=r-t(r)/s(r);return r}function mc(t,s){return t*Math.sqrt(1-s*s)}const A2=["duration","bounce"],T2=["stiffness","damping","mass"];function fx(t,s){return s.some(a=>t[a]!==void 0)}function k2(t){let s={velocity:os.velocity,stiffness:os.stiffness,damping:os.damping,mass:os.mass,isResolvedFromDuration:!1,...t};if(!fx(t,T2)&&fx(t,A2))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*qa(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:os.mass,stiffness:n,damping:i}}else{const a=w2(t);s={...s,...a,mass:os.mass},s.isResolvedFromDuration=!0}return s}function fl(t=os.visualDuration,s=os.bounce){const a=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:s}:t;let{restSpeed:r,restDelta:n}=a;const i=a.keyframes[0],l=a.keyframes[a.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:m,duration:p,velocity:x,isResolvedFromDuration:h}=k2({...a,velocity:-ya(a.velocity||0)}),g=x||0,f=d/(2*Math.sqrt(c*m)),b=l-i,y=ya(Math.sqrt(c/m)),j=Math.abs(b)<5;r||(r=j?os.restSpeed.granular:os.restSpeed.default),n||(n=j?os.restDelta.granular:os.restDelta.default);let v;if(f<1){const T=mc(y,f);v=A=>{const k=Math.exp(-f*y*A);return l-k*((g+f*y*b)/T*Math.sin(T*A)+b*Math.cos(T*A))}}else if(f===1)v=T=>l-Math.exp(-y*T)*(b+(g+y*b)*T);else{const T=y*Math.sqrt(f*f-1);v=A=>{const k=Math.exp(-f*y*A),D=Math.min(T*A,300);return l-k*((g+f*y*b)*Math.sinh(D)+T*b*Math.cosh(D))/T}}const N={calculatedDuration:h&&p||null,next:T=>{const A=v(T);if(h)o.done=T>=p;else{let k=T===0?g:0;f<1&&(k=T===0?Ba(g):bf(v,T,A));const D=Math.abs(k)<=r,F=Math.abs(l-A)<=n;o.done=D&&F}return o.value=o.done?l:A,o},toString:()=>{const T=Math.min(Td(N),gl),A=ff(k=>N.next(T*k).value,T,30);return T+"ms "+A},toTransition:()=>{}};return N}fl.applyToOptions=t=>{const s=v2(t,100,fl);return t.ease=s.ease,t.duration=Ba(s.duration),t.type="keyframes",t};function uc({keyframes:t,velocity:s=0,power:a=.8,timeConstant:r=325,bounceDamping:n=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:m}){const p=t[0],x={done:!1,value:p},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,y=l===void 0?b:l(b);y!==b&&(f=y-p);const j=D=>-f*Math.exp(-D/r),v=D=>y+j(D),N=D=>{const F=j(D),w=v(D);x.done=Math.abs(F)<=d,x.value=x.done?y:w};let T,A;const k=D=>{h(x.value)&&(T=D,A=fl({keyframes:[x.value,g(x.value)],velocity:bf(v,D,x.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return k(0),{calculatedDuration:null,next:D=>{let F=!1;return!A&&T===void 0&&(F=!0,N(D),k(D)),T!==void 0&&D>=T?A.next(D-T):(!F&&N(D),x)}}}function D2(t,s,a){const r=[],n=a||er.mix||gf,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]||Na:s;o=Si(c,o)}r.push(o)}return r}function R2(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(fd(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=D2(s,r,n),c=o.length,d=m=>{if(l&&m<t[0])return s[0];let p=0;if(c>1)for(;p<t.length-2&&!(m<t[p+1]);p++);const x=oi(t[p],t[p+1],m);return o[p](x)};return a?m=>d(qa(t[0],t[i-1],m)):d}function I2(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=oi(0,s,r);t.push(ns(a,1,n))}}function F2(t){const s=[0];return I2(s,t.length-1),s}function P2(t,s){return t.map(a=>a*s)}function E2(t,s){return t.map(()=>s||nf).splice(0,t.length-1)}function qn({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=HC(r)?r.map(ux):ux(r),i={done:!1,value:s[0]},l=P2(a&&a.length===s.length?a:F2(s),t),o=R2(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 _2=t=>t!==null;function kd(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(_2),o=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const M2={decay:uc,inertia:uc,tween:qn,keyframes:qn,spring:fl};function jf(t){typeof t.type=="string"&&(t.type=M2[t.type])}class Dd{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 L2=t=>t/100;class Rd extends Dd{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!==ra.now()&&this.tick(ra.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;jf(s);const{type:a=qn,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:l=0}=s;let{keyframes:o}=s;const c=a||qn;c!==qn&&typeof o[0]!="number"&&(this.mixKeyframes=Si(L2,gf(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:x,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 y=this.currentTime-d*(this.playbackSpeed>=0?1:-1),j=this.playbackSpeed>=0?y<0:y>n;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let v=this.currentTime,N=r;if(p){const D=Math.min(this.currentTime,n)/o;let F=Math.floor(D),w=D%1;!w&&D>=1&&(w=1),w===1&&F--,F=Math.min(F,p+1),!!(F%2)&&(x==="reverse"?(w=1-w,h&&(w-=h/o)):x==="mirror"&&(N=l)),v=qa(0,1,w)*o}const T=j?{done:!1,value:m[0]}:N.next(v);i&&(T.value=i(T.value));let{done:A}=T;!j&&c!==null&&(A=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const k=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&A);return k&&g!==uc&&(T.value=kd(m,this.options,b,this.speed)),f&&f(T.value),k&&this.finish(),T}then(s,a){return this.finished.then(s,a)}get duration(){return ya(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ya(s)}get time(){return ya(this.currentTime)}set time(s){var a;s=Ba(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(ra.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=ya(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=y2,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(ra.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 O2(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const zr=t=>t*180/Math.PI,xc=t=>{const s=zr(Math.atan2(t[1],t[0]));return hc(s)},$2={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:xc,rotateZ:xc,skewX:t=>zr(Math.atan(t[1])),skewY:t=>zr(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},hc=t=>(t=t%360,t<0&&(t+=360),t),bx=xc,jx=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),yx=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),U2={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:jx,scaleY:yx,scale:t=>(jx(t)+yx(t))/2,rotateX:t=>hc(zr(Math.atan2(t[6],t[5]))),rotateY:t=>hc(zr(Math.atan2(-t[2],t[0]))),rotateZ:bx,rotate:bx,skewX:t=>zr(Math.atan(t[4])),skewY:t=>zr(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function pc(t){return t.includes("scale")?1:0}function gc(t,s){if(!t||t==="none")return pc(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=U2,n=a;else{const o=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=$2,n=o}if(!n)return pc(s);const i=r[s],l=n[1].split(",").map(z2);return typeof i=="function"?i(l):l[i]}const B2=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return gc(a,s)};function z2(t){return parseFloat(t.trim())}const In=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Fn=new Set(In),vx=t=>t===Rn||t===ct,V2=new Set(["x","y","z"]),W2=In.filter(t=>!V2.has(t));function H2(t){const s=[];return W2.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const Vr={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})=>gc(s,"x"),y:(t,{transform:s})=>gc(s,"y")};Vr.translateX=Vr.x;Vr.translateY=Vr.y;const Wr=new Set;let fc=!1,bc=!1,jc=!1;function yf(){if(bc){const t=Array.from(Wr).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=H2(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)})}bc=!1,fc=!1,Wr.forEach(t=>t.complete(jc)),Wr.clear()}function vf(){Wr.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(bc=!0)})}function G2(){jc=!0,vf(),yf(),jc=!1}class Id{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?(Wr.add(this),fc||(fc=!0,es.read(vf),es.resolveKeyframes(yf))):(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])}O2(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),Wr.delete(this)}cancel(){this.state==="scheduled"&&(Wr.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Y2=t=>t.startsWith("--");function Q2(t,s,a){Y2(s)?t.style.setProperty(s,a):t.style[s]=a}const K2=bd(()=>window.ScrollTimeline!==void 0),X2={};function J2(t,s){const a=bd(t);return()=>X2[s]??a()}const Nf=J2(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Kn=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,Nx={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Kn([0,.65,.55,1]),circOut:Kn([.55,0,1,.45]),backIn:Kn([.31,.01,.66,-.59]),backOut:Kn([.33,1.53,.69,.99])};function wf(t,s){if(t)return typeof t=="function"?Nf()?ff(t,s):"ease-out":lf(t)?Kn(t):Array.isArray(t)?t.map(a=>wf(a,s)||Nx.easeOut):Nx[t]}function Z2(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=wf(o,n);Array.isArray(p)&&(m.easing=p);const x={delay:r,duration:n,easing:Array.isArray(p)?"linear":p,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(x.pseudoElement=d),t.animate(m,x)}function Cf(t){return typeof t=="function"&&"applyToOptions"in t}function q2({type:t,...s}){return Cf(t)&&Nf()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class eS extends Dd{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,fd(typeof s.type!="string");const d=q2(s);this.animation=Z2(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=kd(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(m):Q2(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 ya(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ya(s)}get time(){return ya(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=Ba(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&&K2()?(this.animation.timeline=s,Na):a(this)}}const Sf={anticipate:sf,backInOut:tf,circInOut:rf};function tS(t){return t in Sf}function sS(t){typeof t.ease=="string"&&tS(t.ease)&&(t.ease=Sf[t.ease])}const wx=10;class aS extends eS{constructor(s){sS(s),jf(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=Ba(this.finishedTime??this.time);a.setWithVelocity(o.sample(c-wx).value,o.sample(c).value,wx),o.stop()}}const Cx=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(br.test(t)||t==="0")&&!t.startsWith("url("));function rS(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 nS(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=Cx(n,s),o=Cx(i,s);return!l||!o?!1:rS(t)||(a==="spring"||Cf(a))&&r}function yc(t){t.duration=0,t.type="keyframes"}const iS=new Set(["opacity","clipPath","filter","transform"]),lS=bd(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function oS(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 lS()&&a&&iS.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&l!=="inertia"}const cS=40;class dS extends Dd{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=ra.now();const x={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)||Id;this.keyframeResolver=new h(o,(f,b,y)=>this.onKeyframesResolved(f,b,x,!y),c,d,m),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(s,a,r,n){this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:m}=r;this.resolvedAt=ra.now(),nS(s,i,l,o)||((er.instantAnimations||!c)&&(m==null||m(kd(s,r,a))),s[0]=s[s.length-1],yc(r),r.repeat=0);const x={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>cS?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},h=!d&&oS(x)?new aS({...x,element:x.motionValue.owner.current}):new Rd(x);h.finished.then(()=>this.notifyFinished()).catch(Na),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(),G2()),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 mS=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function uS(t){const s=mS.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Af(t,s,a=1){const[r,n]=uS(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const l=i.trim();return Yg(l)?parseFloat(l):l}return wd(n)?Af(n,s,a+1):n}function Fd(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const Tf=new Set(["width","height","top","left","right","bottom",...In]),xS={test:t=>t==="auto",parse:t=>t},kf=t=>s=>s.test(t),Df=[Rn,ct,za,mr,r2,a2,xS],Sx=t=>Df.find(kf(t));function hS(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Kg(t):!0}const pS=new Set(["brightness","contrast","saturate","opacity"]);function gS(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(Cd)||[];if(!r)return t;const n=a.replace(r,"");let i=pS.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const fS=/\b([a-z-]*)\(.*?\)/gu,vc={...br,getAnimatableNone:t=>{const s=t.match(fS);return s?s.map(gS).join(" "):t}},Ax={...Rn,transform:Math.round},bS={rotate:mr,rotateX:mr,rotateY:mr,rotateZ:mr,scale:Li,scaleX:Li,scaleY:Li,scaleZ:Li,skew:mr,skewX:mr,skewY:mr,distance:ct,translateX:ct,translateY:ct,translateZ:ct,x:ct,y:ct,z:ct,perspective:ct,transformPerspective:ct,opacity:ci,originX:xx,originY:xx,originZ:ct},Pd={borderWidth:ct,borderTopWidth:ct,borderRightWidth:ct,borderBottomWidth:ct,borderLeftWidth:ct,borderRadius:ct,radius:ct,borderTopLeftRadius:ct,borderTopRightRadius:ct,borderBottomRightRadius:ct,borderBottomLeftRadius:ct,width:ct,maxWidth:ct,height:ct,maxHeight:ct,top:ct,right:ct,bottom:ct,left:ct,padding:ct,paddingTop:ct,paddingRight:ct,paddingBottom:ct,paddingLeft:ct,margin:ct,marginTop:ct,marginRight:ct,marginBottom:ct,marginLeft:ct,backgroundPositionX:ct,backgroundPositionY:ct,...bS,zIndex:Ax,fillOpacity:ci,strokeOpacity:ci,numOctaves:Ax},jS={...Pd,color:fs,backgroundColor:fs,outlineColor:fs,fill:fs,stroke:fs,borderColor:fs,borderTopColor:fs,borderRightColor:fs,borderBottomColor:fs,borderLeftColor:fs,filter:vc,WebkitFilter:vc},Rf=t=>jS[t];function If(t,s){let a=Rf(t);return a!==vc&&(a=br),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const yS=new Set(["auto","none","0"]);function vS(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!yS.has(i)&&di(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=If(a,n)}class NS extends Id{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(),wd(d))){const m=Af(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!Tf.has(r)||s.length!==2)return;const[n,i]=s,l=Sx(n),o=Sx(i);if(l!==o)if(vx(l)&&vx(o))for(let c=0;c<s.length;c++){const d=s[c];typeof d=="string"&&(s[c]=parseFloat(d))}else Vr[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||hS(s[n]))&&r.push(n);r.length&&vS(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=Vr[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]=Vr[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 wS(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 Ff=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function Pf(t){return Qg(t)&&"offsetHeight"in t}const Tx=30,CS=t=>!isNaN(parseFloat(t));class SS{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=ra.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=ra.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=CS(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 jd);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=ra.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>Tx)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,Tx);return Xg(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 wn(t,s){return new SS(t,s)}const{schedule:Ed}=of(queueMicrotask,!1),Fa={x:!1,y:!1};function Ef(){return Fa.x||Fa.y}function AS(t){return t==="x"||t==="y"?Fa[t]?null:(Fa[t]=!0,()=>{Fa[t]=!1}):Fa.x||Fa.y?null:(Fa.x=Fa.y=!0,()=>{Fa.x=Fa.y=!1})}function _f(t,s){const a=wS(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function kx(t){return!(t.pointerType==="touch"||Ef())}function TS(t,s,a={}){const[r,n,i]=_f(t,a),l=o=>{if(!kx(o))return;const{target:c}=o,d=s(c,o);if(typeof d!="function"||!c)return;const m=p=>{kx(p)&&(d(p),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(o=>{o.addEventListener("pointerenter",l,n)}),i}const Mf=(t,s)=>s?t===s?!0:Mf(t,s.parentElement):!1,_d=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,kS=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function DS(t){return kS.has(t.tagName)||t.tabIndex!==-1}const tl=new WeakSet;function Dx(t){return s=>{s.key==="Enter"&&t(s)}}function yo(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const RS=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=Dx(()=>{if(tl.has(a))return;yo(a,"down");const n=Dx(()=>{yo(a,"up")}),i=()=>yo(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 _d(t)&&!Ef()}function IS(t,s,a={}){const[r,n,i]=_f(t,a),l=o=>{const c=o.currentTarget;if(!Rx(o))return;tl.add(c);const d=s(c,o),m=(h,g)=>{window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",x),tl.has(c)&&tl.delete(c),Rx(h)&&typeof d=="function"&&d(h,{success:g})},p=h=>{m(h,c===window||c===document||a.useGlobalTarget||Mf(c,h.target))},x=h=>{m(h,!1)};window.addEventListener("pointerup",p,n),window.addEventListener("pointercancel",x,n)};return r.forEach(o=>{(a.useGlobalTarget?window:o).addEventListener("pointerdown",l,n),Pf(o)&&(o.addEventListener("focus",d=>RS(d,n)),!DS(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function Lf(t){return Qg(t)&&"ownerSVGElement"in t}function FS(t){return Lf(t)&&t.tagName==="svg"}const Bs=t=>!!(t&&t.getVelocity),PS=[...Df,fs,br],ES=t=>PS.find(kf(t)),Md=u.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function Ix(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function _S(...t){return s=>{let a=!1;const r=t.map(n=>{const i=Ix(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():Ix(t[n],null)}}}}function MS(...t){return u.useCallback(_S(...t),t)}class LS extends u.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=Pf(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 OS({children:t,isPresent:s,anchorX:a,root:r}){const n=u.useId(),i=u.useRef(null),l=u.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:o}=u.useContext(Md),c=MS(i,t==null?void 0:t.ref);return u.useInsertionEffect(()=>{const{width:d,height:m,top:p,left:x,right:h}=l.current;if(s||!i.current||!d||!m)return;const g=a==="left"?`left: ${x}`:`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(LS,{isPresent:s,childRef:i,sizeRef:l,children:u.cloneElement(t,{ref:c})})}const $S=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=xd(US),m=u.useId();let p=!0,x=u.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&&(x={...x}),u.useMemo(()=>{d.forEach((h,g)=>d.set(g,!1))},[a]),u.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(OS,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(Wl.Provider,{value:x,children:t})};function US(){return new Map}function Of(t=!0){const s=u.useContext(Wl);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=u.useId();u.useEffect(()=>{if(t)return n(i)},[t]);const l=u.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const Oi=t=>t.key||"";function Fx(t){const s=[];return u.Children.forEach(t,a=>{u.isValidElement(a)&&s.push(a)}),s}const Hl=({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]=Of(l),p=u.useMemo(()=>Fx(t),[t]),x=l&&!d?[]:p.map(Oi),h=u.useRef(!0),g=u.useRef(p),f=xd(()=>new Map),[b,y]=u.useState(p),[j,v]=u.useState(p);Gg(()=>{h.current=!1,g.current=p;for(let A=0;A<j.length;A++){const k=Oi(j[A]);x.includes(k)?f.delete(k):f.get(k)!==!0&&f.set(k,!1)}},[j,x.length,x.join("-")]);const N=[];if(p!==b){let A=[...p];for(let k=0;k<j.length;k++){const D=j[k],F=Oi(D);x.includes(F)||(A.splice(k,0,D),N.push(D))}return i==="wait"&&N.length&&(A=N),v(Fx(A)),y(p),null}const{forceRender:T}=u.useContext(ud);return e.jsx(e.Fragment,{children:j.map(A=>{const k=Oi(A),D=l&&!d?!1:p===j||x.includes(k),F=()=>{if(f.has(k))f.set(k,!0);else return;let w=!0;f.forEach(L=>{L||(w=!1)}),w&&(T==null||T(),v(g.current),l&&(m==null||m()),r&&r())};return e.jsx($S,{isPresent:D,initial:!h.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:D?void 0:F,anchorX:o,children:A},k)})})},$f=u.createContext({strict:!1}),Px={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"]},Cn={};for(const t in Px)Cn[t]={isEnabled:s=>Px[t].some(a=>!!s[a])};function BS(t){for(const s in t)Cn[s]={...Cn[s],...t[s]}}const zS=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 bl(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||zS.has(t)}let Uf=t=>!bl(t);function VS(t){typeof t=="function"&&(Uf=s=>s.startsWith("on")?!bl(s):t(s))}try{VS(require("@emotion/is-prop-valid").default)}catch{}function WS(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(Uf(n)||a===!0&&bl(n)||!s&&!bl(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Gl=u.createContext({});function Yl(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function mi(t){return typeof t=="string"||Array.isArray(t)}const Ld=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Od=["initial",...Ld];function Ql(t){return Yl(t.animate)||Od.some(s=>mi(t[s]))}function Bf(t){return!!(Ql(t)||t.variants)}function HS(t,s){if(Ql(t)){const{initial:a,animate:r}=t;return{initial:a===!1||mi(a)?a:void 0,animate:mi(r)?r:void 0}}return t.inherit!==!1?s:{}}function GS(t){const{initial:s,animate:a}=HS(t,u.useContext(Gl));return u.useMemo(()=>({initial:s,animate:a}),[Ex(s),Ex(a)])}function Ex(t){return Array.isArray(t)?t.join(" "):t}const ui={};function YS(t){for(const s in t)ui[s]=t[s],Nd(s)&&(ui[s].isCSSVariable=!0)}function zf(t,{layout:s,layoutId:a}){return Fn.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!ui[t]||t==="opacity")}const QS={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},KS=In.length;function XS(t,s,a){let r="",n=!0;for(let i=0;i<KS;i++){const l=In[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=Ff(o,Pd[l]);if(!c){n=!1;const m=QS[l]||l;r+=`${m}(${d}) `}a&&(s[l]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function $d(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(Fn.has(c)){l=!0;continue}else if(Nd(c)){n[c]=d;continue}else{const m=Ff(d,Pd[c]);c.startsWith("origin")?(o=!0,i[c]=m):r[c]=m}}if(s.transform||(l||a?r.transform=XS(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 Ud=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Vf(t,s,a){for(const r in s)!Bs(s[r])&&!zf(r,a)&&(t[r]=s[r])}function JS({transformTemplate:t},s){return u.useMemo(()=>{const a=Ud();return $d(a,s,t),Object.assign({},a.vars,a.style)},[s])}function ZS(t,s){const a=t.style||{},r={};return Vf(r,a,t),Object.assign(r,JS(t,s)),r}function qS(t,s){const a={},r=ZS(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 eA={offset:"stroke-dashoffset",array:"stroke-dasharray"},tA={offset:"strokeDashoffset",array:"strokeDasharray"};function sA(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?eA:tA;t[i.offset]=ct.transform(-r);const l=ct.transform(s),o=ct.transform(a);t[i.array]=`${l} ${o}`}function Wf(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if($d(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:p,style:x}=t;p.transform&&(x.transform=p.transform,delete p.transform),(x.transform||p.transformOrigin)&&(x.transformOrigin=p.transformOrigin??"50% 50%",delete p.transformOrigin),x.transform&&(x.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete p.transformBox),s!==void 0&&(p.x=s),a!==void 0&&(p.y=a),r!==void 0&&(p.scale=r),n!==void 0&&sA(p,n,i,l,!1)}const Hf=()=>({...Ud(),attrs:{}}),Gf=t=>typeof t=="string"&&t.toLowerCase()==="svg";function aA(t,s,a,r){const n=u.useMemo(()=>{const i=Hf();return Wf(i,s,Gf(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};Vf(i,t.style,t),n.style={...i,...n.style}}return n}const rA=["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 Bd(t){return typeof t!="string"||t.includes("-")?!1:!!(rA.indexOf(t)>-1||/[A-Z]/u.test(t))}function nA(t,s,a,{latestValues:r},n,i=!1){const o=(Bd(t)?aA:qS)(s,r,n,t),c=WS(s,typeof t=="string",i),d=t!==u.Fragment?{...c,...o,ref:a}:{},{children:m}=s,p=u.useMemo(()=>Bs(m)?m.get():m,[m]);return u.createElement(t,{...d,children:p})}function _x(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function zd(t,s,a,r){if(typeof s=="function"){const[n,i]=_x(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]=_x(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function sl(t){return Bs(t)?t.get():t}function iA({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:lA(a,r,n,t),renderState:s()}}function lA(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=sl(i[x]);let{initial:l,animate:o}=t;const c=Ql(t),d=Bf(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"&&!Yl(p)){const x=Array.isArray(p)?p:[p];for(let h=0;h<x.length;h++){const g=zd(t,x[h]);if(g){const{transitionEnd:f,transition:b,...y}=g;for(const j in y){let v=y[j];if(Array.isArray(v)){const N=m?v.length-1:0;v=v[N]}v!==null&&(n[j]=v)}for(const j in f)n[j]=f[j]}}}return n}const Yf=t=>(s,a)=>{const r=u.useContext(Gl),n=u.useContext(Wl),i=()=>iA(t,s,r,n);return a?i():xd(i)};function Vd(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(Bs(r[l])||s.style&&Bs(s.style[l])||zf(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const oA=Yf({scrapeMotionValuesFromProps:Vd,createRenderState:Ud});function Qf(t,s,a){const r=Vd(t,s,a);for(const n in t)if(Bs(t[n])||Bs(s[n])){const i=In.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const cA=Yf({scrapeMotionValuesFromProps:Qf,createRenderState:Hf}),dA=Symbol.for("motionComponentSymbol");function mn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function mA(t,s,a){return u.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):mn(a)&&(a.current=r))},[s])}const Wd=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),uA="framerAppearId",Kf="data-"+Wd(uA),Xf=u.createContext({});function xA(t,s,a,r,n){var f,b;const{visualElement:i}=u.useContext(Gl),l=u.useContext($f),o=u.useContext(Wl),c=u.useContext(Md).reducedMotion,d=u.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=u.useContext(Xf);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&hA(d.current,a,n,p);const x=u.useRef(!1);u.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const h=a[Kf],g=u.useRef(!!h&&!((f=window.MotionHandoffIsComplete)!=null&&f.call(window,h))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,h)));return Gg(()=>{m&&(x.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),u.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,h)}),g.current=!1),m.enteringChildren=void 0)}),m}function hA(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:Jf(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&mn(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function Jf(t){if(t)return t.options.allowProjection!==!1?t.projection:Jf(t.parent)}function vo(t,{forwardMotionProps:s=!1}={},a,r){a&&BS(a);const n=Bd(t)?cA:oA;function i(o,c){let d;const m={...u.useContext(Md),...o,layoutId:pA(o)},{isStatic:p}=m,x=GS(o),h=n(o,p);if(!p&&hd){gA();const g=fA(m);d=g.MeasureLayout,x.visualElement=xA(t,h,m,r,g.ProjectionNode)}return e.jsxs(Gl.Provider,{value:x,children:[d&&x.visualElement?e.jsx(d,{visualElement:x.visualElement,...m}):null,nA(t,o,mA(h,x.visualElement,c),h,p,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=u.forwardRef(i);return l[dA]=t,l}function pA({layoutId:t}){const s=u.useContext(ud).id;return s&&t!==void 0?s+"-"+t:t}function gA(t,s){u.useContext($f).strict}function fA(t){const{drag:s,layout:a}=Cn;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 bA(t,s){if(typeof Proxy>"u")return vo;const a=new Map,r=(i,l)=>vo(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,vo(l,void 0,t,s)),a.get(l))})}function Zf({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function jA({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function yA(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 No(t){return t===void 0||t===1}function Nc({scale:t,scaleX:s,scaleY:a}){return!No(t)||!No(s)||!No(a)}function Mr(t){return Nc(t)||qf(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function qf(t){return Mx(t.x)||Mx(t.y)}function Mx(t){return t&&t!=="0%"}function jl(t,s,a){const r=t-a,n=s*r;return a+n}function Lx(t,s,a,r,n){return n!==void 0&&(t=jl(t,n,r)),jl(t,a,r)+s}function wc(t,s=0,a=1,r,n){t.min=Lx(t.min,s,a,r,n),t.max=Lx(t.max,s,a,r,n)}function e0(t,{x:s,y:a}){wc(t.x,s.translate,s.scale,s.originPoint),wc(t.y,a.translate,a.scale,a.originPoint)}const Ox=.999999999999,$x=1.0000000000001;function vA(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&&xn(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),l&&(s.x*=l.x.scale,s.y*=l.y.scale,e0(t,l)),r&&Mr(i.latestValues)&&xn(t,i.latestValues))}s.x<$x&&s.x>Ox&&(s.x=1),s.y<$x&&s.y>Ox&&(s.y=1)}function un(t,s){t.min=t.min+s,t.max=t.max+s}function Ux(t,s,a,r,n=.5){const i=ns(t.min,t.max,n);wc(t,s,a,i,r)}function xn(t,s){Ux(t.x,s.x,s.scaleX,s.scale,s.originX),Ux(t.y,s.y,s.scaleY,s.scale,s.originY)}function t0(t,s){return Zf(yA(t.getBoundingClientRect(),s))}function NA(t,s,a){const r=t0(t,a),{scroll:n}=s;return n&&(un(r.x,n.offset.x),un(r.y,n.offset.y)),r}const Bx=()=>({translate:0,scale:1,origin:0,originPoint:0}),hn=()=>({x:Bx(),y:Bx()}),zx=()=>({min:0,max:0}),hs=()=>({x:zx(),y:zx()}),Cc={current:null},s0={current:!1};function wA(){if(s0.current=!0,!!hd)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>Cc.current=t.matches;t.addEventListener("change",s),s()}else Cc.current=!1}const CA=new WeakMap;function SA(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,wn(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,wn(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Vx=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class AA{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=Id,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const x=ra.now();this.renderScheduledAt<x&&(this.renderScheduledAt=x,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=Ql(a),this.isVariantNode=Bf(a),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(s&&s.current);const{willChange:m,...p}=this.scrapeMotionValuesFromProps(a,{},this);for(const x in p){const h=p[x];c[x]!==void 0&&Bs(h)&&h.set(c[x])}}mount(s){var a;this.current=s,CA.set(s,this),this.projection&&!this.projection.instance&&this.projection.mount(s),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((r,n)=>this.bindToMotionValue(n,r)),s0.current||wA(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Cc.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),fr(this.notifyUpdate),fr(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=Fn.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 Cn){const a=Cn[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<Vx.length;r++){const n=Vx[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=SA(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=wn(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"&&(Yg(r)||Kg(r))?r=parseFloat(r):!ES(r)&&br.test(a)&&(r=If(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=zd(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 jd),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){Ed.render(this.render)}}class a0 extends AA{constructor(){super(...arguments),this.KeyframeResolver=NS}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 r0(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 TA(t){return window.getComputedStyle(t)}class kA extends a0{constructor(){super(...arguments),this.type="html",this.renderInstance=r0}readValueFromInstance(s,a){var r;if(Fn.has(a))return(r=this.projection)!=null&&r.isProjecting?pc(a):B2(s,a);{const n=TA(s),i=(Nd(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return t0(s,a)}build(s,a,r){$d(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return Vd(s,a,r)}}const n0=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 DA(t,s,a,r){r0(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(n0.has(n)?n:Wd(n),s.attrs[n])}class RA extends a0{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=hs}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Fn.has(a)){const r=Rf(a);return r&&r.default||0}return a=n0.has(a)?a:Wd(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return Qf(s,a,r)}build(s,a,r){Wf(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){DA(s,a,r,n)}mount(s){this.isSVGTag=Gf(s.tagName),super.mount(s)}}const IA=(t,s)=>Bd(t)?new RA(s):new kA(s,{allowProjection:t!==u.Fragment});function vn(t,s,a){const r=t.getProps();return zd(r,s,a!==void 0?a:r.custom,t)}const Sc=t=>Array.isArray(t);function FA(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,wn(a))}function PA(t){return Sc(t)?t[t.length-1]||0:t}function EA(t,s){const a=vn(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=PA(i[l]);FA(t,l,o)}}function _A(t){return!!(Bs(t)&&t.add)}function Ac(t,s){const a=t.getValue("willChange");if(_A(a))return a.add(s);if(!a&&er.WillChange){const r=new er.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function i0(t){return t.props[Kf]}const MA=t=>t!==null;function LA(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(MA),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const OA={type:"spring",stiffness:500,damping:25,restSpeed:10},$A=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),UA={type:"keyframes",duration:.8},BA={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},zA=(t,{keyframes:s})=>s.length>2?UA:Fn.has(t)?t.startsWith("scale")?$A(s[1]):OA:BA;function VA({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 Hd=(t,s,a,r={},n,i)=>l=>{const o=Fd(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Ba(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:x=>{s.set(x),o.onUpdate&&o.onUpdate(x)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};VA(o)||Object.assign(m,zA(t,m)),m.duration&&(m.duration=Ba(m.duration)),m.repeatDelay&&(m.repeatDelay=Ba(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let p=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(yc(m),m.delay===0&&(p=!0)),(er.instantAnimations||er.skipAnimations)&&(p=!0,yc(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,p&&!i&&s.get()!==void 0){const x=LA(m.keyframes,o);if(x!==void 0){es.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Rd(m):new dS(m)};function WA({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function l0(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const p=t.getValue(m,t.latestValues[m]??null),x=o[m];if(x===void 0||d&&WA(d,m))continue;const h={delay:a,...Fd(i||{},m)},g=p.get();if(g!==void 0&&!p.isAnimating&&!Array.isArray(x)&&x===g&&!h.velocity)continue;let f=!1;if(window.MotionHandoffAnimation){const y=i0(t);if(y){const j=window.MotionHandoffAnimation(y,m,es);j!==null&&(h.startTime=j,f=!0)}}Ac(t,m),p.start(Hd(m,p,x,t.shouldReduceMotion&&Tf.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 o0(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 Tc(t,s,a={}){var c;const r=vn(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(l0(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:p,staggerDirection:x}=n;return HA(t,s,d,m,p,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function HA(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(Tc(c,s,{...l,delay:a+(typeof r=="function"?0:r)+o0(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function GA(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>Tc(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=Tc(t,s,a);else{const n=typeof s=="function"?vn(t,s,a.custom):s;r=Promise.all(l0(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function c0(t,s){if(!Array.isArray(s))return!1;const a=s.length;if(a!==t.length)return!1;for(let r=0;r<a;r++)if(s[r]!==t[r])return!1;return!0}const YA=Od.length;function d0(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?d0(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<YA;a++){const r=Od[a],n=t.props[r];(mi(n)||n===!1)&&(s[r]=n)}return s}const QA=[...Ld].reverse(),KA=Ld.length;function XA(t){return s=>Promise.all(s.map(({animation:a,options:r})=>GA(t,a,r)))}function JA(t){let s=XA(t),a=Wx(),r=!0;const n=c=>(d,m)=>{var x;const p=vn(t,m,c==="exit"?(x=t.presenceContext)==null?void 0:x.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=d0(t.parent)||{},p=[],x=new Set;let h={},g=1/0;for(let b=0;b<KA;b++){const y=QA[b],j=a[y],v=d[y]!==void 0?d[y]:m[y],N=mi(v),T=y===c?j.isActive:null;T===!1&&(g=b);let A=v===m[y]&&v!==d[y]&&N;if(A&&r&&t.manuallyAnimateOnMount&&(A=!1),j.protectedKeys={...h},!j.isActive&&T===null||!v&&!j.prevProp||Yl(v)||typeof v=="boolean")continue;const k=ZA(j.prevProp,v);let D=k||y===c&&j.isActive&&!A&&N||b>g&&N,F=!1;const w=Array.isArray(v)?v:[v];let L=w.reduce(n(y),{});T===!1&&(L={});const{prevResolvedValues:_={}}=j,W={..._,...L},I=R=>{D=!0,x.has(R)&&(F=!0,x.delete(R)),j.needsAnimating[R]=!0;const C=t.getValue(R);C&&(C.liveStyle=!1)};for(const R in W){const C=L[R],H=_[R];if(h.hasOwnProperty(R))continue;let z=!1;Sc(C)&&Sc(H)?z=!c0(C,H):z=C!==H,z?C!=null?I(R):x.add(R):C!==void 0&&x.has(R)?I(R):j.protectedKeys[R]=!0}j.prevProp=v,j.prevResolvedValues=L,j.isActive&&(h={...h,...L}),r&&t.blockInitialAnimation&&(D=!1);const $=A&&k;D&&(!$||F)&&p.push(...w.map(R=>{const C={type:y};if(typeof R=="string"&&r&&!$&&t.manuallyAnimateOnMount&&t.parent){const{parent:H}=t,z=vn(H,R);if(H.enteringChildren&&z){const{delayChildren:P}=z.transition||{};C.delay=o0(H.enteringChildren,t,P)}}return{animation:R,options:C}}))}if(x.size){const b={};if(typeof d.initial!="boolean"){const y=vn(t,Array.isArray(d.initial)?d.initial[0]:d.initial);y&&y.transition&&(b.transition=y.transition)}x.forEach(y=>{const j=t.getBaseTarget(y),v=t.getValue(y);v&&(v.liveStyle=!0),b[y]=j??null}),p.push({animation:b})}let f=!!p.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(f=!1),r=!1,f?s(p):Promise.resolve()}function o(c,d){var p;if(a[c].isActive===d)return Promise.resolve();(p=t.variantChildren)==null||p.forEach(x=>{var h;return(h=x.animationState)==null?void 0:h.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const x in a)a[x].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Wx()}}}function ZA(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!c0(s,t):!1}function Fr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Wx(){return{animate:Fr(!0),whileInView:Fr(),whileHover:Fr(),whileTap:Fr(),whileDrag:Fr(),whileFocus:Fr(),exit:Fr()}}class Nr{constructor(s){this.isMounted=!1,this.node=s}update(){}}class qA extends Nr{constructor(s){super(s),s.animationState||(s.animationState=JA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Yl(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 e5=0;class t5 extends Nr{constructor(){super(...arguments),this.id=e5++}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 s5={animation:{Feature:qA},exit:{Feature:t5}};function xi(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function ki(t){return{point:{x:t.pageX,y:t.pageY}}}const a5=t=>s=>_d(s)&&t(s,ki(s));function ei(t,s,a,r){return xi(t,s,a5(a),r)}const m0=1e-4,r5=1-m0,n5=1+m0,u0=.01,i5=0-u0,l5=0+u0;function Ys(t){return t.max-t.min}function o5(t,s,a){return Math.abs(t-s)<=a}function Hx(t,s,a,r=.5){t.origin=r,t.originPoint=ns(s.min,s.max,t.origin),t.scale=Ys(a)/Ys(s),t.translate=ns(a.min,a.max,t.origin)-t.originPoint,(t.scale>=r5&&t.scale<=n5||isNaN(t.scale))&&(t.scale=1),(t.translate>=i5&&t.translate<=l5||isNaN(t.translate))&&(t.translate=0)}function ti(t,s,a,r){Hx(t.x,s.x,a.x,r?r.originX:void 0),Hx(t.y,s.y,a.y,r?r.originY:void 0)}function Gx(t,s,a){t.min=a.min+s.min,t.max=t.min+Ys(s)}function c5(t,s,a){Gx(t.x,s.x,a.x),Gx(t.y,s.y,a.y)}function Yx(t,s,a){t.min=s.min-a.min,t.max=t.min+Ys(s)}function si(t,s,a){Yx(t.x,s.x,a.x),Yx(t.y,s.y,a.y)}function ja(t){return[t("x"),t("y")]}const x0=({current:t})=>t?t.ownerDocument.defaultView:null,Qx=(t,s)=>Math.abs(t-s);function d5(t,s){const a=Qx(t.x,s.x),r=Qx(t.y,s.y);return Math.sqrt(a**2+r**2)}class h0{constructor(s,a,{transformPagePoint:r,contextWindow:n=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const x=Co(this.lastMoveEventInfo,this.history),h=this.startEvent!==null,g=d5(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!h&&!g)return;const{point:f}=x,{timestamp:b}=_s;this.history.push({...f,timestamp:b});const{onStart:y,onMove:j}=this.handlers;h||(y&&y(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),j&&j(this.lastMoveEvent,x)},this.handlePointerMove=(x,h)=>{this.lastMoveEvent=x,this.lastMoveEventInfo=wo(h,this.transformPagePoint),es.update(this.updatePoint,!0)},this.handlePointerUp=(x,h)=>{this.end();const{onEnd:g,onSessionEnd:f,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Co(x.type==="pointercancel"?this.lastMoveEventInfo:wo(h,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,y),f&&f(x,y)},!_d(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=ki(s),c=wo(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=_s;this.history=[{...d,timestamp:m}];const{onSessionStart:p}=a;p&&p(s,Co(c,this.history)),this.removeListeners=Si(ei(this.contextWindow,"pointermove",this.handlePointerMove),ei(this.contextWindow,"pointerup",this.handlePointerUp),ei(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),fr(this.updatePoint)}}function wo(t,s){return s?{point:s(t.point)}:t}function Kx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function Co({point:t},s){return{point:t,delta:Kx(t,p0(s)),offset:Kx(t,m5(s)),velocity:u5(s,.1)}}function m5(t){return t[0]}function p0(t){return t[t.length-1]}function u5(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=p0(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>Ba(s)));)a--;if(!r)return{x:0,y:0};const i=ya(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 x5(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 Xx(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 h5(t,{top:s,left:a,bottom:r,right:n}){return{x:Xx(t.x,a,n),y:Xx(t.y,s,r)}}function Jx(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 p5(t,s){return{x:Jx(t.x,s.x),y:Jx(t.y,s.y)}}function g5(t,s){let a=.5;const r=Ys(t),n=Ys(s);return n>r?a=oi(s.min,s.max-r,t.min):r>n&&(a=oi(t.min,t.max-n,s.min)),qa(0,1,a)}function f5(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 kc=.35;function b5(t=kc){return t===!1?t=0:t===!0&&(t=kc),{x:Zx(t,"left","right"),y:Zx(t,"top","bottom")}}function Zx(t,s,a){return{min:qx(t,s),max:qx(t,a)}}function qx(t,s){return typeof t=="number"?t:t[s]||0}const j5=new WeakMap;class y5{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:x}=this.getProps();x?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(ki(p).point)},l=(p,x)=>{const{drag:h,dragPropagation:g,onDragStart:f}=this.getProps();if(h&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=AS(h),!this.openDragLock))return;this.latestPointerEvent=p,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ja(y=>{let j=this.getAxisMotionValue(y).get()||0;if(za.test(j)){const{projection:v}=this.visualElement;if(v&&v.layout){const N=v.layout.layoutBox[y];N&&(j=Ys(N)*(parseFloat(j)/100))}}this.originPoint[y]=j}),f&&es.postRender(()=>f(p,x)),Ac(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},o=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x;const{dragPropagation:h,dragDirectionLock:g,onDirectionLock:f,onDrag:b}=this.getProps();if(!h&&!this.openDragLock)return;const{offset:y}=x;if(g&&this.currentDirection===null){this.currentDirection=v5(y),this.currentDirection!==null&&f&&f(this.currentDirection);return}this.updateAxis("x",x.point,y),this.updateAxis("y",x.point,y),this.visualElement.render(),b&&b(p,x)},c=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x,this.stop(p,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>ja(p=>{var x;return this.getAnimationState(p)==="paused"&&((x=this.getAxisMotionValue(p).animation)==null?void 0:x.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new h0(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:x0(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||!$i(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=x5(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&&mn(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=h5(r.layoutBox,s):this.constraints=!1,this.elastic=b5(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&ja(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=f5(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!mn(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=NA(r,n.root,this.visualElement.getTransformPagePoint());let l=p5(n.layout.layoutBox,i);if(a){const o=a(jA(l));this.hasMutatedConstraints=!!o,o&&(l=Zf(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=ja(m=>{if(!$i(m,a,this.currentDirection))return;let p=c&&c[m]||{};l&&(p={min:0,max:0});const x=n?200:1e6,h=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:x,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 Ac(this.visualElement,s),r.start(Hd(s,r,0,a,this.visualElement,!1))}stopAnimation(){ja(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){ja(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){ja(a=>{const{drag:r}=this.getProps();if(!$i(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(!mn(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};ja(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=g5({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(),ja(l=>{if(!$i(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;j5.set(this.visualElement,this);const s=this.visualElement.current,a=ei(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();mn(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=xi(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(ja(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=kc,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function $i(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function v5(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class N5 extends Nr{constructor(s){super(s),this.removeGroupControls=Na,this.removeListeners=Na,this.controls=new y5(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Na}unmount(){this.removeGroupControls(),this.removeListeners()}}const eh=t=>(s,a)=>{t&&es.postRender(()=>t(s,a))};class w5 extends Nr{constructor(){super(...arguments),this.removePointerDownListener=Na}onPointerDown(s){this.session=new h0(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:x0(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:eh(s),onStart:eh(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&es.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=ei(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 al={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function th(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const Bn={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(ct.test(t))t=parseFloat(t);else return t;const a=th(t,s.target.x),r=th(t,s.target.y);return`${a}% ${r}%`}},C5={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=br.parse(t);if(n.length>5)return r;const i=br.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 So=!1;class S5 extends u.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;YS(A5),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),So&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),al.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,So=!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(),Ed.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;So=!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 g0(t){const[s,a]=Of(),r=u.useContext(ud);return e.jsx(S5,{...t,layoutGroup:r,switchLayoutGroup:u.useContext(Xf),isPresent:s,safeToRemove:a})}const A5={borderRadius:{...Bn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Bn,borderTopRightRadius:Bn,borderBottomLeftRadius:Bn,borderBottomRightRadius:Bn,boxShadow:C5};function T5(t,s,a){const r=Bs(t)?t:wn(t);return r.start(Hd("",r,s,a)),r.animation}const k5=(t,s)=>t.depth-s.depth;class D5{constructor(){this.children=[],this.isDirty=!1}add(s){pd(this.children,s),this.isDirty=!0}remove(s){gd(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(k5),this.isDirty=!1,this.children.forEach(s)}}function R5(t,s){const a=ra.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(fr(r),t(i-s))};return es.setup(r,!0),()=>fr(r)}const f0=["TopLeft","TopRight","BottomLeft","BottomRight"],I5=f0.length,sh=t=>typeof t=="string"?parseFloat(t):t,ah=t=>typeof t=="number"||ct.test(t);function F5(t,s,a,r,n,i){n?(t.opacity=ns(0,a.opacity??1,P5(r)),t.opacityExit=ns(s.opacity??1,0,E5(r))):i&&(t.opacity=ns(s.opacity??1,a.opacity??1,r));for(let l=0;l<I5;l++){const o=`border${f0[l]}Radius`;let c=rh(s,o),d=rh(a,o);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||ah(c)===ah(d)?(t[o]=Math.max(ns(sh(c),sh(d),r),0),(za.test(d)||za.test(c))&&(t[o]+="%")):t[o]=d}(s.rotate||a.rotate)&&(t.rotate=ns(s.rotate||0,a.rotate||0,r))}function rh(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const P5=b0(0,.5,af),E5=b0(.5,.95,Na);function b0(t,s,a){return r=>r<t?0:r>s?1:a(oi(t,s,r))}function nh(t,s){t.min=s.min,t.max=s.max}function ba(t,s){nh(t.x,s.x),nh(t.y,s.y)}function ih(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function lh(t,s,a,r,n){return t-=s,t=jl(t,1/a,r),n!==void 0&&(t=jl(t,1/n,r)),t}function _5(t,s=0,a=1,r=.5,n,i=t,l=t){if(za.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=lh(t.min,s,a,o,n),t.max=lh(t.max,s,a,o,n)}function oh(t,s,[a,r,n],i,l){_5(t,s[a],s[r],s[n],s.scale,i,l)}const M5=["x","scaleX","originX"],L5=["y","scaleY","originY"];function ch(t,s,a,r){oh(t.x,s,M5,a?a.x:void 0,r?r.x:void 0),oh(t.y,s,L5,a?a.y:void 0,r?r.y:void 0)}function dh(t){return t.translate===0&&t.scale===1}function j0(t){return dh(t.x)&&dh(t.y)}function mh(t,s){return t.min===s.min&&t.max===s.max}function O5(t,s){return mh(t.x,s.x)&&mh(t.y,s.y)}function uh(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function y0(t,s){return uh(t.x,s.x)&&uh(t.y,s.y)}function xh(t){return Ys(t.x)/Ys(t.y)}function hh(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class $5{constructor(){this.members=[]}add(s){pd(this.members,s),s.scheduleRender()}remove(s){if(gd(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 U5(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:p,rotateY:x,skewX:h,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),p&&(r+=`rotateX(${p}deg) `),x&&(r+=`rotateY(${x}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 Ao=["","X","Y","Z"],B5=1e3;let z5=0;function To(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function v0(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=i0(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&&v0(r)}function N0({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=z5++,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(H5),this.nodes.forEach(K5),this.nodes.forEach(X5),this.nodes.forEach(G5)},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 D5)}addEventListener(l,o){return this.eventHandlers.has(l)||this.eventHandlers.set(l,new jd),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=Lf(l)&&!FS(l),this.instance=l;const{layoutId:o,layout:c,visualElement:d}=this.options;if(d&&!d.current&&d.mount(l),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||o)&&(this.isLayoutDirty=!0),t){let m,p=0;const x=()=>this.root.updateBlockedByResize=!1;es.read(()=>{p=window.innerWidth}),t(l,()=>{const h=window.innerWidth;h!==p&&(p=h,this.root.updateBlockedByResize=!0,m&&m(),m=R5(x,250),al.hasAnimatedSinceResize&&(al.hasAnimatedSinceResize=!1,this.nodes.forEach(fh)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:p,hasRelativeLayoutChanged:x,layout:h})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||tT,{onLayoutAnimationStart:f,onLayoutAnimationComplete:b}=d.getProps(),y=!this.targetLayout||!y0(this.targetLayout,h),j=!p&&x;if(this.options.layoutRoot||this.resumeFrom||j||p&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const v={...Fd(g,"layout"),onPlay:f,onComplete:b};(d.shouldReduceMotion||this.options.layoutRoot)&&(v.delay=0,v.type=!1),this.startAnimation(v),this.setAnimationOrigin(m,j)}else p||fh(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(),fr(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(J5),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&&v0(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(ph);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(gh);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Q5),this.nodes.forEach(V5),this.nodes.forEach(W5)):this.nodes.forEach(gh),this.clearAllSnapshots();const o=ra.now();_s.delta=qa(0,1e3/60,o-_s.timestamp),_s.timestamp=o,_s.isProcessing=!0,po.update.process(_s),po.preRender.process(_s),po.render.process(_s),_s.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Ed.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Y5),this.sharedNodes.forEach(Z5)}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&&!Ys(this.snapshot.measuredBox.x)&&!Ys(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&&!j0(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,m=d!==this.prevTransformTemplateValue;l&&this.instance&&(o||Mr(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)),sT(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(aT))){const{scroll:m}=this.root;m&&(un(o.x,m.offset.x),un(o.y,m.offset.y))}return o}removeElementScroll(l){var c;const o=hs();if(ba(o,l),(c=this.scroll)!=null&&c.wasRoot)return o;for(let d=0;d<this.path.length;d++){const m=this.path[d],{scroll:p,options:x}=m;m!==this.root&&p&&x.layoutScroll&&(p.wasRoot&&ba(o,l),un(o.x,p.offset.x),un(o.y,p.offset.y))}return o}applyTransform(l,o=!1){const c=hs();ba(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&&xn(c,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),Mr(m.latestValues)&&xn(c,m.latestValues)}return Mr(this.latestValues)&&xn(c,this.latestValues),c}removeTransform(l){const o=hs();ba(o,l);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!Mr(d.latestValues))continue;Nc(d.latestValues)&&d.updateSnapshot();const m=hs(),p=d.measurePageBox();ba(m,p),ch(o,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return Mr(this.latestValues)&&ch(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!==_s.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(l=!1){var x;const o=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=o.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=o.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=o.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==o;if(!(l||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(x=this.parent)!=null&&x.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:m,layoutId:p}=this.options;if(!(!this.layout||!(m||p))){if(this.resolvedRelativeTargetAt=_s.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(),si(this.relativeTargetOrigin,this.layout.layoutBox,h.layout.layoutBox),ba(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(),c5(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):ba(this.target,this.layout.layoutBox),e0(this.target,this.targetDelta)):ba(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(),si(this.relativeTargetOrigin,this.target,h.target),ba(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Nc(this.parent.latestValues)||qf(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===_s.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;ba(this.layoutCorrected,this.layout.layoutBox);const p=this.treeScale.x,x=this.treeScale.y;vA(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():(ih(this.prevProjectionDelta.x,this.projectionDelta.x),ih(this.prevProjectionDelta.y,this.projectionDelta.y)),ti(this.projectionDelta,this.layoutCorrected,h,this.latestValues),(this.treeScale.x!==p||this.treeScale.y!==x||!hh(this.projectionDelta.x,this.prevProjectionDelta.x)||!hh(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=hn(),this.projectionDelta=hn(),this.projectionDeltaWithTransform=hn()}setAnimationOrigin(l,o=!1){const c=this.snapshot,d=c?c.latestValues:{},m={...this.latestValues},p=hn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!o;const x=hs(),h=c?c.source:void 0,g=this.layout?this.layout.source:void 0,f=h!==g,b=this.getStack(),y=!b||b.members.length<=1,j=!!(f&&!y&&this.options.crossfade===!0&&!this.path.some(eT));this.animationProgress=0;let v;this.mixTargetDelta=N=>{const T=N/1e3;bh(p.x,l.x,T),bh(p.y,l.y,T),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(si(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),q5(this.relativeTarget,this.relativeTargetOrigin,x,T),v&&O5(this.relativeTarget,v)&&(this.isProjectionDirty=!1),v||(v=hs()),ba(v,this.relativeTarget)),f&&(this.animationValues=m,F5(m,d,this.latestValues,T,j,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=T},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(fr(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=es.update(()=>{al.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=wn(0)),this.currentAnimation=T5(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(B5),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:m}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&w0(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||hs();const p=Ys(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+p;const x=Ys(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}ba(o,c),xn(o,m),ti(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new $5),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&&To("z",l,d,this.animationValues);for(let m=0;m<Ao.length;m++)To(`rotate${Ao[m]}`,l,d,this.animationValues),To(`skew${Ao[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=sl(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=sl(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!Mr(this.latestValues)&&(l.transform=c?c({},""):"none",this.hasProjected=!1);return}l.visibility="";const m=d.animationValues||d.latestValues;this.applyTransformsToTarget();let p=U5(this.projectionDeltaWithTransform,this.treeScale,m);c&&(p=c(m,p)),l.transform=p;const{x,y:h}=this.projectionDelta;l.transformOrigin=`${x.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 ui){if(m[g]===void 0)continue;const{correct:f,applyTo:b,isCSSVariable:y}=ui[g],j=p==="none"?m[g]:f(m[g],d);if(b){const v=b.length;for(let N=0;N<v;N++)l[b[N]]=j}else y?this.options.visualElement.renderState.vars[g]=j:l[g]=j}this.options.layoutId&&(l.pointerEvents=d===this?sl(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(ph),this.root.sharedNodes.clear()}}}function V5(t){t.updateLayout()}function W5(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"?ja(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],h=Ys(x);x.min=r[p].min,x.max=x.min+h}):w0(i,s.layoutBox,r)&&ja(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],h=Ys(r[p]);x.max=x.min+h,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[p].max=t.relativeTarget[p].min+h)});const o=hn();ti(o,r,s.layoutBox);const c=hn();l?ti(c,t.applyTransform(n,!0),s.measuredBox):ti(c,r,s.layoutBox);const d=!j0(o);let m=!1;if(!t.resumeFrom){const p=t.getClosestProjectingParent();if(p&&!p.resumeFrom){const{snapshot:x,layout:h}=p;if(x&&h){const g=hs();si(g,s.layoutBox,x.layoutBox);const f=hs();si(f,r,h.layoutBox),y0(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 H5(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 G5(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Y5(t){t.clearSnapshot()}function ph(t){t.clearMeasurements()}function gh(t){t.isLayoutDirty=!1}function Q5(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function fh(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function K5(t){t.resolveTargetDelta()}function X5(t){t.calcProjection()}function J5(t){t.resetSkewAndRotation()}function Z5(t){t.removeLeadSnapshot()}function bh(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 jh(t,s,a,r){t.min=ns(s.min,a.min,r),t.max=ns(s.max,a.max,r)}function q5(t,s,a,r){jh(t.x,s.x,a.x,r),jh(t.y,s.y,a.y,r)}function eT(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const tT={duration:.45,ease:[.4,0,.1,1]},yh=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),vh=yh("applewebkit/")&&!yh("chrome/")?Math.round:Na;function Nh(t){t.min=vh(t.min),t.max=vh(t.max)}function sT(t){Nh(t.x),Nh(t.y)}function w0(t,s,a){return t==="position"||t==="preserve-aspect"&&!o5(xh(s),xh(a),.2)}function aT(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const rT=N0({attachResizeListener:(t,s)=>xi(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ko={current:void 0},C0=N0({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!ko.current){const t=new rT({});t.mount(window),t.setOptions({layoutScroll:!0}),ko.current=t}return ko.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),nT={pan:{Feature:w5},drag:{Feature:N5,ProjectionNode:C0,MeasureLayout:g0}};function wh(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,ki(s)))}class iT extends Nr{mount(){const{current:s}=this.node;s&&(this.unmount=TS(s,(a,r)=>(wh(this.node,r,"Start"),n=>wh(this.node,n,"End"))))}unmount(){}}class lT extends Nr{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=Si(xi(this.node.current,"focus",()=>this.onFocus()),xi(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ch(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,ki(s)))}class oT extends Nr{mount(){const{current:s}=this.node;s&&(this.unmount=IS(s,(a,r)=>(Ch(this.node,r,"Start"),(n,{success:i})=>Ch(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Dc=new WeakMap,Do=new WeakMap,cT=t=>{const s=Dc.get(t.target);s&&s(t)},dT=t=>{t.forEach(cT)};function mT({root:t,...s}){const a=t||document;Do.has(a)||Do.set(a,{});const r=Do.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(dT,{root:t,...s})),r[n]}function uT(t,s,a){const r=mT(s);return Dc.set(t,a),r.observe(t),()=>{Dc.delete(t),r.unobserve(t)}}const xT={some:0,all:1};class hT extends Nr{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:xT[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:p}=this.node.getProps(),x=d?m:p;x&&x(c)};return uT(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(pT(s,a))&&this.startObserver()}unmount(){}}function pT({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const gT={inView:{Feature:hT},tap:{Feature:oT},focus:{Feature:lT},hover:{Feature:iT}},fT={layout:{ProjectionNode:C0,MeasureLayout:g0}},bT={...s5,...gT,...nT,...fT},Gt=bA(bT,IA),zn=[{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:Et,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:Ip,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 jT({open:t,onClose:s,onSelectTemplate:a}){var d,m,p;const[r,n]=u.useState(null),[i,l]=u.useState(!1);u.useEffect(()=>{const x=nt.getUserData();l((x==null?void 0:x.jobTitle)==="Dealer")},[]);const o=x=>{if(i)return;const h=zn.find(g=>g.id===x);h!=null&&h.disabled||n(x)},c=()=>{r&&(a(r),s())};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{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(ut,{className:"sr-only",children:"Select a Template"}),e.jsx(Mt,{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(Cs,{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(Gt.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(Dl,{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:zn.map((x,h)=>{const g=x.icon,f=r===x.id,b=i||x.disabled;return e.jsx(Gt.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(x.id),children:[e.jsxs(de,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${x.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),f&&e.jsx(Gt.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(Ha,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ue,{className:"text-xl mb-2",children:x.name}),e.jsx(Te,{className:"text-sm leading-relaxed",children:x.description}),i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsx(Ze,{className:"w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Not accessible for Dealers"})]}),x.comingSoon&&!i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-blue-50 border border-blue-200 rounded-lg",children:[e.jsx(Ze,{className:"w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-blue-800 font-semibold",children:"Coming Soon"})]})]})]}),e.jsxs(ee,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(oe,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Zt,{}),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:x.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:[x.steps," steps"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx("p",{className:"text-xs text-gray-500 font-semibold",children:"Key Features:"}),e.jsxs("div",{className:"space-y-1.5",children:[x.features.slice(0,3).map((y,j)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(Ve,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:y})]},j)),x.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",x.features.length-3," more features"]})]})]})]})]})},x.id)})}),e.jsxs(Gt.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(O,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(O,{onClick:c,disabled:!r||i||((d=zn.find(x=>x.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=zn.find(x=>x.id===r))!=null&&m.disabled)?"bg-blue-600 hover:bg-blue-700":"bg-gray-400 cursor-not-allowed"}`,children:["Continue with Template",e.jsx(ys,{className:"w-4 h-4"})]})]}),e.jsx(Hl,{children:r&&e.jsx(Gt.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=zn.find(x=>x.id===r))==null?void 0:p.name})]})})})]})})]})})}function qr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const c="https://reflow-uat.royalenfield.com/".trim().replace(/\/$/,""),[d,m]=u.useState(100),[p,x]=u.useState(0),[h,g]=u.useState(null),[f,b]=u.useState(!1),[y,j]=u.useState(null),v=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),N=s.toLowerCase().includes("pdf"),T=v||N;u.useEffect(()=>{if(!l||!T||!a){g(null);return}return(async()=>{b(!0),j(null);try{let W=a;a.startsWith("/")&&!a.startsWith("//")&&(W=`${c}${a}`);const $=await fetch(W,{headers:{Accept:N?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!$.ok){const C=await $.text().catch(()=>"");throw new Error(`Failed to load file: ${$.status} ${$.statusText}. ${C}`)}const M=await $.blob();if(M.size===0)throw new Error("File is empty or could not be loaded");N&&!M.type.includes("pdf")&&M.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${M.type}`);const R=window.URL.createObjectURL(M);g(R)}catch(L){console.error("Failed to load file for preview:",L),j(L instanceof Error?L.message:"Failed to load file for preview")}finally{b(!1)}})(),()=>{h&&(window.URL.revokeObjectURL(h),g(null))}},[l,a,T,N]);const A=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},k=()=>m(w=>Math.min(w+25,200)),D=()=>m(w=>Math.max(w-25,50)),F=()=>x(w=>(w+90)%360);return e.jsx(ht,{open:l,onOpenChange:o,children:e.jsx(mt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(pt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(wt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ut,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`• ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[v&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(O,{variant:"ghost",size:"sm",onClick:D,disabled:d<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(ly,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[d,"%"]}),e.jsx(O,{variant:"ghost",size:"sm",onClick:k,disabled:d>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(oy,{className:"h-4 w-4"})}),e.jsx(O,{variant:"ghost",size:"sm",onClick:F,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(Fp,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(O,{variant:"outline",size:"sm",onClick:A,className:"gap-2 h-9",children:[e.jsx(kt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})]})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:f?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx(ze,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):y?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(vt,{className:"w-10 h-10 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Failed"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:y}),i&&n&&e.jsxs(O,{onClick:A,className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",t]})]}):T&&h?e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:h,alt:t,style:{transform:`scale(${d/100}) rotate(${p}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),N&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:h,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(wt,{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(O,{onClick:A,className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function Di({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Mt,{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(O,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const pa=async t=>{const s=t?{category:t}:{};return(await Se.get("/users/configurations",{params:s})).data.data},Kl=async t=>{const s=t?{category:t}:{};return(await Se.get("/admin/configurations",{params:s})).data.data},Gs=async(t,s)=>{await Se.put(`/admin/configurations/${t}`,{configValue:s})},yT=async t=>{await Se.post(`/admin/configurations/${t}/reset`)},vT=async()=>{const t=await Se.get("/admin/form16-config");return t.data.data??t.data},NT=async t=>{await Se.put("/admin/form16-config",t)},wT=async()=>{const t=await Se.get("/admin/cpc-csd-config");return t.data.data??t.data},CT=async t=>{await Se.put("/admin/cpc-csd-config",t)},ST=async t=>{const s=t?{year:t}:{};return(await Se.get("/admin/holidays",{params:s})).data.data},AT=async t=>(await Se.post("/admin/holidays",t)).data.data,TT=async(t,s)=>(await Se.put(`/admin/holidays/${t}`,s)).data.data,kT=async t=>{await Se.delete(`/admin/holidays/${t}`)},DT=async()=>(await Se.get("/config/activity-types")).data.data,RT=async t=>{const s={activeOnly:t.toString()};return(await Se.get("/admin/activity-types",{params:s})).data.data},IT=async t=>(await Se.post("/admin/activity-types",t)).data.data,FT=async(t,s)=>(await Se.put(`/admin/activity-types/${t}`,s)).data.data,PT=async t=>{await Se.delete(`/admin/activity-types/${t}`)},ET={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 _T(t,s,a){const[r,n]=u.useState(ET),[i,l]=u.useState(null),[o,c]=u.useState(t),[d,m]=u.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[p,x]=u.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[h,g]=u.useState([]);return u.useEffect(()=>{(async()=>{var y;try{const j=await pa("DOCUMENT_POLICY"),v={};j.forEach(L=>{v[L.configKey]=L.configValue});const N=parseInt(v.MAX_FILE_SIZE_MB||"10"),A=(v.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(L=>L.trim().toLowerCase());x({maxFileSizeMB:N,allowedFileTypes:A});const k=await pa("SYSTEM_SETTINGS"),D=await pa("WORKFLOW_SHARING"),F=[...k,...D],w={};F.forEach(L=>{w[L.configKey]=L.configValue}),m({maxApprovalLevels:parseInt(w.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(w.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((y=w.ALLOW_ADD_SPECTATOR)==null?void 0:y.toLowerCase())==="true",maxSpectators:parseInt(w.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(j){console.error("Failed to load policies:",j)}})()},[]),u.useEffect(()=>{if(!t||!s)return;let b=!0;return(async()=>{try{c(!0);const y=await Ms(s);if(!b||!y)return;const j=y.workflow||{},v=Array.isArray(y.approvals)?y.approvals:[],N=Array.isArray(y.participants)?y.participants:[],T=Array.isArray(y.documents)?y.documents.filter(_=>!_.isDeleted):[];g(T);const A=(j.priority||"").toString().toLowerCase(),k={standard:"standard",express:"express"},D=j.templateType==="TEMPLATE"?"existing-template":"custom",F=a.find(_=>_.id===D)||a[0]||null;l(F);const w=v.sort((_,W)=>(_.levelNumber||0)-(W.levelNumber||0)).map(_=>{const W=Number(_.tatHours||24),I=Math.floor(W/24),$=W%24;return{id:_.approverId||`temp-${_.levelNumber}`,name:_.approverName||_.approverEmail||"",email:_.approverEmail||"",role:_.levelName||`Level ${_.levelNumber}`,department:"",avatar:(_.approverName||_.approverEmail||"XX").substring(0,2).toUpperCase(),level:_.levelNumber||1,canClose:!1,tat:I>0?I:$,tatType:I>0?"days":"hours",userId:_.approverId}}),L=N.filter(_=>(_.participantType||_.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(_.userEmail||_.user_email||_.email):!1).map((_,W)=>{const I=_.userId||_.user_id||_.id,$=_.userName||_.user_name||_.name||"",M=_.userEmail||_.user_email||_.email||"",C=($||M||"XX").split(" ").map(H=>H[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:I||`spectator-${s}-${W}-${Date.now()}`,userId:I,name:$||M||"Spectator",email:M,role:"Spectator",department:_.department||"",avatar:C,level:1,canClose:!1}});n(_=>({..._,template:D,title:j.title||"",description:j.description||"",priority:k[A]||"standard",approvers:w,approverCount:w.length||1,spectators:L,maxLevel:Math.max(...w.map(W=>W.level||1),1)}))}catch(y){console.error("Failed to load draft:",y)}finally{b&&c(!1)}})(),()=>{b=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(b,y)=>{n(j=>({...j,[b]:y}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:p,existingDocuments:h,setExistingDocuments:g}}const Sh=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function MT(t,s,a){const[r,n]=u.useState(t?2:1),i=Sh.length,l=p=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p),o=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(p=>{if(!p||!p.email||!l(p.email))return!1;if(!p.userId)return!0;const x=p.tatType||"hours";return x==="hours"?p.tat&&p.tat>0&&p.tat<=720:x==="days"?p.tat&&p.tat>0&&p.tat<=30:!1});case 4:return!0;case 5:return!0;case 6:return!0;default:return!1}};return{currentStep:r,setCurrentStep:n,totalSteps:i,stepNames:Sh,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 LT(){const[t,s]=u.useState({open:!1,type:"error",email:"",message:""}),[a,r]=u.useState({open:!1,violations:[]}),[n,i]=u.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(x,h,g="")=>{s({open:!0,type:x,email:h,message:g})},closeValidationModal:()=>{s(x=>({...x,open:!1}))},openPolicyViolationModal:x=>{r({open:!0,violations:x})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:x=>{i({open:!0,errors:x})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function OT(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function $T(t,s,a){var n;const r=OT(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 UT(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return $T(a,n,n===s)})}function Ah(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=UT(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 BT(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 kh(t,s){return{id:(await dd(t,s||[],"SUPPORTING")).id}}async function Dh(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await NC(t,s,a||[],r):await vC(t,s)}function zT({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=u.useState(!1),[m,p]=u.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var f,b;if(c||m)return;const g=BT(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const y=Th(t,n,r,!1);await Dh(l,y,a,r),Q.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been submitted and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const y=Ah(t,s,n,!1),j=await kh(y,a);Q.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been created and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:j.id,template:s})}}catch(y){console.error("Failed to submit workflow:",y),Q.error("Failed to Submit Request",{description:((b=(f=y==null?void 0:y.response)==null?void 0:f.data)==null?void 0:b.message)||(y==null?void 0:y.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 Dh(l,b,a,r),Q.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=Ah(t,s,n,!0),y=await kh(b,a);Q.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:y.id,template:s})}}catch(b){console.error("Failed to save draft:",b),Q.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 Sa(t,s=10,a="default"){return await Se.get("/users/search",{params:{q:t,limit:s,source:a}})}async function wa(t){var a;const s=await Se.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function VT(t,s){return await Se.post("/admin/users/assign-role",{email:t,role:s})}async function WT(t,s){return await Se.put(`/admin/users/${t}/role`,{role:s})}async function HT(t,s=1,a=10){return await Se.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function GT(){return await Se.get("/admin/users/role-statistics")}async function YT(t){var a;const s=await Se.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function QT(){var s,a;return((a=(s=(await Se.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const ua={searchUsers:Sa,getUserById:YT,ensureUserExists:wa,assignRole:VT,updateUserRole:WT,getUsersByRole:HT,getRoleStatistics:GT,getAllUsers:QT};async function KT(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 Sa(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 wa({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 XT(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 KT(l,s);if(!o.success)return{success:!1,error:o.error};try{const m=(((n=(await Sa(l.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const p=await wa({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 JT({selectedTemplate:t,setSelectedTemplate:s,updateFormData:a,formData:r,currentStep:n,isStepValid:i,wizardNextStep:l,wizardPrevStep:o,user:c,openValidationModal:d,systemPolicy:m,onPolicyViolation:p,onSubmit:x}){const h=gs(),[g,f]=u.useState(!1),[b,y]=u.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 F=new Date;F.setDate(F.getDate()+D.suggestedSLA),a("slaEndDate",F),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"):x&&x({templateType:D})},nextStep:async()=>{var D;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){f(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&p){const L=r.approverCount||1;if(L>m.maxApprovalLevels){p([{type:"Maximum Approval Levels Exceeded",message:`The request has ${L} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:L,maxValue:m.maxApprovalLevels}]);return}}const F=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",w=await XT(r.approvers,F);if(!w.success&&w.error){d(w.error.type,w.error.email,w.error.message);return}w.validatedApprovers&&a("approvers",w.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(D,F)=>{if(F){const w=D.documentId||D.document_id||"";y({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:Dn(w),fileSize:Number(D.fileSize||D.file_size||0),documentId:w})}else{const w=URL.createObjectURL(D);y({fileName:D.name,fileType:D.type||"application/octet-stream",fileUrl:w,fileSize:D.size,file:D})}},closePreview:()=>{b!=null&&b.fileUrl&&(b!=null&&b.file)&&URL.revokeObjectURL(b.fileUrl),y(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:Rl,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:Ee,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let Hr=null;const Ih=()=>Hr,ZT=async t=>{const a=(await Se.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 Hr&&Hr.push(r),r},Xl=async()=>{var r;const a=(((r=(await Se.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 Hr=a,a},qT=async(t,s)=>{const r=(await Se.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 Hr&&(Hr=Hr.map(i=>i.id===t?n:i)),n};function S0({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(Ha,{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 ek({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(O,{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(Cs,{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(O,{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(O,{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(Pp,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(O,{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(ys,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const Fh=t=>{switch(t){case"high":return e.jsx(Ma,{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(Ks,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ts,{className:"w-4 h-4 text-gray-600"})}};function tk({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=u.useState("main"),l=gs(),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(Gt.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(O,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(Cs,{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(cy,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):c.map(m=>{var g;const x=m.id==="admin-templates-category",h=(s==null?void 0:s.id)===m.id;return e.jsx(Gt.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":x?"border-blue-200 bg-blue-50/30 hover:border-blue-400 hover:shadow-lg cursor-pointer":"border-gray-200 hover:border-blue-300 hover:shadow-lg cursor-pointer"}`,onClick:()=>o(m),"data-testid":`template-card-${m.id}-clickable`,children:[e.jsxs(de,{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||x?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${h||x?"text-blue-600":"text-gray-600"}`})}),h&&e.jsx(Gt.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(Ha,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsx(ue,{className:"text-xl","data-testid":`template-card-${m.id}-name`,children:m.name}),!1]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),Fh(m.priority)]})]})]}),e.jsxs(ee,{className:"pt-0 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed line-clamp-2","data-testid":`template-card-${m.id}-description`,children:m.description}),!x&&e.jsxs(e.Fragment,{children:[e.jsx(Zt,{}),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"]})]})]})]}),x&&e.jsx("div",{className:"pt-2",children:e.jsx("p",{className:"text-xs text-blue-600 font-medium flex items-center gap-1",children:"Click to browse templates →"})})]})]})},m.id)})}),e.jsx(Hl,{children:s&&e.jsx(Gt.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(de,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Jr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-sla",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Suggested SLA"}),e.jsxs("p",{className:"text-blue-700 mt-1",children:[s.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-priority",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[Fh(s.priority),e.jsx("span",{className:"text-blue-700 capitalize",children:s.priority})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-duration",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Estimated Duration"}),e.jsx("p",{className:"text-blue-700 mt-1",children:s.estimatedTime})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-approvers",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,p)=>e.jsx(oe,{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 _e({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:$e("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground flex h-9 w-full min-w-0 rounded-md border border-gray-400 bg-white px-3 py-1 text-base text-gray-900 transition-all outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","hover:border-gray-500","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...a})}function sk({className:t,...s}){return e.jsx(bj,{"data-slot":"radio-group",className:$e("grid gap-3",t),...s})}function Ph({className:t,...s}){return e.jsx(jj,{"data-slot":"radio-group-item",className:$e("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(yj,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Bc,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function ak({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(Gt.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(Ee,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(re,{htmlFor:"title",className:"text-base font-semibold",children:"Request Title *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Be specific and descriptive. This will be visible to all participants."}),e.jsx(_e,{id:"title",placeholder:"e.g., Approval on new office location",value:t.title,onChange:r=>a("title",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-title-input"})]}),e.jsxs("div",{"data-testid":"basic-information-description-field",children:[e.jsx(re,{htmlFor:"description",className:"text-base font-semibold",children:"Detailed Description *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Ci,{value:t.description||"",onChange:r=>a("description",r),placeholder:"Provide comprehensive details about your request including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px","data-testid":"basic-information-description-textarea"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6","data-testid":"basic-information-priority-section",children:e.jsxs("div",{"data-testid":"basic-information-priority-field",children:[e.jsx(re,{className:"text-base font-semibold",children:"Priority Level *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"select priority for your request"}),e.jsxs(sk,{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(Ph,{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(kl,{className:"w-4 h-4 text-red-600"}),e.jsx(re,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(oe,{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(Ph,{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(re,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(oe,{variant:"secondary",className:"text-xs",children:"DEFAULT"})]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Includes working days in TAT - regular processing timeline"})]})]})]})]})}),((s==null?void 0:s.fields.amount)||(s==null?void 0:s.fields.vendor)||(s==null?void 0:s.fields.timeline)||(s==null?void 0:s.fields.impact))&&e.jsxs("div",{className:"border-t pt-6","data-testid":"basic-information-additional-details",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Additional Details"}),e.jsxs("div",{className:"space-y-6",children:[(s==null?void 0:s.fields.amount)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-testid":"basic-information-amount-field",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(_e,{id:"amount",placeholder:"Enter amount",value:t.amount,onChange:r=>a("amount",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-amount-input"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(He,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Ye,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Qe,{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(re,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(_e,{id:"vendor",placeholder:"Enter vendor or supplier name",value:t.vendor,onChange:r=>a("vendor",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-vendor-input"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{"data-testid":"basic-information-cost-center-field",children:[e.jsx(re,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(_e,{id:"costCenter",placeholder:"e.g., Marketing, IT, Operations",value:t.costCenter,onChange:r=>a("costCenter",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-cost-center-input"})]}),e.jsxs("div",{"data-testid":"basic-information-project-field",children:[e.jsx(re,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(_e,{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 A0(){const[t,s]=u.useState([]),[a,r]=u.useState(!1),n=u.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 Sa(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 wa({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 T0(){const[t,s]=u.useState({}),[a,r]=u.useState({}),n=u.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 Sa(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(x=>({...x,[o]:[]}))}finally{r(p=>({...p,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function rk({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var p;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=T0();u.useEffect(()=>{const x=t.approverCount||1,h=t.approvers||[];if(h.length<x){const g=[...h];for(let f=h.length;f<x;f++)g[f]||(g[f]={email:"",name:"",level:f+1,tat:""});s("approvers",g)}else h.length>x&&s("approvers",h.slice(0,x))},[t.approverCount,s]);const d=(x,h)=>{var y,j,v,N,T;const g=[...t.approvers],b=((y=g[x])==null?void 0:y.email)!==h;if(g[x]={...g[x],email:h,level:x+1,userId:b||(j=g[x])==null?void 0:j.userId,name:b||(v=g[x])==null?void 0:v.name,department:b||(N=g[x])==null?void 0:N.department,avatar:b||(T=g[x])==null?void 0:T.avatar},s("approvers",g),!h||!h.startsWith("@")||h.length<2){c(x);return}o(x,h,10)},m=async(x,h)=>{var g,f;try{if((g=t.approvers)==null?void 0:g.some((N,T)=>{var A,k;return T!==x&&(N.userId===h.userId||((A=N.email)==null?void 0:A.toLowerCase())===((k=h.email)==null?void 0:k.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(N=>{var T,A;return N.userId===h.userId||((T=N.email)==null?void 0:T.toLowerCase())===((A=h.email)==null?void 0:A.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 j=await wa({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[x]={...v[x],email:h.email,name:h.displayName||[h.firstName,h.lastName].filter(Boolean).join(" "),userId:j.userId,level:x+1},s("approvers",v),c(x)}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(Gt.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(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(hr,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(Te,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(ee,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(re,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(O,{type:"button",variant:"outline",size:"sm",onClick:()=>{const x=t.approverCount||1,h=Math.max(1,x-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(zc,{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(O,{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(is,{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(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(bs,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(Te,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx("div",{className:"p-4 rounded-lg border-2 border-blue-200 bg-blue-50","data-testid":"approval-workflow-initiator-card",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:e.jsx(Wt,{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(oe,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-sm text-blue-700",children:"Creates and submits the request"})]})]})}),Array.from({length:t.approverCount||1},(x,h)=>{var y,j;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(oe,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(re,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),b.email&&b.userId&&e.jsxs(oe,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Ve,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(_e,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",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]||(((y=i[h])==null?void 0:y.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:l[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:(j=i[h])==null?void 0:j.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(re,{htmlFor:`tat-${g}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(_e,{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 N=[...t.approvers];N[h]={...N[h],tat:parseInt(v.target.value)||"",level:g,tatType:b.tatType||"hours"},s("approvers",N)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(He,{value:b.tatType||"hours",onValueChange:v=>{const N=[...t.approvers];N[h]={...N[h],tatType:v,level:g,tat:""},s("approvers",N)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(Ye,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Qe,{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(Jr,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," → ",Array.from({length:t.approverCount||1},(x,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 x=((g=t.approvers)==null?void 0:g.reduce((f,b)=>{const y=Number(b.tat||0);return(b.tatType||"hours")==="days"?f+y:f+y/24},0))||0,h=Math.ceil(x);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((x,h)=>{const g=Number(x.tat||0),b=(x.tatType||"hours")==="days"?g*24:g;return g?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",h+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[b," ",b===1?"hour":"hours"]})]})},h):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((f,b)=>{const y=Number(b.tat||0);return(b.tatType||"hours")==="days"?f+y*24:f+y},0))||0,h=Math.ceil(x/8);return x===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[x,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children: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 nk({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=u.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=A0(),p=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},x=async g=>{var f,b;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(v=>{var N,T;return v.userId===g.userId||((N=v.email)==null?void 0:N.toLowerCase())===((T=g.email)==null?void 0:T.toLowerCase())}),j=(f=t.approvers)==null?void 0:f.some(v=>{var N,T;return v.userId===g.userId||((N=v.email)==null?void 0:N.toLowerCase())===((T=g.email)==null?void 0:T.toLowerCase())});if(y){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(j){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),N={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},T=[...t.spectators,N];s("spectators",T),i(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(v=>{var N;return((N=v.email)==null?void 0:N.toLowerCase())===n.toLowerCase()}),j=(b=t.approvers)==null?void 0:b.some(v=>{var N;return((N=v.email)==null?void 0:N.toLowerCase())===n.toLowerCase()});if(y){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(j){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(Gt.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(wt,{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(de,{children:[e.jsxs(ue,{className:"flex items-center justify-between text-base","data-testid":"participants-spectators-title",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(oe,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(Te,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2","data-testid":"participants-spectators-add-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-full",children:[e.jsx(_e,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>p(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await x())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(o||l.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:o?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:l.map(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>x(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(O,{size:"sm",onClick:()=>x(),disabled:!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"data-testid":"participants-spectators-add-button",children:"Add"})]}),e.jsxs("p",{className:"text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1",children:[e.jsx(Jr,{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(ds,{className:"h-6 w-6",children:e.jsx(ms,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>h(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(vt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function ik({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 y=t.maxFileSizeMB*1024*1024,j=[],v=[];b.forEach(N=>{if(N.size>y){j.push({fileName:N.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(N.size/1048576).toFixed(2)}MB`});return}const T=N.name.toLowerCase(),A=T.substring(T.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(A)){j.push({fileName:N.name,reason:`File type "${A}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}v.push(N)}),v.length>0&&i([...a,...v]),j.length>0&&d&&d(j),f.target&&(f.target.value="")},x=f=>{const b=a.filter((y,j)=>j!==f);i(b)},h=f=>{o([...n,f])},g=(f,b=!1)=>{if(b){const y=(f.fileType||f.file_type||"").toLowerCase(),j=(f.originalFileName||f.fileName||"").toLowerCase();return y.includes("image")||y.includes("pdf")||j.endsWith(".jpg")||j.endsWith(".jpeg")||j.endsWith(".png")||j.endsWith(".gif")||j.endsWith(".pdf")}else{const y=(f.type||"").toLowerCase(),j=(f.name||"").toLowerCase();return y.includes("image")||y.includes("pdf")||j.endsWith(".jpg")||j.endsWith(".jpeg")||j.endsWith(".png")||j.endsWith(".gif")||j.endsWith(".pdf")}};return e.jsxs(Gt.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(vs,{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(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Ee,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(Te,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(ee,{children:e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-gray-400 transition-colors","data-testid":"documents-upload-area",children:[e.jsx(vs,{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(O,{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(is,{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(de,{children:e.jsxs(ue,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(oe,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(f=>!n.includes(f.documentId||f.document_id||"")).length," file",r.filter(f=>!n.includes(f.documentId||f.document_id||"")).length!==1?"s":""]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(f=>{const b=f.documentId||f.document_id||"";return n.includes(b)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Ee,{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(O,{variant:"ghost",size:"sm",onClick:()=>c(f,!0),"data-testid":`documents-existing-${b}-preview`,children:e.jsx(wt,{className:"h-4 w-4"})}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>h(b),"data-testid":`documents-existing-${b}-delete`,children:e.jsx(vt,{className:"h-4 w-4 text-red-600"})})]})]},b)})})})]}),a.length>0&&e.jsxs(Z,{"data-testid":"documents-new-card",children:[e.jsx(de,{children:e.jsxs(ue,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(oe,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((f,b)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Ee,{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(O,{variant:"ghost",size:"sm",onClick:()=>c(f,!1),"data-testid":`documents-new-${b}-preview`,children:e.jsx(wt,{className:"h-4 w-4"})}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>x(b),"data-testid":`documents-new-${b}-remove`,children:e.jsx(vt,{className:"h-4 w-4"})})]})]},b))})})]})]})]})}const lk=t=>{switch(t){case"high":return e.jsx(Ma,{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(Ks,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ts,{className:"w-4 h-4 text-gray-600"})}};function ok({formData:t,selectedTemplate:s}){return e.jsxs(Gt.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(Ve,{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(de,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(Pp,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6","data-testid":"review-submit-overview-grid",children:[e.jsxs("div",{"data-testid":"review-submit-overview-type",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(oe,{variant:"outline",className:"mt-2 text-xs border-green-300 text-green-700",children:s==null?void 0:s.category})]}),e.jsxs("div",{"data-testid":"review-submit-overview-priority",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[lk(t.priority),e.jsx("span",{className:"text-green-800 capitalize",children:t.priority})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-workflow",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Workflow Type"}),e.jsx("p",{className:"text-green-800 mt-1 capitalize",children:t.workflowType}),e.jsxs("p",{className:"text-sm text-green-700",children:[t.approverCount||1," Level",(t.approverCount||1)>1?"s":""]})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-title",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(Z,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(de,{children:e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Ee,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(re,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(Ls,{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(Pa,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(Z,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(de,{children:[e.jsxs(ue,{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(Te,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(ee,{className:"space-y-6",children:e.jsx("div",{className:"space-y-4","data-testid":"review-submit-approval-levels",children:Array.from({length:t.approverCount||1},(a,r)=>{const n=r+1,i=n===(t.approverCount||1),l=t.approvers[r];return e.jsx("div",{className:"p-4 bg-white rounded-lg border border-orange-200","data-testid":`review-submit-approval-level-${n}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${l!=null&&l.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:n})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",n]}),i&&e.jsx(oe,{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(de,{children:e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(wt,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(ee,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(re,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(oe,{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(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(vs,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(Te,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3","data-testid":"review-submit-documents-list",children:t.documents.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg border","data-testid":`review-submit-document-${r}`,children:[e.jsx(Ee,{className:"w-5 h-5 text-gray-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.name}),e.jsx("div",{className:"flex items-center gap-3 text-xs text-gray-500 mt-1",children:e.jsxs("span",{children:[(a.size/(1024*1024)).toFixed(2)," MB"]})})]})]},r))})})]}),e.jsx(Z,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Ve,{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 ck({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(O,{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(Cs,{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 dk({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(Hl,{mode:"wait",children:t})})})}function mk({modal:t,onClose:s}){return e.jsx(ht,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Mt,{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(Rl,{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(O,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function uk({modal:t,documentPolicy:s,onClose:a}){return e.jsx(ht,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(mt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Mt,{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(O,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function Eh({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Aa(),i=gs(),l=n.requestId||a||"",o=r&&!!l,{user:c}=us(),[d,m]=u.useState([]);u.useEffect(()=>{(async()=>{try{const Ce=(await Xl()).map(ce=>({id:ce.id,name:ce.name,description:ce.description,category:ce.category,icon:Ee,estimatedTime:ce.estimatedTime,commonApprovers:ce.approvers.map(Re=>Re.name),workflowApprovers:ce.approvers,suggestedSLA:ce.suggestedSLA,priority:ce.priority,fields:ce.fields||{}}));m(Ce)}catch(Ue){console.error("Failed to fetch admin templates:",Ue)}})()},[]);const p=u.useMemo(()=>[...Rh,...d],[d]),{formData:x,updateFormData:h,selectedTemplate:g,setSelectedTemplate:f,loadingDraft:b,systemPolicy:y,documentPolicy:j,existingDocuments:v,setExistingDocuments:N}=_T(o,l,p),{currentStep:T,totalSteps:A,stepNames:k,isStepValid:D,nextStep:F,prevStep:w}=MT(o,g,x),[L,_]=u.useState([]),[W,I]=u.useState([]),$=u.useRef(null),{validationModal:M,policyViolationModal:R,documentErrorModal:C,openValidationModal:H,closeValidationModal:z,openPolicyViolationModal:P,closePolicyViolationModal:S,openDocumentErrorModal:U,closeDocumentErrorModal:Y}=LT(),{submitting:B,savingDraft:E,handleSubmit:V,handleSaveDraft:G}=zT({formData:x,selectedTemplate:g,documents:L,documentsToDelete:W,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:J,setShowTemplateModal:q,previewDocument:se,selectTemplate:ne,handleTemplateSelection:te,nextStep:ge,prevStep:we,handlePreviewDocument:fe,closePreview:ke}=JT({selectedTemplate:g,setSelectedTemplate:f,updateFormData:h,formData:x,currentStep:T,isStepValid:D,wizardNextStep:F,wizardPrevStep:w,user:c,openValidationModal:H,systemPolicy:y,onPolicyViolation:P,onSubmit:s}),le=u.useCallback(()=>{if(T===1){i("/dashboard",{replace:!0});return}T===3||T===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):we()},[T,t,i,we]),Ne=u.useRef(!0),ae=u.useRef(!1);u.useEffect(()=>{Ne.current&&x.documents&&x.documents.length>0&&!ae.current&&(_(x.documents),ae.current=!0),Ne.current=!1},[x.documents]);const he=u.useRef(!1),ie=u.useRef(L);u.useEffect(()=>{if(he.current){he.current=!1,ie.current=L;return}ie.current!==L&&(h("documents",L),ie.current=L)},[L]);const je=()=>{switch(T){case 1:return e.jsx(tk,{templates:Rh,selectedTemplate:g,onSelectTemplate:ne,adminTemplates:d});case 2:return e.jsx(ak,{formData:x,selectedTemplate:g,updateFormData:h});case 3:return e.jsx(rk,{formData:x,updateFormData:h,systemPolicy:y,onValidationError:Fe=>H(Fe.type,Fe.email,Fe.message),onPolicyViolation:P});case 4:return e.jsx(nk,{formData:x,updateFormData:h,onValidationError:Fe=>H(Fe.type,Fe.email,Fe.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(ik,{documentPolicy:j,isEditing:o,documents:L,existingDocuments:v,documentsToDelete:W,onDocumentsChange:_,onExistingDocumentsChange:N,onDocumentsToDeleteChange:I,onPreviewDocument:fe,onDocumentErrors:Fe=>U(Fe),fileInputRef:$});case 6:return e.jsx(ok,{formData:x,selectedTemplate:g});default:return null}};return b?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center","data-testid":"create-request-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading draft..."})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gradient-to-br from-gray-50 to-white","data-testid":"create-request",children:[e.jsx(ck,{isEditing:o,currentStep:T,totalSteps:A,stepNames:k,onBack:le}),e.jsx(S0,{currentStep:T,totalSteps:A,stepNames:k}),e.jsx(dk,{children:je()}),e.jsx(ek,{currentStep:T,totalSteps:A,isStepValid:D(),onPrev:we,onNext:ge,onSubmit:V,onSaveDraft:G,submitting:B,savingDraft:E,loadingDraft:b,isEditing:o}),e.jsx(jT,{open:J,onClose:()=>q(!1),onSelectTemplate:te}),se&&e.jsx(qr,{fileName:se.fileName,fileType:se.fileType,fileUrl:se.fileUrl,fileSize:se.fileSize,open:!!se,onClose:ke,onDownload:async()=>{if(se.file){const Fe=document.createElement("a");Fe.href=se.fileUrl,Fe.download=se.fileName,document.body.appendChild(Fe),Fe.click(),document.body.removeChild(Fe)}else se.documentId&&await $s(se.documentId)},attachmentId:se.documentId}),e.jsx(mk,{modal:M,onClose:z}),e.jsx(uk,{modal:C,documentPolicy:j,onClose:Y}),e.jsx(Di,{open:R.open,onClose:S,violations:R.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}function Ri({className:t,...s}){return e.jsx(vj,{"data-slot":"tabs",className:$e("flex flex-col gap-2",t),...s})}function Ii({className:t,...s}){return e.jsx(Nj,{"data-slot":"tabs-list",className:$e("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function Ut({className:t,...s}){return e.jsx(wj,{"data-slot":"tabs-trigger",className:$e("data-[state=active]:bg-card dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-xl border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}function Bt({className:t,...s}){return e.jsx(Cj,{"data-slot":"tabs-content",className:$e("flex-1 outline-none",t),...s})}function hi(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 Gd(t,s=[],a){const[r,n]=u.useState(null),[i,l]=u.useState(!1),[o,c]=u.useState(!0),[d,m]=u.useState(null),[p,x]=u.useState(null),[h,g]=u.useState(!1),f=(A,k)=>(A||k||"NA").toString().split(" ").map(F=>F[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),b=A=>{const k=(A||"").toUpperCase();return k==="IN_PROGRESS"?"in-review":k==="PENDING"?"pending":k==="APPROVED"?"approved":k==="REJECTED"?"rejected":k==="CLOSED"?"closed":k==="SKIPPED"?"skipped":(A||"").toLowerCase()},y=A=>{const k=String(A||"").trim();if(!k)return"Document";const D=k.lastIndexOf("."),F=D>0&&D<k.length-1,w=F?k.slice(0,D):k,L=F?k.slice(D):"";return`${w.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"}${L}`},j=u.useCallback(async()=>{var A,k,D,F,w,L,_,W,I,$,M,R,C,H,z;l(!0);try{const P=await Xs.getWorkflowDetails(t);if(!P){console.warn("[useRequestDetails] No details returned from API");return}const S=P.workflow||{},U=Array.isArray(P.approvals)?P.approvals:[],Y=Array.isArray(P.participants)?P.participants:[],B=Array.isArray(P.documents)?P.documents:[],E=P.summary||{},V=Array.isArray(P.tatAlerts)?P.tatAlerts:[];V.length>0;const G=(E==null?void 0:E.currentLevel)||S.currentLevel||1,J=U.map(Ce=>{const ce=Ce.levelNumber||0,Re=(Ce.status||"").toString().toUpperCase(),qe=Ce.levelId||Ce.level_id;let at=b(Ce.status);ce>G&&Re!=="APPROVED"&&Re!=="REJECTED"?at="waiting":ce===G&&Re==="PENDING"&&(at="pending");const ft=V.filter(Ft=>Ft.levelId===qe);return{step:ce,levelId:qe,role:Ce.levelName||Ce.approverName||"Approver",status:at,approver:Ce.approverName||Ce.approverEmail,approverId:Ce.approverId||Ce.approver_id,approverEmail:Ce.approverEmail,tatHours:Number(Ce.tatHours||0),elapsedHours:Number(Ce.elapsedHours||0),remainingHours:Number(Ce.remainingHours||0),tatPercentageUsed:Number(Ce.tatPercentageUsed||0),actualHours:Ce.levelEndTime&&Ce.levelStartTime?Math.max(0,(new Date(Ce.levelEndTime).getTime()-new Date(Ce.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:Ce.comments||void 0,timestamp:Ce.actionDate||void 0,levelStartTime:Ce.levelStartTime||Ce.tatStartTime,tatAlerts:ft,skipReason:Ce.skipReason||void 0,isSkipped:Re==="SKIPPED"||Ce.isSkipped||!1}}),q=Y.filter(Ce=>(Ce.participantType||Ce.participant_type||"").toUpperCase()==="SPECTATOR").map(Ce=>({name:Ce.userName||Ce.user_name||Ce.userEmail||Ce.user_email,role:"Spectator",email:Ce.userEmail||Ce.user_email,avatar:f(Ce.userName||Ce.user_name,Ce.userEmail||Ce.user_email)})),se=Ce=>{var Re,qe;if(!Ce)return;const ce=Y.find(at=>at.userId===Ce||at.user_id===Ce);return ce!=null&&ce.userName||ce!=null&&ce.user_name?ce.userName||ce.user_name:S.initiatorId===Ce?((Re=S.initiator)==null?void 0:Re.displayName)||((qe=S.initiator)==null?void 0:qe.email):Ce},ne=B.map(Ce=>{const ce=Number(Ce.fileSize||Ce.file_size||0),Re=(ce/(1024*1024)).toFixed(2)+" MB";return{documentId:Ce.documentId||Ce.document_id,name:y(Ce.originalFileName||Ce.fileName||Ce.file_name),fileType:Ce.fileType||Ce.file_type||"",size:Re,sizeBytes:ce,uploadedBy:se(Ce.uploadedBy||Ce.uploaded_by),uploadedAt:Ce.uploadedAt||Ce.uploaded_at}}),te=Array.isArray(P.activities)?P.activities.filter(Ce=>(Ce.type||"").toLowerCase()!=="sla_warning"):[];let ge=null;if(S.isPaused||!1)try{ge=await lx(S.requestId)}catch{}let fe=null,ke=null,le=null,Ne=null,ae=[],he=null;if(hi(S)){try{const Ce=await Se.get(`/dealer-claims/${S.requestId}/credit-note-wfm`),ce=Ce.data??Ce;he=Array.isArray(ce==null?void 0:ce.data)?ce.data:Array.isArray(ce)?ce:[]}catch(Ce){console.warn("[useRequestDetails] Error fetching credit note WFM data:",Ce)}try{const Ce=await Se.get(`/dealer-claims/${S.requestId}`),ce=((A=Ce.data)==null?void 0:A.data)||Ce.data;if(ce){fe=ce.claimDetails||ce.claim_details,ke=ce.proposalDetails||ce.proposal_details,le=ce.completionDetails||ce.completion_details,Ne=ce.internalOrder||ce.internal_order||null,ae=ce.internalOrders||ce.internal_orders||[];const Re=ce.budgetTracking||ce.budget_tracking||null,qe=ce.invoice||null,at=ce.creditNote||ce.credit_note||null,ft=ce.completionExpenses||ce.completion_expenses||null;fe&&(fe.budgetTracking=Re,fe.invoice=qe,fe.creditNote=at,fe.completionExpenses=ft,fe.creditNoteWfmData=he)}else console.warn("[useRequestDetails] No claimData found in response")}catch(Ce){console.error("[useRequestDetails] Error fetching claim details:",{error:(Ce==null?void 0:Ce.message)||Ce,status:(k=Ce==null?void 0:Ce.response)==null?void 0:k.status,statusText:(D=Ce==null?void 0:Ce.response)==null?void 0:D.statusText,responseData:(F=Ce==null?void 0:Ce.response)==null?void 0:F.data,requestId:S.requestId})}}const ie={...S,id:S.requestNumber||S.requestId,requestId:S.requestId,requestNumber:S.requestNumber,initiatorId:S.initiatorId||S.initiator_id,title:S.title,description:S.description,status:b(S.status),priority:(S.priority||"").toString().toLowerCase(),workflowType:S.workflowType||(S.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:J,approvals:U,participants:Y,documents:ne,spectators:q,summary:E,sla:(E==null?void 0:E.sla)||S.sla||null,initiator:{userId:((w=S.initiator)==null?void 0:w.userId)||((L=S.initiator)==null?void 0:L.user_id)||S.initiatorId||S.initiator_id,name:((_=S.initiator)==null?void 0:_.displayName)||((W=S.initiator)==null?void 0:W.email),role:((I=S.initiator)==null?void 0:I.designation)||void 0,department:(($=S.initiator)==null?void 0:$.department)||void 0,email:((M=S.initiator)==null?void 0:M.email)||void 0,phone:((R=S.initiator)==null?void 0:R.phone)||void 0,avatar:f((C=S.initiator)==null?void 0:C.displayName,(H=S.initiator)==null?void 0:H.email)},createdAt:S.createdAt,updatedAt:S.updatedAt,totalSteps:S.totalLevels||1,currentStepRaw:(E==null?void 0:E.currentLevel)||S.currentLevel||1,currentStep:Math.min(Math.max(1,(E==null?void 0:E.currentLevel)||S.currentLevel||1),S.totalLevels||1),auditTrail:te,conclusionRemark:S.conclusionRemark||null,closureDate:S.closureDate||null,pauseInfo:ge||null,claimDetails:fe||null,proposalDetails:ke||null,completionDetails:le||null,internalOrder:Ne||null,internalOrders:ae||[],budgetTracking:(fe==null?void 0:fe.budgetTracking)||null,invoice:(fe==null?void 0:fe.invoice)||(fe==null?void 0:fe.invoice)||null,creditNote:(fe==null?void 0:fe.creditNote)||null,creditNoteWfmData:he||(fe==null?void 0:fe.creditNoteWfmData)||null,completionExpenses:(fe==null?void 0:fe.completionExpenses)||null,templateType:S.templateType||S.template_type,form16Submission:P.form16Submission||null};n(ie);const je=(z=a==null?void 0:a.email)==null?void 0:z.toLowerCase(),Fe=U.find(Ce=>{const ce=(Ce.status||"").toString().toUpperCase(),Re=(Ce.approverEmail||"").toLowerCase(),qe=Ce.levelNumber||0;return(ce==="PENDING"||ce==="IN_PROGRESS"||ce==="PAUSED")&&Re===je&&qe===G});x(Fe||null);const Ue=a==null?void 0:a.userId;if(Ue){const Ce=Y.some(ce=>(ce.participantType||ce.participant_type||"").toUpperCase()==="SPECTATOR"&&(ce.userId||ce.user_id)===Ue);g(Ce)}else g(!1)}catch(P){console.error("[useRequestDetails] Error refreshing details:",P),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);u.useEffect(()=>{if(!t){c(!1);return}let A=!0;return c(!0),m(null),(async()=>{var k,D,F,w,L,_,W,I,$,M,R,C,H,z;try{const P=await Xs.getWorkflowDetails(t);if(!A||!P){A&&c(!1);return}const S=P.workflow||{},U=Array.isArray(P.approvals)?P.approvals:[],Y=Array.isArray(P.participants)?P.participants:[],B=Array.isArray(P.documents)?P.documents:[],E=P.summary||{},V=Array.isArray(P.tatAlerts)?P.tatAlerts:[],G=(S.priority||"").toString().toLowerCase(),J=(E==null?void 0:E.currentLevel)||S.currentLevel||1,q=U.map(ce=>{const Re=ce.levelNumber||0,qe=(ce.status||"").toString().toUpperCase(),at=ce.levelId||ce.level_id;let ft=b(ce.status);qe==="PAUSED"?ft="paused":Re>J&&qe!=="APPROVED"&&qe!=="REJECTED"?ft="waiting":Re===J&&(qe==="PENDING"||qe==="IN_PROGRESS")&&(ft=qe==="IN_PROGRESS"?"in-review":"pending");const Ft=V.filter(me=>me.levelId===at);return{step:Re,levelId:at,role:ce.levelName||ce.approverName||"Approver",status:ft,approver:ce.approverName||ce.approverEmail,approverId:ce.approverId||ce.approver_id,approverEmail:ce.approverEmail,tatHours:Number(ce.tatHours||0),elapsedHours:Number(ce.elapsedHours||0),remainingHours:Number(ce.remainingHours||0),tatPercentageUsed:Number(ce.tatPercentageUsed||0),actualHours:ce.elapsedHours!==void 0&&ce.elapsedHours!==null?Number(ce.elapsedHours):void 0,comment:ce.comments||void 0,timestamp:ce.actionDate||void 0,levelStartTime:ce.levelStartTime||ce.tatStartTime,tatAlerts:Ft}}),se=Y.filter(ce=>(ce.participantType||"").toUpperCase()==="SPECTATOR").map(ce=>({name:ce.userName||ce.userEmail,role:"Spectator",avatar:f(ce.userName,ce.userEmail)})),ne=ce=>{var qe,at;if(!ce)return;const Re=Y.find(ft=>ft.userId===ce);return Re!=null&&Re.userName?Re.userName:S.initiatorId===ce?((qe=S.initiator)==null?void 0:qe.displayName)||((at=S.initiator)==null?void 0:at.email):ce},te=B.map(ce=>{const Re=Number(ce.fileSize||0),qe=(Re/(1024*1024)).toFixed(2)+" MB";return{documentId:ce.documentId||ce.document_id,name:y(ce.originalFileName||ce.fileName),fileType:ce.fileType||ce.file_type||"",size:qe,sizeBytes:Re,uploadedBy:ne(ce.uploadedBy),uploadedAt:ce.uploadedAt}}),ge=Array.isArray(P.activities)?P.activities.filter(ce=>(ce.type||"").toLowerCase()!=="sla_warning"):[];let we=null;if(S.isPaused||!1)try{we=await lx(S.requestId)}catch{}let ke=null,le=null,Ne=null,ae=null,he=[],ie=null;if(hi(S)){try{const ce=await Se.get(`/dealer-claims/${S.requestId}/credit-note-wfm`),Re=ce.data??ce;ie=Array.isArray(Re==null?void 0:Re.data)?Re.data:Array.isArray(Re)?Re:[]}catch(ce){console.warn("[useRequestDetails] Error fetching credit note WFM data:",ce)}try{const ce=await Se.get(`/dealer-claims/${S.requestId}`),Re=((k=ce.data)==null?void 0:k.data)||ce.data;if(Re){ke=Re.claimDetails||Re.claim_details,le=Re.proposalDetails||Re.proposal_details,Ne=Re.completionDetails||Re.completion_details,ae=Re.internalOrder||Re.internal_order||null,he=Re.internalOrders||Re.internal_orders||[];const qe=Re.budgetTracking||Re.budget_tracking||null,at=Re.invoice||null,ft=Re.creditNote||Re.credit_note||null,Ft=Re.completionExpenses||Re.completion_expenses||null;ke&&(ke.budgetTracking=qe,ke.invoice=at,ke.creditNote=ft,ke.completionExpenses=Ft,ke.creditNoteWfmData=ie)}}catch(ce){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(ce==null?void 0:ce.message)||ce,status:(D=ce==null?void 0:ce.response)==null?void 0:D.status,requestId:S.requestId})}}const je={id:S.requestNumber||S.requestId,requestId:S.requestId,title:S.title,description:S.description,priority:G,status:b(S.status),workflowType:S.workflowType||(S.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:E,initiator:{name:((F=S.initiator)==null?void 0:F.displayName)||((w=S.initiator)==null?void 0:w.email),role:((L=S.initiator)==null?void 0:L.designation)||void 0,department:((_=S.initiator)==null?void 0:_.department)||void 0,email:((W=S.initiator)==null?void 0:W.email)||void 0,phone:((I=S.initiator)==null?void 0:I.phone)||void 0,avatar:f(($=S.initiator)==null?void 0:$.displayName,(M=S.initiator)==null?void 0:M.email)},createdAt:S.createdAt,updatedAt:S.updatedAt,totalSteps:S.totalLevels||1,currentStepRaw:(E==null?void 0:E.currentLevel)||S.currentLevel||1,currentStep:Math.min(Math.max(1,(E==null?void 0:E.currentLevel)||S.currentLevel||1),S.totalLevels||1),approvalFlow:q,approvals:U,documents:te,spectators:se,auditTrail:ge,conclusionRemark:S.conclusionRemark||null,closureDate:S.closureDate||null,pauseInfo:we||null,claimDetails:ke||null,proposalDetails:le||null,completionDetails:Ne||null,internalOrder:ae||null,internalOrders:he||[],budgetTracking:(ke==null?void 0:ke.budgetTracking)||null,invoice:(ke==null?void 0:ke.invoice)||null,creditNote:(ke==null?void 0:ke.creditNote)||null,creditNoteWfmData:ie||(ke==null?void 0:ke.creditNoteWfmData)||null,completionExpenses:(ke==null?void 0:ke.completionExpenses)||null,templateType:S.templateType||S.template_type,form16Submission:P.form16Submission||null};n(je);const Fe=(R=a==null?void 0:a.email)==null?void 0:R.toLowerCase(),Ue=U.find(ce=>{const Re=(ce.status||"").toString().toUpperCase(),qe=(ce.approverEmail||"").toLowerCase(),at=ce.levelNumber||0;return(Re==="PENDING"||Re==="IN_PROGRESS"||Re==="PAUSED")&&qe===Fe&&at===J});x(Ue||null);const Ce=a==null?void 0:a.userId;if(Ce){const ce=Y.some(Re=>(Re.participantType||"").toUpperCase()==="SPECTATOR"&&Re.userId===Ce);g(ce)}else g(!1)}catch(P){if(console.error("[useRequestDetails] Error loading request details:",P),A){if(((C=P==null?void 0:P.response)==null?void 0:C.status)===403){const S=((z=(H=P==null?void 0:P.response)==null?void 0:H.data)==null?void 0:z.message)||"You do not have permission to view this request. Access is restricted to the initiator, approvers, and spectators of this request.";m({denied:!0,message:S})}n(null)}}finally{A&&c(!1)}})(),()=>{A=!1}},[t,a]);const v=u.useMemo(()=>{if(r)return r;const A=s.find(k=>k.id===t||k.requestNumber===t||k.request_number===t);return A||null},[t,s,r]),N=u.useMemo(()=>{var D,F,w;if(!v||!a)return!1;const A=(D=a==null?void 0:a.email)==null?void 0:D.toLowerCase(),k=(w=(F=v.initiator)==null?void 0:F.email)==null?void 0:w.toLowerCase();return A===k},[v,a]),T=u.useMemo(()=>{var k;if(!v)return[];const A=[];return(k=v.initiator)!=null&&k.email&&A.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(D=>{D.approverEmail&&A.push({email:D.approverEmail.toLowerCase(),participantType:"APPROVER",name:D.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(D=>{D.email&&A.push({email:D.email.toLowerCase(),participantType:"SPECTATOR",name:D.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(D=>{const F=(D.userEmail||D.email||"").toLowerCase(),w=(D.participantType||D.participant_type||"").toUpperCase(),L=D.userName||D.user_name||D.name;F&&w&&!A.find(_=>_.email===F)&&A.push({email:F,participantType:w,name:L})}),A},[v]);return u.useEffect(()=>{if(!t||!r)return;const A=Kr();if(!A)return;const k=D=>{((D==null?void 0:D.requestId)===r.requestId||(D==null?void 0:D.requestNumber)===t)&&j()};return A.on("request:updated",k),()=>{A.off("request:updated",k)}},[t,r,j]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:j,currentApprovalLevel:p,isSpectator:h,isInitiator:N,existingParticipants:T,accessDenied:d}}function k0(t,s,a,r){const[n,i]=u.useState([]),[l,o]=u.useState(0),[c,d]=u.useState([]);return u.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 Xs.getWorkflowDetails(t);(f=b==null?void 0:b.workflow)!=null&&f.requestId&&m&&(p=b.workflow.requestId)}catch(b){console.error("[useRequestSocket] Failed to resolve UUID:",b)}if(!m)return;const x=Kr();if(!x){console.error("[useRequestSocket] Socket not available");return}const h=r==null?void 0:r.userId,g=()=>{lc(x,p,h)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Jp(x,p))}})(),()=>{m=!1}},[t,r]),u.useEffect(()=>{!t||!s||(async()=>{try{const m=await yn(t),p=s.auditTrail||[],x=[...m,...p];x.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(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),u.useEffect(()=>{if(!t)return;const m=Kr();if(!m)return;const p=h=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await yn(t),f=(s==null?void 0:s.auditTrail)||[],b=[...g,...f].sort((y,j)=>{const v=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime(),N=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime();return v-N});i(b)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=h=>{const g=h.type==="breach"?"⏰":h.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const f=await Xs.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",x),()=>{m.off("noteHandler",p),m.off("worknote:new",p),m.off("tat:alert",x)}},[t,a,s]),u.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function Xn(t,s,a="SUPPORTING"){var l;const r=new FormData;r.append("file",t),r.append("requestId",s),r.append("category",a);const n=await Se.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 xk=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],hk={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 Yd(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(!xk.includes(a))return!1;const r=hk[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(", "))),Q.error(r,{description:i||n,duration:8e3,style:{background:"#fef2f2",border:"1px solid #fca5a5",color:"#991b1b"}}),!0}function D0(t,s){const[a,r]=u.useState(!1),[n,i]=u.useState(null),[l,o]=u.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=u.useState({show:!1,errors:[]});u.useEffect(()=>{(async()=>{try{const g=await pa("DOCUMENT_POLICY"),f={};g.forEach(v=>{f[v.configKey]=v.configValue});const b=parseInt(f.MAX_FILE_SIZE_MB||"10"),j=(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:j})}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 j,v;const g=h.target.files;if(!g||g.length===0)return;const f=Array.from(g),b=[],y=[];if(f.forEach(N=>{const T=m(N);T.valid?y.push(N):b.push({fileName:N.name,reason:T.reason||"Unknown validation error"})}),b.length>0&&d({show:!0,errors:b}),y.length===0){h.target&&(h.target.value="");return}r(!0);try{const N=y[0],T=t==null?void 0:t.requestId;if(!T){Q.error("Request ID not found");return}N&&await Xn(N,T,"SUPPORTING"),await s(),y.length<f.length?Q.warning(`${y.length} of ${f.length} file(s) were uploaded. ${b.length} file(s) were rejected.`):Q.success("Document uploaded successfully")}catch(N){console.error("[useDocumentUpload] Upload error:",N),Yd(N)||Q.error(((v=(j=N==null?void 0:N.response)==null?void 0:j.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 pk="modulepreload",gk=function(t){return"/"+t},_h={},Ro=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=gk(c),c in _h)return;_h[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":pk,d||(p.as="script"),p.crossOrigin="",p.href=c,o&&p.setAttribute("nonce",o),document.head.appendChild(p),d)return new Promise((x,h)=>{p.addEventListener("load",x),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 R0(t,s,a,r,n,i,l){const[o,c]=u.useState(""),[d,m]=u.useState(!1),[p,x]=u.useState(!1),[h,g]=u.useState(!1),[f,b]=u.useState(0),[y,j]=u.useState(!1),[v,N]=u.useState(!1),[T,A]=u.useState(0),k=async()=>{var _;const w=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),L=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(w||L){c(w||L),g(!!L);return}try{const{getConclusion:W}=await Ro(async()=>{const{getConclusion:$}=await import("./conclusionApi-CFo0PF7I.js");return{getConclusion:$}},__vite__mapDeps([0,1,2,3,4,5,6,7])),I=await W(t.requestId||s);I&&(I.aiGeneratedRemark||I.finalRemark)&&(c(I.finalRemark||I.aiGeneratedRemark||""),g(!!I.aiGeneratedRemark))}catch(W){((_=W==null?void 0:W.response)==null?void 0:_.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",W)}},D=async()=>{if(!v)try{m(!0),j(!1);const{generateConclusion:w}=await Ro(async()=>{const{generateConclusion:I}=await import("./conclusionApi-CFo0PF7I.js");return{generateConclusion:I}},__vite__mapDeps([0,1,2,3,4,5,6,7])),L=await w(t.requestId||s),_=f+1;if(b(_),!(L!=null&&L.aiGeneratedRemark)||L.aiGeneratedRemark.toLowerCase().includes("unable to generate")||L.aiGeneratedRemark.toLowerCase().includes("sorry")){const I=T+1;A(I),I>=2?(N(!0),i==null||i({success:!1,title:"AI Generation Limit Reached",message:"We're unable to process a conclusion remark at this time after 2 attempts. Please proceed with a manual approach using the editor below."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process a conclusion remark at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0),c((L==null?void 0:L.aiGeneratedRemark)||""),g(!1);return}c(L.aiGeneratedRemark),g(!0),A(0),_>=2&&(N(!0),i==null||i({success:!0,title:"Maximum Attempts Reached",message:"You've reached the maximum of 2 regeneration attempts. Feel free to manually edit the current suggestion to fit your specific needs."}),l==null||l(!0))}catch(w){console.error("[useConclusionRemark] AI generation failed:",w);const L=T+1;A(L),g(!1),L>=2?(N(!0),i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. Since the maximum of 2 attempts is reached, please proceed with a manual approach."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0)}finally{m(!1)}},F=async()=>{var L,_;const w=o.replace(/<[^>]*>/g,"").trim();if(!w){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(w.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),l==null||l(!0);return}try{x(!0);const{finalizeConclusion:W}=await Ro(async()=>{const{finalizeConclusion:I}=await import("./conclusionApi-CFo0PF7I.js");return{finalizeConclusion:I}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await W(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(W){i==null||i({success:!1,title:"Error",message:((_=(L=W.response)==null?void 0:L.data)==null?void 0:_.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{x(!1)}};return u.useEffect(()=>{var I;const w=(I=t==null?void 0:t.status)==null?void 0:I.toLowerCase();if(!((w==="approved"||w==="rejected"||w==="closed")&&a&&!o))return;const _=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),W=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);_||W?(c(_||W),g(!!W)):k()},[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:F,generationAttempts:f,generationFailed:y,maxAttemptsReached:v}}function I0(t,s,a){const[r,n]=u.useState(!1),[i,l]=u.useState(!1),[o,c]=u.useState(!1),[d,m]=u.useState(!1),[p,x]=u.useState(!1),[h,g]=u.useState(!1),[f,b]=u.useState(null),[y,j]=u.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:p,setShowSkipApproverModal:x,showActionStatusModal:h,setShowActionStatusModal:g,skipApproverData:f,setSkipApproverData:b,actionStatus:y,setActionStatus:j,handleApproveConfirm:async D=>{var w,L;const F=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!F){alert("Approval level not found");return}await Qn(t,F,D||""),await new Promise(_=>setTimeout(_,500)),await a(),(w=window==null?void 0:window.closeModal)==null||w.call(window),(L=window==null?void 0:window.toast)==null||L.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var w,L;if(!(D!=null&&D.trim())){alert("Comments & remarks are required");return}const F=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!F){alert("Approval level not found");return}await _r(t,F,D.trim(),D.trim()),await a(),(w=window==null?void 0:window.closeModal)==null||w.call(window),(L=window==null?void 0:window.toast)==null||L.call(window,"Rejected successfully")},handleAddApprover:async(D,F,w)=>{var L,_;try{await Lg(t,D,F,w),await a(),c(!1),j==null||j({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${w} with ${F}h TAT`}),g==null||g(!0)}catch(W){throw j==null||j({success:!1,title:"Failed to Add Approver",message:((_=(L=W==null?void 0:W.response)==null?void 0:L.data)==null?void 0:_.error)||"Failed to add approver. Please try again."}),g==null||g(!0),W}},handleSkipApprover:async D=>{var F,w;if(f)try{await gC(t,f.levelId,D),await a(),x(!1),b(null),j==null||j({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),g==null||g(!0)}catch(L){throw j==null||j({success:!1,title:"Failed to Skip Approver",message:((w=(F=L==null?void 0:L.response)==null?void 0:F.data)==null?void 0:w.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),L}},handleAddSpectator:async D=>{var F,w;try{await Og(t,D),await a(),m(!1),j==null||j({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),g==null||g(!0)}catch(L){throw j==null||j({success:!1,title:"Failed to Add Spectator",message:((w=(F=L==null?void 0:L.response)==null?void 0:F.data)==null?void 0:w.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),L}}}}function fk({requestId:t,request:s,onRefresh:a}){const[r,n]=u.useState(null),[i,l]=u.useState(!0),[o,c]=u.useState(null),m=!!(s==null?void 0:s.form16Submission),p=!!r&&r.status!=="withdrawn";u.useEffect(()=>{if(!t){l(!1);return}let g=!1;return(async()=>{try{const f=await yg(t);g||n(f?{id:typeof f.id=="number"?f.id:Number(f.id),status:f.status||""}:null)}catch{g||n(null)}finally{g||l(!1)}})(),()=>{g=!0}},[t]);const x=async()=>{if(!(!t||!window.confirm("Cancel this Form 16 submission? The request will be marked as rejected."))){c("cancel");try{await xN(t),Q.success("Submission cancelled"),a==null||a()}catch(g){Q.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 hN(t),Q.success("Marked as resubmission needed"),a==null||a()}catch(g){Q.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(de,{className:"pb-2",children:[e.jsxs(ue,{className:"text-sm flex items-center gap-2 text-blue-800",children:[e.jsx(Et,{className:"w-4 h-4"}),"Form 16 actions"]}),e.jsx(Te,{className:"text-xs text-gray-600",children:"View the document in the Documents tab. Cancel submission or mark resubmission needed."})]}),e.jsxs(ee,{className:"space-y-2",children:[e.jsxs(O,{variant:"outline",size:"sm",className:"w-full justify-start border-red-300 text-red-700 hover:bg-red-50",onClick:x,disabled:!!o,children:[o==="cancel"?e.jsx(ze,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(vt,{className:"w-3 h-3 mr-1"}),"Cancel submission"]}),e.jsxs(O,{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(Ep,{className:"w-3 h-3 mr-1"}),"Resubmission needed"]})]})]})}const bk=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 Gr({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(Ee,{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 "]}),js(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&bk(t.fileType)&&s&&e.jsx(O,{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(wt,{className:"w-4 h-4"})}),a&&e.jsx(O,{variant:"ghost",size:"sm",onClick:async()=>{if(!t.documentId){alert("Document ID not available");return}try{await a(t.documentId)}catch{alert("Failed to download document")}},title:"Download file","data-testid":`${n}-download-btn`,children:e.jsx(kt,{className:"w-4 h-4"})})]})]})}function jk({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l,isSpectator:o=!1}){var m,p,x,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("."),y=b>0&&b<f.length-1,j=y?f.slice(0,b):f,v=y?f.slice(b):"";return`${j.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(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base text-amber-800",children:[e.jsx(Ee,{className:"w-4 h-4 sm:w-5 sm:h-5 text-amber-600"}),"Previous submission(s) same quarter"]}),e.jsxs(Te,{className:"text-xs sm:text-sm mt-1",children:["Documents from earlier Form 16A submissions for this request's financial year and quarter only (",(x=t==null?void 0:t.form16Submission)==null?void 0:x.financialYear," ",(h=t==null?void 0:t.form16Submission)==null?void 0:h.quarter,")"]})]}),e.jsx(ee,{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,y=f.requestNumber||b;g.has(y)||g.set(y,[]),g.get(y).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((y,j)=>{const v=y.documentId??y.document_id,N=d(y.originalFileName??y.original_file_name??y.fileName??y.file_name??"Document"),T=Number(y.fileSize??y.file_size??0),A=T>0?(T/(1024*1024)).toFixed(2)+" MB":"—";return e.jsx(Gr,{document:{documentId:v,name:N,fileType:y.fileType??y.file_type??"",size:A,sizeBytes:T,uploadedBy:y.uploadedBy??y.uploaded_by,uploadedAt:y.uploadedAt??y.uploaded_at},onPreview:k=>i(k),onDownload:l,testId:"form16-previous-document"},v||j)})})]},f))})()})})]}),e.jsxs(Z,{children:[e.jsx(de,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ee,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),c?"Current submission":"Request Documents"]}),e.jsx(Te,{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(O,{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(vs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a?"Uploading...":t.status==="closed"?"Closed":"Upload",e.jsx("span",{className:"hidden sm:inline",children:t.status==="closed"?"":"Document"})]}),e.jsxs("p",{className:"text-xs text-gray-500 whitespace-nowrap",children:["Max ",r.maxFileSizeMB,"MB"]})]})]})}),e.jsx(ee,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((g,f)=>e.jsx(Gr,{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(de,{children:[e.jsxs(ue,{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-purple-600"}),"Work Note Attachments"]}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(ee,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((g,f)=>e.jsx(Gr,{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:y}=require("@/services/workflowApi");await y(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 yk=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"}}},Mh=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:_t,iconColor:"text-blue-600"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Ve,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected",icon:At,iconColor:"text-red-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-300",label:"closed",icon:Ve,iconColor:"text-gray-600"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped",icon:zt,iconColor:"text-orange-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:ss,iconColor:"text-gray-600"}}},vk=t=>{switch(t){case"approval":case"approved":return e.jsx(Ve,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(At,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(Qs,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(_t,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(Il,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Ee,{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(Tl,{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(zt,{className:"w-5 h-5 text-gray-600"})}};function Nk(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),x=c==="duplicate"||l==="duplicate";if(a.push({type:"document_added",action:"Form 16A uploaded",details:"Form 16A certificate was uploaded and received.",timestamp:i}),a.push({type:"created",action:"OCR extraction",details:d?"Certificate data was extracted from the uploaded PDF.":"OCR extraction was performed on the uploaded document.",timestamp:i}),p?a.push({type:"rejection",action:"26AS matching",details:"Values of Form 16 did not match with 26AS. Please submit Form 16 with correct data.",timestamp:i}):x?a.push({type:"rejection",action:"26AS matching",details:"Duplicate. A submission for this FY and quarter already exists; credit note was issued for the earlier submission.",timestamp:i}):a.push({type:"status_change",action:"26AS matching",details:l==="success"||m?"26AS matching completed.":"26AS matching was performed.",timestamp:i}),m){const 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 wk({request:t}){const s=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",a=s?Nk(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(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(zt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(Te,{className:"text-xs sm:text-sm",children:s?"Form 16 submission steps and audit trail":"Complete audit trail of all request activities"})]}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-4 sm:space-y-6",children:n.length>0?n.map((i,l)=>e.jsxs("div",{className:"flex items-start gap-4","data-testid":`activity-item-${l}`,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${i.type==="rejection"?"bg-red-50":"bg-gray-100"}`,children:vk(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:js(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(zt,{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 F0({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsx(pt,{children:e.jsxs(ut,{className:"flex items-center gap-2",children:[a?e.jsx(Ve,{className:"w-5 h-5 text-green-600"}):e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),r||(a?"Success":"Error")]})}),e.jsx("div",{className:"py-6",children:e.jsx("div",{className:"flex flex-col items-center text-center",children:a?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-4",children:e.jsx(Ve,{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(At,{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(O,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function P0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=u.useState(""),[l,o]=u.useState(!1),[c,d]=u.useState([]),[m,p]=u.useState(!1),[x,h]=u.useState(null),g=u.useRef(null),f=u.useRef(null),[b,y]=u.useState({open:!1,type:"error",email:"",message:""}),[j,v]=u.useState({open:!1,violations:[]}),[N,T]=u.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});u.useEffect(()=>{t&&(async()=>{var L;try{const _=await pa("WORKFLOW_SHARING"),W=await pa("TAT_SETTINGS"),I=[..._,...W],$={};I.forEach(M=>{$[M.configKey]=M.configValue}),T({maxApprovalLevels:parseInt($.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt($.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((L=$.ALLOW_ADD_SPECTATOR)==null?void 0:L.toLowerCase())==="true",maxSpectators:parseInt($.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(_){console.error("Failed to load system policy:",_)}})()},[t]);const A=async()=>{var R,C;const w=n.trim().toLowerCase();if(!w){y({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(w)){y({open:!0,type:"error",email:w,message:"Please enter a valid email address"});return}const _=r.find(H=>(H.email||"").toLowerCase()===w);if(_){const H=((R=_.participantType)==null?void 0:R.toUpperCase())||"PARTICIPANT",z=_.name||w;if(H==="INITIATOR"){y({open:!0,type:"error",email:w,message:`${z} is the request initiator and cannot be added as a spectator.`});return}else if(H==="APPROVER"){y({open:!0,type:"error",email:w,message:`${z} is already an approver on this request and cannot be added as a spectator.`});return}else if(H==="SPECTATOR"){y({open:!0,type:"error",email:w,message:`${z} is already a spectator on this request.`});return}else{y({open:!0,type:"error",email:w,message:`${z} is already a participant on this request.`});return}}const W=[];N.allowSpectators||W.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const $=r.filter(H=>(H.participantType||"").toUpperCase()==="SPECTATOR").length;$>=N.maxSpectators&&W.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:$,maxValue:N.maxSpectators});const M=r.length+1;if(M>N.maxParticipants&&W.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:M,maxValue:N.maxParticipants}),W.length>0){v({open:!0,violations:W});return}if(!x||x.email.toLowerCase()!==w)try{const z=((C=(await Sa(w,1)).data)==null?void 0:C.data)||[];if(z.length===0){y({open:!0,type:"not-found",email:w,message:""});return}const P=z[0];await wa({userId:P.userId,email:P.email,displayName:P.displayName,firstName:P.firstName,lastName:P.lastName,department:P.department,phone:P.phone,mobilePhone:P.mobilePhone,designation:P.designation,jobTitle:P.jobTitle,manager:P.manager,employeeId:P.employeeId,employeeNumber:P.employeeNumber,secondEmail:P.secondEmail,location:P.location})}catch(H){console.error("Failed to validate spectator:",H),y({open:!0,type:"error",email:w,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(w),i(""),h(null),s()}catch(H){console.error("Failed to add spectator:",H)}finally{o(!1)}},k=()=>{l||(i(""),h(null),d([]),p(!1),s())};u.useEffect(()=>{c.length>0&&f.current&&f.current.scrollTo({top:f.current.scrollHeight,behavior:"smooth"})},[c.length]),u.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const D=w=>{if(i(w),x&&x.email.toLowerCase()!==w.toLowerCase()&&h(null),g.current&&clearTimeout(g.current),!w||!w.startsWith("@")||w.length<2){d([]),p(!1);return}p(!0),g.current=setTimeout(async()=>{var L;try{const _=w.slice(1),I=((L=(await Sa(_,10)).data)==null?void 0:L.data)||[];d(I)}catch(_){console.error("Search failed:",_),d([])}finally{p(!1)}},300)},F=async w=>{try{await wa({userId:w.userId,email:w.email,displayName:w.displayName,firstName:w.firstName,lastName:w.lastName,department:w.department,phone:w.phone,mobilePhone:w.mobilePhone,designation:w.designation,jobTitle:w.jobTitle,manager:w.manager,employeeId:w.employeeId,employeeNumber:w.employeeNumber,secondEmail:w.secondEmail,location:w.location}),i(w.email),h(w),d([]),p(!1)}catch(L){console.error("Failed to ensure user exists:",L),y({open:!0,type:"error",email:w.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ht,{open:t,onOpenChange:k,children:[e.jsxs(mt,{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:l,children:[e.jsx(vt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center",children:e.jsx(wt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(ut,{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(Fl,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(_e,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:w=>D(w.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(w=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>F(w),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ds,{className:"h-8 w-8",children:e.jsx(ms,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(w.displayName||w.email).split(" ").map(L=>L[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:w.displayName||[w.firstName,w.lastName].filter(Boolean).join(" ")||w.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:w.email}),w.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:w.designation})]})]})},w.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(O,{type:"button",variant:"outline",onClick:k,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(O,{type:"button",onClick:A,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(ht,{open:b.open,onOpenChange:w=>y(L=>({...L,open:w})),children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(ut,{className:"flex items-center gap-2",children:b.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Mt,{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(Rl,{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(O,{onClick:()=>y(w=>({...w,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Di,{open:j.open,onClose:()=>v({open:!1,violations:[]}),violations:j.violations,policyDetails:{maxApprovalLevels:N.maxApprovalLevels,maxParticipants:N.maxParticipants,allowSpectators:N.allowSpectators,maxSpectators:N.maxSpectators}})]})}function E0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=u.useState(""),[d,m]=u.useState(24),[p,x]=u.useState(null),[h,g]=u.useState(!1),[f,b]=u.useState([]),[y,j]=u.useState(!1),[v,N]=u.useState(null),T=u.useRef(null),A=u.useRef(null),[k,D]=u.useState({open:!1,type:"error",email:"",message:""}),F=n.filter(C=>C&&(C.status==="approved"||C.status==="rejected"||C.status==="skipped")),w=Math.max(1,F.length+1),L=Math.max(1,n.length+1),_=L>=w?Array.from({length:L-w+1},(C,H)=>w+H):[w];u.useEffect(()=>{_.length>0&&p===null&&x(_[0]||null)},[_.length,p]);const W=async()=>{var U,Y;const C=o.trim().toLowerCase();if(!C){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(C)){D({open:!0,type:"error",email:C,message:"Please enter a valid email address"});return}if(!d||d<=0){D({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(d>720){D({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!p){D({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(p<w){D({open:!0,type:"error",email:"",message:`Cannot add approver at level ${p}. Minimum allowed level is ${w} (after completed levels)`});return}const z=n.length>0?Math.max(...n.map(B=>B.levelNumber),0):0,P=p>z?p:z+1;if(i&&P>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${p} would result in ${P} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:P,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${z} level(s).`});return}const S=r.find(B=>(B.email||"").toLowerCase()===C);if(S){const B=((U=S.participantType)==null?void 0:U.toUpperCase())||"PARTICIPANT",E=S.name||C;if(B==="INITIATOR"){D({open:!0,type:"error",email:C,message:`${E} is the request initiator and cannot be added as an approver.`});return}else if(B==="APPROVER"){D({open:!0,type:"error",email:C,message:`${E} is already an approver on this request.`});return}else if(B==="SPECTATOR"){D({open:!0,type:"error",email:C,message:`${E} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{D({open:!0,type:"error",email:C,message:`${E} is already a participant on this request.`});return}}if(!v||v.email.toLowerCase()!==C)try{const E=((Y=(await Sa(C,1)).data)==null?void 0:Y.data)||[];if(E.length===0){D({open:!0,type:"not-found",email:C,message:""});return}const V=E[0];await wa({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(B){console.error("Failed to validate approver:",B),D({open:!0,type:"error",email:C,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(C,d,p),c(""),m(24),x(null),N(null),s()}catch(B){console.error("Failed to add approver:",B)}finally{g(!1)}},I=()=>{h||(c(""),m(24),x(null),N(null),b([]),j(!1),s())},$=C=>{const H=C.toLowerCase();return H==="approved"?e.jsx(Ve,{className:"w-4 h-4 text-green-600"}):H==="rejected"?e.jsx(At,{className:"w-4 h-4 text-red-600"}):H==="skipped"?e.jsx(Ze,{className:"w-4 h-4 text-orange-600"}):H==="in-review"||H==="pending"?e.jsx(it,{className:"w-4 h-4 text-blue-600"}):e.jsx(it,{className:"w-4 h-4 text-gray-400"})};u.useEffect(()=>{f.length>0&&A.current&&A.current.scrollTo({top:A.current.scrollHeight,behavior:"smooth"})},[f.length]),u.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const M=C=>{if(c(C),v&&v.email.toLowerCase()!==C.toLowerCase()&&N(null),T.current&&clearTimeout(T.current),!C||!C.startsWith("@")||C.length<2){b([]),j(!1);return}j(!0),T.current=setTimeout(async()=>{var H;try{const z=C.slice(1),S=((H=(await Sa(z,10)).data)==null?void 0:H.data)||[];b(S)}catch(z){console.error("Search failed:",z),b([])}finally{j(!1)}},300)},R=async C=>{try{await wa({userId:C.userId,email:C.email,displayName:C.displayName,firstName:C.firstName,lastName:C.lastName,department:C.department,phone:C.phone,mobilePhone:C.mobilePhone,designation:C.designation,jobTitle:C.jobTitle,manager:C.manager,employeeId:C.employeeId,employeeNumber:C.employeeNumber,secondEmail:C.secondEmail,location:C.location}),c(C.email),N(C),b([]),j(!1)}catch(H){console.error("Failed to ensure user exists:",H),D({open:!0,type:"error",email:C.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ht,{open:t,onOpenChange:I,children:[e.jsxs(mt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:I,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:h,children:[e.jsx(vt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(qt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(ut,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:A,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a new approver at a specific level. Existing approvers at and after the selected level will be shifted down."}),i&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-2",children:e.jsxs("p",{className:"text-xs text-blue-800",children:[" Max: ",i," level",i!==1?"s":"",n.length>0&&e.jsxs("span",{className:"ml-2",children:["(",Math.max(...n.map(C=>C.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(C=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${C.status==="approved"?"bg-green-100 border border-green-200":C.status==="rejected"?"bg-red-100 border border-red-200":C.status==="skipped"?"bg-orange-100 border border-orange-200":"bg-white border border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-blue-600 text-white text-xs font-semibold flex items-center justify-center",children:C.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:C.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[C.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$(C.status),e.jsx(oe,{variant:"outline",className:`text-xs ${C.status==="approved"?"bg-green-50 text-green-700 border-green-300":C.status==="rejected"?"bg-red-50 text-red-700 border-red-300":C.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:C.status})]})]},C.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:[" New approver can only be added at level ",w," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(He,{value:(p==null?void 0:p.toString())||"",onValueChange:C=>x(Number(C)),disabled:h,children:[e.jsx(Ye,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select level"})}),e.jsx(Qe,{children:_.map(C=>e.jsx(X,{value:C.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",C]}),C<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",C,")"]})]})},C))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Choose where to insert the new approver. Existing levels will be automatically shifted."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_e,{type:"number",min:"1",max:"720",value:d,onChange:C=>m(Number(C.target.value)),className:"h-11 border-gray-300 flex-1",disabled:h,placeholder:"24"}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-600 bg-gray-100 px-3 h-11 rounded-md border border-gray-300",children:[e.jsx(it,{className:"w-4 h-4"}),"hours"]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum time for this approver to respond (1-720 hours)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fl,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(_e,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:C=>M(C.target.value),className:"pl-10 h-11 border-gray-300",disabled:h,autoFocus:!0}),(y||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:y?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):f.length>0?e.jsx("ul",{className:"divide-y",children:f.map(C=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>R(C),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ds,{className:"h-8 w-8",children:e.jsx(ms,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(C.displayName||C.email).split(" ").map(H=>H[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:C.displayName||[C.firstName,C.lastName].filter(Boolean).join(" ")||C.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:C.email}),C.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:C.designation})]})]})},C.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(O,{type:"button",variant:"outline",onClick:I,className:"flex-1 h-11 border-gray-300",disabled:h,children:"Cancel"}),e.jsxs(O,{type:"button",onClick:W,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(ht,{open:k.open,onOpenChange:C=>D(H=>({...H,open:C})),children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(ut,{className:"flex items-center gap-2",children:k.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Mt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[k.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:k.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(Rl,{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."]})})]}),k.type==="error"&&e.jsxs(e.Fragment,{children:[k.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:k.email}),"."]}),k.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:k.message})})]})]})})]}),e.jsx(Dt,{children:e.jsx(O,{onClick:()=>D(C=>({...C,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Ck=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"}},Sk=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},Ak=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 Ua(s)},Tk=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Lh=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Ee,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(Mp,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Ee,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Ee,{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(Qi,{className:`${s} text-purple-600`}):e.jsx(Tl,{className:`${s} text-gray-600`})};function _0({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d,maxApprovalLevels:m,onPolicyViolation:p}){const x=Aa(),h=t||x.requestId||"",[g,f]=u.useState(""),[b,y]=u.useState(""),[j,v]=u.useState(!1),[N,T]=u.useState([]),[A,k]=u.useState(!1),[D,F]=u.useState([]),[w,L]=u.useState(null),[_,W]=u.useState(null),[I,$]=u.useState(!1),[M,R]=u.useState(!1),[C,H]=u.useState(!1),[z,P]=u.useState({success:!0,title:"",message:""}),S=u.useRef(null),U=u.useRef(null),Y=u.useRef(null),B=u.useRef(!1),[E,V]=u.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[G,J]=u.useState({open:!1,errors:[]}),q=u.useMemo(()=>({id:h,title:n||"Request Details"}),[h,n]),[se,ne]=u.useState([]),te=se.filter(me=>me.status==="online"),ge=N.filter(me=>me.content.toLowerCase().includes(b.toLowerCase())||me.user.name.toLowerCase().includes(b.toLowerCase())),we=u.useMemo(()=>o!==void 0?o:!w||se.length===0?!1:se.some(me=>{const Oe=me.userId||me.user_id,xe=(me.role||"").toString().toUpperCase(),Je=(me.participantType||me.participant_type||"").toString().toUpperCase();return Oe===w&&(xe==="SPECTATOR"||Je==="SPECTATOR")}),[o,w,se]);u.useEffect(()=>{},[se]),u.useEffect(()=>{!h||!w||s||(async()=>{try{const me=await yn(h),Oe=Array.isArray(me)?me.map(xe=>{const Je=xe.userId||xe.user_id;return{id:xe.noteId||xe.id||String(Math.random()),user:{name:xe.userName||"User",avatar:(xe.userName||"U").slice(0,2).toUpperCase(),role:xe.userRole||"Participant"},content:xe.message||"",timestamp:xe.createdAt||new Date().toISOString(),isCurrentUser:Je===w,attachments:Array.isArray(xe.attachments)?xe.attachments.map(Ke=>({attachmentId:Ke.attachmentId||Ke.attachment_id,name:Ke.fileName||Ke.file_name||Ke.name,fileName:Ke.fileName||Ke.file_name||Ke.name,url:Ke.storageUrl||Ke.storage_url||Ke.url||"#",type:Ke.fileType||Ke.file_type||Ke.type||"file",fileType:Ke.fileType||Ke.file_type||Ke.type||"file",fileSize:Ke.fileSize||Ke.file_size})):void 0}}):[];T(Oe)}catch(me){console.error("[WorkNoteChat] Failed to load messages:",me)}})()},[h,w,s]);const fe=u.useMemo(()=>{const me=[];return N.forEach(Oe=>{Oe.attachments&&Oe.attachments.length>0&&Oe.attachments.forEach(xe=>{me.push({attachmentId:xe.attachmentId||xe.attachment_id,name:xe.fileName||xe.file_name||xe.name||"Untitled",fileName:xe.fileName||xe.file_name||xe.name||"Untitled",size:xe.fileSize||xe.file_size,type:xe.fileType||xe.file_type||xe.type||"file",uploadedBy:Oe.user.name,uploadedAt:Oe.timestamp,url:xe.storageUrl||xe.storage_url||xe.url||"#"})})}),me},[N]);u.useEffect(()=>{i&&fe.length>=0&&i(fe)},[fe,i]);const ke=u.useMemo(()=>se.map(me=>({email:(me.email||"").toLowerCase(),participantType:me.role==="Initiator"?"INITIATOR":me.role==="Approver"?"APPROVER":me.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:me.name})),[se]),le=me=>{if(!me)return"Participant";switch(me.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return me.charAt(0).toUpperCase()+me.slice(1).toLowerCase()}},Ne=()=>{var me;(me=S.current)==null||me.scrollIntoView({behavior:"smooth"})};u.useEffect(()=>{Ne()},[N]);const ae=me=>{switch(me.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return me.charAt(0).toUpperCase()+me.slice(1).toLowerCase()}};u.useEffect(()=>{B.current||h&&(async()=>{try{const me=await Ms(h),Oe=Array.isArray(me==null?void 0:me.participants)?me.participants:[];if(Oe.length===0)return;const xe=Oe.map(Xe=>{const lt=Xe.participantType||Xe.participant_type||"participant",et=Xe.userId||Xe.user_id||"";return{name:Xe.userName||Xe.user_name||Xe.user_email||Xe.userEmail||"User",avatar:(Xe.userName||Xe.user_name||Xe.user_email||"U").toString().split(" ").map(xt=>xt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:ae(lt.toString()),status:"offline",email:Xe.userEmail||Xe.user_email||"",permissions:["read","write","mention"],userId:et}});B.current=!0,ne(xe);let Je=0;const Ke=3,rt=()=>{Y.current&&Y.current.connected?(Y.current.emit("request:online-users",{requestId:h}),Je++,Je<Ke&&setTimeout(rt,500)):(Je++,Je<Ke&&setTimeout(rt,200))};setTimeout(rt,100)}catch(me){console.error("[WorkNoteChat] ❌ Failed to load participants:",me)}})()},[h]),u.useEffect(()=>()=>{h&&(B.current=!1)},[h]),u.useEffect(()=>{const me=localStorage.getItem("userData");if(me)try{const Oe=JSON.parse(me),xe=(Oe==null?void 0:Oe.id)||(Oe==null?void 0:Oe.userId)||(Oe==null?void 0:Oe.user_id)||null;L(xe)}catch(Oe){console.error("[WorkNoteChat] Failed to parse userData:",Oe)}},[]),u.useEffect(()=>{(async()=>{try{const Oe=await pa("DOCUMENT_POLICY"),xe={};Oe.forEach(Xe=>{xe[Xe.configKey]=Xe.configValue});const Je=parseInt(xe.MAX_FILE_SIZE_MB||"10"),rt=(xe.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Xe=>Xe.trim().toLowerCase());V({maxFileSizeMB:Je,allowedFileTypes:rt})}catch(Oe){console.error("Failed to load document policy:",Oe)}})()},[]),u.useEffect(()=>{if(!w)return;let me=h;return(async()=>{var Oe;try{const xe=await Ms(h);(Oe=xe==null?void 0:xe.workflow)!=null&&Oe.requestId&&(me=xe.workflow.requestId)}catch{}try{const xe=Kr();r?ne(Nt=>Nt.map(Pt=>Pt.userId===w?{...Pt,status:"online"}:Pt)):(lc(xe,me,w),ne(Nt=>Nt.map(Pt=>Pt.userId===w?{...Pt,status:"online"}:Pt)));const Je=Nt=>{const gt=(Nt==null?void 0:Nt.note)||Nt;if(!gt)return;const Pt=gt.noteId||gt.id;T(Ss=>{if(Ss.some(Ot=>Ot.id===Pt))return Ss;const as=gt.userName||gt.user_name||"User",Ya=gt.userRole||gt.user_role,Qa=le(Ya),wr=gt.userId||gt.user_id,Ta={id:Pt||String(Date.now()),user:{name:as,avatar:as.split(" ").map(Ot=>Ot[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Qa},content:gt.message||"",timestamp:gt.createdAt||new Date().toISOString(),isCurrentUser:wr===w,attachments:Array.isArray(gt.attachments)?gt.attachments.map(Ot=>({attachmentId:Ot.attachmentId||Ot.attachment_id,name:Ot.fileName||Ot.file_name||Ot.name,fileName:Ot.fileName||Ot.file_name||Ot.name,url:Ot.storageUrl||Ot.storage_url||Ot.url||"#",type:Ot.fileType||Ot.file_type||Ot.type||"file",fileType:Ot.fileType||Ot.file_type||Ot.type||"file",fileSize:Ot.fileSize||Ot.file_size})):void 0};return[...Ss,Ta]})},Ke=Nt=>{ne(gt=>gt.length===0||!gt.find(as=>as.userId===Nt.userId)?gt:gt.map(as=>as.userId===Nt.userId?{...as,status:"online"}:as))},rt=Nt=>{Nt.userId!==w&&ne(gt=>gt.length===0||!gt.find(as=>as.userId===Nt.userId)?gt:gt.map(as=>as.userId===Nt.userId?{...as,status:"offline"}:as))},Xe=Nt=>{ne(gt=>gt.length===0?gt:gt.map(Ss=>{const as=Ss.userId||"";if(as===w)return{...Ss,status:"online"};const Qa=Nt.userIds.includes(as);return{...Ss,status:Qa?"online":"offline"}}))},lt=()=>{ne(Nt=>Nt.map(Pt=>Pt.userId===w?{...Pt,status:"online"}:Pt)),r||lc(xe,me,w),B.current&&(xe.emit("request:online-users",{requestId:me}),setTimeout(()=>xe.emit("request:online-users",{requestId:me}),300),setTimeout(()=>xe.emit("request:online-users",{requestId:me}),800))},et=Nt=>{console.error("[WorkNoteChat] ❌ Socket error:",Nt)},xt=Nt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",Nt),ne(gt=>gt.map(Pt=>Pt.userId===w?Pt:{...Pt,status:"offline"}))},Hs=Nt=>{Nt.includes("presence")||Nt.includes("worknote")||Nt.includes("request")};xe.on("connect",lt),xe.on("disconnect",xt),xe.on("error",et),xe.on("worknote:new",Je),xe.on("presence:join",Ke),xe.on("presence:leave",rt),xe.on("presence:online",Xe),xe.onAny(Hs),Y.current=xe,xe.connected&&B.current&&(xe.emit("request:online-users",{requestId:me}),setTimeout(()=>{xe.emit("request:online-users",{requestId:me})},300),setTimeout(()=>{xe.emit("request:online-users",{requestId:me})},800),setTimeout(()=>{xe.emit("request:online-users",{requestId:me})},1500));const ls=()=>{xe.off("connect",lt),xe.off("disconnect",xt),xe.off("error",et),xe.off("worknote:new",Je),xe.off("presence:join",Ke),xe.off("presence:leave",rt),xe.off("presence:online",Xe),xe.offAny(Hs),r||Jp(xe,me),Y.current=null};window.__wn_cleanup=ls}catch{}})(),()=>{var Oe;try{(Oe=window.__wn_cleanup)==null||Oe.call(window)}catch{}}},[h,w,r]);const he=async()=>{if(g.trim()||D.length>0){const me=at(g),Oe=me.map(Ke=>{const rt=se.find(Xe=>Xe.name.toLowerCase().includes(Ke.toLowerCase()));return rt==null?void 0:rt.userId}).filter(Boolean),xe=D.map(Ke=>({name:Ke.name,url:URL.createObjectURL(Ke),type:Ke.type.split("/")[1]||"file"})),Je={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:me,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:xe.length>0?xe:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await Mg(h,{message:g,mentions:Oe},D);const Ke=await yn(h),rt=Array.isArray(Ke)?Ke.map(Xe=>{const lt=Xe.userId||Xe.user_id;return{id:Xe.noteId||Xe.id||String(Math.random()),user:{name:Xe.userName||"User",avatar:(Xe.userName||"U").slice(0,2).toUpperCase(),role:Xe.userRole||"Participant"},content:Xe.message||"",timestamp:Xe.createdAt||new Date().toISOString(),isCurrentUser:lt===w,attachments:Array.isArray(Xe.attachments)?Xe.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}}):[];T(rt)}catch{T(Ke=>[...Ke,Je])}f(""),F([])}};u.useEffect(()=>{if(s&&Array.isArray(s))try{const Oe=s.filter(xe=>(xe.type||"").toLowerCase()!=="sla_warning").map(xe=>{var Ke;if(xe.type||xe.activityType||xe.isSystem)return{id:xe.id||`activity-${xe.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:xe.details||xe.action||xe.content||"",timestamp:xe.timestamp||xe.createdAt||xe.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const rt=xe.userName||xe.user_name||((Ke=xe.user)==null?void 0:Ke.name)||"User",Xe=xe.userRole||xe.user_role,lt=le(Xe),et=xe.userId||xe.user_id;return{id:xe.noteId||xe.note_id||xe.id||String(Math.random()),user:{name:rt,avatar:rt.split(" ").map(xt=>xt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:lt},content:xe.message||xe.content||"",timestamp:xe.createdAt||xe.created_at||xe.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(xe.attachments)?xe.attachments.map(xt=>({attachmentId:xt.attachmentId||xt.attachment_id,name:xt.fileName||xt.file_name||xt.name,fileName:xt.fileName||xt.file_name||xt.name,url:xt.storageUrl||xt.storage_url||xt.url||"#",type:xt.fileType||xt.file_type||xt.type||"file",fileType:xt.fileType||xt.file_type||xt.type||"file",fileSize:xt.fileSize||xt.file_size})):void 0,isCurrentUser:et===w}}}).sort((xe,Je)=>new Date(xe.timestamp).getTime()-new Date(Je.timestamp).getTime());T(Oe)}catch(me){console.error("[WorkNoteChat] Error mapping messages:",me)}else(async()=>{try{const me=await yn(h),Oe=Array.isArray(me)?me.map(xe=>{const Je=xe.userName||xe.user_name||"User",Ke=xe.userRole||xe.user_role,rt=le(Ke),Xe=xe.userId||xe.user_id;return{id:xe.noteId||xe.note_id||xe.id||String(Math.random()),user:{name:Je,avatar:Je.split(" ").map(lt=>lt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:rt},content:xe.message||"",timestamp:xe.createdAt||xe.created_at||new Date().toISOString(),attachments:Array.isArray(xe.attachments)?xe.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:Xe===w}}):[];T(Oe)}catch(me){console.error("[WorkNoteChat] Error loading work notes:",me)}})()},[s,h,se]);const ie=me=>{const Oe=E.maxFileSizeMB*1024*1024;if(me.size>Oe)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${E.maxFileSizeMB}MB. Current size: ${(me.size/(1024*1024)).toFixed(2)}MB`};const xe=me.name.toLowerCase(),Je=xe.substring(xe.lastIndexOf(".")+1);return E.allowedFileTypes.includes(Je)?{valid:!0}:{valid:!1,reason:`File type "${Je}" is not allowed. Allowed types: ${E.allowedFileTypes.join(", ")}`}},je=me=>{if(!me.target.files||me.target.files.length===0)return;const Oe=Array.from(me.target.files),xe=[],Je=[];Oe.forEach(Ke=>{const rt=ie(Ke);rt.valid?Je.push(Ke):xe.push({fileName:Ke.name,reason:rt.reason||"Unknown validation error"})}),xe.length>0&&J({open:!0,errors:xe}),Je.length>0&&(F(Ke=>[...Ke,...Je]),Je.length<Oe.length?Q.warning(`${Je.length} of ${Oe.length} file(s) were added. ${xe.length} file(s) were rejected.`):Q.success(`${Je.length} file(s) added successfully`)),me.target&&(me.target.value="")},Fe=me=>{F(Oe=>Oe.filter((xe,Je)=>Je!==me)),U.current&&(U.current.value="")},Ue=me=>{f(Oe=>Oe+me),v(!1)},Ce=()=>{var me;(me=U.current)==null||me.click()},ce=async me=>{var Oe,xe;try{await Og(h,me);const Je=await Ms(h),Ke=Array.isArray(Je==null?void 0:Je.participants)?Je.participants:[];if(Ke.length){const rt=Ke.map(Xe=>{const lt=Xe.participantType||Xe.participant_type||"participant",et=Xe.userId||Xe.user_id||"",xt=Xe.userName||Xe.user_name||Xe.userEmail||Xe.user_email||"User",Hs=Xe.userEmail||Xe.user_email||"",ls=xt.split(" ").map(Nt=>Nt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:xt,avatar:ls,role:ae(lt),status:"offline",email:Hs,lastSeen:void 0,permissions:["read"],userId:et}});ne(rt),Y.current&&Y.current.connected&&Y.current.emit("request:online-users",{requestId:h})}$(!1),P({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),H(!0)}catch(Je){throw console.error("Failed to add spectator:",Je),P({success:!1,title:"Failed to Add Spectator",message:((xe=(Oe=Je==null?void 0:Je.response)==null?void 0:Oe.data)==null?void 0:xe.error)||"Failed to add spectator. Please try again."}),H(!0),Je}},Re=async(me,Oe,xe)=>{var Je,Ke;if(d)await d(me,Oe,xe),R(!1);else try{await Lg(h,me,Oe,xe);const rt=await Ms(h),Xe=Array.isArray(rt==null?void 0:rt.participants)?rt.participants:[];if(Xe.length){const lt=Xe.map(et=>{const xt=et.participantType||et.participant_type||"participant",Hs=et.userId||et.user_id||"",ls=et.userName||et.user_name||et.userEmail||et.user_email||"User",Nt=et.userEmail||et.user_email||"",gt=ls.split(" ").map(Pt=>Pt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ls,avatar:gt,role:ae(xt),status:"offline",email:Nt,lastSeen:void 0,permissions:["read"],userId:Hs}});ne(lt),Y.current&&Y.current.connected&&Y.current.emit("request:online-users",{requestId:h})}R(!1),P({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${xe} with ${Oe}h TAT`}),H(!0)}catch(rt){throw console.error("Failed to add approver:",rt),P({success:!1,title:"Failed to Add Approver",message:((Ke=(Je=rt==null?void 0:rt.response)==null?void 0:Je.data)==null?void 0:Ke.error)||"Failed to add approver. Please try again."}),H(!0),rt}},qe=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","","","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],at=me=>{const Oe=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,xe=[];let Je;for(;(Je=Oe.exec(me))!==null;)if(Je[1]){const Ke=Je.index+Je[0].length,rt=me.slice(Ke),Xe=me[Ke];(rt.startsWith("@")||!Xe||/\s|[.,!?;:]|@/.test(Xe))&&xe.push(Je[1].trim())}return xe},ft=me=>{me.key==="Enter"&&!me.shiftKey&&(me.preventDefault(),he())},Ft=(me,Oe)=>{T(xe=>xe.map(Je=>{if(Je.id===me){const Ke=Je.reactions||[],rt=Ke.find(Xe=>Xe.emoji===Oe);if(rt)if(rt.users.includes("You")){if(rt.users=rt.users.filter(Xe=>Xe!=="You"),rt.users.length===0)return{...Je,reactions:Ke.filter(Xe=>Xe.emoji!==Oe)}}else rt.users.push("You");else Ke.push({emoji:Oe,users:["You"]});return{...Je,reactions:Ke}}return Je}))};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(Qs,{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:q.title}),e.jsx(oe,{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:[te.slice(0,3).map((me,Oe)=>e.jsx(ds,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(ms,{className:"bg-blue-500 text-white text-xs font-semibold",children:me.avatar})},Oe)),te.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:["+",te.length-3]})]})}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>k(!A),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(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(_e,{placeholder:"Search messages...",value:b,onChange:me=>y(me.target.value),className:"pl-10 bg-gray-50 border-gray-200 h-9 sm:h-10"})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-2 sm:px-3 lg:px-6 py-2 sm:py-4 min-h-0",children:e.jsxs("div",{className:"space-y-3 sm:space-y-6 max-w-full",children:[ge.map(me=>{const Oe=me.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${me.isSystem?"justify-center":Oe?"justify-end":""}`,children:[!me.isSystem&&!Oe&&e.jsx(ds,{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(ms,{className:`text-white font-semibold text-xs sm:text-sm ${me.user.role==="Initiator"?"bg-green-600":me.user.role==="Current User"?"bg-blue-500":me.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:me.user.avatar})}),e.jsx("div",{className:`${Oe?"max-w-[70%]":"flex-1"} min-w-0 ${me.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:me.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(zt,{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:me.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:js(me.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${Oe?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[me.user.name," ",Oe&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(oe,{variant:"outline",className:"text-xs flex-shrink-0",children:me.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"}),js(me.timestamp)]}),me.isHighPriority&&e.jsxs(oe,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(dy,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${Oe?"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:Ak(me.content)}}),me.attachments&&me.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:me.attachments.map((xe,Je)=>{const Ke=xe.fileSize||xe.file_size,rt=xe.fileName||xe.file_name||xe.name,Xe=xe.fileType||xe.file_type||xe.type||"",lt=xe.attachmentId||xe.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(Lh,{type:Xe})}),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}),Ke&&e.jsx("p",{className:"text-xs text-gray-500",children:Tk(Ke)})]}),lt&&(()=>{const et=(Xe||"").toLowerCase();return et.includes("image")||et.includes("pdf")||et.includes("jpg")||et.includes("jpeg")||et.includes("png")||et.includes("gif")})()&&e.jsx(O,{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 xt=yC(lt);W({fileName:rt,fileType:Xe,fileUrl:xt,fileSize:Ke,attachmentId:lt})},title:"Preview file",children:e.jsx(wt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(O,{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){Q.error("Cannot download: Attachment ID missing");return}try{await ox(lt)}catch{Q.error("Failed to download file")}},title:"Download file",children:e.jsx(kt,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Je)})})}),me.reactions&&me.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:[me.reactions.map((xe,Je)=>e.jsxs("button",{onClick:()=>Ft(me.id,xe.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${xe.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:xe.emoji}),e.jsx("span",{className:"text-xs font-medium",children:xe.users.length})]},Je)),e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>v(!j),children:e.jsx(is,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!me.isSystem&&Oe&&e.jsx(ds,{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(ms,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:me.user.avatar})})]},me.id)}),e.jsx("div",{ref:S})]})}),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:U,onChange:je,className:"hidden",multiple:!0,accept:E.allowedFileTypes.map(me=>`.${me}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((me,Oe)=>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(Lh,{type:me.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:me.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(me.size/1024).toFixed(1)," KB"]}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>Fe(Oe),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(vt,{className:"h-3 w-3 text-red-600"})})]},Oe))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const me=g.lastIndexOf("@"),Oe=me>=0;if(!Oe)return null;const xe=g.slice(me+1),Je=xe.trim(),Ke=xe.endsWith(" "),rt=Je.length>0,Xe=Je.includes(" ")&&!Ke,lt=Ke&&rt;if(!(Oe&&xe.length<=20&&!Xe&&!lt))return null;const xt=Je.toLowerCase(),Hs=se.filter(ls=>ls.userId===w?!1:xt?ls.name.toLowerCase().includes(xt):!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((ls,Nt)=>e.jsxs("button",{type:"button",onClick:gt=>{gt.preventDefault(),gt.stopPropagation();const Pt=g.lastIndexOf("@"),Ss=g.slice(0,Pt);f(Ss+"@"+ls.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(ds,{className:"h-10 w-10",children:e.jsx(ms,{className:`text-white text-sm font-semibold ${ls.role==="Initiator"?"bg-green-600":ls.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:ls.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:ls.name}),e.jsx("p",{className:"text-xs text-gray-600",children:ls.role})]})]},Nt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:xt?`No participants found matching "${xt}"`:"No other participants available"})})]})})(),e.jsx(Vs,{placeholder:we?"Spectators cannot send messages":"Type your message... Use @username to mention someone",value:g,onChange:me=>f(me.target.value),onKeyPress:ft,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:we}),j&&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(O,{variant:"ghost",size:"sm",onClick:()=>v(!1),className:"h-6 w-6 p-0",children:e.jsx(vt,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:qe.map((me,Oe)=>e.jsx("button",{onClick:()=>Ue(me),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:me,children:me},Oe))})]})]}),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(O,{variant:"ghost",size:"sm",onClick:Ce,disabled:we,title:we?"Spectators cannot attach files":"Attach file",children:e.jsx(Tl,{className:"h-4 w-4"})}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>v(!j),disabled:we,title:we?"Spectators cannot add emojis":"Add emoji",children:e.jsx(my,{className:"h-4 w-4"})}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>f(me=>me+"@"),disabled:we,title:we?"Spectators cannot mention users":"Mention someone",children:e.jsx(Fl,{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(O,{onClick:he,disabled:!g.trim()&&D.length===0||we,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:we?"Spectators cannot send messages":"Send",children:[e.jsx(_p,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),A&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>k(!1)}),e.jsxs("div",{className:`
w-72 sm:w-80 bg-white border-l border-gray-200 flex flex-col
lg:relative lg:translate-x-0 lg:shadow-none
${A?"fixed right-0 top-0 bottom-0 z-50 shadow-xl":"hidden lg:flex"}
`,children:[e.jsxs("div",{className:"p-4 sm:p-6 border-b border-gray-200 flex-1 flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900",children:"Participants"}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>k(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(vt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:se.map((me,Oe)=>{const xe=me.userId===w;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ds,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(ms,{className:`text-white font-semibold text-sm ${me.role==="Initiator"?"bg-green-600":xe?"bg-blue-500":"bg-slate-600"}`,children:me.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${Ck(me.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:[me.name," ",xe&&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:me.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:Sk(me.status)})]}),me.lastSeen&&me.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:me.lastSeen})]})]},Oe)})})]}),!we&&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(O,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>R(!0),children:[e.jsx(Il,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(O,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>$(!0),children:[e.jsx(wt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),_&&e.jsx(qr,{fileName:_.fileName,fileType:_.fileType,fileUrl:_.fileUrl,fileSize:_.fileSize,attachmentId:_.attachmentId,onDownload:ox,open:!!_,onClose:()=>W(null)}),!we&&e.jsx(P0,{open:I,onClose:()=>$(!1),onConfirm:ce,requestIdDisplay:h,requestTitle:q.title,existingParticipants:ke}),!we&&l&&e.jsx(E0,{open:M,onClose:()=>R(!1),onConfirm:Re,requestIdDisplay:h,requestTitle:q.title,existingParticipants:ke,currentLevels:c,maxApprovalLevels:m,onPolicyViolation:p}),e.jsx(ht,{open:G.open,onOpenChange:me=>J(Oe=>({...Oe,open:me})),children:e.jsxs(mt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Mt,{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:G.errors.map((me,Oe)=>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:me.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:me.reason})]},Oe))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",E.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",E.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Dt,{children:e.jsx(O,{onClick:()=>J({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(F0,{open:C,onClose:()=>H(!1),success:z.success,title:z.title,message:z.message})]})}function kk({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(_0,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d})})}function Dk({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const c=o.toLowerCase();return c==="approved"?e.jsx(Ve,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(At,{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(Ee,{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(O,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(Sn,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(oe,{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(Ls,{content:t.description,className:"text-gray-700"})})]}),e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Initiator"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:st(new Date(t.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),t.approvers&&t.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),t.approvers.map((o,c)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsx("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:o.levelName||`Approver ${o.levelNumber}`}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l(o.designation,o.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[n(o.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o.status})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:st(new Date(o.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),o.remarks?e.jsx(Ls,{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(oe,{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(Ls,{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(Ee,{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 Rk({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(ur,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(Ve,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(At,{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(ur,{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(oe,{className:`text-xs ${c.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(oa,{value:i,className:"h-3 mb-2",indicatorClassName:c.progress,"data-testid":`${r}-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("span",{className:"text-gray-600","data-testid":`${r}-elapsed`,children:[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: ",_a(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(ml,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function Ik({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var g,f;const c=yk((t==null?void 0:t.priority)||"standard"),d=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",m=(g=t==null?void 0:t.form16Submission)==null?void 0:g.displayStatus,p=m&&/balance mismatch|failed/i.test(String(m)),x=m&&String(m).toLowerCase()==="duplicate",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":x?"bg-amber-100 !text-amber-800 border-amber-200":"bg-gray-100 !text-gray-700 border-gray-200",icon:Mh((t==null?void 0:t.status)||"pending").icon,label:m}:Mh((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(O,{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(Cs,{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(Ee,{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(oe,{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(oe,{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),y=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",j=(y==null?void 0:y.toString().toUpperCase())||"",v=j==="FORM_16",N=b==="CLAIM_MANAGEMENT"||y==="claim-management",T=b==="DEALER_CLAIM"||j==="DEALER CLAIM"||j==="DEALER_CLAIM";let A="Non-Templatized",k="bg-purple-100 !text-purple-600 border-purple-200";return v?(A="Form 16",k="bg-emerald-100 !text-emerald-700 border-emerald-200"):T?(A="Dealer Claim",k="bg-blue-100 !text-blue-700 border-blue-200"):N?(A="Claim Management",k="bg-blue-100 !text-blue-700 border-blue-200"):j==="TEMPLATE"&&(A="Template"),e.jsx(oe,{className:`${k} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:A})})()]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&i&&((f=t==null?void 0:t.status)==null?void 0:f.toLowerCase())==="closed"&&e.jsxs(O,{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(Sn,{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(O,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:r,disabled:s,"data-testid":"refresh-button",children:[e.jsx(_t,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:s?"Refreshing...":"Refresh"})]})]})]}),e.jsx("div",{className:"mt-3 ml-0 sm:ml-14",children:e.jsx("h2",{className:"text-base sm:text-lg md:text-xl font-semibold text-gray-900 line-clamp-2","data-testid":"request-title",children:t.title})})]}),l!==void 0&&e.jsx("div",{className:`px-3 sm:px-4 md:px-6 py-3 sm:py-4 border-b border-gray-200 ${o?"bg-gradient-to-r from-gray-100 to-gray-200":"bg-gradient-to-r from-blue-50 to-indigo-50"}`,"data-testid":"sla-section",children:e.jsx(Rk,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function Qd(t){return(await Se.get(`/summaries/${t}`)).data.data}async function Fk(t,s){return(await Se.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function Pk(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await Se.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 M0(t){await Se.patch(`/summaries/shared/${t}/view`)}async function L0(t){var s;try{return(await Se.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 Ek(t){return(await Se.get(`/summaries/${t}/recipients`)).data.data||[]}function _k({activityInfo:t,className:s,createdAt:a,updatedAt:r}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(Z,{className:s,children:e.jsx(ee,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Activity information not available"})})});const n=l=>{const o=typeof l=="string"?parseFloat(l):l;return isNaN(o)?"N/A":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`},i=l=>{if(!l)return"N/A";try{return st(new Date(l),"MMM d, yyyy")}catch{return l}};return e.jsxs(Z,{className:s,children:[e.jsx(de,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(bt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.activityName})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Type"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.activityType})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Location"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(Vc,{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(Pa,{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(Et,{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(Ls,{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:js(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:js(r)})]})]})]})]})}function Mk({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(Z,{className:s,children:e.jsx(ee,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(Z,{className:s,children:[e.jsx(de,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(Pl,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Code"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.dealerCode})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.dealerName})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Contact Information"}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx(Ca,{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(bi,{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(Vc,{className:"w-4 h-4 text-gray-400 mt-0.5"}),e.jsx("span",{children:t.address})]})]})]})]})]}):(console.warn("[DealerInformationCard] dealerInfo is missing"),e.jsx(Z,{className:s,children:e.jsx(ee,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function Lk({dmsDetails:t,claimAmount:s,estimatedBudgetBreakdown:a,closedExpensesBreakdown:r,visibility:n,onEditClaimAmount:i,className:l}){const o=x=>x==null||Number.isNaN(x)?"₹0.00":`₹${x.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,c=x=>{if(!x)return"";try{return st(new Date(x),"MMM d, yyyy, h:mm a")}catch{return x||""}},d=x=>!x||x.length===0?0:x.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(de,{children:[e.jsxs(ue,{className:"text-base flex items-center gap-2",children:[e.jsx(zt,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(Te,{children:"Workflow reference numbers"})]}),e.jsxs(ee,{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(zt,{className:"w-4 h-4 text-purple-600"}),e.jsx(re,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice Details"})]}),e.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(O,{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(Et,{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(Et,{className:"w-4 h-4 text-pink-600"}),e.jsx(re,{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((x,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: ",x.DOC_NO||"N/A"]}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-sm text-white font-medium self-start whitespace-nowrap ${x.MSG_TYP==="E"?"bg-red-500":"bg-green-500"}`,children:x.MSG_TYP==="E"?"Error":x.MSG_TYP==="S"?"Success":x.MSG_TYP||"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:x.TRNS_UNIQ_NO||"N/A"})]}),x.TDS_AMT!==void 0&&x.TDS_AMT!==null&&x.TDS_AMT!==""&&(Number.isNaN(Number(x.TDS_AMT))||Number(x.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(x.TDS_AMT))?String(x.TDS_AMT):o(Number(x.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:x.CREDITED_TOTAL_AMT!==void 0&&x.CREDITED_TOTAL_AMT!==null&&x.CREDITED_TOTAL_AMT!==""?Number.isNaN(Number(x.CREDITED_TOTAL_AMT))?String(x.CREDITED_TOTAL_AMT):o(Number(x.CREDITED_TOTAL_AMT)):o(0)})]})]}),x.MESSAGE&&e.jsx("div",{className:"text-gray-700 italic border-l-2 border-pink-200 pl-1.5 mt-1 leading-tight",children:x.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(Pa,{className:"w-4 h-4 text-green-600"}),e.jsx(re,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),n.canEditClaimAmount&&i&&e.jsxs(O,{variant:"outline",size:"sm",onClick:i,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(ni,{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(Et,{className:"w-4 h-4 text-amber-600"}),e.jsx(re,{className:"text-xs font-semibold text-amber-900 uppercase tracking-wide",children:"Estimated Budget Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[a.map((x,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:x.description,children:x.description}),e.jsx("span",{className:"font-bold text-gray-900 whitespace-nowrap",children:o(x.totalAmt??x.amount+(x.gstAmt??0))})]}),(x.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(x.amount)]}),e.jsxs("span",{children:["GST: ",o(x.gstAmt)]})]}),x.hsnCode&&e.jsxs("span",{children:["HSN/SAC: ",x.hsnCode]})]}),!(x.gstAmt??0)&&x.hsnCode&&e.jsxs("div",{className:"text-[9px] text-gray-500 pl-2 italic",children:["HSN/SAC: ",x.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(Et,{className:"w-4 h-4 text-indigo-600"}),e.jsx(re,{className:"text-xs font-semibold text-indigo-900 uppercase tracking-wide",children:"Closed Expenses Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[r.map((x,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:x.description,children:x.description}),e.jsx("span",{className:"font-bold text-gray-900 whitespace-nowrap",children:o(x.totalAmt??x.amount+(x.gstAmt??0))})]}),(x.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(x.amount)]}),e.jsxs("span",{children:["GST: ",o(x.gstAmt)]})]}),x.hsnCode&&e.jsxs("span",{children:["HSN/SAC: ",x.hsnCode]})]}),!(x.gstAmt??0)&&x.hsnCode&&e.jsxs("div",{className:"text-[9px] text-gray-500 pl-2 italic",children:["HSN/SAC: ",x.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 Ok({proposalDetails:t,className:s}){const r=(()=>{const o=t.totalEstimatedBudget??t.estimatedBudgetTotal;return o??(t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((d,m)=>{const p=m.amount||0,x=m.gstAmt||0,h=m.totalAmt||Number(p)+Number(x);return d+(Number.isNaN(h)?0:h)},0):0)})(),n=o=>o==null||Number.isNaN(o)?"₹0.00":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,i=o=>{if(!o)return"";try{return st(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return st(new Date(o),"MMM d, yyyy")}catch{return o||"-"}};return e.jsxs(Z,{className:s,children:[e.jsxs(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(Et,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs(Te,{children:["Submitted on ",i(t.submittedOn)]})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Cost Breakup"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Item Description"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Base Amount"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"GST"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Total"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-200",children:[(t.costBreakup||[]).map((o,c)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsxs("td",{className:"px-4 py-3 text-sm text-gray-900",children:[e.jsx("div",{children:o.description}),o.gstRate?e.jsx("div",{className:"text-[10px] text-gray-400",children:o.cgstAmt?`CGST: ${o.gstRate/2}%, SGST: ${o.gstRate/2}%`:`IGST: ${o.gstRate}%`}):null]}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.amount)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.gstAmt)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right font-medium",children:n(o.totalAmt||Number(o.amount||0)+Number(o.gstAmt||0))})]},c)),e.jsxs("tr",{className:"bg-green-50 font-semibold",children:[e.jsx("td",{colSpan:3,className:"px-4 py-3 text-sm text-gray-900",children:"Estimated Budget (Total Inclusive of GST)"}),e.jsx("td",{className:"px-4 py-3 text-sm text-green-700 text-right",children:n(r)})]})]})]})})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Timeline for Closure"}),e.jsx("div",{className:"mt-2 bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{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 $k({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(de,{children:e.jsx(ue,{className:"text-base",children:"Request Initiator"})}),e.jsx(ee,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(ds,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(ms,{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(Ca,{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(bi,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function O0(t,s){var a,r,n,i,l;try{if(!hi(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||{},x=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,y=o.activityName||o.activity_name||"",j=o.activityType||o.activity_type||"",v=o.location||"",N=p.proposalEstimatedBudget??p.proposal_estimated_budget??p.initialEstimatedBudget??p.initial_estimated_budget??o.estimatedBudget??o.estimated_budget,T=(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),A=T!=null?Number(T):void 0,k=Array.isArray(g)&&g.length>0?g.map(C=>({description:C.description||C.itemDescription||C.item_description||"",amount:Number(C.amount)||0,gstRate:C.gstRate??C.gst_rate,gstAmt:C.gstAmt??C.gst_amt,cgstAmt:C.cgstAmt??C.cgst_amt,sgstAmt:C.sgstAmt??C.sgst_amt,igstAmt:C.igstAmt??C.igst_amt,totalAmt:C.totalAmt??C.total_amt,hsnCode:C.hsnCode||C.hsn_code||C.hsnCd||C.hsn_cd||""})):(d==null?void 0:d.closedExpenses)||(d==null?void 0:d.closed_expenses)||(d==null?void 0:d.closedExpensesBreakdown)||[],D={activityName:y,activityType:j,defaultGstRate:o.defaultGstRate||18,requestedDate:o.activityDate||o.activity_date||t.createdAt,location:v,period:f&&b?{startDate:f,endDate:b}:void 0,estimatedBudget:N,closedExpenses:A,closedExpensesBreakdown:k,description:t.description||""},F={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)||""};(!F.dealerCode||!F.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!o,dealerCode:F.dealerCode,dealerName:F.dealerName,rawClaimDetails:o,availableKeys:o?Object.keys(o):[]});const w=(c==null?void 0:c.expectedCompletionDate)||(c==null?void 0:c.expected_completion_date),_=!!(c&&Object.keys(c).length>0&&(Array.isArray(c.costItems||c.cost_items)&&(c.costItems||c.cost_items).length>0||Array.isArray(c.costBreakup||c.cost_breakup)&&(c.costBreakup||c.cost_breakup).length>0||c.proposalDocumentUrl||c.proposal_document_url||c.totalEstimatedBudget||c.total_estimated_budget||c.expectedCompletionDate||c.expected_completion_date||c.submittedAt||c.submitted_at))?{proposalDocumentUrl:c.proposalDocumentUrl||c.proposal_document_url,costBreakup:Array.isArray(c.costItems||c.cost_items)?(c.costItems||c.cost_items).map(C=>({description:C.description||C.itemDescription||C.item_description||"",amount:Number(C.amount)||0,gstRate:Number(C.gstRate??C.gst_rate??0),gstAmt:Number(C.gstAmt??C.gst_amt??0),cgstAmt:Number(C.cgstAmt??C.cgst_amt??0),sgstAmt:Number(C.sgstAmt??C.sgst_amt??0),igstAmt:Number(C.igstAmt??C.igst_amt??0),totalAmt:Number(C.totalAmt??C.total_amt??0),hsnCode:C.hsnCode||C.hsn_code||""})):Array.isArray(c.costBreakup||c.cost_breakup)?(c.costBreakup||c.cost_breakup).map(C=>({description:C.description||C.itemDescription||C.item_description||"",amount:Number(C.amount)||0,gstRate:C.gstRate??C.gst_rate,gstAmt:C.gstAmt??C.gst_amt,cgstAmt:C.cgstAmt??C.cgst_amt,sgstAmt:C.sgstAmt??C.sgst_amt,igstAmt:C.igstAmt??C.igst_amt,totalAmt:C.totalAmt??C.total_amt,hsnCode:C.hsnCode||C.hsn_code||""})):[],totalEstimatedBudget:c.totalEstimatedBudget||c.total_estimated_budget||0,timelineMode:c.timelineMode||c.timeline_mode,expectedCompletionDate:w,timelineForClosure:w,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,W={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||""},I=t.invoice||t.claimInvoice||t.claim_invoice||((n=t.claimRequest)==null?void 0:n.invoice)||((i=t.request)==null?void 0:i.invoice)||x||{},$=o||{},M={eInvoiceNumber:I.invoiceNumber||I.invoice_number||$.eInvoiceNumber||$.e_invoice_number||I.dmsNumber||I.dms_number,eInvoiceDate:I.invoiceDate||I.invoice_date||$.eInvoiceDate||$.e_invoice_date,dmsNumber:I.dmsNumber||I.dms_number||$.dmsNumber||$.dms_number,creditNoteNumber:h.creditNoteNumber||h.credit_note_number||$.creditNoteNumber||$.credit_note_number,creditNoteDate:h.creditNoteDate||h.credit_note_date||$.creditNoteDate||$.credit_note_date,creditNoteAmount:h.creditNoteAmount!==void 0&&h.creditNoteAmount!==null?Number(h.creditNoteAmount):h.credit_note_amount!==void 0&&h.credit_note_amount!==null?Number(h.credit_note_amount):$.creditNoteAmount!==void 0&&$.creditNoteAmount!==null?Number($.creditNoteAmount):$.credit_note_amount!==void 0&&$.credit_note_amount!==null?Number($.credit_note_amount):void 0,irn:I.irn||$.irn,ackNo:I.ackNo||I.ack_no||$.ackNo||$.ack_no,ackDate:I.ackDate||I.ack_date||$.ackDate||$.ack_date,signedInvoiceUrl:I.signedInvoiceUrl||I.signed_invoice_url||$.signedInvoiceUrl||$.signed_invoice_url,taxBreakdown:I.taxBreakdown||$.taxBreakdown,creditNoteWfmData:(((l=t.creditNote)==null?void 0:l.items)||t.creditNoteWfmData||o.creditNoteWfmData||[]).map(C=>{var H;return{...C,DOC_NO:C.creditNoteNumber||((H=t.creditNote)==null?void 0:H.creditNoteNumber)||C.DOC_NO,TRNS_UNIQ_NO:C.transactionNo||C.TRNS_UNIQ_NO,MESSAGE:C.description||C.MESSAGE,TDS_AMT:C.tdsAmount||C.TDS_AMT,CREDITED_TOTAL_AMT:C.creditAmount||C.amount||C.CREDITED_TOTAL_AMT}})},R={estimated:D.estimatedBudget||0,closed:D.closedExpenses||0};return{activityInfo:D,dealerInfo:F,proposalDetails:_,ioDetails:Object.keys(W).some(C=>W[C])?W:void 0,dmsDetails:Object.keys(M).some(C=>M[C])?M:void 0,claimAmount:R}}catch(o){return console.error("[claimDataMapper] Error mapping claim data:",o),null}}function $0(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:[],x=p.find(v=>{var N;return v.userId===s||v.user_id===s||((N=v.user)==null?void 0:N.userId)===s}),h=m((x==null?void 0:x.userEmail)||(x==null?void 0:x.user_email)||(x==null?void 0:x.email)||((a=x==null?void 0:x.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 N,T;return(v.userId===s||v.user_id===s||((N=v.user)==null?void 0:N.userId)===s||((T=v.user)==null?void 0:T.user_id)===s)&&(v.participantType||v.participant_type||v.type||"").toString().toUpperCase()==="DEALER"}))return"DEALER";const b=t.approvalLevels||[];return b.find(v=>{var N;return v.levelNumber===3&&(v.approverId===s||((N=v.approver)==null?void 0:N.userId)===s)})?"DEPARTMENT_LEAD":b.find(v=>{var N;return(v.approverId===s||((N=v.approver)==null?void 0:N.userId)===s)&&v.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(m){return console.error("[claimDataMapper] Error determining user role:",m),"SPECTATOR"}}function U0(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 Uk({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:l,onReject:o,onPause:c,onResume:d,onRetrigger:m,summaryId:p,refreshTrigger:x,pausedByUserId:h,currentUserId:g,apiRequest:f,onEditClaimAmount:b,hideApproveReject:y=!1}){var R,C,H,z,P;const{user:j}=us(),[v,N]=u.useState([]),[T,A]=u.useState(!1),[k,D]=u.useState(!1),F=(t==null?void 0:t.status)==="closed",w=((R=t==null?void 0:t.pauseInfo)==null?void 0:R.isPaused)||!1,L=h||((H=(C=t==null?void 0:t.pauseInfo)==null?void 0:C.pausedBy)==null?void 0:H.userId),_=g||(j==null?void 0:j.userId)||"",W=!w&&!F&&(r||s),I=w&&d&&(r||s),$=w&&s&&L&&L!==_&&m;u.useEffect(()=>{if(!w||!r||!(t!=null&&t.requestId)){D(!1);return}(async()=>{var U;try{const E=(((U=(await xr.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:U.notifications)||[]).some(V=>V.requestId===t.requestId&&V.notificationType==="pause_retrigger_request");D(E)}catch(Y){console.error("Failed to check retrigger notifications:",Y),D(!1)}})()},[w,r,t==null?void 0:t.requestId,x]),u.useEffect(()=>{(async()=>{if(!F||!p||!s){N([]);return}try{A(!0);const U=await Ek(p);N(U)}catch(U){console.error("Failed to fetch shared recipients:",U),N([])}finally{A(!1)}})()},[F,p,s,x]);const M=u.useMemo(()=>{if(!f||!hi(f))return null;const S=O0(f);if(!S)return null;const U=$0(f,_),Y=U0(U);return{claimRequest:S,visibility:Y}},[f,_]);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(de,{className:"pb-2",children:e.jsx(ue,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(ee,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(O,{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(Il,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(O,{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(wt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),W&&c&&e.jsxs(O,{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(pr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),I&&e.jsxs(O,{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(dl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),$&&e.jsxs(O,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:m,"data-testid":"request-resume-button",children:[e.jsx(Ze,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Request Resume"]}),e.jsxs("div",{className:"pt-3 sm:pt-4 space-y-2",children:[r&&!w&&!y&&e.jsxs(e.Fragment,{children:[e.jsxs(O,{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(Ve,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(O,{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(At,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),w&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:L===_?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:[k&&e.jsx(Ze,{className:"w-3.5 h-3.5"}),k?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:k?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&L!==_&&k?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[e.jsx(Ze,{className:"w-3.5 h-3.5"}),"Initiator has requested resume"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Please review and resume if appropriate"})]}):r&&L!==_?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&&L&&L!==_?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Approver has paused this workflow"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:$?'Click "Request Resume" to notify approver':"Resume request sent - Waiting for approver"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Workflow is paused"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Actions are disabled until resumed"})]})})]})]})]}),e.jsxs(Z,{"data-testid":"spectators-card",children:[e.jsx(de,{className:"pb-2",children:e.jsx(ue,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(ee,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((S,U)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${U}`,children:[e.jsx(ds,{className:"h-8 w-8",children:e.jsx(ms,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:S.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:S.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:S.role})]})]},U)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),F&&s&&e.jsxs(Z,{"data-testid":"shared-recipients-card",children:[e.jsx(de,{className:"pb-2",children:e.jsxs(ue,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Sn,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(ee,{className:"space-y-3",children:T?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((S,U)=>{const Y=(S.displayName||"NA").split(" ").map(B=>B[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${U}`,children:[e.jsx(ds,{className:"h-8 w-8",children:e.jsx(ms,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:Y})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:S.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:S.email}),S.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},S.userId||U)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),M&&e.jsx(Lk,{ioDetails:M.claimRequest.ioDetails,dmsDetails:M.claimRequest.dmsDetails,claimAmount:{amount:M.claimRequest.claimAmount.closed||M.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(z=M.claimRequest.proposalDetails)==null?void 0:z.costBreakup,closedExpensesBreakdown:(P=M.claimRequest.activityInfo)==null?void 0:P.closedExpensesBreakdown,visibility:M.visibility,onEditClaimAmount:b})]})}function Bk({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=u.useState(r),[d,m]=u.useState(!1),p=(o==null?void 0:o.length)||0,x=u.useMemo(()=>o.slice(0,500),[o]),h=async()=>{try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(ht,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(mt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(pt,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex items-center justify-center",children:e.jsx(Ve,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(ut,{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(oe,{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(Vs,{value:x,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(p,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-green-50 border-green-200 text-green-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Ve,{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(O,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(O,{onClick:h,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Ve,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function zk({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=u.useState(r),[d,m]=u.useState(!1),p=(o==null?void 0:o.length)||0,x=u.useMemo(()=>o.slice(0,500),[o]),h=async()=>{if(!x.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(ht,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(mt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(pt,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx(At,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ut,{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(oe,{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(Vs,{value:x,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(p,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-red-50 border-red-200 text-red-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Ze,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Rejection Guidelines"}),e.jsx("div",{children:"Please provide specific, actionable feedback to help the initiator improve their request."})]})]}),e.jsxs(Dt,{className:"mt-4",children:[e.jsx(O,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(O,{variant:"destructive",onClick:h,disabled:d,children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function Vk({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,c]=u.useState(""),[d,m]=u.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)}},x=()=>{d||(c(""),s())};return e.jsx(ht,{open:t,onOpenChange:x,children:e.jsxs(mt,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:x,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:d,children:[e.jsx(vt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center",children:e.jsx(Ze,{className:"w-5 h-5 text-orange-600"})}),e.jsx(ut,{className:"text-xl font-bold text-gray-900",children:"Skip Approver"})]})}),e.jsxs("div",{className:"space-y-4 px-6 py-4 overflow-y-auto flex-1",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ze,{className:"w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-orange-900 mb-1",children:"Important Notice"}),e.jsx("p",{className:"text-sm text-orange-800",children:"You are about to skip the current approver. The request will be moved to the next approval level."})]})]})}),(i||l)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-semibold text-gray-700",children:"Request Details"}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3 space-y-1",children:[i&&e.jsxs("p",{className:"text-sm text-gray-900",children:[e.jsx("span",{className:"font-medium",children:"Request ID:"})," ",i]}),l&&e.jsxs("p",{className:"text-sm text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Title:"})," ",l]})]})]}),(r||n)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-semibold text-gray-700",children:"Approver Being Skipped"}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-1",children:[n&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Level:"})," ",n]}),r&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Approver:"})," ",r]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(Vs,{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(O,{type:"button",variant:"outline",onClick:x,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(O,{type:"button",onClick:p,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:d||!o.trim(),children:[e.jsx(Ze,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function Wk({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:l,documentError:o,request:c,skipApproverData:d,actionStatus:m,existingParticipants:p,currentLevels:x,maxApprovalLevels:h,onPolicyViolation:g,setShowApproveModal:f,setShowRejectModal:b,setShowAddApproverModal:y,setShowAddSpectatorModal:j,setShowSkipApproverModal:v,setShowActionStatusModal:N,setPreviewDocument:T,setDocumentError:A,setSkipApproverData:k,setActionStatus:D,handleApproveConfirm:F,handleRejectConfirm:w,handleAddApprover:L,handleAddSpectator:_,handleSkipApprover:W,downloadDocument:I,documentPolicy:$}){return e.jsxs(e.Fragment,{children:[e.jsx(Bk,{open:t,onClose:()=>f(!1),onConfirm:F,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(zk,{open:s,onClose:()=>b(!1),onConfirm:w,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(E0,{open:a,onClose:()=>y(!1),onConfirm:L,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p,currentLevels:x,maxApprovalLevels:h,onPolicyViolation:g}),e.jsx(P0,{open:r,onClose:()=>j(!1),onConfirm:_,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p}),e.jsx(Vk,{open:n,onClose:()=>{v(!1),k(null)},onConfirm:W,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),l&&e.jsx(qr,{fileName:l.fileName,fileType:l.fileType,fileUrl:Dn(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:I,open:!!l,onClose:()=>T(null)}),m&&e.jsx(F0,{open:i,onClose:()=>{N(!1),D(null)},success:m.success,title:m.title,message:m.message}),e.jsx(ht,{open:o.show,onOpenChange:M=>A(R=>({...R,show:M})),children:e.jsxs(mt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Mt,{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((M,R)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:M.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:M.reason})]},R))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",$.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",$.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Dt,{children:e.jsx(O,{onClick:()=>A({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const B0={DocumentsTab:jk,ActivityTab:wk,WorkNotesTab:kk,SummaryTab:Dk,RequestDetailHeader:Ik,QuickActionsSidebar:Uk,RequestDetailModals:Wk};function Kd({className:t,...s}){return e.jsx(Sj,{"data-slot":"checkbox",className:$e("peer border bg-input-background dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(Aj,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Ha,{className:"size-3.5"})})})}function z0({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,l]=u.useState(""),[o,c]=u.useState([]),[d,m]=u.useState(new Set),[p,x]=u.useState(!1),[h,g]=u.useState(!1);u.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),x(!1);return}const j=setTimeout(async()=>{var v;try{x(!0);const N=i.slice(1),T=await Sa(N,10),A=((v=T==null?void 0:T.data)==null?void 0:v.data)||(T==null?void 0:T.data)||[];c(Array.isArray(A)?A:[])}catch(N){console.error("Failed to search users:",N),Q.error("Failed to search users")}finally{x(!1)}},300);return()=>clearTimeout(j)},[i,t]);const f=j=>{m(v=>{const N=new Set(v);return N.has(j)?N.delete(j):N.add(j),N})},b=async()=>{var j,v;if(d.size===0){Q.error("Please select at least one user to share with");return}try{g(!0),await Fk(a,Array.from(d)),Q.success(`Summary shared with ${d.size} user(s)`),m(new Set),l(""),c([]),n==null||n(),s()}catch(N){console.error("Failed to share summary:",N),Q.error(((v=(j=N==null?void 0:N.response)==null?void 0:j.data)==null?void 0:v.message)||"Failed to share summary")}finally{g(!1)}},y=()=>{m(new Set),l(""),c([]),s()};return e.jsx(ht,{open:t,onOpenChange:y,children:e.jsxs(mt,{className:"sm:max-w-[500px]",children:[e.jsx(pt,{children:e.jsx(ut,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Request"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:r})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(_e,{id:"user-search",placeholder:"Type @ to search users...",value:i,onChange:j=>l(j.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(j=>{const v=d.has(j.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(j.userId),children:[e.jsx("div",{onClick:N=>N.stopPropagation(),onMouseDown:N=>N.stopPropagation(),className:"flex items-center",children:e.jsx(Kd,{checked:v,onCheckedChange:()=>f(j.userId)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:j.displayName||j.email})]}),(j.designation||j.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:j.designation||j.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:j.email})]})]},j.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(j=>{const v=o.find(N=>N.userId===j);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)||j}),e.jsx("button",{onClick:()=>f(j),className:"ml-1 hover:text-red-600",children:e.jsx(vt,{className:"h-3 w-3"})})]},j)})})]})]}),e.jsxs(Dt,{children:[e.jsx(O,{variant:"outline",onClick:y,disabled:h,children:"Cancel"}),e.jsx(O,{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 V0({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=u.useState(""),[o,c]=u.useState(""),[d,m]=u.useState(!1),p=()=>rs().add(1,"month").format("YYYY-MM-DD"),x=()=>rs().add(1,"month").format("YYYY-MM-DD"),h=()=>rs().add(1,"day").format("YYYY-MM-DD");u.useEffect(()=>{t&&!o&&c(p())},[t]);const g=async()=>{var v,N,T,A;if(!i.trim()){Q.error("Please provide a reason for pausing");return}if(!o){Q.error("Please select a resume date");return}const b=rs(o),y=rs().add(1,"month"),j=rs().add(1,"day");if(b.isAfter(y)){Q.error("Resume date cannot be more than 1 month from now");return}if(b.isBefore(j,"day")){Q.error("Resume date must be at least 1 day from now");return}try{m(!0),await fC(a,r,i.trim(),b.toDate()),Q.success("Workflow paused successfully"),n&&await n(),l(""),c(p()),s()}catch(k){console.error("Failed to pause workflow:",k),Q.error(((N=(v=k==null?void 0:k.response)==null?void 0:v.data)==null?void 0:N.error)||((A=(T=k==null?void 0:k.response)==null?void 0:T.data)==null?void 0:A.message)||"Failed to pause workflow")}finally{m(!1)}},f=()=>{d||(l(""),c(p()),s())};return e.jsx(ht,{open:t,onOpenChange:f,children:e.jsxs(mt,{className:"sm:max-w-[500px]",children:[e.jsx(pt,{children:e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"w-5 h-5 text-orange-600"}),"Pause Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-orange-800",children:[e.jsx("strong",{children:"Note:"})," Pausing will temporarily halt TAT calculations and notifications. The workflow will automatically resume on the selected date."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Vs,{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(re,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(_e,{id:"resume-date",type:"date",value:o,onChange:b=>c(b.target.value),min:h(),max:x(),className:"text-sm",disabled:d}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum 1 month from today. The workflow will automatically resume on this date."})]})]}),e.jsxs(Dt,{children:[e.jsx(O,{variant:"outline",onClick:f,disabled:d,children:"Cancel"}),e.jsx(O,{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(pr,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function W0({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=u.useState(""),[l,o]=u.useState(!1),c=async()=>{var m,p,x,h;try{o(!0),await bC(a,n.trim()||void 0),Q.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),Q.error(((p=(m=g==null?void 0:g.response)==null?void 0:m.data)==null?void 0:p.error)||((h=(x=g==null?void 0:g.response)==null?void 0:x.data)==null?void 0:h.message)||"Failed to resume workflow")}finally{o(!1)}},d=()=>{l||(i(""),s())};return e.jsx(ht,{open:t,onOpenChange:d,children:e.jsxs(mt,{className:"sm:max-w-[500px]",children:[e.jsx(pt,{children:e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(dl,{className:"w-5 h-5 text-green-600"}),"Resume Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-green-50 border border-green-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-green-800",children:[e.jsx("strong",{children:"Note:"})," Resuming will restart TAT calculations and notifications. The workflow will continue from where it was paused."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(Vs,{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(O,{variant:"outline",onClick:d,disabled:l,children:"Cancel"}),e.jsx(O,{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(dl,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function H0({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=u.useState(!1),o=async()=>{var c,d,m,p;try{l(!0),await jC(a),Q.success("Retrigger request sent to approver"),n&&await n(),s()}catch(x){console.error("Failed to retrigger pause:",x),Q.error(((d=(c=x==null?void 0:x.response)==null?void 0:c.data)==null?void 0:d.error)||((p=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:p.message)||"Failed to send retrigger request")}finally{l(!1)}};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-[450px]",children:[e.jsx(pt,{children:e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-orange-600"}),"Request Resume"]})}),e.jsxs("div",{className:"py-4",children:[e.jsxs("p",{className:"text-sm text-gray-700 mb-4",children:["You are requesting the approver",r?` (${r})`:""," to cancel the pause and resume work on this request."]}),e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-orange-800",children:"A notification will be sent to the approver who paused this workflow, requesting them to resume it."})})]}),e.jsxs(Dt,{children:[e.jsx(O,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(O,{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(Ze,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:Hk,ActivityTab:Gk,WorkNotesTab:Yk,SummaryTab:Qk,RequestDetailHeader:Kk,QuickActionsSidebar:Xk,RequestDetailModals:Jk}=B0;let Zk=class extends u.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(O,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(O,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function qk({requestId:t,onBack:s,dynamicRequests:a=[]}){var sn,tr,Sr,sr,Ar,Tr,ar,Oa,rr;const n=Aa().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=u.useState(l),[d,m]=u.useState(!1),[p,x]=u.useState(null),[h,g]=u.useState(null),[f,b]=u.useState(!1),[y,j]=u.useState(0),[v,N]=u.useState(!1),[T,A]=u.useState(!1),[k,D]=u.useState(!1),[F,w]=u.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[L,_]=u.useState({open:!1,violations:[]}),{user:W}=us(),{request:I,apiRequest:$,loading:M,refreshing:R,refreshDetails:C,currentApprovalLevel:H,isSpectator:z,isInitiator:P,existingParticipants:S,accessDenied:U}=Gd(n,a,W),{mergedMessages:Y,unreadWorkNotes:B,workNoteAttachments:E,setWorkNoteAttachments:V}=k0(n,$,o,W),{uploadingDocument:G,triggerFileInput:J,previewDocument:q,setPreviewDocument:se,documentPolicy:ne,documentError:te,setDocumentError:ge}=D0($,C),{showApproveModal:we,setShowApproveModal:fe,showRejectModal:ke,setShowRejectModal:le,showAddApproverModal:Ne,setShowAddApproverModal:ae,showAddSpectatorModal:he,setShowAddSpectatorModal:ie,showSkipApproverModal:je,setShowSkipApproverModal:Fe,showActionStatusModal:Ue,setShowActionStatusModal:Ce,skipApproverData:ce,setSkipApproverData:Re,actionStatus:qe,setActionStatus:at,handleApproveConfirm:ft,handleRejectConfirm:Ft,handleAddApprover:me,handleSkipApprover:Oe,handleAddSpectator:xe}=I0(n,H,C),{conclusionRemark:Je,setConclusionRemark:Ke,conclusionLoading:rt,conclusionSubmitting:Xe,aiGenerated:lt,handleGenerateConclusion:et,handleFinalizeConclusion:xt,generationAttempts:Hs,generationFailed:ls,maxAttemptsReached:Nt}=R0(I,n,P,C,s,at,Ce);u.useEffect(()=>{(async()=>{var As;try{const ca=await pa("SYSTEM_SETTINGS"),kr=await pa("WORKFLOW_SHARING"),Dr=[...ca,...kr],Da={};Dr.forEach(nr=>{Da[nr.configKey]=nr.configValue}),w({maxApprovalLevels:parseInt(Da.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Da.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((As=Da.ALLOW_ADD_SPECTATOR)==null?void 0:As.toLowerCase())==="true",maxSpectators:parseInt(Da.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(ca){console.error("Failed to load system policy:",ca)}})()},[]),u.useEffect(()=>{const As=new URLSearchParams(window.location.search).get("tab");As&&c(As)},[n]);const gt=()=>{C()},Pt=()=>{N(!0)},Ss=()=>{A(!0)},as=async()=>{await C()},Ya=()=>{D(!0)},Qa=async()=>{await C()},wr=async()=>{await C()},Ta=async()=>{if(!($!=null&&$.requestId)){Q.error("Request ID not found");return}if(!p){Q.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Ot=((I==null?void 0:I.status)==="approved"||(I==null?void 0:I.status)==="rejected")&&P,ka=(I==null?void 0:I.status)==="closed"||(I==null?void 0:I.status)==="approved"&&!P||(I==null?void 0:I.status)==="rejected"&&!P,Us=((I==null?void 0:I.templateType)||(I==null?void 0:I.template_type)||"").toString().toUpperCase()==="FORM_16";u.useEffect(()=>{Us&&o==="worknotes"&&c("overview")},[Us,o]),u.useEffect(()=>{(async()=>{if(!ka||!($!=null&&$.requestId)){g(null),x(null);return}try{b(!0);const As=await L0($.requestId);if(As!=null&&As.summaryId){x(As.summaryId);try{const ca=await Qd(As.summaryId);g(ca)}catch(ca){console.error("Failed to fetch summary details:",ca),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{b(!1)}})()},[ka,$==null?void 0:$.requestId]);const en=((I==null?void 0:I.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(M&&!I&&!$)return e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(_t,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading custom request details..."})]})});if(U!=null&&U.denied)return e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"access-denied-state",children:e.jsxs("div",{className:"max-w-lg w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(Lp,{className:"w-10 h-10 text-red-500"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Access Denied"}),e.jsx("p",{className:"text-gray-600 mb-6 leading-relaxed",children:U.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(O,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(O,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});if(!I)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(Ee,{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(O,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(O,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});const tn=(W==null?void 0:W.role)==="MANAGEMENT"||(W==null?void 0:W.role)==="ADMIN",Cr=((sn=nt.getUserData())==null?void 0:sn.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(Kk,{request:I,refreshing:R,onBack:s||(()=>window.history.back()),onRefresh:gt,onShareSummary:Ta,isInitiator:P,slaData:((tr=I==null?void 0:I.summary)==null?void 0:tr.sla)||(I==null?void 0:I.sla)||null,isPaused:((Sr=I==null?void 0:I.pauseInfo)==null?void 0:Sr.isPaused)||!1}),e.jsxs(Ri,{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(Ii,{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(Ut,{value:"overview",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-overview",children:[e.jsx(Op,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:Us?"Form 16":"Overview"})]}),ka&&h&&e.jsxs(Ut,{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(Wc,{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(Ut,{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(Ks,{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(Ut,{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(Ee,{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(Ut,{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(zt,{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(Ut,{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(Qs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),B>0&&e.jsx(oe,{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:B>9?"9+":B})]})]})}),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(Bt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:Us?e.jsx(MC,{request:I}):e.jsx(DC,{request:I,isInitiator:P,needsClosure:Ot,conclusionRemark:Je,setConclusionRemark:Ke,conclusionLoading:rt,conclusionSubmitting:Xe,aiGenerated:lt,handleGenerateConclusion:et,handleFinalizeConclusion:xt,onPause:Pt,onResume:Ss,onRetrigger:Ya,currentUserIsApprover:!!H,pausedByUserId:(Ar=(sr=I==null?void 0:I.pauseInfo)==null?void 0:sr.pausedBy)==null?void 0:Ar.userId,currentUserId:W==null?void 0:W.userId,generationAttempts:Hs,generationFailed:ls,maxAttemptsReached:Nt})}),ka&&e.jsx(Bt,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(Qk,{summary:h,loading:f,onShare:Ta,isInitiator:P})}),e.jsx(Bt,{value:"workflow",className:"mt-0",children:Us?e.jsx(OC,{request:I,requestId:($==null?void 0:$.requestId)||n,isReUser:tn,onRefresh:C}):e.jsx(PC,{request:I,user:W,isInitiator:P,onSkipApprover:Qt=>{if(!Qt.levelId){alert("Level ID not available");return}Re(Qt),Fe(!0)},onRefresh:C})}),e.jsx(Bt,{value:"documents",className:"mt-0",children:e.jsx(Hk,{request:I,workNoteAttachments:E,uploadingDocument:G,documentPolicy:ne,triggerFileInput:J,setPreviewDocument:se,downloadDocument:$s,isSpectator:z})}),e.jsx(Bt,{value:"activity",className:"mt-0",children:e.jsx(Gk,{request:I})}),!Us&&e.jsx(Bt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(Yk,{requestId:n,requestTitle:I.title,mergedMessages:Y,setWorkNoteAttachments:V,isInitiator:P,isSpectator:z,currentLevels:en,onAddApprover:me,maxApprovalLevels:F.maxApprovalLevels,onPolicyViolation:Qt=>_({open:!0,violations:Qt})})})]}),!Cr&&o!=="worknotes"&&e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[Us&&tn&&e.jsx(fk,{requestId:($==null?void 0:$.requestId)||n,request:I,onRefresh:C}),e.jsx(Xk,{request:I,isInitiator:P,isSpectator:z,currentApprovalLevel:H,onAddApprover:()=>ae(!0),onAddSpectator:()=>ie(!0),onApprove:()=>fe(!0),onReject:()=>le(!0),onPause:Pt,onResume:Ss,onRetrigger:Ya,summaryId:p,refreshTrigger:y,pausedByUserId:(ar=(Tr=I==null?void 0:I.pauseInfo)==null?void 0:Tr.pausedBy)==null?void 0:ar.userId,currentUserId:W==null?void 0:W.userId,apiRequest:$,hideApproveReject:Cr})]})]})]})]})}),d&&p&&e.jsx(z0,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(I==null?void 0:I.title)||"N/A",onSuccess:()=>{C(),j(Qt=>Qt+1)}}),v&&($==null?void 0:$.requestId)&&e.jsx(V0,{isOpen:v,onClose:()=>N(!1),requestId:$.requestId,levelId:(H==null?void 0:H.levelId)||null,onSuccess:Qa}),T&&($==null?void 0:$.requestId)&&e.jsx(W0,{isOpen:T,onClose:()=>A(!1),requestId:$.requestId,onSuccess:as}),k&&($==null?void 0:$.requestId)&&e.jsx(H0,{isOpen:k,onClose:()=>D(!1),requestId:$.requestId,approverName:(rr=(Oa=I==null?void 0:I.pauseInfo)==null?void 0:Oa.pausedBy)==null?void 0:rr.name,onSuccess:wr}),e.jsx(Jk,{showApproveModal:we,showRejectModal:ke,showAddApproverModal:Ne,showAddSpectatorModal:he,showSkipApproverModal:je,showActionStatusModal:Ue,previewDocument:q,documentError:te,request:I,skipApproverData:ce,actionStatus:qe,existingParticipants:S,currentLevels:en,maxApprovalLevels:F.maxApprovalLevels,onPolicyViolation:Qt=>_({open:!0,violations:Qt}),setShowApproveModal:fe,setShowRejectModal:le,setShowAddApproverModal:ae,setShowAddSpectatorModal:ie,setShowSkipApproverModal:Fe,setShowActionStatusModal:Ce,setPreviewDocument:se,setDocumentError:ge,setSkipApproverData:Re,setActionStatus:at,handleApproveConfirm:ft,handleRejectConfirm:Ft,handleAddApprover:me,handleAddSpectator:xe,handleSkipApprover:Oe,downloadDocument:$s,documentPolicy:ne}),e.jsx(Di,{open:L.open,onClose:()=>_({open:!1,violations:[]}),violations:L.violations,policyDetails:{maxApprovalLevels:F.maxApprovalLevels,maxParticipants:F.maxParticipants,allowSpectators:F.allowSpectators,maxSpectators:F.maxSpectators}})]})}function e4(t){return e.jsx(Zk,{children:e.jsx(qk,{...t})})}const t4=[{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 s4(){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 a4({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,onSearchChange:c,onStatusFilterChange:d,onPriorityFilterChange:m,onTemplateTypeFilterChange:p,onForm16FinancialYearChange:x,onForm16QuarterChange:h,onSortByChange:g,onSortOrderChange:f,onClearFilters:b,activeFiltersCount:y}){const j=s4(),v=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0",children:[e.jsx(de,{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(Ga,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:y>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[y," filter",y>1?"s":""," active"]})})]})]}),y>0&&e.jsxs(O,{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(vt,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ee,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Jt,{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(_e,{placeholder:"Search requests, IDs...",value:t,onChange:N=>c(N.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors"})]}),e.jsxs(He,{value:a,onValueChange:m,children:[e.jsx(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"All Priorities"})}),e.jsxs(Qe,{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(Ma,{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(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"All Statuses"})}),e.jsxs(Qe,{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(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Request type"})}),e.jsxs(Qe,{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&&x&&e.jsxs(He,{value:n||void 0,onValueChange:x,children:[e.jsx(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Financial Year"})}),e.jsx(Qe,{children:j.map(N=>e.jsx(X,{value:N,children:N},N))})]}),v&&h&&e.jsxs(He,{value:i||void 0,onValueChange:h,children:[e.jsx(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Quarter"})}),e.jsx(Qe,{children:t4.map(N=>e.jsx(X,{value:N.value,children:N.label},N.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:l,onValueChange:N=>g(N),children:[e.jsx(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Qe,{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(O,{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(El,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(_l,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}const r4=[{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 n4(){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 i4({searchTerm:t,priorityFilter:s,statusFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,activeFiltersCount:c,onSearchChange:d,onPriorityChange:m,onStatusChange:p,onTemplateTypeChange:x,onForm16FinancialYearChange:h,onForm16QuarterChange:g,onSortByChange:f,onSortOrderChange:b,onClearFilters:y}){const j=n4(),v=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(de,{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(Ga,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:c>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[c," filter",c>1?"s":""," active"]})})]})]}),c>0&&e.jsxs(O,{variant:"ghost",size:"sm",onClick:y,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(vt,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ee,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Jt,{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(_e,{placeholder:"Search requests, IDs...",value:t,onChange:N=>d(N.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white transition-colors","data-testid":"closed-requests-search"})]}),e.jsxs(He,{value:s,onValueChange:m,children:[e.jsx(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-priority-filter",children:e.jsx(Ge,{placeholder:"All Priorities"})}),e.jsxs(Qe,{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(Ma,{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(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-status-filter",children:e.jsx(Ge,{placeholder:"Closure Type"})}),e.jsxs(Qe,{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(Ve,{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(At,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs(He,{value:r,onValueChange:x,children:[e.jsx(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-template-type-filter",children:e.jsx(Ge,{placeholder:"Request type"})}),e.jsxs(Qe,{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(Ye,{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(Qe,{children:j.map(N=>e.jsx(X,{value:N,children:N},N))})]}),v&&g&&e.jsxs(He,{value:i||void 0,onValueChange:g,children:[e.jsx(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white",children:e.jsx(Ge,{placeholder:"Quarter"})}),e.jsx(Qe,{children:r4.map(N=>e.jsx(X,{value:N.value,children:N.label},N.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:l,onValueChange:N=>f(N),children:[e.jsx(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-sort-by",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Qe,{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(O,{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(El,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(_l,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function l4({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,departmentFilter:n,slaComplianceFilter:i,initiatorFilter:l,approverFilter:o,approverFilterType:c,dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:x,departments:h,loadingDepartments:g,initiatorSearch:f,approverSearch:b,showForm16Filter:y=!1,form16FinancialYear:j="all",form16Quarter:v="all",onForm16FinancialYearChange:N,onForm16QuarterChange:T,onSearchChange:A,onStatusChange:k,onPriorityChange:D,onTemplateTypeChange:F,onDepartmentChange:w,onSlaComplianceChange:L,onInitiatorChange:_,onApproverChange:W,onApproverTypeChange:I,onDateRangeChange:$,onCustomStartDateChange:M,onCustomEndDateChange:R,onShowCustomDatePickerChange:C,onApplyCustomDate:H,onClearFilters:z,hasActiveFilters:P}){return e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"user-all-requests-filters",children:e.jsx(ee,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),P&&e.jsx(oe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),P&&e.jsxs(O,{variant:"ghost",size:"sm",onClick:z,className:"gap-2",children:[e.jsx(_t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Zt,{}),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(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(_e,{placeholder:"Search requests...",value:t,onChange:S=>A(S.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:k,children:[e.jsx(Ye,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Qe,{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(Ye,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"All Priority"})}),e.jsxs(Qe,{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:F,children:[e.jsx(Ye,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Qe,{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"}),y&&e.jsx(X,{value:"FORM_16",children:"Form 16"})]})]}),y&&r==="FORM_16"&&e.jsxs(e.Fragment,{children:[e.jsxs(He,{value:j,onValueChange:N??(()=>{}),children:[e.jsx(Ye,{className:"h-10","data-testid":"form16-financial-year-filter",children:e.jsx(Ge,{placeholder:"Financial Year"})}),e.jsxs(Qe,{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:T??(()=>{}),children:[e.jsx(Ye,{className:"h-10","data-testid":"form16-quarter-filter",children:e.jsx(Ge,{placeholder:"Quarter"})}),e.jsxs(Qe,{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:w,disabled:g||h.length===0,children:[e.jsx(Ye,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ge,{placeholder:g?"Loading...":"All Departments"})}),e.jsxs(Qe,{children:[e.jsx(X,{value:"all",children:"All Departments"}),h.map(S=>e.jsx(X,{value:S,children:S},S))]})]}),e.jsxs(He,{value:i,onValueChange:L,children:[e.jsx(Ye,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"All SLA Status"})}),e.jsxs(Qe,{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(re,{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(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:f.handleClear,children:e.jsx(vt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{placeholder:"Search initiator...",value:f.searchQuery,onChange:S=>f.handleSearch(S.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(S=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(S),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:S.displayName||S.email}),S.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:S.email})]})},S.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approver"}),o!=="all"&&I&&e.jsxs(He,{value:c,onValueChange:S=>I(S),children:[e.jsx(Ye,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Qe,{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(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:b.handleClear,children:e.jsx(vt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{placeholder:"Search approver...",value:b.searchQuery,onChange:S=>b.handleSearch(S.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(S=>e.jsx("button",{type:"button",onClick:()=>b.handleSelect(S),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:S.displayName||S.email}),S.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:S.email})]})},S.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(bt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:d,onValueChange:S=>$(S),children:[e.jsx(Ye,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Qe,{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(na,{open:x,onOpenChange:C,children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(bt,{className:"w-4 h-4"}),m&&p?`${st(m,"MMM d, yyyy")} - ${st(p,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(la,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",children:"Start Date"}),e.jsx(aa,{value:m||null,onChange:S=>{const U=S?new Date(S):void 0;U?(M==null||M(U),p&&U>p&&(R==null||R(U))):M==null||M(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",children:"End Date"}),e.jsx(aa,{value:p||null,onChange:S=>{const U=S?new Date(S):void 0;U?(R==null||R(U),m&&U<m&&(M==null||M(U))):R==null||R(void 0)},minDate:m||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(O,{size:"sm",onClick:H,disabled:!m||!p,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply Range"}),e.jsx(O,{size:"sm",variant:"outline",onClick:()=>{C==null||C(!1),M==null||M(void 0),R==null||R(void 0),$("month")},children:"Cancel"})]})]})})]})]})]})})})}function o4({request:t,apiRequest:s,currentUserId:a,isInitiator:r,onEditClaimAmount:n,className:i="",needsClosure:l=!1,conclusionRemark:o="",setConclusionRemark:c,conclusionLoading:d=!1,conclusionSubmitting:m=!1,aiGenerated:p=!1,handleGenerateConclusion:x,handleFinalizeConclusion:h,generationAttempts:g=0,generationFailed:f=!1,maxAttemptsReached:b=!1}){var T,A,k,D,F,w,L,_,W;if(!hi(s))return e.jsx("div",{className:"text-center py-8 text-gray-500",children:e.jsx("p",{children:"This is not a claim management request."})});const y=O0(s);if(!y)return console.warn("[ClaimManagementOverviewTab] Failed to map claim data:",{apiRequest:s,hasClaimDetails:!!(s!=null&&s.claimDetails),hasProposalDetails:!!(s!=null&&s.proposalDetails),hasCompletionDetails:!!(s!=null&&s.completionDetails)}),e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx("p",{children:"Unable to load claim management data."}),e.jsx("p",{className:"text-xs mt-2",children:"Please ensure the request has been properly initialized."})]});const j=$0(s,a),v=U0(j),N={name:((T=s.initiator)==null?void 0:T.name)||((A=s.initiator)==null?void 0:A.displayName)||((k=s.initiator)==null?void 0:k.email)||"Unknown",role:((D=s.initiator)==null?void 0:D.role)||((F=s.initiator)==null?void 0:F.designation)||"Initiator",department:((w=s.initiator)==null?void 0:w.department)||s.department||"",email:((L=s.initiator)==null?void 0:L.email)||"N/A",phone:((_=s.initiator)==null?void 0:_.phone)||((W=s.initiator)==null?void 0:W.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(_k,{activityInfo:y.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(Mk,{dealerInfo:y.dealerInfo}),v.showProposalDetails&&y.proposalDetails&&e.jsx(Ok,{proposalDetails:y.proposalDetails}),e.jsx($k,{initiatorInfo:N}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ve,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(Te,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(ee,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Ls,{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 ",js(s.closureDate)]}),e.jsxs("span",{children:["By ",N.name]})]})]})]}),l&&e.jsxs(Z,{"data-testid":"conclusion-remark-card",children:[e.jsx(de,{className:`bg-gradient-to-r border-b ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:`flex items-center gap-2 text-base sm:text-lg ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(Ve,{className:`w-5 h-5 ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(Te,{className:"mt-1 text-xs sm:text-sm",children:((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"This request was rejected. Please review the AI-generated closure remark and finalize it to close this request.":"All approvals are complete. Please review and finalize the conclusion to close this request."})]}),x&&e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(O,{variant:"outline",size:"sm",onClick:x,disabled:d||b,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(_t,{className:`w-3.5 h-3.5 ${d?"animate-spin":""}`}),p?"Regenerate":"Generate with AI"]}),p&&!b&&!f&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-g," attempts remaining"]})]})]})}),e.jsx(ee,{className:"pt-4",children:d?e.jsx("div",{className:"flex items-center justify-center py-8","data-testid":"conclusion-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx(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(Ci,{value:o,onChange:I=>c(I),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(O,{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(Ve,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function c4({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]=u.useState(""),[p,x]=u.useState(!1),[h,g]=u.useState(null),f=async()=>{if(!d.trim()){Q.error("Please provide approval comments");return}try{x(!0),g("approve"),await a(d),y(),s()}catch(v){console.error("Failed to approve request:",v),Q.error("Failed to approve request. Please try again.")}finally{x(!1),g(null)}},b=async()=>{if(!d.trim()){Q.error("Please provide rejection reason");return}try{x(!0),g("reject"),await r(d),y(),s()}catch(v){console.error("Failed to reject request:",v),Q.error("Failed to reject request. Please try again.")}finally{x(!1),g(null)}},y=()=>{m(""),g(null)},j=()=>{p||(y(),s())};return t?e.jsx(ht,{open:t,onOpenChange:j,children:e.jsxs(mt,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(pt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(ut,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(Ve,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(Mt,{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(Ee,{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(Qs,{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(Ls,{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(Vs,{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(At,{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(O,{variant:"outline",onClick:j,disabled:p,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(O,{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(At,{className:"w-4 h-4 mr-2"}),"Reject"]})}),e.jsx(O,{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(Ve,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function d4({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:c,dueDate:d,taxationType:m}){const[p,x]=u.useState(!1),[h,g]=u.useState(!1),f=m==="Non GST"||m==="Non-GST",b=(n==null?void 0:n.creditNoteNumber)&&(n==null?void 0:n.creditNoteNumber)!=="",y=(n==null?void 0:n.creditNoteNumber)||"",j=n!=null&&n.creditNoteDate?js(n.creditNoteDate,{includeTime:!1,format:"short"}):"",v=(n==null?void 0:n.creditNoteAmount)||0,N=(n==null?void 0:n.transactionNo)||"",T=(n==null?void 0:n.tdsAmount)||0,A=(n==null?void 0:n.creditAmount)||0,k=(n==null?void 0:n.status)||"PENDING",D=(n==null?void 0:n.items)||[],F=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",w=(i==null?void 0:i.dealerCode)||"RE-JP-009",L=l||"Activity",_=o||"RE-REQ-2024-CM-101",W=d?js(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",I=(()=>{var C,H;if(D.length>1){const z=(C=D[0])==null?void 0:C.transactionNo,P=(H=D[D.length-1])==null?void 0:H.transactionNo;return z&&P&&z!==P?`${z} - ${P}`:z||N||"N/A"}return N||"N/A"})(),$=async()=>{if(a)try{x(!0),await a(),Q.success("Credit note downloaded successfully")}catch(C){console.error("Failed to download credit note:",C),Q.error("Failed to download credit note. Please try again.")}finally{x(!1)}else Q.info("Credit note will be automatically saved to Documents tab")},M=async()=>{if(r)try{g(!0),await r(),Q.success("Credit note sent to dealer successfully"),s()}catch(C){console.error("Failed to send credit note to dealer:",C),Q.error("Failed to send credit note. Please try again.")}finally{g(!1)}else Q.info("Email notification will be sent to dealer with credit note attachment")},R=C=>`₹${C.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(pt,{children:[e.jsxs(ut,{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(Et,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note Details"]}),m&&e.jsx(oe,{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(Mt,{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(oe,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(Ve,{className:"w-4 h-4 mr-2"}),k==="APPROVED"?"Approved":k==="ISSUED"?"Issued":k==="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(re,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(sc,{className:"w-3 h-3"}),"Credit Note No"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1",children:y})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100 shadow-sm",children:[e.jsxs(re,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(bt,{className:"w-3 h-3"}),"Issue Date"]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:j})]}),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(re,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Ee,{className:"w-3 h-3"}),"Transaction ID"]}),e.jsx("p",{className:"font-bold text-emerald-700 mt-1 break-all",children:I})]})]})]}),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(re,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(Pa,{className:"w-3 h-3"}),"Gross Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-blue-700",children:R(v)})]}),e.jsxs("div",{className:"bg-orange-50 border-2 border-orange-200 rounded-lg p-4",children:[e.jsxs(re,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(Pa,{className:"w-3 h-3"}),"TDS Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-orange-700",children:R(T)})]}),e.jsxs("div",{className:"bg-emerald-50 border-2 border-emerald-200 rounded-lg p-4",children:[e.jsxs(re,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(Pa,{className:"w-3 h-3"}),"Net Credit Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-emerald-700",children:R(A)})]})]}),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(Ee,{className:"w-4 h-4 text-slate-500"}),"Line Item Breakdown"]}),e.jsxs(oe,{variant:"outline",className:"text-[10px] font-medium uppercase tracking-wider",children:[D.length," ",D.length===1?"Item":"Items"]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto",children:e.jsxs("table",{className:"w-full text-sm text-left border-collapse",children:[e.jsx("thead",{className:"bg-white sticky top-0 shadow-sm z-10",children:e.jsxs("tr",{className:"border-b border-slate-200",children:[e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"Sl No"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"Transaction Code"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"HSN/SAC"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"Claim Amount"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"TDS"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"Net Credit"})]})}),e.jsx("tbody",{children:D.map((C,H)=>e.jsxs("tr",{className:"border-b border-slate-100 hover:bg-slate-50/50 transition-colors",children:[e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:C.slNo}),e.jsx("td",{className:"px-4 py-2.5 font-medium text-slate-900 font-mono text-[11px]",children:C.transactionNo||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:C.hsnCd||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-right font-medium text-slate-700",children:R(C.claimAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-orange-600 font-medium",children:R(C.tdsAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-emerald-700 font-bold",children:R(C.creditAmount||0)})]},H))})]})})]})]}):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(Et,{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(Pl,{className:"w-5 h-5"}),"Dealer Information"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(re,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(re,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:w})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(re,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Activity"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:L})]})]})]}),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(Ee,{className:"w-4 h-4"}),"Reference Details"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx(re,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Request ID"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:_})]}),e.jsxs("div",{children:[e.jsx(re,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Due Date"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:W})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Ee,{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(O,{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(O,{variant:"outline",onClick:$,disabled:p||h,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),p?"Downloading...":"Download"]}),e.jsxs(O,{onClick:M,disabled:p||h,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(_p,{className:"w-4 h-4 mr-2"}),h?"Sending...":"Send to Dealer"]})]})})]})]})})}var Oh=1,m4=.9,u4=.8,x4=.17,Io=.1,Fo=.999,h4=.9999,p4=.99,g4=/[\\\/_+.#"@\[\(\{&]/,f4=/[\\\/_+.#"@\[\(\{&]/g,b4=/[\s-]/,G0=/[\s-]/g;function Rc(t,s,a,r,n,i,l){if(i===s.length)return n===t.length?Oh:p4;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,x,h,g;d>=0;)p=Rc(t,s,a,r,d+1,i+1,l),p>m&&(d===n?p*=Oh:g4.test(t.charAt(d-1))?(p*=u4,h=t.slice(n,d-1).match(f4),h&&n>0&&(p*=Math.pow(Fo,h.length))):b4.test(t.charAt(d-1))?(p*=m4,g=t.slice(n,d-1).match(G0),g&&n>0&&(p*=Math.pow(Fo,g.length))):(p*=x4,n>0&&(p*=Math.pow(Fo,d-n))),t.charAt(d)!==s.charAt(i)&&(p*=h4)),(p<Io&&a.charAt(d-1)===r.charAt(i+1)||r.charAt(i+1)===r.charAt(i)&&a.charAt(d-1)!==r.charAt(i))&&(x=Rc(t,s,a,r,d+1,i+2,l),x*Io>p&&(p=x*Io)),p>m&&(m=p),d=a.indexOf(c,d+1);return l[o]=m,m}function $h(t){return t.toLowerCase().replace(G0," ")}function j4(t,s,a){return t=a&&a.length>0?`${t+" "+a.join(" ")}`:t,Rc(t,s,$h(t),$h(s),0,0,{})}var Vn='[cmdk-group=""]',Po='[cmdk-group-items=""]',y4='[cmdk-group-heading=""]',Y0='[cmdk-item=""]',Uh=`${Y0}:not([aria-disabled="true"])`,Ic="cmdk-item-select",ln="data-value",v4=(t,s,a)=>j4(t,s,a),Q0=u.createContext(void 0),Fi=()=>u.useContext(Q0),K0=u.createContext(void 0),Xd=()=>u.useContext(K0),X0=u.createContext(void 0),J0=u.forwardRef((t,s)=>{let a=on(()=>{var S,U;return{search:"",value:(U=(S=t.value)!=null?S:t.defaultValue)!=null?U:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=on(()=>new Set),n=on(()=>new Map),i=on(()=>new Map),l=on(()=>new Set),o=Z0(t),{label:c,children:d,value:m,onValueChange:p,filter:x,shouldFilter:h,loop:g,disablePointerSelection:f=!1,vimBindings:b=!0,...y}=t,j=gn(),v=gn(),N=gn(),T=u.useRef(null),A=F4();Xr(()=>{if(m!==void 0){let S=m.trim();a.current.value=S,k.emit()}},[m]),Xr(()=>{A(6,W)},[]);let k=u.useMemo(()=>({subscribe:S=>(l.current.add(S),()=>l.current.delete(S)),snapshot:()=>a.current,setState:(S,U,Y)=>{var B,E,V,G;if(!Object.is(a.current[S],U)){if(a.current[S]=U,S==="search")_(),w(),A(1,L);else if(S==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let J=document.getElementById(N);J?J.focus():(B=document.getElementById(j))==null||B.focus()}if(A(7,()=>{var J;a.current.selectedItemId=(J=I())==null?void 0:J.id,k.emit()}),Y||A(5,W),((E=o.current)==null?void 0:E.value)!==void 0){let J=U??"";(G=(V=o.current).onValueChange)==null||G.call(V,J);return}}k.emit()}},emit:()=>{l.current.forEach(S=>S())}}),[]),D=u.useMemo(()=>({value:(S,U,Y)=>{var B;U!==((B=i.current.get(S))==null?void 0:B.value)&&(i.current.set(S,{value:U,keywords:Y}),a.current.filtered.items.set(S,F(U,Y)),A(2,()=>{w(),k.emit()}))},item:(S,U)=>(r.current.add(S),U&&(n.current.has(U)?n.current.get(U).add(S):n.current.set(U,new Set([S]))),A(3,()=>{_(),w(),a.current.value||L(),k.emit()}),()=>{i.current.delete(S),r.current.delete(S),a.current.filtered.items.delete(S);let Y=I();A(4,()=>{_(),(Y==null?void 0:Y.getAttribute("id"))===S&&L(),k.emit()})}),group:S=>(n.current.has(S)||n.current.set(S,new Set),()=>{i.current.delete(S),n.current.delete(S)}),filter:()=>o.current.shouldFilter,label:c||t["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:j,inputId:N,labelId:v,listInnerRef:T}),[]);function F(S,U){var Y,B;let E=(B=(Y=o.current)==null?void 0:Y.filter)!=null?B:v4;return S?E(S,a.current.search,U):0}function w(){if(!a.current.search||o.current.shouldFilter===!1)return;let S=a.current.filtered.items,U=[];a.current.filtered.groups.forEach(B=>{let E=n.current.get(B),V=0;E.forEach(G=>{let J=S.get(G);V=Math.max(J,V)}),U.push([B,V])});let Y=T.current;$().sort((B,E)=>{var V,G;let J=B.getAttribute("id"),q=E.getAttribute("id");return((V=S.get(q))!=null?V:0)-((G=S.get(J))!=null?G:0)}).forEach(B=>{let E=B.closest(Po);E?E.appendChild(B.parentElement===E?B:B.closest(`${Po} > *`)):Y.appendChild(B.parentElement===Y?B:B.closest(`${Po} > *`))}),U.sort((B,E)=>E[1]-B[1]).forEach(B=>{var E;let V=(E=T.current)==null?void 0:E.querySelector(`${Vn}[${ln}="${encodeURIComponent(B[0])}"]`);V==null||V.parentElement.appendChild(V)})}function L(){let S=$().find(Y=>Y.getAttribute("aria-disabled")!=="true"),U=S==null?void 0:S.getAttribute(ln);k.setState("value",U||void 0)}function _(){var S,U,Y,B;if(!a.current.search||o.current.shouldFilter===!1){a.current.filtered.count=r.current.size;return}a.current.filtered.groups=new Set;let E=0;for(let V of r.current){let G=(U=(S=i.current.get(V))==null?void 0:S.value)!=null?U:"",J=(B=(Y=i.current.get(V))==null?void 0:Y.keywords)!=null?B:[],q=F(G,J);a.current.filtered.items.set(V,q),q>0&&E++}for(let[V,G]of n.current)for(let J of G)if(a.current.filtered.items.get(J)>0){a.current.filtered.groups.add(V);break}a.current.filtered.count=E}function W(){var S,U,Y;let B=I();B&&(((S=B.parentElement)==null?void 0:S.firstChild)===B&&((Y=(U=B.closest(Vn))==null?void 0:U.querySelector(y4))==null||Y.scrollIntoView({block:"nearest"})),B.scrollIntoView({block:"nearest"}))}function I(){var S;return(S=T.current)==null?void 0:S.querySelector(`${Y0}[aria-selected="true"]`)}function $(){var S;return Array.from(((S=T.current)==null?void 0:S.querySelectorAll(Uh))||[])}function M(S){let U=$()[S];U&&k.setState("value",U.getAttribute(ln))}function R(S){var U;let Y=I(),B=$(),E=B.findIndex(G=>G===Y),V=B[E+S];(U=o.current)!=null&&U.loop&&(V=E+S<0?B[B.length-1]:E+S===B.length?B[0]:B[E+S]),V&&k.setState("value",V.getAttribute(ln))}function C(S){let U=I(),Y=U==null?void 0:U.closest(Vn),B;for(;Y&&!B;)Y=S>0?R4(Y,Vn):I4(Y,Vn),B=Y==null?void 0:Y.querySelector(Uh);B?k.setState("value",B.getAttribute(ln)):R(S)}let H=()=>M($().length-1),z=S=>{S.preventDefault(),S.metaKey?H():S.altKey?C(1):R(1)},P=S=>{S.preventDefault(),S.metaKey?M(0):S.altKey?C(-1):R(-1)};return u.createElement(yr.div,{ref:s,tabIndex:-1,...y,"cmdk-root":"",onKeyDown:S=>{var U;(U=y.onKeyDown)==null||U.call(y,S);let Y=S.nativeEvent.isComposing||S.keyCode===229;if(!(S.defaultPrevented||Y))switch(S.key){case"n":case"j":{b&&S.ctrlKey&&z(S);break}case"ArrowDown":{z(S);break}case"p":case"k":{b&&S.ctrlKey&&P(S);break}case"ArrowUp":{P(S);break}case"Home":{S.preventDefault(),M(0);break}case"End":{S.preventDefault(),H();break}case"Enter":{S.preventDefault();let B=I();if(B){let E=new Event(Ic);B.dispatchEvent(E)}}}}},u.createElement("label",{"cmdk-label":"",htmlFor:D.inputId,id:D.labelId,style:E4},c),Jl(t,S=>u.createElement(K0.Provider,{value:k},u.createElement(Q0.Provider,{value:D},S))))}),N4=u.forwardRef((t,s)=>{var a,r;let n=gn(),i=u.useRef(null),l=u.useContext(X0),o=Fi(),c=Z0(t),d=(r=(a=c.current)==null?void 0:a.forceMount)!=null?r:l==null?void 0:l.forceMount;Xr(()=>{if(!d)return o.item(n,l==null?void 0:l.id)},[d]);let m=q0(n,i,[t.value,t.children,i],t.keywords),p=Xd(),x=jr(A=>A.value&&A.value===m.current),h=jr(A=>d||o.filter()===!1?!0:A.search?A.filtered.items.get(n)>0:!0);u.useEffect(()=>{let A=i.current;if(!(!A||t.disabled))return A.addEventListener(Ic,g),()=>A.removeEventListener(Ic,g)},[h,t.onSelect,t.disabled]);function g(){var A,k;f(),(k=(A=c.current).onSelect)==null||k.call(A,m.current)}function f(){p.setState("value",m.current,!0)}if(!h)return null;let{disabled:b,value:y,onSelect:j,forceMount:v,keywords:N,...T}=t;return u.createElement(yr.div,{ref:ai(i,s),...T,id:n,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!x,"data-disabled":!!b,"data-selected":!!x,onPointerMove:b||o.getDisablePointerSelection()?void 0:f,onClick:b?void 0:g},t.children)}),w4=u.forwardRef((t,s)=>{let{heading:a,children:r,forceMount:n,...i}=t,l=gn(),o=u.useRef(null),c=u.useRef(null),d=gn(),m=Fi(),p=jr(h=>n||m.filter()===!1?!0:h.search?h.filtered.groups.has(l):!0);Xr(()=>m.group(l),[]),q0(l,o,[t.value,t.heading,c]);let x=u.useMemo(()=>({id:l,forceMount:n}),[n]);return u.createElement(yr.div,{ref:ai(o,s),...i,"cmdk-group":"",role:"presentation",hidden:p?void 0:!0},a&&u.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},a),Jl(t,h=>u.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":a?d:void 0},u.createElement(X0.Provider,{value:x},h))))}),C4=u.forwardRef((t,s)=>{let{alwaysRender:a,...r}=t,n=u.useRef(null),i=jr(l=>!l.search);return!a&&!i?null:u.createElement(yr.div,{ref:ai(n,s),...r,"cmdk-separator":"",role:"separator"})}),S4=u.forwardRef((t,s)=>{let{onValueChange:a,...r}=t,n=t.value!=null,i=Xd(),l=jr(d=>d.search),o=jr(d=>d.selectedItemId),c=Fi();return u.useEffect(()=>{t.value!=null&&i.setState("search",t.value)},[t.value]),u.createElement(yr.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)}})}),A4=u.forwardRef((t,s)=>{let{children:a,label:r="Suggestions",...n}=t,i=u.useRef(null),l=u.useRef(null),o=jr(d=>d.selectedItemId),c=Fi();return u.useEffect(()=>{if(l.current&&i.current){let d=l.current,m=i.current,p,x=new ResizeObserver(()=>{p=requestAnimationFrame(()=>{let h=d.offsetHeight;m.style.setProperty("--cmdk-list-height",h.toFixed(1)+"px")})});return x.observe(d),()=>{cancelAnimationFrame(p),x.unobserve(d)}}},[]),u.createElement(yr.div,{ref:ai(i,s),...n,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},Jl(t,d=>u.createElement("div",{ref:ai(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),T4=u.forwardRef((t,s)=>{let{open:a,onOpenChange:r,overlayClassName:n,contentClassName:i,container:l,...o}=t;return u.createElement(bp,{open:a,onOpenChange:r},u.createElement(fp,{container:l},u.createElement(Ec,{"cmdk-overlay":"",className:n}),u.createElement(_c,{"aria-label":t.label,"cmdk-dialog":"",className:i},u.createElement(J0,{ref:s,...o}))))}),k4=u.forwardRef((t,s)=>jr(a=>a.filtered.count===0)?u.createElement(yr.div,{ref:s,...t,"cmdk-empty":"",role:"presentation"}):null),D4=u.forwardRef((t,s)=>{let{progress:a,children:r,label:n="Loading...",...i}=t;return u.createElement(yr.div,{ref:s,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":100,"aria-label":n},Jl(t,l=>u.createElement("div",{"aria-hidden":!0},l)))}),Pn=Object.assign(J0,{List:A4,Item:N4,Input:S4,Group:w4,Separator:C4,Dialog:T4,Empty:k4,Loading:D4});function R4(t,s){let a=t.nextElementSibling;for(;a;){if(a.matches(s))return a;a=a.nextElementSibling}}function I4(t,s){let a=t.previousElementSibling;for(;a;){if(a.matches(s))return a;a=a.previousElementSibling}}function Z0(t){let s=u.useRef(t);return Xr(()=>{s.current=t}),s}var Xr=typeof window>"u"?u.useEffect:u.useLayoutEffect;function on(t){let s=u.useRef();return s.current===void 0&&(s.current=t()),s}function jr(t){let s=Xd(),a=()=>t(s.snapshot());return u.useSyncExternalStore(s.subscribe,a,a)}function q0(t,s,a,r=[]){let n=u.useRef(),i=Fi();return Xr(()=>{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(ln,o),n.current=o}),n}var F4=()=>{let[t,s]=u.useState(),a=on(()=>new Map);return Xr(()=>{a.current.forEach(r=>r()),a.current=new Map},[t]),(r,n)=>{a.current.set(r,n),s({})}};function P4(t){let s=t.type;return typeof s=="function"?s(t.props):"render"in s?s.render(t.props):t}function Jl({asChild:t,children:s},a){return t&&u.isValidElement(s)?u.cloneElement(P4(s),{ref:s.ref},a(s.props.children)):a(s)}var E4={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function _4({className:t,...s}){return e.jsx(Pn,{"data-slot":"command",className:$e("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",t),...s})}function M4({className:t,wrapperClassName:s,...a}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:$e("flex h-9 items-center gap-2 border-b px-3",s),children:[e.jsx(Jt,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Pn.Input,{"data-slot":"command-input",className:$e("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 L4({className:t,...s}){return e.jsx(Pn.List,{"data-slot":"command-list",className:$e("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",t),...s})}function O4({...t}){return e.jsx(Pn.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...t})}function $4({className:t,...s}){return e.jsx(Pn.Group,{"data-slot":"command-group",className:$e("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 U4({className:t,...s}){return e.jsx(Pn.Item,{"data-slot":"command-item",className:$e("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 eb(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 Se.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 B4(t){var a;const s=await Se.post("/hsn-sac",t);return((a=s.data)==null?void 0:a.data)||s.data}async function z4(t,s){var r;const a=await Se.patch(`/hsn-sac/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function V4(t){await Se.delete(`/hsn-sac/${t}`)}async function W4(t){var a;const s=await Se.patch(`/hsn-sac/${t}/toggle-active`);return((a=s.data)==null?void 0:a.data)||s.data}function tb({value:t,onChange:s,type:a,placeholder:r,disabled:n,className:i}){var p;const[l,o]=u.useState(!1),[c,d]=u.useState([]);u.useEffect(()=>{const x=async()=>{try{const h=await eb(!0,1,1e3);d(h.codes)}catch(h){console.error("Failed to fetch HSN/SAC codes for selector:",h)}};l&&c.length===0&&x()},[l,c.length]);const m=u.useMemo(()=>c.filter(x=>x.type===a),[c,a]);return e.jsxs(na,{open:l,onOpenChange:o,children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{variant:"outline",role:"combobox","aria-expanded":l,disabled:n,className:$e("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(x=>x.code===t))==null?void 0:p.code)||t:r||`Select ${a}...`}),e.jsx(uy,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(la,{className:"w-[320px] p-0 shadow-2xl border-slate-200",align:"start",children:e.jsxs(_4,{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(Jt,{className:"w-4 h-4 text-slate-400"}),e.jsx(M4,{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(L4,{className:"max-h-[350px] scrollbar-thin scrollbar-thumb-slate-200",children:[e.jsx(O4,{className:"py-8 text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Jt,{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($4,{className:"p-1.5",children:m.map(x=>e.jsxs(U4,{value:x.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:x.code}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Ha,{className:$e("h-4 w-4 text-re-green transition-all",t===x.code?"opacity-100 scale-100":"opacity-0 scale-75")})})]}),x.description&&e.jsx("span",{className:"text-[11px] text-slate-500 line-clamp-2 leading-tight pr-4",children:x.description})]},x.id))})]})]})})]})}const va=(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:""}},H4={"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"},G4="33",Y4=new Set(["04","25","26","31","35","38"]),sb=t=>{if(!t||t.length<2)return null;const s=t.substring(0,2);return H4[s]?s:null},Q4=t=>t?Y4.has(t):!1,K4=t=>t?t!==G4:!1,ab=t=>{if(!t)return{isIGST:!1,isCGST:!0,isSGST:!0,isUTGST:!1};if(K4(t))return{isIGST:!0,isCGST:!1,isSGST:!1,isUTGST:!1};const a=Q4(t);return{isIGST:!1,isCGST:!0,isSGST:!a,isUTGST:a}};function X4({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]=u.useState(""),[x,h]=u.useState(""),g=u.useMemo(()=>{const ie=sb(n);return ab(ie)},[n]),f=u.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),[b,y]=u.useState([]),[j,v]=u.useState([]),[N,T]=u.useState([]),[A,k]=u.useState([]),[D,F]=u.useState(null),[w,L]=u.useState(""),[_,W]=u.useState(!1),[I,$]=u.useState(null),M=u.useRef(null),R=u.useRef(null),C=u.useRef(null),H=u.useRef(null),z=ie=>{const je=ie.type.toLowerCase(),Fe=ie.name.toLowerCase();return je.includes("image")||je.includes("pdf")||Fe.endsWith(".pdf")||Fe.endsWith(".jpg")||Fe.endsWith(".jpeg")||Fe.endsWith(".png")||Fe.endsWith(".gif")||Fe.endsWith(".webp")};u.useEffect(()=>()=>{I!=null&&I.url&&URL.revokeObjectURL(I.url)},[I]),u.useEffect(()=>{b.length===0&&y([{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 P=ie=>{if(!z(ie)){Q.error("Preview is only available for images and PDF files");return}I!=null&&I.url&&URL.revokeObjectURL(I.url);const je=URL.createObjectURL(ie);$({file:ie,url:je})},S=ie=>{const je=URL.createObjectURL(ie),Fe=document.createElement("a");Fe.href=je,Fe.download=ie.name,document.body.appendChild(Fe),Fe.click(),document.body.removeChild(Fe),URL.revokeObjectURL(je)},U=u.useMemo(()=>b.reduce((ie,je)=>ie+(je.totalAmt||je.amount||0),0),[b]),Y=(ie,je,Fe=1)=>{const Ue=ie*Fe,Ce=Ue*(je.cgstRate||0)/100,ce=Ue*(je.sgstRate||0)/100,Re=Ue*(je.utgstRate||0)/100,qe=Ue*(je.igstRate||0)/100,at=Ce+ce+Re+qe,ft=Ue+at;return{cgstRate:je.cgstRate,cgstAmt:Ce,sgstRate:je.sgstRate,sgstAmt:ce,utgstRate:je.utgstRate,utgstAmt:Re,igstRate:je.igstRate,igstAmt:qe,gstAmt:at,gstRate:(je.cgstRate||0)+(je.sgstRate||0)+(je.utgstRate||0)+(je.igstRate||0),totalAmt:ft}},B=u.useMemo(()=>{const ie=m!=="",je=j.length>0,Fe=N.length>0,Ue=w.trim().length>0,Ce=b.length>0&&b.every(Re=>Re.description.trim()!==""&&Re.amount>0),ce=f?!1:b.some(Re=>{const{isValid:qe}=va(Re.hsnCode,Re.isService);return!qe});return ie&&je&&Fe&&Ue&&Ce&&!ce},[m,j,N,w,f,b]),E=new Date().toISOString().split("T")[0],V=()=>{y([...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}])},G=(ie,je,Fe)=>{y(b.map(Ue=>{if(Ue.id===ie){let Ce={...Ue,[je]:Fe};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate","quantity"].includes(je)){const ce=parseFloat(Fe);if(!isNaN(ce)&&ce<0)return Q.error("Value cannot be negative"),Ue;const Re=je==="amount"?parseFloat(Fe)||0:Ue.amount,qe=je==="quantity"?parseInt(Fe)||1:Ue.quantity;let at=Ue.cgstRate,ft=Ue.sgstRate,Ft=Ue.utgstRate,me=Ue.igstRate;if(je==="cgstRate"){if(!g.isCGST)return Ue;at=parseFloat(Fe)||0,g.isUTGST?(Ft=at,ft=0):(ft=at,Ft=0),me=0}else if(je==="sgstRate"){if(!g.isSGST)return Ue;ft=parseFloat(Fe)||0,at=ft,Ft=0,me=0}else if(je==="utgstRate"){if(!g.isUTGST)return Ue;Ft=parseFloat(Fe)||0,at=Ft,ft=0,me=0}else if(je==="igstRate"){if(!g.isIGST)return Ue;me=parseFloat(Fe)||0,at=0,ft=0,Ft=0}else if(je==="gstRate"){const xe=parseFloat(Fe)||0;g.isIGST?(me=xe,at=0,ft=0,Ft=0):(at=xe/2,g.isUTGST?(Ft=xe/2,ft=0):(ft=xe/2,Ft=0),me=0)}const Oe=Y(Re,{cgstRate:at,sgstRate:ft,igstRate:me,utgstRate:Ft},qe);return je==="isService"&&(Ce.hsnCode=""),{...Ce,amount:Re,quantity:qe,...Oe}}return je==="isService"&&(Ce.hsnCode=""),Ce}return Ue}))},J=ie=>{y(b.filter(je=>je.id!==ie))},q=ie=>{const je=Array.from(ie.target.files||[]);if(je.length>0){const Fe=[],Ue=c.maxFileSizeMB*1024*1024,Ce=[".pdf",".doc",".docx",".zip",".rar"];je.forEach(ce=>{var at,ft;const Re="."+((at=ce.name.split(".").pop())==null?void 0:at.toLowerCase()),qe=((ft=ce.name.split(".").pop())==null?void 0:ft.toLowerCase())||"";if(ce.size>Ue){Q.error(`"${ce.name}" exceeds ${c.maxFileSizeMB}MB limit and was not added.`);return}if(!Ce.includes(Re)){Q.error(`"${ce.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!c.allowedFileTypes.includes(qe)){Q.error(`"${ce.name}" has an unallowed file type according to system policy.`);return}Fe.push(ce)}),Fe.length>0&&v([...j,...Fe]),M.current&&(M.current.value="")}},se=ie=>{v(j.filter((je,Fe)=>Fe!==ie))},ne=ie=>{const je=Array.from(ie.target.files||[]);if(je.length>0){const Fe=[],Ue=c.maxFileSizeMB*1024*1024;je.forEach(Ce=>{var Re;const ce=((Re=Ce.name.split(".").pop())==null?void 0:Re.toLowerCase())||"";if(Ce.size>Ue){Q.error(`Photo "${Ce.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!Ce.type.startsWith("image/")){Q.error(`"${Ce.name}" is not an image file.`);return}if(!c.allowedFileTypes.includes(ce)){Q.error(`"${Ce.name}" has an unsupported image format.`);return}Fe.push(Ce)}),Fe.length>0&&T([...N,...Fe]),R.current&&(R.current.value="")}},te=ie=>{T(N.filter((je,Fe)=>Fe!==ie))},ge=ie=>{const je=Array.from(ie.target.files||[]);if(je.length>0){const Fe=[],Ue=c.maxFileSizeMB*1024*1024,Ce=[".pdf",".jpg",".jpeg",".png"];je.forEach(ce=>{var at,ft;const Re="."+((at=ce.name.split(".").pop())==null?void 0:at.toLowerCase()),qe=((ft=ce.name.split(".").pop())==null?void 0:ft.toLowerCase())||"";if(ce.size>Ue){Q.error(`Invoice "${ce.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!Ce.includes(Re)){Q.error(`"${ce.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!c.allowedFileTypes.includes(qe)){Q.error(`"${ce.name}" format is not allowed by system policy.`);return}Fe.push(ce)}),Fe.length>0&&k([...A,...Fe]),C.current&&(C.current.value="")}},we=ie=>{k(A.filter((je,Fe)=>Fe!==ie))},fe=ie=>{var Fe,Ue,Ce;const je=(Fe=ie.target.files)==null?void 0:Fe[0];if(je){const ce=c.maxFileSizeMB*1024*1024,Re=[".pdf",".xlsx",".xls",".csv"],qe="."+((Ue=je.name.split(".").pop())==null?void 0:Ue.toLowerCase()),at=((Ce=je.name.split(".").pop())==null?void 0:Ce.toLowerCase())||"";if(je.size>ce){Q.error(`Attendance file exceeds ${c.maxFileSizeMB}MB limit.`),H.current&&(H.current.value="");return}if(!Re.includes(qe)){Q.error("Please upload PDF, Excel, or CSV files only"),H.current&&(H.current.value="");return}if(!c.allowedFileTypes.includes(at)){Q.error(`"${je.name}" format is not allowed by system policy.`),H.current&&(H.current.value="");return}F(je)}},ke=async()=>{if(!B){Q.error("Please fill all required fields");return}if(b.some(Ue=>Ue.amount<0||Ue.quantity<1)){Q.error("Please ensure all amounts are non-negative and quantity is at least 1");return}const je=b.filter(Ue=>Ue.description.trim()!==""&&Ue.amount>0);if(!f&&je.some(Ue=>Ue.description.trim()!==""&&Ue.amount>0&&(Ue.gstRate===0||!Ue.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.`)){W(!1);return}try{W(!0),await a({activityCompletionDate:m,numberOfParticipants:x?parseInt(x):void 0,closedExpenses:je,totalClosedExpenses:U,completionDocuments:j,activityPhotos:N,invoicesReceipts:A.length>0?A:void 0,attendanceSheet:D||void 0,completionDescription:w}),le(),s()}catch(Ue){console.error("Failed to submit completion documents:",Ue),Yd(Ue)||Q.error("Failed to submit completion documents. Please try again.")}finally{W(!1)}},le=()=>{I!=null&&I.url&&URL.revokeObjectURL(I.url),$(null),p(""),h(""),y([{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([]),T([]),k([]),F(null),L(""),M.current&&(M.current.value=""),R.current&&(R.current.value=""),C.current&&(C.current.value=""),H.current&&(H.current.value="")},Ne=()=>{_||(le(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(ht,{open:t,onOpenChange:Ne,children:e.jsxs(mt,{className:"dealer-completion-documents-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs(ut,{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(vs,{className:"w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]"}),"Activity Completion Documents"]}),d&&e.jsx(oe,{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(Mt,{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(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Completion Date *"]}),e.jsx(aa,{value:m||null,onChange:ie=>p(ie||""),maxDate:E,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(O,{type:"button",onClick:V,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(is,{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(ie=>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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item description"}),e.jsx(_e,{placeholder:"e.g., Venue rental, Refreshments",value:ie.description,onChange:je=>G(ie.id,"description",je.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(zs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(_e,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:ie.amount||"",onChange:je=>G(ie.id,"amount",je.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(zs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(_e,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:ie.amount||"",onChange:je=>G(ie.id,"amount",je.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN/SAC Code"}),e.jsx(tb,{value:ie.hsnCode||"",onChange:je=>G(ie.id,"hsnCode",je),type:ie.isService?"SAC":"HSN",className:va(ie.hsnCode,ie.isService).isValid?"":"border-red-500",placeholder:ie.isService?"SAC":"HSN"}),!va(ie.hsnCode,ie.isService).isValid&&e.jsx("span",{className:"text-[10px] text-red-500 absolute left-0 bottom-0 block leading-tight",children:va(ie.hsnCode,ie.isService).message})]}),e.jsxs("div",{className:"w-24 sm:w-28 flex-shrink-0",children:[e.jsx(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item Type"}),e.jsxs("select",{value:ie.isService?"SAC":"HSN",onChange:je=>G(ie.id,"isService",je.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"CGST %"}),e.jsx(_e,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ie.cgstRate||"",onChange:je=>G(ie.id,"cgstRate",je.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"SGST %"}),e.jsx(_e,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ie.sgstRate||"",onChange:je=>G(ie.id,"sgstRate",je.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"UTGST %"}),e.jsx(_e,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ie.utgstRate||"",onChange:je=>G(ie.id,"utgstRate",je.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"IGST %"}),e.jsx(_e,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ie.igstRate||"",onChange:je=>G(ie.id,"igstRate",je.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(O,{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:()=>J(ie.id),children:e.jsx(vt,{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:["₹",(ie.cgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),ie.sgstAmt>0&&e.jsxs("span",{children:["SGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(ie.sgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),ie.utgstAmt>0&&e.jsxs("span",{children:["UTGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(ie.utgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs("span",{children:["IGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(ie.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:["₹",(ie.gstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs(oe,{className:"bg-[#2d4a3e] text-white px-3 py-1 text-xs",children:["Item Total: ₹",(ie.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:["₹",(ie.amount||0).toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]})]},ie.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&&U>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:["₹",U.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(oe,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsxs(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Ee,{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 ${j.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:M,type:"file",multiple:!0,accept:[".pdf",".doc",".docx",".zip",".rar"].filter(ie=>c.allowedFileTypes.includes(ie.replace(".",""))).join(","),className:"hidden",id:"completionDocs",onChange:q}),e.jsx("label",{htmlFor:"completionDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:j.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:[j.length," document",j.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(vs,{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"})]})})]}),j.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 (",j.length,"):"]}),j.map((ie,je)=>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(Ee,{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:ie.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[z(ie)&&e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>P(ie),title:"Preview file",children:e.jsx(wt,{className:"w-3.5 h-3.5"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>S(ie),title:"Download file",children:e.jsx(kt,{className:"w-3.5 h-3.5"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>se(je),title:"Remove document",children:e.jsx(vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},je))]})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Photos *"]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload photos from the completed activity (event photos, installations, etc.)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${N.length>0?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:R,type:"file",multiple:!0,accept:[".jpg",".jpeg",".png",".gif",".webp"].filter(ie=>c.allowedFileTypes.includes(ie.replace(".",""))).join(","),className:"hidden",id:"completionPhotos",onChange:ne}),e.jsx("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:N.length>0?e.jsxs(e.Fragment,{children:[e.jsx(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:[N.length," photo",N.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-green-600",children:"Click to add more photos"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Qi,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload photos (JPG, PNG - multiple files allowed)"})]})})]}),N.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Photos (",N.length,"):"]}),N.map((ie,je)=>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(Qi,{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:ie.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[z(ie)&&e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>P(ie),title:"Preview photo",children:e.jsx(wt,{className:"w-3.5 h-3.5"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>S(ie),title:"Download photo",children:e.jsx(kt,{className:"w-3.5 h-3.5"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>te(je),title:"Remove photo",children:e.jsx(vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},je))]})]})]})]}),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(oe,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsxs(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Et,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Invoices / Receipts"]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload invoices and receipts for expenses incurred"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${A.length>0?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:C,type:"file",multiple:!0,accept:[".pdf",".jpg",".jpeg",".png"].filter(ie=>c.allowedFileTypes.includes(ie.replace(".",""))).join(","),className:"hidden",id:"invoiceReceipts",onChange:ge}),e.jsx("label",{htmlFor:"invoiceReceipts",className:"cursor-pointer flex flex-col items-center gap-2",children:A.length>0?e.jsxs(e.Fragment,{children:[e.jsx(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:[A.length," document",A.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-blue-600",children:"Click to add more documents"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload invoices/receipts (PDF, JPG, PNG)"})]})})]}),A.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",A.length,"):"]}),A.map((ie,je)=>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(Et,{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:ie.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[z(ie)&&e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>P(ie),title:"Preview file",children:e.jsx(wt,{className:"w-3.5 h-3.5"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>S(ie),title:"Download file",children:e.jsx(kt,{className:"w-3.5 h-3.5"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>we(je),title:"Remove document",children:e.jsx(vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},je))]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm sm:text-base font-semibold",children:"Attendance Sheet / Participant List"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload attendance records or participant lists (if applicable)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${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:H,type:"file",accept:[".pdf",".xlsx",".xls",".csv"].filter(ie=>c.allowedFileTypes.includes(ie.replace(".",""))).join(","),className:"hidden",id:"attendanceDoc",onChange:fe}),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(vs,{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(Ee,{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:[z(D)&&e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>P(D),title:"Preview file",children:e.jsx(wt,{className:"w-3.5 h-3.5"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>S(D),title:"Download file",children:e.jsx(kt,{className:"w-3.5 h-3.5"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>{F(null),H.current&&(H.current.value="")},title:"Remove document",children:e.jsx(vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5 sm:space-y-2 max-w-3xl",children:[e.jsx(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(Vs,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:w,onChange:ie=>L(ie.target.value),className:"min-h-[100px] sm:min-h-[120px] text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[w.length," characters"]})]}),!B&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 sm:p-4 flex items-start gap-2 sm:gap-3",children:[e.jsx(Ze,{className:"w-4 h-4 sm:w-5 sm:h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs sm:text-sm text-amber-800",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Missing 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(O,{variant:"outline",onClick:Ne,disabled:_,className:"border-2",children:"Cancel"}),e.jsx(O,{onClick:ke,disabled:_||!B,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:_?"Submitting...":"Submit Documents"})]})]})}),I&&e.jsx(ht,{open:!!I,onOpenChange:()=>{I!=null&&I.url&&URL.revokeObjectURL(I.url),$(null)},children:e.jsx(mt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(pt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(wt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ut,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:I.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[I.file.type||"Unknown type"," • ",(I.file.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>S(I.file),className:"gap-2 h-9",children:[e.jsx(kt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:(ae=I.file.type)!=null&&ae.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:I.url,alt:I.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(he=I.file.type)!=null&&he.includes("pdf")||I.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:I.url,className:"w-full h-full rounded-lg border-0",title:I.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(wt,{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(O,{onClick:()=>S(I.file),className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",I.file.name]})]})})]})})})]})}function J4({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",dealerGSTIN:n,activityName:i="Activity",requestId:l,previousProposalData:o,defaultGstRate:c=18,documentPolicy:d,taxationType:m,totalBlockedAmount:p=0}){const[x,h]=u.useState(null),g=u.useMemo(()=>{const le=sb(n);return ab(le)},[n]),f=u.useMemo(()=>m==="Non GST"||m==="Non-GST",[m]),[b,y]=u.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}]),j=(le,Ne,ae=1)=>{const he=le*ae,ie=he*(Ne.cgstRate||0)/100,je=he*(Ne.sgstRate||0)/100,Fe=he*(Ne.utgstRate||0)/100,Ue=he*(Ne.igstRate||0)/100,Ce=ie+je+Fe+Ue,ce=he+Ce;return{cgstRate:Ne.cgstRate,cgstAmt:ie,sgstRate:Ne.sgstRate,sgstAmt:je,utgstRate:Ne.utgstRate,utgstAmt:Fe,igstRate:Ne.igstRate,igstAmt:Ue,gstAmt:Ce,gstRate:(Ne.cgstRate||0)+(Ne.sgstRate||0)+(Ne.utgstRate||0)+(Ne.igstRate||0),totalAmt:ce}},[v,N]=u.useState("date"),[T,A]=u.useState(""),[k,D]=u.useState(""),[F,w]=u.useState([]),[L,_]=u.useState(""),[W,I]=u.useState(!1),[$,M]=u.useState(null),[R,C]=u.useState(!1),H=u.useRef(null),z=u.useRef(null),P=le=>{if(!le)return!1;const Ne=le.toLowerCase();return Ne.endsWith(".pdf")||!!Ne.match(/\.(jpg|jpeg|png|gif|webp)$/i)},S=le=>P(le.name);u.useEffect(()=>()=>{$!=null&&$.fileUrl&&$.fileUrl.startsWith("blob:")&&URL.revokeObjectURL($.fileUrl)},[$]);const U=le=>{if(!S(le)){Q.error("Preview is only available for images and PDF files");return}$!=null&&$.fileUrl&&$.fileUrl.startsWith("blob:")&&URL.revokeObjectURL($.fileUrl);const Ne=URL.createObjectURL(le);M({fileName:le.name,fileType:le.type,documentId:"",fileUrl:Ne,fileSize:le.size})},Y=le=>{const Ne=le.originalFileName||le.fileName||le.name||"Document",ae=le.documentId||le.id||"",he=Ne.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let ie="";if(ae)ie=Dn(ae);else if(ie=le.storageUrl||le.documentUrl||"",ie&&!ie.startsWith("http")){const je="https://reflow-uat.royalenfield.com/",Fe=je.endsWith("/")?je.slice(0,-1):je,Ue=ie.startsWith("/")?ie:`/${ie}`;ie=`${Fe}${Ue}`}M({fileName:Ne,fileType:he,documentId:ae,fileUrl:ie})},B=le=>{const Ne=URL.createObjectURL(le),ae=document.createElement("a");ae.href=Ne,ae.download=le.name,document.body.appendChild(ae),ae.click(),document.body.removeChild(ae),URL.revokeObjectURL(Ne)};u.useEffect(()=>{if(t&&o){const le=p>0;if(o.costItems&&o.costItems.length>0){const Ne=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}));y(Ne)}o.expectedCompletionDate&&(A(o.expectedCompletionDate.split("T")[0]),N("date"))}else t&&!o&&(y([{id:"1",description:"",amount:0,gstRate:c||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),A(""),_(""))},[t,o,c,p]);const E=u.useMemo(()=>b.reduce((le,Ne)=>le+(Ne.totalAmt||Ne.amount||0),0),[b]),V=u.useMemo(()=>{const le=x!==null,Ne=b.length>0&&b.every(je=>je.description.trim()!==""&&je.amount>0),ae=v==="date"?T!=="":k!==""&&parseInt(k)>0,he=L.trim().length>0,ie=f?!1:b.some(je=>{const{isValid:Fe}=va(je.hsnCode,je.isService);return!Fe});return le&&Ne&&ae&&he&&!ie},[x,b,v,T,k,L,f]),G=le=>{var ae,he,ie;const Ne=(ae=le.target.files)==null?void 0:ae[0];if(Ne){const je=d.maxFileSizeMB*1024*1024;if(Ne.size>je){Q.error(`File size exceeds the maximum allowed size of ${d.maxFileSizeMB}MB. Current size: ${(Ne.size/(1024*1024)).toFixed(2)}MB`),H.current&&(H.current.value="");return}const Fe=[".pdf",".doc",".docx"],Ue="."+((he=Ne.name.split(".").pop())==null?void 0:he.toLowerCase()),Ce=((ie=Ne.name.split(".").pop())==null?void 0:ie.toLowerCase())||"";if(!Fe.includes(Ue)||!d.allowedFileTypes.includes(Ce)){Q.error("Please upload a valid PDF, DOC, or DOCX file as per system policy"),H.current&&(H.current.value="");return}h(Ne)}},J=le=>{const Ne=Array.from(le.target.files||[]),ae=[],he=d.maxFileSizeMB*1024*1024;Ne.forEach(ie=>{var Fe;if(ie.size>he){Q.error(`"${ie.name}" exceeds ${d.maxFileSizeMB}MB limit and was not added.`);return}const je=((Fe=ie.name.split(".").pop())==null?void 0:Fe.toLowerCase())||"";if(!d.allowedFileTypes.includes(je)){Q.error(`"${ie.name}" has an unsupported file type and was not added.`);return}ae.push(ie)}),ae.length>0&&w(ie=>[...ie,...ae]),z.current&&(z.current.value="")},q=()=>{y(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}])},se=le=>{b.length>1&&y(Ne=>Ne.filter(ae=>ae.id!==le))},ne=(le,Ne,ae)=>{y(he=>he.map(ie=>{if(ie.id===le){let je={...ie,[Ne]:ae};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate"].includes(Ne)){const Fe=parseFloat(ae);if(!isNaN(Fe)&&Fe<0)return Q.error("Value cannot be negative"),ie;const Ue=Ne==="amount"?parseFloat(ae)||0:ie.amount,Ce=1;let ce=ie.cgstRate,Re=ie.sgstRate,qe=ie.utgstRate,at=ie.igstRate;if(Ne==="cgstRate"){if(!g.isCGST)return ie;ce=parseFloat(ae)||0,g.isUTGST?(qe=ce,Re=0):(Re=ce,qe=0),at=0}else if(Ne==="sgstRate"){if(!g.isSGST)return ie;Re=parseFloat(ae)||0,ce=Re,qe=0,at=0}else if(Ne==="utgstRate"){if(!g.isUTGST)return ie;qe=parseFloat(ae)||0,ce=qe,Re=0,at=0}else if(Ne==="igstRate"){if(!g.isIGST)return ie;at=parseFloat(ae)||0,ce=0,Re=0,qe=0}else if(Ne==="gstRate"){const Ft=parseFloat(ae)||0;g.isIGST?(at=Ft,ce=0,Re=0,qe=0):(ce=Ft/2,g.isUTGST?(qe=Ft/2,Re=0):(Re=Ft/2,qe=0),at=0)}const ft=j(Ue,{cgstRate:ce,sgstRate:Re,igstRate:at,utgstRate:qe},Ce);return{...je,amount:Ue,quantity:Ce,...ft}}return je}return ie}))},te=le=>{w(Ne=>Ne.filter((ae,he)=>he!==le))},ge=async()=>{if(!V){Q.error("Please fill all required fields");return}if(b.some(ae=>ae.amount<0)){Q.error("Please ensure all amounts are non-negative");return}if(v==="days"&&(parseInt(k)<=0||isNaN(parseInt(k)))){Q.error("Please enter a valid number of days greater than 0");return}let Ne=T||"";if(v==="days"&&k){const ae=parseInt(k),he=new Date;he.setDate(he.getDate()+ae),Ne=he.toISOString().split("T")[0]}try{if(I(!0),!f&&b.some(je=>je.description.trim()!==""&&je.amount>0&&(je.gstRate===0||!je.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.`)){I(!1);return}const he=p>0,ie=b.filter(je=>je.description.trim()!==""&&je.amount>0).map(je=>({...je,description:o&&he&&!je.isOriginal?`[ADDITIONAL] ${je.description}`:je.description}));await a({proposalDocument:x,costBreakup:ie,totalEstimatedBudget:E,expectedCompletionDate:Ne,timelineMode:v,expectedCompletionDays:v==="days"?parseInt(k):0,otherDocuments:F,dealerComments:L}),we(),s()}catch(ae){console.error("Failed to submit proposal:",ae),Yd(ae)||Q.error("Failed to submit proposal. Please try again.")}finally{I(!1)}},we=()=>{$!=null&&$.fileUrl&&$.fileUrl.startsWith("blob:")&&URL.revokeObjectURL($.fileUrl),M(null),h(null),y([{id:"1",description:"",amount:0,gstRate:0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),N("date"),A(""),D(""),w([]),_(""),H.current&&(H.current.value=""),z.current&&(z.current.value="")},fe=()=>{W||(we(),s())},ke=new Date().toISOString().split("T")[0];return e.jsxs(ht,{open:t,onOpenChange:fe,children:[e.jsxs(mt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"flex-shrink-0 pb-3 lg:pb-4",children:[e.jsxs(ut,{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(vs,{className:"w-5 h-5 lg:w-6 lg:h-6 text-[--re-green]"}),"Dealer Proposal Submission"]}),m&&e.jsx(oe,{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(Mt,{className:"text-sm lg:text-base",children:"Step 1: Upload proposal and planning details"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs lg:text-sm text-gray-600",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",i]})]}),e.jsx("div",{className:"mt-1",children:"Please upload proposal document, provide cost breakdown, timeline, and detailed comments."})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden min-h-0 py-3 lg:py-4",children:[o&&e.jsx("div",{className:"mb-6 mx-1",children:e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg overflow-hidden cursor-pointer hover:bg-amber-100/50 transition-colors",onClick:()=>C(!R),children:[e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ee,{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(oe,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(o.totalEstimatedBudget||o.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:R?e.jsx(zc,{className:"w-4 h-4"}):e.jsx(is,{className:"w-4 h-4"})})]}),R&&e.jsxs("div",{className:"px-4 pb-4 border-t border-amber-200 space-y-4 bg-white/50",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-xs",children:[o.expectedCompletionDate&&e.jsxs("div",{className:"flex items-center gap-1.5 text-gray-700",children:[e.jsx(bt,{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:P(o.documentUrl)?e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:o.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"View Previous Document"})]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:o.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"Download Previous Document"})]})}),o.otherDocuments&&o.otherDocuments.length>0&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1.5 flex items-center gap-1",children:[e.jsx(Ee,{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,Ne)=>e.jsx(Gr,{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:P(le.originalFileName||le.fileName||le.name||"")?()=>Y(le):void 0,onDownload:async ae=>{if(ae)await $s(ae);else{let he=le.storageUrl||le.documentUrl;if(he&&!he.startsWith("http")){const ie="https://reflow-uat.royalenfield.com/",je=ie.endsWith("/")?ie.slice(0,-1):ie,Fe=he.startsWith("/")?he:`/${he}`;he=`${je}${Fe}`}he&&window.open(he,"_blank")}}},Ne))})]})]}),(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,Ne)=>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")]})]},Ne)),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(oe,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${x?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:[e.jsx("input",{ref:H,type:"file",accept:[".pdf",".doc",".docx"].filter(le=>d.allowedFileTypes.includes(le.replace(".",""))).join(","),className:"hidden",id:"proposalDoc",onChange:G}),e.jsx("label",{htmlFor:"proposalDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:x?e.jsxs("div",{className:"flex flex-col items-center gap-2 w-full text-center",children:[e.jsx(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:x.name}),e.jsxs("div",{className:"flex gap-2",children:[S(x)&&e.jsx(O,{type:"button",variant:"outline",size:"sm",onClick:()=>U(x),className:"h-7 text-[10px]",children:"Preview"}),e.jsx(O,{type:"button",variant:"outline",size:"sm",onClick:()=>B(x),className:"h-7 text-[10px]",children:"Download"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(vs,{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(oe,{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(O,{type:"button",onClick:()=>N("date"),className:v==="date"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Date"}),e.jsx(O,{type:"button",onClick:()=>N("days"),className:v==="days"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Days"})]}),v==="date"?e.jsx(aa,{value:T||null,onChange:le=>A(le||""),minDate:ke,placeholderText:"dd/mm/yyyy",className:"w-full"}):e.jsx(_e,{type:"number",placeholder:"Enter number of days",min:"1",value:k,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(oe,{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(O,{type:"button",onClick:q,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(is,{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(re,{className:"text-[10px] uppercase text-gray-500 font-bold",children:"Item Description"}),le.isOriginal?e.jsx(oe,{className:"text-[9px] h-4 bg-gray-200 text-gray-700 hover:bg-gray-200 border-none",children:"ORIGINAL"}):o&&p>0?e.jsx(oe,{className:"text-[9px] h-4 bg-amber-100 text-amber-700 hover:bg-amber-100 border-none",children:"ADDITIONAL"}):null]}),e.jsx(_e,{placeholder:"e.g., Venue branding, Logistics, etc.",value:le.description,onChange:Ne=>ne(le.id,"description",Ne.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(zs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(_e,{type:"number",value:le.amount||"",onChange:Ne=>ne(le.id,"amount",Ne.target.value),className:`pl-8 bg-white shadow-sm ${le.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:le.isOriginal})]})]}),e.jsx(O,{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:()=>se(le.id),disabled:b.length===1||le.isOriginal,children:e.jsx(vt,{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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(zs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(_e,{type:"number",value:le.amount||"",onChange:Ne=>ne(le.id,"amount",Ne.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN/SAC Code"}),e.jsx(tb,{value:le.hsnCode||"",onChange:Ne=>ne(le.id,"hsnCode",Ne),type:le.isService?"SAC":"HSN",disabled:le.isOriginal,className:va(le.hsnCode,le.isService).isValid?"":"border-red-500",placeholder:le.isService?"Select SAC":"Select HSN"}),!va(le.hsnCode,le.isService).isValid&&e.jsx("span",{className:"text-[10px] text-red-500 absolute left-0 bottom-0 block leading-tight",children:va(le.hsnCode,le.isService).message})]}),e.jsxs("div",{className:"w-28 sm:w-32",children:[e.jsx(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Type"}),e.jsxs("select",{value:le.isService?"SAC":"HSN",onChange:Ne=>ne(le.id,"isService",Ne.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"CGST %"}),e.jsx(_e,{type:"number",value:le.cgstRate||"",onChange:Ne=>ne(le.id,"cgstRate",Ne.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"SGST %"}),e.jsx(_e,{type:"number",value:le.sgstRate||"",onChange:Ne=>ne(le.id,"sgstRate",Ne.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"UTGST %"}),e.jsx(_e,{type:"number",value:le.utgstRate||"",onChange:Ne=>ne(le.id,"utgstRate",Ne.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(re,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"IGST %"}),e.jsx(_e,{type:"number",value:le.igstRate||"",onChange:Ne=>ne(le.id,"igstRate",Ne.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(zs,{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:["₹",E.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(oe,{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 ${F.length>0?"border-blue-500 bg-blue-50":"border-gray-300 bg-white"}`,children:[e.jsx("input",{ref:z,type:"file",multiple:!0,accept:d.allowedFileTypes.map(le=>`.${le}`).join(","),className:"hidden",id:"otherDocs",onChange:J}),e.jsxs("label",{htmlFor:"otherDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(vs,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:F.length>0?`${F.length} files selected`:"Upload supporting files"}),e.jsx("span",{className:"text-[10px] text-gray-400",children:"Click to add documents"})]})]}),F.length>0&&e.jsx("div",{className:"mt-2 space-y-2 max-h-[120px] overflow-y-auto",children:F.map((le,Ne)=>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(Ee,{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:[S(le)&&e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",onClick:()=>U(le),children:e.jsx(wt,{className:"w-3 h-3"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",onClick:()=>B(le),children:e.jsx(kt,{className:"w-3 h-3"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100 hover:text-red-600",onClick:()=>te(Ne),children:e.jsx(vt,{className:"w-3 h-3"})})]})]},Ne))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"font-semibold text-base lg:text-lg",children:"Dealer Comments *"}),e.jsx(Vs,{placeholder:"Details about execution, special requirements, etc.",value:L,onChange:le=>_(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(Ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs lg:text-sm text-amber-800",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Missing Required Information"}),e.jsx("p",{children:"Please ensure proposal document, cost breakup, timeline, and dealer comments are provided before submitting."})]})]})]}),e.jsxs(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(O,{variant:"outline",onClick:fe,disabled:W,className:"border-2",children:"Cancel"}),e.jsx(O,{onClick:ge,disabled:!V||W,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:W?"Submitting...":"Submit Documents"})]})]}),$&&e.jsx(qr,{fileName:$.fileName||"",fileType:$.fileType||"",fileUrl:$.fileUrl||"",fileSize:$.fileSize||0,attachmentId:$.documentId||"",onDownload:$s,open:!!$,onClose:()=>M(null)})]})}function Z4({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n,requestId:i,preFilledIONumber:l,preFilledBlockedAmount:o,preFilledRemainingBalance:c,taxationType:d}){const[m,p]=u.useState("approve"),[x,h]=u.useState(""),[g,f]=u.useState(!1),b=u.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),y=l||"";u.useEffect(()=>{t&&(h(""),p("approve"))},[t]);const j=x.length,v=500,N=u.useMemo(()=>(m==="reject"||y.trim().length>0)&&x.trim().length>0,[m,y,x]),T=async()=>{if(!N){if(m==="approve"&&!y.trim()){Q.error("IO number is required. Please block amount from IO tab first.");return}if(!x.trim()){Q.error("Please provide comments");return}return}try{f(!0),m==="approve"?await a({ioNumber:y.trim(),comments:x.trim()}):await r(x.trim()),A(),s()}catch(D){console.error(`Failed to ${m} request:`,D),Q.error(`Failed to ${m} request. Please try again.`)}finally{f(!1)}},A=()=>{p("approve"),h("")},k=()=>{g||(A(),s())};return e.jsx(ht,{open:t,onOpenChange:k,children:e.jsxs(mt,{className:"dept-lead-io-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"flex-shrink-0 px-6 pt-6 pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 mb-2",children:[e.jsx("div",{className:"p-1.5 lg:p-2 rounded-lg bg-green-100",children:e.jsx(Ve,{className:"w-5 h-5 lg:w-6 lg:h-6 text-green-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ut,{className:"font-semibold text-lg lg:text-xl flex items-center gap-2 flex-wrap",children:["Review and Approve",d&&e.jsx(oe,{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(Mt,{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(oe,{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(oe,{className:"bg-green-100 text-green-800 border-green-200 text-xs",children:[e.jsx(Ve,{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(O,{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(Ve,{className:"w-4 h-4 mr-1"}),"Approve"]}),e.jsxs(O,{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(At,{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(Et,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),e.jsx("h4",{className:"font-semibold text-sm lg:text-base text-blue-900",children:"IO Organisation Details"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(re,{htmlFor:"ioNumber",className:"text-xs lg:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["IO Number ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(_e,{id:"ioNumber",value:y||"—",disabled:!0,readOnly:!0,className:"bg-gray-100 h-8 lg:h-9 cursor-not-allowed text-xs lg:text-sm"}),!y&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:"⚠️ IO number not found. Please block amount from IO tab first."}),y&&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(re,{htmlFor:"comment",className:"text-xs lg:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Comments & Remarks ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Vs,{id:"comment",placeholder:m==="approve"?"Enter your approval comments and any conditions or notes...":"Enter detailed reasons for rejection...",value:x,onChange:D=>{const F=D.target.value;F.length<=v&&h(F)},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:[j,"/",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(O,{variant:"outline",onClick:k,disabled:g,className:"text-sm lg:text-base",children:"Cancel"}),e.jsx(O,{onClick:T,disabled:!N||g,className:`text-sm lg:text-base ${m==="approve"?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700"} text-white`,children:g?`${m==="approve"?"Approving":"Rejecting"}...`:e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"w-4 h-4 mr-2"}),m==="approve"?"Approve Request":"Reject Request"]})})]})]})})}function q4({isOpen:t,onClose:s,onPush:a,onReQuotation:r,completionDetails:n,ioDetails:i,completionDocuments:l,requestTitle:o,requestNumber:c,taxationType:d}){var I,$;const m=u.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),[p,x]=u.useState(""),[h,g]=u.useState(!1),[f,b]=u.useState(null),[y,j]=u.useState(!1),v=p.length,N=500,T=u.useMemo(()=>n!=null&&n.totalClosedExpenses?n.totalClosedExpenses:n!=null&&n.closedExpenses&&Array.isArray(n.closedExpenses)?n.closedExpenses.reduce((M,R)=>{const C=typeof R=="object"&&R.amount||0,H=typeof R=="object"&&R.gstAmt||0,z=R.totalAmt||C+H;return M+(Number(z)||0)},0):0,[n]),A=M=>{if(!M)return"—";try{return new Date(M).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return M}},k=M=>`₹${M.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,D=M=>{if(!M.name)return!1;const R=M.name.toLowerCase();return R.endsWith(".pdf")||R.endsWith(".jpg")||R.endsWith(".jpeg")||R.endsWith(".png")||R.endsWith(".gif")||R.endsWith(".webp")},F=async M=>{if(!M.id){Q.error("Document preview not available - document ID missing");return}j(!0);try{const R=Dn(M.id),C=M.name.toLowerCase(),H=C.endsWith(".pdf"),z=C.match(/\.(jpg|jpeg|png|gif|webp)$/i),P=!0,S=P?null:localStorage.getItem("accessToken"),Y=await fetch(R,{headers:{Accept:H?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!Y.ok)throw new Error(`Failed to load file: ${Y.status} ${Y.statusText}`);const B=await Y.blob();if(B.size===0)throw new Error("File is empty or could not be loaded");const E=window.URL.createObjectURL(B);b({name:M.name,url:E,type:B.type||(H?"application/pdf":z?"image":void 0),size:B.size})}catch(R){console.error("Failed to load document preview:",R),Q.error("Failed to load document preview")}finally{j(!1)}};u.useEffect(()=>()=>{f!=null&&f.url&&f.url.startsWith("blob:")&&window.URL.revokeObjectURL(f.url)},[f]);const w=async()=>{if(!p.trim()){Q.error("Please provide comments before proceeding");return}try{g(!0),await a(p.trim()),L(),s()}catch(M){console.error("Failed to generate e-invoice:",M),Q.error("Failed to generate e-invoice. Please try again.")}finally{g(!1)}},L=()=>{x("")},_=async()=>{if(!p.trim()){Q.error("Please provide comments (reason) for re-quotation request");return}if(!r){Q.error("Re-quotation handler not provided");return}try{g(!0),await r(p.trim()),L(),s()}catch(M){console.error("Failed to request re-quotation:",M)}finally{g(!1)}},W=()=>{h||(L(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(ht,{open:t,onOpenChange:W,children:e.jsxs(mt,{className:"settlement-push-modal overflow-hidden flex flex-col w-full max-w-none",children:[e.jsxs(pt,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 mb-2",children:[e.jsx("div",{className:"p-1.5 sm:p-2 rounded-lg bg-indigo-100",children:e.jsx(zt,{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(ut,{className:"font-semibold text-lg sm:text-xl flex items-center gap-2 flex-wrap",children:["E-Invoice Generation & Sync",d&&e.jsx(oe,{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(Mt,{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(oe,{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(oe,{className:"bg-indigo-100 text-indigo-800 border-indigo-200 text-xs",children:[e.jsx(zt,{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(de,{className:"pb-3",children:[e.jsxs(ue,{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(Te,{className:"text-xs sm:text-sm",children:"Review activity completion information"})]}),e.jsxs(ee,{className:"space-y-2 sm:space-y-3",children:[n.activityCompletionDate&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Activity Completion Date:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:A(n.activityCompletionDate)})]}),n.numberOfParticipants!==void 0&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Number of Participants:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:n.numberOfParticipants})]}),n.completionDescription&&e.jsxs("div",{className:"pt-2",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Completion Description:"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-900 line-clamp-3",children:n.completionDescription})]})]})]}),i&&i.ioNumber&&e.jsxs(Z,{children:[e.jsxs(de,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Et,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"IO Details"]}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Internal Order information for budget reference"})]}),e.jsxs(ee,{className:"space-y-2 sm:space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"IO Number:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900 font-mono",children:i.ioNumber})]}),i.blockedAmount!==void 0&&i.blockedAmount>0&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Blocked Amount:"}),e.jsx("span",{className:"text-xs sm:text-sm font-bold text-green-700",children:k(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:k(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(de,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Pa,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Expense Breakdown"]}),e.jsx(Te,{className:"text-xs sm:text-sm",children:"Review closed expenses breakdown (Base + GST)"})]}),e.jsxs(ee,{children:[e.jsxs("div",{className:"grid grid-cols-12 gap-2 mb-2 px-3 text-xs font-medium text-gray-500 uppercase tracking-wider hidden sm:grid",children:[e.jsx("div",{className:`${m?"col-span-8":"col-span-4"}`,children:"Description"}),e.jsx("div",{className:"col-span-2 text-right",children:"Base"}),!m&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"col-span-2 text-right",children:"GST Rate"}),e.jsx("div",{className:"col-span-2 text-right",children:"GST Amt"})]}),e.jsx("div",{className:"col-span-2 text-right",children:"Total"})]}),e.jsx("div",{className:"space-y-2 max-h-[300px] overflow-y-auto",children:n.closedExpenses.map((M,R)=>{const C=typeof M=="object"&&M.amount||0,H=typeof M=="object"&&M.gstRate||0,z=typeof M=="object"&&M.gstAmt||0,P=typeof M=="object"?M.totalAmt||C+z: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:M.description||`Expense ${R+1}`}),e.jsx("span",{className:"font-bold text-gray-900",children:k(P)})]}),e.jsxs("div",{className:"sm:hidden flex justify-between w-full text-xs text-gray-500",children:[e.jsxs("span",{children:["Base: ",k(C)]}),!m&&e.jsxs("span",{children:["GST: ",H,"% (",k(z),")"]})]}),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:M.description,children:M.description||`Expense ${R+1}`})}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:k(C)}),!m&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:[H,"%"]}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:k(z)})]}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right font-semibold text-gray-900",children:k(P)})]},R)})}),e.jsxs("div",{className:"flex items-center justify-between py-2 sm:py-3 px-3 sm:px-4 bg-blue-50 rounded border-2 border-blue-200 mt-3 sm:mt-4",children:[e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:"Total Closed Expenses:"}),e.jsx("span",{className:"text-sm sm:text-base font-bold text-blue-700",children:k(T)})]})]})]})]}),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(oe,{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((M,R)=>e.jsxs("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 min-w-0 flex-1",children:[e.jsx(ps,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600 flex-shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:M.name,children:M.name})})]}),M.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[D(M)&&e.jsx("button",{type:"button",onClick:()=>F(M),disabled:y,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:y?e.jsx(ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(wt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{M.id&&await $s(M.id)}catch(C){console.error("Failed to download document:",C),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(kt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},R))})]}),l.activityPhotos&&l.activityPhotos.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"font-semibold text-sm sm:text-base flex items-center gap-2",children:[e.jsx(zt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Activity Photos"]}),e.jsxs(oe,{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((M,R)=>e.jsxs("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 min-w-0 flex-1",children:[e.jsx(zt,{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:M.name,children:M.name})})]}),M.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[D(M)&&e.jsx("button",{type:"button",onClick:()=>F(M),disabled:y,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview photo",children:y?e.jsx(ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(wt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{M.id&&await $s(M.id)}catch(C){console.error("Failed to download document:",C),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download photo",children:e.jsx(kt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},R))})]}),l.invoicesReceipts&&l.invoicesReceipts.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"font-semibold text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Et,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Invoices / Receipts"]}),e.jsxs(oe,{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((M,R)=>e.jsxs("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 min-w-0 flex-1",children:[e.jsx(Et,{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:M.name,children:M.name})})]}),M.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[D(M)&&e.jsx("button",{type:"button",onClick:()=>F(M),disabled:y,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:y?e.jsx(ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(wt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{M.id&&await $s(M.id)}catch(C){console.error("Failed to download document:",C),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(kt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},R))})]}),l.attendanceSheet&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm sm:text-base flex items-center gap-2",children:[e.jsx(zt,{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(zt,{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:()=>F(l.attendanceSheet),disabled:y,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:y?e.jsx(ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(wt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var M;try{(M=l.attendanceSheet)!=null&&M.id&&await $s(l.attendanceSheet.id)}catch(R){console.error("Failed to download document:",R),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(kt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]})]})]}),e.jsx("div",{className:"p-2.5 sm:p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(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(re,{htmlFor:"comment",className:"text-xs sm:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Comments & Remarks ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Vs,{id:"comment",placeholder:"Enter your comments about e-invoice generation (e.g., verified expenses, ready for settlement)...",value:p,onChange:M=>{const R=M.target.value;R.length<=N&&x(R)},rows:4,className:"text-sm min-h-[80px] resize-none"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ss,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[v,"/",N]})]})]})]})}),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(O,{variant:"outline",onClick:W,disabled:h,children:"Cancel"}),r&&e.jsxs(O,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:_,disabled:!p.trim()||h,children:[h?e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(_t,{className:"w-4 h-4 mr-2"}),"Request Re-quotation"]}),e.jsx(O,{onClick:w,disabled:!p.trim()||h,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:h?"Processing...":e.jsxs(e.Fragment,{children:[e.jsx(zt,{className:"w-4 h-4 mr-2"}),"Generate & Sync"]})})]})]})}),f&&e.jsx(ht,{open:!!f,onOpenChange:()=>b(null),children:e.jsx(mt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(pt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(wt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ut,{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(O,{variant:"outline",size:"sm",onClick:()=>{const M=document.createElement("a");M.href=f.url,M.download=f.name,M.click()},className:"gap-2 h-9",children:[e.jsx(kt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:y?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")||(I=f.type)!=null&&I.includes("pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:f.url,className:"w-full h-full rounded-lg border-0",title:f.name,style:{minHeight:"70vh",height:"100%"}})}):f.name.match(/\.(jpg|jpeg|png|gif|webp)$/i)||($=f.type)!=null&&$.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:f.url,alt:f.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(wt,{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(O,{onClick:()=>{const M=document.createElement("a");M.href=f.url,M.download=f.name,M.click()},className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",f.name]})]})})]})})})]})}function e6({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(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(pt,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center",children:e.jsx(Ca,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ut,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(Mt,{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(Wt,{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(Ca,{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(Pl,{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(bt,{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(oe,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(oe,{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(O,{variant:"outline",onClick:s,className:"h-9",children:[e.jsx(vt,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function t6({isOpen:t,onClose:s,onApprove:a,onReject:r,onRequestRevision:n,proposalData:i,dealerName:l="Dealer",activityName:o="Activity",requestId:c,request:d,previousProposalData:m,taxationType:p}){const x=u.useMemo(()=>p==="Non GST"||p==="Non-GST",[p]),[h,g]=u.useState(""),[f,b]=u.useState(!1),[y,j]=u.useState(null),[v,N]=u.useState(!1),T=u.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const z=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(z)?z.reduce((P,S)=>{const U=typeof S=="object"&&S.amount||0,Y=typeof S=="object"&&S.quantity||1,B=U*Y,E=typeof S=="object"&&S.gstAmt||0,V=S.totalAmt||B+E;return P+(Number(V)||0)},0):0},[i]),A=u.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const z=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(z)?z.reduce((P,S)=>{const U=typeof S=="object"&&S.amount||0,Y=typeof S=="object"&&S.quantity||1;return P+Number(U)*Number(Y)},0):0},[i]),k=u.useMemo(()=>{const z=(d==null?void 0:d.internalOrders)||(d==null?void 0:d.internal_orders)||[];if(Array.isArray(z)&&z.length>0)return z.reduce((S,U)=>{const Y=Number(U.ioBlockedAmount||U.io_blocked_amount||0);return S+Y},0);const P=(d==null?void 0:d.internalOrder)||(d==null?void 0:d.internal_order);return Number((P==null?void 0:P.ioBlockedAmount)||(P==null?void 0:P.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=k>=A-.01,F=Math.max(0,A-k),[w,L]=u.useState(null),_=z=>{if(!z)return"—";try{return new Date(z).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return z}},W=z=>{if(!z.name)return!1;const P=z.name.toLowerCase();return P.endsWith(".pdf")||P.endsWith(".jpg")||P.endsWith(".jpeg")||P.endsWith(".png")||P.endsWith(".gif")||P.endsWith(".webp")},I=z=>{let P=z.url||z.storageUrl||"";const S=z.id||z.documentId||"";if(!S&&!P){Q.error("Document preview not available");return}if(P&&!P.startsWith("http")&&!P.startsWith("blob:")){const U="https://reflow-uat.royalenfield.com/",Y=U.endsWith("/")?U.slice(0,-1):U,B=P.startsWith("/")?P:`/${P}`;P=`${Y}${B}`}L({name:z.name||"Document",url:P||(S?Dn(S):""),type:(z.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:S})};u.useEffect(()=>()=>{w!=null&&w.url&&w.url.startsWith("blob:")&&window.URL.revokeObjectURL(w.url)},[w]);const $=async()=>{if(!h.trim()){Q.error("Please provide approval comments");return}try{b(!0),j("approve"),await a(h),C(),s()}catch(z){console.error("Failed to approve proposal:",z),Q.error("Failed to approve proposal. Please try again.")}finally{b(!1),j(null)}},M=async()=>{if(!h.trim()){Q.error("Please provide rejection reason");return}try{b(!0),j("reject"),await r(h),C(),s()}catch(z){console.error("Failed to reject proposal:",z),Q.error("Failed to reject proposal. Please try again.")}finally{b(!1),j(null)}},R=async()=>{if(!h.trim()){Q.error("Please provide reasons for requesting a revision");return}if(!n){Q.error("Revision feature is not available");return}try{b(!0),j("revision"),await n(h),C(),s()}catch(z){console.error("Failed to request revision:",z),Q.error("Failed to request revision. Please try again.")}finally{b(!1),j(null)}},C=()=>{g(""),j(null)},H=()=>{f||(C(),s())};return t?e.jsxs(ht,{open:t,onOpenChange:H,children:[e.jsxs(mt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(ut,{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(Ve,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),p&&e.jsx(oe,{className:`ml-2 border-none shadow-sm ${x?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:x?"Non-GST Claim":"GST Claim"})]}),e.jsx(Mt,{className:"text-xs lg:text-sm",children:"Step 2: Review dealer proposal and make a decision"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",l]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",o]})]}),e.jsxs("div",{className:"mt-1 text-amber-600 font-medium",children:["Decision: ",e.jsx("strong",{children:"Confirms?"})," (YES → Continue to Dept Lead / NO → Request is cancelled)"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden min-h-0 py-3 lg:py-4 px-6",children:[m&&e.jsx("div",{className:"mb-6",children:e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg overflow-hidden cursor-pointer hover:bg-amber-100/50 transition-colors",onClick:()=>N(!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(Ee,{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(oe,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(m.totalEstimatedBudget||m.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:v?e.jsx(zc,{className:"w-4 h-4"}):e.jsx(is,{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(bt,{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:W({name:m.documentUrl})?e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:m.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"View Previous Document"})]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:m.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"Download Previous Document"})]})})]}),(m.costItems||m.costBreakup)&&(m.costItems||m.costBreakup).length>0&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-2 flex items-center gap-1",children:[e.jsx(zs,{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((z,P)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:z.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(z.amount).toLocaleString("en-IN")]})]},P)),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(Ee,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:m.otherDocuments.map((z,P)=>e.jsx(Gr,{document:{documentId:z.documentId||z.id||"",name:z.originalFileName||z.fileName||z.name||"Supporting Document",fileType:(z.originalFileName||z.fileName||z.name||"").split(".").pop()||"file",uploadedAt:z.uploadedAt||new Date().toISOString()},onPreview:W({name:z.originalFileName||z.fileName||z.name||""})?()=>I(z):void 0,onDownload:async S=>{if(S)await $s(S);else{let U=z.storageUrl||z.documentUrl;if(U&&!U.startsWith("http")){const Y="https://reflow-uat.royalenfield.com/",B=Y.endsWith("/")?Y.slice(0,-1):Y,E=U.startsWith("/")?U:`/${U}`;U=`${B}${E}`}U&&window.open(U,"_blank")}}},P))})]}),(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(Qs,{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(Ee,{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(Ee,{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.submittedAt)]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:i.proposalDocument.id&&e.jsxs(e.Fragment,{children:[W(i.proposalDocument)&&e.jsx("button",{type:"button",onClick:()=>I(i.proposalDocument),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(wt,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var z;try{(z=i.proposalDocument)!=null&&z.id&&await $s(i.proposalDocument.id)}catch(P){console.error("Failed to download document:",P),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(kt,{className:"w-5 h-5 text-gray-600"})})]})})]}):e.jsx("p",{className:"text-xs text-gray-500 italic",children:"No proposal document available"})]}),(i==null?void 0:i.otherDocuments)&&i.otherDocuments.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(Ee,{className:"w-4 h-4 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(oe,{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((z,P)=>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(Ee,{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:z.name,children:z.name})]}),z.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[W(z)&&e.jsx("button",{type:"button",onClick:()=>I(z),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(wt,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{z.id&&await $s(z.id)}catch(S){console.error("Failed to download document:",S),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(kt,{className:"w-5 h-5 text-gray-600"})})]})]},P))})]})]}),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(zs,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const z=i!=null&&i.costBreakup?Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[]:[];return z&&Array.isArray(z)&&z.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden max-h-[200px] lg:max-h-[180px] overflow-y-auto",children:[e.jsx("div",{className:"bg-gray-50 px-3 lg:px-4 py-2 border-b sticky top-0",children:e.jsxs("div",{className:`grid ${x?"grid-cols-3":"grid-cols-4"} gap-4 text-xs lg:text-sm font-semibold text-gray-700`,children:[e.jsx("div",{className:"col-span-1",children:"Item Description"}),e.jsx("div",{className:"text-right",children:"Base"}),!x&&e.jsx("div",{className:"text-right",children:"GST"}),e.jsx("div",{className:"text-right",children:"Total"})]})}),e.jsx("div",{className:"divide-y",children:z.map((P,S)=>{var U,Y;return e.jsxs("div",{className:`px-3 lg:px-4 py-2 lg:py-3 grid ${x?"grid-cols-3":"grid-cols-4"} gap-4`,children:[e.jsxs("div",{className:"col-span-1 text-xs lg:text-sm text-gray-700",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[e.jsx("span",{className:"font-medium",children:(U=P==null?void 0:P.description)!=null&&U.startsWith("[ADDITIONAL]")?P.description.replace("[ADDITIONAL]","").trim():(P==null?void 0:P.description)||"N/A"}),z.some(B=>{var E;return(E=B==null?void 0:B.description)==null?void 0:E.startsWith("[ADDITIONAL]")})&&((Y=P==null?void 0:P.description)!=null&&Y.startsWith("[ADDITIONAL]")?e.jsx(oe,{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(oe,{className:"text-[9px] h-3.5 px-1 bg-gray-100 text-gray-600 hover:bg-gray-100 border-none leading-none",children:"ORIGINAL"}))]}),!x&&(P!=null&&P.gstRate)?e.jsxs("span",{className:"block text-[10px] text-gray-400",children:[P.gstRate,"% GST"]}):null]}),e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(P==null?void 0:P.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!x&&e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(P==null?void 0:P.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((P==null?void 0:P.totalAmt)||((P==null?void 0:P.amount)||0)*((P==null?void 0:P.quantity)||1)+((P==null?void 0:P.gstAmt)||0))||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(P==null?void 0:P.id)||(P==null?void 0:P.description)||S)})})]}),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(zs,{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:["₹",T.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(bt,{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.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(Qs,{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(Vs,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:h,onChange:z=>g(z.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(At,{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(O,{variant:"outline",onClick:H,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(O,{onClick:R,disabled:!h.trim()||f,variant:"secondary",className:"bg-amber-100 hover:bg-amber-200 text-amber-900 border border-amber-200 w-full sm:w-auto",children:f&&y==="revision"?"Requesting...":e.jsxs(e.Fragment,{children:[e.jsx(Qs,{className:"w-4 h-4 mr-2"}),"Request Revised Quotation"]})}),e.jsx(O,{onClick:M,disabled:!h.trim()||f,variant:"destructive",className:"bg-red-600 hover:bg-red-700 w-full sm:w-auto",children:f&&y==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(O,{onClick:$,disabled:!h.trim()||!D||f,className:"bg-green-600 hover:bg-green-700 text-white disabled:opacity-50 disabled:cursor-not-allowed w-full sm:w-auto",title:D?"":"Please block IO budget before approving",children:f&&y==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Ve,{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:k>0?`Pending block: ₹${F.toLocaleString("en-IN",{minimumFractionDigits:2})} more needs to be blocked in the IO Tab.`:"Please block IO budget in the IO Tab before approving."})]})]})]}),w&&e.jsx(qr,{fileName:w.name,fileType:w.type||"",fileUrl:w.url,fileSize:w.size,attachmentId:w.id,onDownload:$s,open:!!w,onClose:()=>L(null)})]}):null}function s6({isOpen:t,onClose:s,snapshot:a,type:r,title:n}){const[i,l]=u.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"},x=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 y="";if(f)y=Dn(f);else if(y=h.storageUrl||h.documentUrl||"",y&&!y.startsWith("http")){const j="https://reflow-uat.royalenfield.com/",v=j.endsWith("/")?j.slice(0,-1):j,N=y.startsWith("/")?y:`/${y}`;y=`${v}${N}`}l({fileName:g,fileType:b,documentId:f,fileUrl:y,fileSize:h.sizeBytes})};return e.jsxs(e.Fragment,{children:[e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs(pt,{className:"px-6 py-4 border-b",children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[o?e.jsx(Ee,{className:"w-5 h-5 text-blue-600"}):e.jsx(Et,{className:"w-5 h-5 text-green-600"}),n||(o?"Proposal Snapshot Details":"Completion Snapshot Details")]}),e.jsxs(Mt,{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(bt,{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(Gr,{document:{documentId:"",name:o?"Proposal Document":"Completion Document",fileType:p(a.documentUrl),uploadedAt:new Date().toISOString()},onPreview:m(a.documentUrl)?()=>x({fileName:o?"Proposal Document":"Completion Document",documentUrl:a.documentUrl}):void 0,onDownload:async()=>{let h=a.documentUrl;if(!h.startsWith("http")){const g="https://reflow-uat.royalenfield.com/",f=g.endsWith("/")?g.slice(0,-1):g,b=h.startsWith("/")?h:`/${h}`;h=`${f}${b}`}window.open(h,"_blank")}})]}),a.otherDocuments&&a.otherDocuments.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1 flex items-center justify-between",children:[e.jsx("span",{children:"Supporting Documents"}),e.jsxs(oe,{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(Gr,{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||"")?()=>x(h):void 0,onDownload:h.documentId?$s:async()=>{let f=h.storageUrl||h.documentUrl;if(f&&!f.startsWith("http")){const b="https://reflow-uat.royalenfield.com/",y=b.endsWith("/")?b.slice(0,-1):b,j=f.startsWith("/")?f:`/${f}`;f=`${y}${j}`}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(kp,{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(O,{onClick:s,children:"Close"})})]})}),i&&e.jsx(qr,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:$s,open:!!i,onClose:()=>l(null)})]})}async function a6(t){var s;try{const a=await Se.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 r6(t){var s;try{const a=await Se.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 n6(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 Se.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 i6(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 Se.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 l6(t,s){var a;try{const r=await Se.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 rb(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 Se.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 o6(t,s){var a;try{const r=await Se.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 c6(t){var s;try{const a=await Se.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 d6(t,s,a){var r;try{const n={};t&&(n.dateRange=t),s&&(n.startDate=s),a&&(n.endDate=a);const i=await Se.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 m6(t){var s;try{const a=await Se.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 nn=t=>{if(!t)return"";try{return js(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}}},u6=t=>{switch(t){case"approved":return e.jsx(Ve,{className:"w-5 h-5 text-green-600"});case"skipped":return e.jsx(Ve,{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(Ve,{className:"w-5 h-5 text-red-600"});default:return e.jsx(it,{className:"w-5 h-5 text-gray-400"})}},x6=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"}},h6=(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",p6=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 g6({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i,isSpectator:l=!1}){var Ar,Tr,ar,Oa,rr,Qt,As,ca,kr,Dr,Da,nr,Rt,xs,Js,ga,an,Ra,ir,En,_n,Mn,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,Im,Fm,Pm,Em,_m,Mm,Lm,Om,$m,Um,Bm,zm,Vm,Wm,Hm,Gm,Ym,Qm,Km,Xm,Jm,Zm,qm,eu,tu,su,au,ru,nu,iu,lu,ou,cu,du,mu,uu,xu,hu,pu,gu,fu,bu,ju,yu,vu,Nu,wu,Cu,Su,Au,Tu,ku,Du,Ru,Iu,Fu;const[o,c]=u.useState(!1),[d,m]=u.useState(!1),[p,x]=u.useState(!1),[h,g]=u.useState(!1),[f,b]=u.useState(!1),[y,j]=u.useState(!1),[v,N]=u.useState(!1),[T,A]=u.useState(null),[k,D]=u.useState(!1),[F,w]=u.useState(null),[L,_]=u.useState([]),[W,I]=u.useState(!1),[$,M]=u.useState(new Set),[R,C]=u.useState(null),[H,z]=u.useState(null),[P,S]=u.useState(!1),[U,Y]=u.useState(!1),[B,E]=u.useState([]),[V,G]=u.useState(0);u.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Be=t.id||t.requestId;try{const De=await Ms(Be),pe=(De==null?void 0:De.approvalLevels)||(De==null?void 0:De.approvals)||[];if(pe&&pe.length>0){const Ae=pe.map(be=>{var Me;return{step:be.levelNumber||be.level_number||0,levelNumber:be.levelNumber||be.level_number||0,levelName:be.levelName||be.level_name,approver:be.approverName||be.approver_name||"",approverEmail:(be.approverEmail||be.approver_email||"").toLowerCase(),status:((Me=be.status)==null?void 0:Me.toLowerCase())||"waiting",tatHours:be.tatHours||be.tat_hours||24,elapsedHours:be.elapsedHours||be.elapsed_hours,approvedAt:be.actionDate||be.action_date,comment:be.comments||be.comment,levelId:be.levelId||be.level_id}}).sort((be,Me)=>(be.levelNumber||0)-(Me.levelNumber||0));E(be=>be.length!==Ae.length||be.some((Le,Pe)=>{const Ct=Ae[Pe];return!Ct||Le.levelNumber!==Ct.levelNumber||Le.levelName!==Ct.levelName||Le.approverEmail!==Ct.approverEmail||Le.status!==Ct.status})?Ae:be)}else E([])}catch(De){console.warn("Failed to load approval flows from API:",De),t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&E(t.approvalFlow)}}else t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&E(t.approvalFlow)})()},[t==null?void 0:t.id,t==null?void 0:t.requestId,t==null?void 0:t.totalLevels,V]),u.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const K=t.id||t.requestId;(async()=>{try{const De=await Ms(K),pe=(De==null?void 0:De.approvalLevels)||(De==null?void 0:De.approvals)||[];if(pe&&pe.length>0){const Ae=pe.map(be=>{var Me;return{step:be.levelNumber||be.level_number||0,levelNumber:be.levelNumber||be.level_number||0,levelName:be.levelName||be.level_name,approver:be.approverName||be.approver_name||"",approverEmail:(be.approverEmail||be.approver_email||"").toLowerCase(),status:((Me=be.status)==null?void 0:Me.toLowerCase())||"waiting",tatHours:be.tatHours||be.tat_hours||24,elapsedHours:be.elapsedHours||be.elapsed_hours,approvedAt:be.actionDate||be.action_date,comment:be.comments||be.comment,levelId:be.levelId||be.level_id}}).sort((be,Me)=>(be.levelNumber||0)-(Me.levelNumber||0));E(Ae)}}catch(De){console.warn("Failed to load approval flows from API:",De)}})()}},[t==null?void 0:t.currentStep,t==null?void 0:t.totalLevels]);const J=async()=>{G(K=>K+1),await new Promise(K=>setTimeout(K,500)),n==null||n(),q()},q=async()=>{if(t!=null&&t.id||t!=null&&t.requestId)try{const Be=[...await CC(t.id||t.requestId)||[]].sort((De,pe)=>new Date(pe.createdAt).getTime()-new Date(De.createdAt).getTime());_(Be)}catch(K){console.warn("Failed to load version history:",K)}};u.useEffect(()=>{q()},[t==null?void 0:t.id,t==null?void 0:t.requestId,V]);const se=(K,Be,De)=>{var be;const pe=((t==null?void 0:t.totalLevels)||0)>5||(((be=t==null?void 0:t.approvalLevels)==null?void 0:be.length)||0)>5;if(Be&&Be.trim()&&(Be.toLowerCase().includes("additional approver")||!/^step\s+\d+$/i.test(Be)))return Be;const Ae=pe?{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 Ae[K]?Ae[K]:De&&De!=="Unknown"&&De!=="System"?`Additional Approver - ${De}`:`Additional Approver - Step ${K}`},ne=(K,Be,De)=>{var Me;if(Be&&Be.toLowerCase().includes("additional approver"))return De&&De!=="Unknown"&&De!=="System"?`${De} will review and approve this request as an additional approver.`:"Additional approver will review and approve this request.";const Ae=((t==null?void 0:t.totalLevels)||0)>5||(((Me=t==null?void 0:t.approvalLevels)==null?void 0:Me.length)||0)>5;if(Be&&Be.trim()){const Le=Be.toLowerCase();if(Le.includes("dealer")&&Le.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(Le.includes("requestor")&&(Le.includes("evaluation")||Le.includes("confirmation")))return"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)";if(Le.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(Le.includes("activity creation"))return"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.";if(Le.includes("dealer")&&(Le.includes("completion")||Le.includes("documents")))return"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description";if(Le.includes("requestor")&&(Le.includes("claim")||Le.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(Le.includes("e-invoice")||Le.includes("invoice generation")||Le.includes("dms"))return"E-Invoice will be generated upon settlement initiation.";if(Le.includes("credit note")||Le.includes("sap"))return"Got credit note from SAP. Review and send to dealer to complete the claim management process."}const be=Ae?{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 be[K]?be[K]:De&&De!=="Unknown"&&De!=="System"?`${De} will review and approve this request.`:`Step ${K} approval required.`},te=K=>{if(!L||L.length===0||!K)return{current:null,previous:null};const pe=[...L.filter(Me=>{var Le;return!!(Me.levelName&&Me.levelName.trim()===K.trim()||(Le=Me.snapshotData)!=null&&Le.levelName&&Me.snapshotData.levelName.trim()===K.trim())})].sort((Me,Le)=>{if(Le.version!==Me.version)return Le.version-Me.version;const Pe=Me.snapshotType==="APPROVE"?1:Me.snapshotType==="PROPOSAL"||Me.snapshotType==="COMPLETION"?2:3,Ct=Le.snapshotType==="APPROVE"?1:Le.snapshotType==="PROPOSAL"||Le.snapshotType==="COMPLETION"?2:3;return Pe-Ct}).filter((Me,Le,Pe)=>Me.snapshotType==="WORKFLOW"?!Pe.some(St=>St.snapshotType==="APPROVE"&&St.levelName===Me.levelName&&St.version>=Me.version):!0),Ae=pe.length>0?pe[0]:null,be=pe.length>1?pe[1]:null;return{current:Ae,previous:be,all:pe}},ge=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),we=ge!=null?Number(ge):null,fe=((t==null?void 0:t.status)||"").toUpperCase(),ke=fe==="REJECTED",le=fe==="CLOSED",Ne=!ke&&!le&&(fe==="PENDING"||fe==="IN_PROGRESS"||fe==="IN-PROGRESS"),ae=B.find(K=>{var pe,Ae;const Be=K.levelId||K.level_id,De=(pe=t==null?void 0:t.approvals)==null?void 0:pe.find(be=>be.levelId===Be);return((Ae=De==null?void 0:De.status)==null?void 0:Ae.toLowerCase())==="rejected"}),he=ae?Number(ae.levelNumber||ae.level_number||ae.step||0):null,ie=B.map((K,Be)=>{var Ia,Ps,ye,jt,Ht,Ns,Tt;const De=Number(K.levelNumber||K.level_number||K.step||Be+1),pe=K.levelName||K.level_name,Ae=(Ia=t==null?void 0:t.approvals)==null?void 0:Ia.find(We=>We.levelId===K.levelId);let be;if(pe&&pe.toLowerCase().includes("department lead")||De===3){const We=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);(We!=null&&We.ioNumber||We!=null&&We.io_number)&&(be={ioNumber:We.ioNumber||We.io_number||"",blockedAmount:We.ioBlockedAmount||We.io_blocked_amount||0,availableBalance:We.ioAvailableBalance||We.io_available_balance||0,remainingBalance:We.ioRemainingBalance||We.io_remaining_balance||0,organizedBy:((Ps=We.organizer)==null?void 0:Ps.displayName)||((ye=We.organizer)==null?void 0:ye.name)||We.organizedBy||K.approver||"N/A",organizedAt:We.organizedAt||We.organized_at||K.approvedAt||(t==null?void 0:t.updatedAt)||""})}let Le;De===6&&(Ae!=null&&Ae.dmsDetails?Le={dmsNumber:Ae.dmsDetails.dmsNumber||"",dmsRemarks:Ae.dmsDetails.dmsRemarks||"",pushedBy:Ae.dmsDetails.pushedBy||K.approver,pushedAt:Ae.dmsDetails.pushedAt||K.approvedAt||""}:t!=null&&t.dmsNumber&&(Le={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((jt=t.dmsDetails)==null?void 0:jt.dmsRemarks)||"",pushedBy:K.approver,pushedAt:K.approvedAt||t.updatedAt||""}));let Pe;if(ke||le)((Ht=Ae==null?void 0:Ae.status)==null?void 0:Ht.toLowerCase())==="rejected"?Pe="rejected":he!==null&&De>he?Pe="waiting":((Ns=Ae==null?void 0:Ae.status)==null?void 0:Ns.toLowerCase())==="approved"?Pe="approved":he!==null&&De<he?((Tt=Ae==null?void 0:Ae.status)==null?void 0:Tt.toLowerCase())==="approved"?Pe="approved":Pe="waiting":(we!==null&&De>we,Pe="waiting");else if(Ne&&we!==null&&we>0)if(De>we)Pe="waiting";else if(De<we)if(Ae!=null&&Ae.status){const We=Ae.status.toLowerCase();We==="approved"?Pe="approved":We==="skipped"?Pe="skipped":We==="rejected"?Pe="rejected":Pe="waiting"}else Pe="waiting";else if(Ae!=null&&Ae.status){const We=Ae.status.toLowerCase();We==="approved"?Pe="approved":We==="rejected"?Pe="rejected":Pe="in_progress"}else{const We=(K.status||"pending").toLowerCase();We==="in-review"||We==="in_review"||We==="in review"||We==="pending"?Pe="in_progress":Pe=We}else if(Ae!=null&&Ae.status){const We=Ae.status.toLowerCase();We==="approved"?Pe="approved":We==="rejected"?Pe="rejected":We==="pending"||We==="in_progress"||We==="in-progress"?Pe="in_progress":Pe=(K.status||"waiting").toLowerCase()}else{const We=(K.status||"waiting").toLowerCase();We==="in-review"||We==="in_review"||We==="in review"||We==="pending"?Pe="in_progress":Pe=We}const St=Pe==="waiting"?0:K.elapsedHours||0,Ts=K.approver||K.approverName||"Unknown",It=pe?te(pe):{current:null,previous:null};return{step:De,title:se(De,pe,Ts),approver:Ts,description:ne(De,pe,Ts)||K.description||"",tatHours:K.tatHours||24,status:Pe,comment:K.comment||(Ae==null?void 0:Ae.comment),approvedAt:K.approvedAt||(Ae==null?void 0:Ae.timestamp),elapsedHours:St,ioDetails:be,dmsDetails:Le,einvoiceUrl:De===7?Ae==null?void 0:Ae.einvoiceUrl:void 0,emailTemplateUrl:(Ae==null?void 0:Ae.emailTemplateUrl)||void 0,versionHistory:It}});let je=null,Fe=1;if(ke||le)he!==null?Fe=he:we!==null?Fe=we:Fe=(t==null?void 0:t.currentStep)||1;else if(Ne){const K=we!==null?ie.find(Be=>Be.step===we):null;je=K&&(K.status==="pending"||K.status==="in_progress")?K:ie.find(Be=>{var pe;const De=((pe=Be.status)==null?void 0:pe.toLowerCase())||"";return De==="pending"||De==="in_progress"||De==="in-review"||De==="in_review"}),Fe=je?je.step:we||(t==null?void 0:t.currentStep)||1}else Fe=we||(t==null?void 0:t.currentStep)||1;const Ue=((Ar=s==null?void 0:s.email)==null?void 0:Ar.toLowerCase())||"",Ce=((Tr=t==null?void 0:t.dealerEmail)==null?void 0:Tr.toLowerCase())||((Oa=(ar=t==null?void 0:t.dealer)==null?void 0:ar.email)==null?void 0:Oa.toLowerCase())||((Qt=(rr=t==null?void 0:t.claimDetails)==null?void 0:rr.dealerEmail)==null?void 0:Qt.toLowerCase())||((ca=(As=t==null?void 0:t.claimDetails)==null?void 0:As.dealer_email)==null?void 0:ca.toLowerCase())||"",ce=Ce&&Ue===Ce,Re=B.find(K=>(K.step||K.levelNumber||K.level_number)===Fe),qe=((Re==null?void 0:Re.approverEmail)||"").toLowerCase(),at=qe&&Ue===qe,ft=((Dr=(kr=t==null?void 0:t.initiator)==null?void 0:kr.email)==null?void 0:Dr.toLowerCase())||((Da=t==null?void 0:t.initiatorEmail)==null?void 0:Da.toLowerCase())||"",Ft=B.find(K=>{const Be=(K.approverEmail||"").toLowerCase(),De=(K.levelName||"").toLowerCase();return ft&&Be===ft||De.includes("requestor evaluation")||De.includes("requestor")&&De.includes("confirmation")}),me=Ft&&(Ft.step||Ft.levelNumber||Ft.level_number)||2,Oe=Ft||B.find(K=>(K.step||K.levelNumber||K.level_number)===2),xe=((Oe==null?void 0:Oe.approverEmail)||"").toLowerCase(),Je=xe&&Ue===xe,Ke=B.find(K=>(K.step||K.levelNumber||K.level_number)===1),rt=((Ke==null?void 0:Ke.approverEmail)||"").toLowerCase(),Xe=rt&&Ue===rt,lt=B.find(K=>(K.levelName||"").toLowerCase().includes("department lead")),et=((lt==null?void 0:lt.approverEmail)||"").toLowerCase(),xt=et&&Ue===et,Hs=async K=>{var Be,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const pe=t.id||t.requestId;K.proposalDocument&&await Xn(K.proposalDocument,pe,"APPROVAL");for(const be of K.otherDocuments)await Xn(be,pe,"SUPPORTING");const Ae=K.costBreakup.reduce((be,Me)=>be+(Me.totalAmt||Me.amount||0),0);await n6(pe,{proposalDocument:K.proposalDocument||void 0,costBreakup:K.costBreakup.map(be=>({description:be.description,amount:be.amount,gstRate:be.gstRate,gstAmt:be.gstAmt,cgstRate:be.cgstRate,cgstAmt:be.cgstAmt,sgstRate:be.sgstRate,sgstAmt:be.sgstAmt,igstRate:be.igstRate,igstAmt:be.igstAmt,utgstRate:be.utgstRate,utgstAmt:be.utgstAmt,cessRate:be.cessRate,cessAmt:be.cessAmt,totalAmt:be.totalAmt,quantity:be.quantity,hsnCode:be.hsnCode,isService:be.isService})),totalEstimatedBudget:Ae,expectedCompletionDate:K.expectedCompletionDate,dealerComments:K.dealerComments}),Q.success("Proposal submitted successfully"),J()}catch(pe){console.error("Failed to submit proposal:",pe);const Ae=((De=(Be=pe==null?void 0:pe.response)==null?void 0:Be.data)==null?void 0:De.message)||(pe==null?void 0:pe.message)||"Failed to submit proposal. Please try again.";throw Q.error(Ae),pe}},ls=async K=>{var Be,De,pe,Ae,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Me=t.id||t.requestId,Le=await Ms(Me),Pe=(Le==null?void 0:Le.approvalLevels)||(Le==null?void 0:Le.approvals)||[],Ct=((De=(Be=t==null?void 0:t.initiator)==null?void 0:Be.email)==null?void 0:De.toLowerCase())||((pe=t==null?void 0:t.initiatorEmail)==null?void 0:pe.toLowerCase())||"",St=Pe.find(It=>{const Ia=(It.approverEmail||It.approver_email||"").toLowerCase(),Ps=(It.levelName||It.level_name||"").toLowerCase(),ye=It.levelNumber||It.level_number;return Ct&&Ia===Ct||Ps.includes("requestor evaluation")||Ps.includes("requestor")&&Ps.includes("confirmation")||ye===me})||Pe.find(It=>(It.levelNumber||It.level_number)===2);if(!(St!=null&&St.levelId)&&!(St!=null&&St.level_id))throw new Error("Initiator approval level not found");const Ts=St.levelId||St.level_id;await Qn(Me,Ts,K),Q.success("Proposal approved successfully"),J()}catch(Me){console.error("Failed to approve proposal:",Me);const Le=((be=(Ae=Me==null?void 0:Me.response)==null?void 0:Ae.data)==null?void 0:be.message)||(Me==null?void 0:Me.message)||"Failed to approve proposal. Please try again.";throw Q.error(Le),Me}},Nt=async K=>{var Be,De,pe,Ae,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Me=t.id||t.requestId,Le=await Ms(Me),Pe=(Le==null?void 0:Le.approvalLevels)||(Le==null?void 0:Le.approvals)||[],Ct=((De=(Be=t==null?void 0:t.initiator)==null?void 0:Be.email)==null?void 0:De.toLowerCase())||((pe=t==null?void 0:t.initiatorEmail)==null?void 0:pe.toLowerCase())||"",St=Pe.find(It=>{const Ia=(It.approverEmail||It.approver_email||"").toLowerCase(),Ps=(It.levelName||It.level_name||"").toLowerCase(),ye=It.levelNumber||It.level_number;return Ct&&Ia===Ct||Ps.includes("requestor evaluation")||Ps.includes("requestor")&&Ps.includes("confirmation")||ye===me})||Pe.find(It=>(It.levelNumber||It.level_number)===2);if(!(St!=null&&St.levelId)&&!(St!=null&&St.level_id))throw new Error("Initiator approval level not found");const Ts=St.levelId||St.level_id;await _r(Me,Ts,"Proposal rejected by requestor",K),Q.success("Proposal rejected. Request has been cancelled."),J()}catch(Me){console.error("Failed to reject proposal:",Me);const Le=((be=(Ae=Me==null?void 0:Me.response)==null?void 0:Ae.data)==null?void 0:be.message)||(Me==null?void 0:Me.message)||"Failed to reject proposal. Please try again.";throw Q.error(Le),Me}},gt=async K=>{var Be,De,pe,Ae,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Me=t.id||t.requestId,Le=await Ms(Me),Pe=(Le==null?void 0:Le.approvalLevels)||(Le==null?void 0:Le.approvals)||[],Ct=((De=(Be=t==null?void 0:t.initiator)==null?void 0:Be.email)==null?void 0:De.toLowerCase())||((pe=t==null?void 0:t.initiatorEmail)==null?void 0:pe.toLowerCase())||"",St=Pe.find(It=>{const Ia=(It.approverEmail||It.approver_email||"").toLowerCase(),Ps=(It.levelName||It.level_name||"").toLowerCase(),ye=It.levelNumber||It.level_number;return Ct&&Ia===Ct||Ps.includes("requestor evaluation")||Ps.includes("requestor")&&Ps.includes("confirmation")||ye===me})||Pe.find(It=>(It.levelNumber||It.level_number)===2);if(!(St!=null&&St.levelId)&&!(St!=null&&St.level_id))throw new Error("Initiator approval level not found");const Ts=St.levelId||St.level_id;await _r(Me,Ts,"Revised Quotation Requested",K),Q.success("Revision requested. Request returned to dealer."),J()}catch(Me){console.error("Failed to request revision:",Me);const Le=((be=(Ae=Me==null?void 0:Me.response)==null?void 0:Ae.data)==null?void 0:be.message)||(Me==null?void 0:Me.message)||"Failed to request revision. Please try again.";throw Q.error(Le),Me}},Pt=async K=>{var Be,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const pe=t.id||t.requestId,Ae=await Ms(pe),Me=((Ae==null?void 0:Ae.approvalLevels)||(Ae==null?void 0:Ae.approvals)||[]).find(Pe=>{const Ct=(Pe.levelName||Pe.level_name||"").toLowerCase();return Ct.includes("requestor claim")||Ct.includes("requestor - claim")});if(!(Me!=null&&Me.levelId)&&!(Me!=null&&Me.level_id))throw new Error("Claim approval level not found");const Le=Me.levelId||Me.level_id;await _r(pe,Le,"Revised Quotation Requested",K),Q.success("Re-quotation requested. Request returned to dealer."),J()}catch(pe){console.error("Failed to request re-quotation:",pe);const Ae=((De=(Be=pe==null?void 0:pe.response)==null?void 0:Be.data)==null?void 0:De.message)||(pe==null?void 0:pe.message)||"Failed to request re-quotation. Please try again.";throw Q.error(Ae),pe}},Ss=async K=>{var Be,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const pe=t.id||t.requestId,Ae=await Ms(pe),be=(Ae==null?void 0:Ae.approvalLevels)||(Ae==null?void 0:Ae.approvals)||[],Me=be.find(Pe=>(Pe.levelName||Pe.level_name||"").toLowerCase().includes("department lead"))||be.find(Pe=>(Pe.levelNumber||Pe.level_number)===3);if(!(Me!=null&&Me.levelId)&&!(Me!=null&&Me.level_id))throw new Error("Department Lead approval level not found");const Le=Me.levelId||Me.level_id;await rb(pe,{ioNumber:K.ioNumber}),await Qn(pe,Le,K.comments),Q.success("Request approved and IO organized successfully"),J()}catch(pe){console.error("Failed to approve and organize IO:",pe);const Ae=((De=(Be=pe==null?void 0:pe.response)==null?void 0:Be.data)==null?void 0:De.message)||(pe==null?void 0:pe.message)||"Failed to approve request. Please try again.";throw Q.error(Ae),pe}},as=async K=>{var Be,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const pe=t.id||t.requestId,Ae=K.closedExpenses.map(be=>({description:be.description,amount:be.amount,gstRate:be.gstRate,gstAmt:be.gstAmt,cgstRate:be.cgstRate,cgstAmt:be.cgstAmt,sgstRate:be.sgstRate,sgstAmt:be.sgstAmt,igstRate:be.igstRate,igstAmt:be.igstAmt,utgstRate:be.utgstRate,utgstAmt:be.utgstAmt,cessRate:be.cessRate,cessAmt:be.cessAmt,totalAmt:be.totalAmt,quantity:be.quantity,hsnCode:be.hsnCode,isService:be.isService}));if(await i6(pe,{activityCompletionDate:K.activityCompletionDate,numberOfParticipants:K.numberOfParticipants,closedExpenses:Ae,totalClosedExpenses:K.totalClosedExpenses,completionDocuments:K.completionDocuments,activityPhotos:K.activityPhotos,completionDescription:K.completionDescription}),K.invoicesReceipts&&K.invoicesReceipts.length>0)for(const be of K.invoicesReceipts)await Xn(be,pe,"SUPPORTING");K.attendanceSheet&&await Xn(K.attendanceSheet,pe,"SUPPORTING"),Q.success("Completion documents submitted successfully"),J()}catch(pe){console.error("Failed to submit completion documents:",pe);const Ae=((De=(Be=pe==null?void 0:pe.response)==null?void 0:Be.data)==null?void 0:De.message)||(pe==null?void 0:pe.message)||"Failed to submit completion documents. Please try again.";throw Q.error(Ae),pe}},Ya=async K=>{var Be,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const pe=t.id||t.requestId,Ae=new Date().toISOString().slice(0,10);await o6(pe,{eInvoiceDate:Ae}),Q.success("E-Invoice generation initiated successfully."),J()}catch(pe){console.error("[DealerClaimWorkflowTab] Error generating e-invoice:",pe);let be=((De=(Be=pe==null?void 0:pe.response)==null?void 0:Be.data)==null?void 0:De.message)||(pe==null?void 0:pe.message)||"E-Invoice generation failed. Please try again.";throw be.length>300&&(be=be.substring(0,300)+"..."),Q.error(be),pe}},Qa=async K=>{var Be,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const pe=t.id||t.requestId,Ae=await Ms(pe),be=(Ae==null?void 0:Ae.approvalLevels)||(Ae==null?void 0:Ae.approvals)||[],Me=be.find(Pe=>(Pe.levelName||Pe.level_name||"").toLowerCase().includes("department lead"))||be.find(Pe=>(Pe.levelNumber||Pe.level_number)===3);if(!(Me!=null&&Me.levelId)&&!(Me!=null&&Me.level_id))throw new Error("Department Lead approval level not found");const Le=Me.levelId||Me.level_id;await _r(pe,Le,"Dept Lead rejected - More clarification required",K),Q.success("Request rejected. Request has been cancelled."),J()}catch(pe){console.error("Failed to reject request:",pe);const Ae=((De=(Be=pe==null?void 0:pe.response)==null?void 0:Be.data)==null?void 0:De.message)||(pe==null?void 0:pe.message)||"Failed to reject request. Please try again.";throw Q.error(Ae),pe}},[wr,Ta]=u.useState(null);u.useEffect(()=>{if(!t){Ta(null);return}(async()=>{try{const Be=t.id||t.requestId;if(!Be){Ta(null);return}const De=await Ms(Be),pe=(De==null?void 0:De.documents)||[],Ae=t.proposalDetails||(De==null?void 0:De.proposalDetails)||{},be=pe.find(Pe=>Pe.category==="APPROVAL"||Pe.type==="proposal"||Pe.documentCategory==="APPROVAL"),Me=pe.filter(Pe=>Pe.category==="SUPPORTING"||Pe.type==="supporting"||Pe.documentCategory==="SUPPORTING");let Le=Ae.costBreakup||[];if(typeof Le=="string")try{Le=JSON.parse(Le)}catch(Pe){console.warn("Failed to parse costBreakup JSON:",Pe),Le=[]}Array.isArray(Le)||(Le=[]),Ta({proposalDocument:be?{name:be.fileName||be.file_name||be.name,id:be.documentId||be.document_id||be.id}:void 0,costBreakup:Le,expectedCompletionDate:Ae.expectedCompletionDate||"",otherDocuments:Me.map(Pe=>({name:Pe.fileName||Pe.file_name||Pe.name,id:Pe.documentId||Pe.document_id||Pe.id})),dealerComments:Ae.dealerComments||"",submittedAt:Ae.submittedAt})}catch(Be){console.warn("Failed to load proposal data:",Be);const De=t.proposalDetails||{};let pe=De.costBreakup||[];if(typeof pe=="string")try{pe=JSON.parse(pe)}catch(Ae){console.warn("Failed to parse costBreakup JSON:",Ae),pe=[]}Array.isArray(pe)||(pe=[]),Ta({proposalDocument:void 0,costBreakup:pe,expectedCompletionDate:De.expectedCompletionDate||"",otherDocuments:[],dealerComments:De.dealerComments||"",submittedAt:De.submittedAt})}})()},[t]);const[Ot,ka]=u.useState(null);u.useEffect(()=>{if(!t){ka(null);return}(async()=>{try{const Be=t.id||t.requestId;if(!Be){ka(null);return}const De=await Ms(Be),pe=(De==null?void 0:De.documents)||[],Ae=[],be=[],Me=[];let Le=null;pe.forEach(Pe=>{const Ct=(Pe.category||Pe.documentCategory||Pe.type||"").toUpperCase(),St=(Pe.fileName||Pe.file_name||Pe.name||"").toLowerCase(),Ts={name:Pe.fileName||Pe.file_name||Pe.name,id:Pe.documentId||Pe.document_id||Pe.id,url:Pe.url||Pe.storageUrl||Pe.storage_url};Ct==="COMPLETION"||Ct==="COMPLETION_DOCUMENT"?Ae.push(Ts):Ct==="ACTIVITY_PHOTO"||Ct==="PHOTO"||Ct==="IMAGE"?be.push(Ts):Ct==="ATTENDANCE"||Ct==="ATTENDANCE_SHEET"?Le=Ts:(Ct==="SUPPORTING"||Ct==="INVOICE"||Ct==="RECEIPT")&&(!Le&&(St.includes("attendance")||St.includes("participant"))?Le=Ts:Me.push(Ts))}),Ae.length===0&&be.length===0&&t.completionDetails,ka({completionDocuments:Ae,activityPhotos:be,invoicesReceipts:Me,attendanceSheet:Le})}catch(Be){console.warn("Failed to load completion documents:",Be),ka(null)}})()},[t]);const Us=async()=>{try{Q.loading("Retriggering WFM push...",{id:"wfm-retrigger"}),await m6(t.id),Q.success("WFM push re-triggered successfully",{id:"wfm-retrigger"}),n?n():window.location.reload()}catch(K){console.error("Error retriggering WFM push:",K),Q.error(K.message||"Failed to re-trigger WFM push",{id:"wfm-retrigger"})}},en=async()=>{try{const K=t.id||t.requestId;if(!K){Q.error("Request ID not found");return}const De=await fetch(`https://reflow-uat.royalenfield.com/api/v1/dealer-claims/${K}/e-invoice/csv`,{headers:{Authorization:`Bearer ${nt.getAccessToken()||""}`},credentials:"include"});if(!De.ok)throw new Error("Failed to download CSV");const pe=await De.blob(),Ae=window.URL.createObjectURL(pe),be=document.createElement("a");be.href=Ae,be.download=`Invoice_${t.requestNumber||"Export"}.csv`,document.body.appendChild(be),be.click(),window.URL.revokeObjectURL(Ae),document.body.removeChild(be),Q.success("CSV downloaded successfully")}catch(K){console.error("Error downloading CSV:",K),Q.error("Failed to download CSV")}},tn=async()=>{try{const K=t.id||t.requestId;if(!K){Q.error("Request ID not found");return}if(!t.invoice&&!t.irn){Q.error("Invoice not generated yet");return}Y(!0),S(!0);const De=await fetch(`https://reflow-uat.royalenfield.com/api/v1/dealer-claims/${K}/e-invoice/pdf`,{headers:{Authorization:`Bearer ${nt.getAccessToken()||""}`},credentials:"include"});if(!De.ok)throw new Error("Failed to fetch invoice PDF");const pe=await De.blob(),Ae=window.URL.createObjectURL(pe);H&&window.URL.revokeObjectURL(H),z(Ae)}catch(K){console.error("Failed to preview invoice:",K),Q.error("Failed to load invoice preview"),S(!1)}finally{Y(!1)}},Cr=()=>{S(!1),H&&(window.URL.revokeObjectURL(H),z(null))},sn=()=>{if(H){const K=document.createElement("a");K.href=H,K.download=`Invoice_${t.requestNumber||"Download"}.pdf`,document.body.appendChild(K),K.click(),document.body.removeChild(K),Q.success("Invoice PDF downloaded")}},tr=((nr=t==null?void 0:t.claimDetails)==null?void 0:nr.dealerName)||((Rt=t==null?void 0:t.dealerInfo)==null?void 0:Rt.name)||"Dealer",Sr=((xs=t==null?void 0:t.claimDetails)==null?void 0:xs.dealerGstin)||((Js=t==null?void 0:t.dealerInfo)==null?void 0:Js.gstin)||((ga=t==null?void 0:t.dealerInfo)==null?void 0:ga.dealerGSTIN),sr=((an=t==null?void 0:t.claimDetails)==null?void 0:an.activityName)||((Ra=t==null?void 0:t.activityInfo)==null?void 0:Ra.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(Z,{children:[e.jsx(de,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(Te,{className:"mt-2",children:"Approval process for dealer claim management"})]})})}),e.jsxs(ee,{children:[(t==null?void 0:t.status)==="rejected"&&!(t!=null&&t.closureDate||t!=null&&t.closure_date)&&a?e.jsxs("div",{className:"mb-6 p-4 bg-amber-50 border-l-4 border-amber-500 rounded-lg flex items-start gap-4 shadow-sm",children:[e.jsx("div",{className:"p-2 bg-amber-100 rounded-full",children:e.jsx(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:ie.map((K,Be)=>{var St,Ts,It,Ia,Ps;const pe=(((St=K.status)==null?void 0:St.toLowerCase())||"")==="in_progress",Ae=K.step===Fe,be=Ne&&pe&&Ae,Me=K.status==="approved"||K.status==="skipped",Le=B.find(ye=>(ye.step||ye.levelNumber||ye.level_number)===K.step),Pe=Le!=null&&Le.levelId?(Ts=t==null?void 0:t.approvals)==null?void 0:Ts.find(ye=>ye.levelId===Le.levelId||ye.level_id===Le.levelId):null,Ct=(Pe==null?void 0:Pe.status)==="PAUSED"||((It=t==null?void 0:t.pauseInfo)==null?void 0:It.isPaused)&&(((Ia=t==null?void 0:t.pauseInfo)==null?void 0:Ia.levelId)===(Pe==null?void 0:Pe.levelId)||((Ps=t==null?void 0:t.pauseInfo)==null?void 0:Ps.level_id)===(Pe==null?void 0:Pe.levelId));return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${h6(K.status,be)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${p6(K.status)}`,children:u6(K.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:K.title}),e.jsx(oe,{className:x6(K.status),children:K.status.toLowerCase()}),K.emailTemplateUrl&&K.status==="approved"&&e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>{A({stepNumber:K.step,stepName:K.title}),N(!0)},children:e.jsx(Ca,{className:"w-3.5 h-3.5 text-blue-600"})}),K.step===7&&K.einvoiceUrl&&Me&&e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",title:"Download E-Invoice",onClick:()=>window.open(K.einvoiceUrl,"_blank"),children:e.jsx(kt,{className:"w-3.5 h-3.5 text-green-600"})}),(()=>{const ye=(K.levelName||K.title||"").toLowerCase().includes("requestor claim")||(K.levelName||K.title||"").toLowerCase().includes("requestor - claim"),jt=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&K.status==="approved";return ye&&jt&&e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-amber-100",title:"Preview Invoice",onClick:tn,children:e.jsx(Et,{className:"w-3.5 h-3.5 text-amber-600"})})})(),(()=>{var Tt,We,ws,Vt;const ye=(K.levelName||K.title||"").toLowerCase().includes("requestor claim")||(K.levelName||K.title||"").toLowerCase().includes("requestor - claim"),jt=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&K.status==="approved",Ht=((Tt=t==null?void 0:t.invoice)==null?void 0:Tt.wfmPushStatus)||((We=t==null?void 0:t.invoice)==null?void 0:We.wfmPushStatus),Ns=((ws=t==null?void 0:t.invoice)==null?void 0:ws.wfmPushError)||((Vt=t==null?void 0:t.invoice)==null?void 0:Vt.wfmPushError);return ye&&jt&&e.jsxs("div",{className:"flex items-center gap-1 ml-1",children:[e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-emerald-100",title:"Export CSV",onClick:en,children:e.jsx(Mp,{className:"w-3.5 h-3.5 text-emerald-600"})}),Ht==="SUCCESS"?e.jsx("div",{title:"Pushed to WFM successfully",children:e.jsx(ps,{className:"w-3.5 h-3.5 text-green-500"})}):Ht==="FAILED"?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{title:`WFM Push Failed: ${Ns||"Unknown error"}`,children:e.jsx(At,{className:"w-3.5 h-3.5 text-red-500"})}),e.jsx(O,{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(O,{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:K.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:K.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",Xt(K.tatHours)]}),K.elapsedHours&&(be||Me)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",Xt(K.elapsedHours)]})]})]}),K.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:K.comment})}),K.versionHistory&&K.versionHistory.all&&K.versionHistory.all.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsxs(O,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs text-amber-700 hover:text-amber-800 hover:bg-amber-50",onClick:()=>{const ye=new Set($);ye.has(K.step)?ye.delete(K.step):ye.add(K.step),M(ye)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($p,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"font-medium",children:"Version History"}),K.versionHistory.all&&K.versionHistory.all.length>0&&e.jsxs(oe,{className:"bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0",children:[K.versionHistory.all.length," Versions"]})]}),$.has(K.step)?e.jsx(Al,{className:"w-4 h-4"}):e.jsx(Qr,{className:"w-4 h-4"})]}),$.has(K.step)&&K.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:K.versionHistory.all.map((ye,jt)=>{var Ht,Ns,Tt,We;return e.jsxs("div",{className:`space-y-2 ${jt>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(oe,{className:`${jt===0?"bg-amber-500":"bg-gray-400"} text-white text-[10px] px-2 py-0.5`,children:[jt===0?"Current":"Previous",": v",ye.version]}),e.jsx("span",{className:"text-[10px] text-gray-600 font-medium",children:nn(ye.createdAt)})]})}),e.jsx("p",{className:"text-xs text-gray-700 font-medium",children:ye.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${jt===0?"bg-blue-100":"bg-gray-100"} flex items-center justify-center`,children:e.jsx("span",{className:`text-[8px] font-bold ${jt===0?"text-blue-600":"text-gray-600"}`,children:((Ns=(Ht=ye.changer)==null?void 0:Ht.displayName)==null?void 0:Ns.charAt(0))||"U"})}),e.jsxs("span",{className:"text-[10px] text-gray-600",children:["By ",((Tt=ye.changer)==null?void 0:Tt.displayName)||((We=ye.changer)==null?void 0:We.email)||"Unknown User"]})]}),ye.snapshotType==="PROPOSAL"&&ye.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(ye.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>C({data:ye.snapshotData,type:"PROPOSAL",title:`Proposal (v${ye.version})`}),children:[e.jsx(wt,{className:"w-3 h-3"}),"View Details"]})]}),ye.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",ye.snapshotData.comments]})]}),ye.snapshotType==="INTERNAL_ORDER"&&ye.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: ",ye.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Blocked Amount: ₹",Number(ye.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),ye.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-[10px] text-gray-600",children:["SAP Doc: ",ye.snapshotData.sapDocumentNumber]})]}),ye.snapshotType==="COMPLETION"&&ye.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(ye.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>C({data:ye.snapshotData,type:"COMPLETION",title:`Completion (v${ye.version})`}),children:[e.jsx(wt,{className:"w-3 h-3"}),"View Details"]})]}),ye.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",ye.snapshotData.comments]})]}),ye.snapshotType==="APPROVE"&&ye.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:[ye.snapshotData.action==="APPROVE"?"Approval":"Rejection"," Snapshot:"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["By: ",ye.snapshotData.approverName||ye.snapshotData.approverEmail||"Unknown"]}),ye.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1",children:["Comments: ",ye.snapshotData.comments.substring(0,100),ye.snapshotData.comments.length>100?"...":""]}),ye.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-[10px] text-red-600 mt-1",children:["Rejection Reason: ",ye.snapshotData.rejectionReason.substring(0,100),ye.snapshotData.rejectionReason.length>100?"...":""]})]}),ye.snapshotType==="WORKFLOW"&&ye.snapshotData&&ye.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:[ye.snapshotData.comments.substring(0,100),ye.snapshotData.comments.length>100?"...":""]})]})]},jt)})})]}),be&&(Pe==null?void 0:Pe.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:Pe.sla.deadline?_a(Pe.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${Ct?"bg-gray-100 border-gray-300":(Pe.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(Pe.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(Pe.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 ",Ct&&"(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:Pe.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:[Pe.sla.elapsedText||"0 hours"," / ",Xt(K.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const ye=Pe.sla.percentageUsed||0,jt=()=>Ct?"bg-gray-500":ye>=100?"bg-red-600":ye>=75?"bg-orange-500":ye>=50?"bg-amber-500":"bg-green-600",Ht=()=>Ct?"text-gray-600":ye>=100?"text-red-600":ye>=75?"text-orange-600":ye>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(oa,{value:ye,className:"h-3",indicatorClassName:jt()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${Ht()}`,children:["Progress: ",Math.min(100,ye),"% of TAT used"]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[Pe.sla.remainingText||"0 hours"," remaining"]})]})]})})(),Pe.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(ml,{className:"w-4 h-4"}),"Deadline Breached"]}),Pe.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 ye=K.levelName||K.level_name;return(ye&&ye.toLowerCase().includes("department lead")||K.title&&K.title.toLowerCase().includes("department lead"))&&!ce&&K.status==="approved"&&K.ioDetails&&K.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(Et,{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:K.ioDetails.ioNumber})]}),K.ioDetails.blockedAmount!==void 0&&K.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:["₹",K.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),K.ioDetails.remainingBalance!==void 0&&K.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:["₹",K.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 ",K.ioDetails.organizedBy||K.approver||"N/A"," on"," ",K.ioDetails.organizedAt?nn(K.ioDetails.organizedAt):K.approvedAt?nn(K.approvedAt):"N/A"]})]})]})})(),K.step===6&&K.dmsDetails&&K.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(zt,{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:K.dmsDetails.dmsNumber})]}),K.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:K.dmsDetails.dmsRemarks})]}),K.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Initiated by ",K.dmsDetails.pushedBy," on"," ",nn(K.dmsDetails.pushedAt)]})]})]}),(()=>{const ye=B.find(We=>(We.step||We.levelNumber||We.level_number)===K.step),jt=((ye==null?void 0:ye.approverEmail)||"").toLowerCase(),Ht=jt&&Ue===jt,Ns=K.step===1||(ye==null?void 0:ye.levelName)&&ye.levelName.toLowerCase().includes("dealer");return be&&(Ht||Ns&&ce)&&!l})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[(()=>{const ye=((Le==null?void 0:Le.levelName)||K.title||"").toLowerCase();return(K.step===1||ye.includes("proposal")||ye.includes("submission"))&&(ce||Xe)})()&&e.jsxs(O,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{c(!0)},children:[e.jsx(vs,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),(()=>{const ye=((Le==null?void 0:Le.levelName)||K.title||"").toLowerCase();return(ye.includes("requestor evaluation")||ye.includes("confirmation")||K.step===me)&&(a||Je)})()&&e.jsxs(O,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{m(!0)},children:[e.jsx(Ve,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const ye=B.find(We=>(We.step||We.levelNumber||We.level_number)===K.step);if(!((ye==null?void 0:ye.levelName)||K.title||"").toLowerCase().includes("initiator action")||!(a||Ue===ft))return null;const Tt=async We=>{var ws,Vt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Es=t.requestId||t.id;await Bg(Es,We,{reason:""}),Q.success(`Action "${We==="REVISE"?"Revision Requested":"Request Reopened"}" performed successfully`),J()}catch(Es){console.error("Failed to perform initiator action:",Es);const Db=((Vt=(ws=Es==null?void 0:Es.response)==null?void 0:ws.data)==null?void 0:Vt.message)||(Es==null?void 0:Es.message)||"Failed to perform action";Q.error(Db)}};return e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(O,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:()=>Tt("REVISE"),children:[e.jsx(_t,{className:"w-4 h-4 mr-2"}),"Request Re-quotation"]}),e.jsxs(O,{variant:"outline",className:"border-blue-500 text-blue-600 hover:bg-blue-50",onClick:()=>Tt("REOPEN"),children:[e.jsx(Fp,{className:"w-4 h-4 mr-2"}),"Reopen"]})]})})(),(()=>{const ye=B.find(Vt=>(Vt.levelName||"").toLowerCase().includes("department lead"));if(!(ye&&K.step===(ye.step||ye.levelNumber||ye.level_number)))return null;const Ht=((ye==null?void 0:ye.approverEmail)||"").toLowerCase();if(!(Ht&&Ue===Ht||xt||at))return null;const Tt=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),We=(Tt==null?void 0:Tt.ioNumber)||(Tt==null?void 0:Tt.io_number)||(t==null?void 0:t.ioNumber)||"",ws=We&&We.trim()!=="";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(O,{className:"bg-green-600 hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>{x(!0)},disabled:!ws,children:[e.jsx(Ve,{className:"w-4 h-4 mr-2"}),"Review and Approve"]}),!ws&&e.jsx("p",{className:"text-xs text-amber-600",children:"Please add an IO number in the IO tab before approving this step."})]})})(),(()=>{const ye=B.find(We=>(We.step||We.levelNumber||We.level_number)===K.step),jt=((ye==null?void 0:ye.approverEmail)||"").toLowerCase(),Ht=ce&&jt===Ce,Ns=((ye==null?void 0:ye.levelName)||K.title||"").toLowerCase(),Tt=Ns.includes("dealer completion")||Ns.includes("completion documents");return Ht&&Tt})()&&e.jsxs(O,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{g(!0)},children:[e.jsx(vs,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const ye=B.find(Tt=>{const We=(Tt.levelName||"").toLowerCase();return We.includes("requestor claim")||We.includes("requestor - claim")});if(!(ye&&K.step===(ye.step||ye.levelNumber||ye.level_number)))return null;const Ht=((ye==null?void 0:ye.approverEmail)||"").toLowerCase();return a||Ht&&Ue===Ht?e.jsxs(O,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{b(!0)},children:[e.jsx(zt,{className:"w-4 h-4 mr-2"}),"Generate E-Invoice & Sync"]}):null})(),(()=>{var ws;const ye=((Le==null?void 0:Le.levelName)||K.title||"").toLowerCase(),jt=ye.includes("credit note")||ye.includes("sap")||K.step===8&&!ye.includes("additional"),Ht=((Le==null?void 0:Le.approverEmail)||"").toLowerCase(),Ns=Ht&&Ue===Ht,Tt=((ws=s==null?void 0:s.role)==null?void 0:ws.toUpperCase())||"";return jt&&(Ns||(Tt==="FINANCE"||Tt==="ADMIN"))})()&&e.jsxs(O,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{j(!0)},children:[e.jsx(Et,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]}),(()=>{const ye=B.find(Tt=>(Tt.step||Tt.levelNumber||Tt.level_number)===K.step),jt=((ye==null?void 0:ye.levelName)||K.title||"").toLowerCase(),Ht=jt.includes("additional approver"),Ns=K.step===1||jt.includes("proposal")||jt.includes("submission")||jt.includes("requestor evaluation")||jt.includes("confirmation")||jt.includes("department lead")||jt.includes("dealer completion")||jt.includes("completion documents")||jt.includes("requestor claim")||jt.includes("requestor - claim")||jt.includes("credit note")||jt.includes("sap");if(Ht||!Ns){const Tt=(ye==null?void 0:ye.levelId)||(ye==null?void 0:ye.level_id);if(Tt){const We=(ye==null?void 0:ye.levelName)||(ye==null?void 0:ye.level_name)||K.title||"Approval Level",ws=(ye==null?void 0:ye.approverName)||(ye==null?void 0:ye.approver_name)||K.approver||"Approver";return e.jsxs(O,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{w({levelId:Tt,levelName:We,approverName:ws}),D(!0)},children:[e.jsx(Ve,{className:"w-4 h-4 mr-2"}),"Review Request"]})}return e.jsxs(e.Fragment,{children:[e.jsxs(O,{className:"bg-green-600 hover:bg-green-700",onClick:async()=>{var We,ws;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Vt=t.id||t.requestId;if(!Tt){Q.error("Approval level not found");return}await Qn(Vt,Tt,""),Q.success("Request approved successfully"),J()}catch(Vt){console.error("Failed to approve:",Vt);const Es=((ws=(We=Vt==null?void 0:Vt.response)==null?void 0:We.data)==null?void 0:ws.message)||(Vt==null?void 0:Vt.message)||"Failed to approve request. Please try again.";Q.error(Es)}},children:[e.jsx(Ve,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(O,{variant:"destructive",onClick:async()=>{var We,ws;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Vt=t.id||t.requestId;if(!Tt){Q.error("Approval level not found");return}const Es=prompt("Please provide a reason for rejection:");if(Es===null)return;await _r(Vt,Tt,"Request rejected",Es),Q.success("Request rejected successfully"),J()}catch(Vt){console.error("Failed to reject:",Vt);const Es=((ws=(We=Vt==null?void 0:Vt.response)==null?void 0:We.data)==null?void 0:ws.message)||(Vt==null?void 0:Vt.message)||"Failed to reject request. Please try again.";Q.error(Es)}},children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),K.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",nn(K.approvedAt)]})]})]})},Be)})})]})]}),e.jsx(J4,{isOpen:o,onClose:()=>c(!1),onSubmit:Hs,dealerName:tr,dealerGSTIN:Sr,activityName:sr,defaultGstRate:(ir=t==null?void 0:t.claimDetails)==null?void 0:ir.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),previousProposalData:(En=L==null?void 0:L.find(K=>K.snapshotType==="PROPOSAL"))==null?void 0:En.snapshotData,documentPolicy:i,taxationType:(_n=t==null?void 0:t.claimDetails)==null?void 0:_n.taxationType,totalBlockedAmount:((t==null?void 0:t.internalOrders)||[]).reduce((K,Be)=>K+Number(Be.ioBlockedAmount||Be.io_blocked_amount||Be.blockedAmount||0),0)}),e.jsx(t6,{isOpen:d,onClose:()=>{m(!1)},onApprove:ls,onReject:Nt,onRequestRevision:gt,proposalData:wr,dealerName:tr,activityName:sr,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const K=(L==null?void 0:L.filter(Be=>Be.snapshotType==="PROPOSAL"))||[];return K.length>1?K[1].snapshotData:null})(),taxationType:(Mn=t==null?void 0:t.claimDetails)==null?void 0:Mn.taxationType}),e.jsx(Z4,{isOpen:p,onClose:()=>x(!1),onApprove:Ss,onReject:Qa,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((qd=t==null?void 0:t.internalOrder)==null?void 0:qd.ioNumber)||((em=t==null?void 0:t.internalOrder)==null?void 0:em.io_number)||((tm=t==null?void 0:t.internal_order)==null?void 0:tm.ioNumber)||((sm=t==null?void 0:t.internal_order)==null?void 0:sm.io_number)||void 0,preFilledBlockedAmount:((am=t==null?void 0:t.internalOrder)==null?void 0:am.ioBlockedAmount)||((rm=t==null?void 0:t.internalOrder)==null?void 0:rm.io_blocked_amount)||((nm=t==null?void 0:t.internal_order)==null?void 0:nm.ioBlockedAmount)||((im=t==null?void 0:t.internal_order)==null?void 0:im.io_blocked_amount)||void 0,preFilledRemainingBalance:((lm=t==null?void 0:t.internalOrder)==null?void 0:lm.ioRemainingBalance)||((om=t==null?void 0:t.internalOrder)==null?void 0:om.io_remaining_balance)||((cm=t==null?void 0:t.internal_order)==null?void 0:cm.ioRemainingBalance)||((dm=t==null?void 0:t.internal_order)==null?void 0:dm.io_remaining_balance)||void 0,taxationType:(mm=t==null?void 0:t.claimDetails)==null?void 0:mm.taxationType}),e.jsx(X4,{isOpen:h,onClose:()=>g(!1),onSubmit:as,dealerName:tr,dealerGSTIN:Sr,activityName:sr,defaultGstRate:(um=t==null?void 0:t.claimDetails)==null?void 0:um.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i,taxationType:(xm=t==null?void 0:t.claimDetails)==null?void 0:xm.taxationType}),e.jsx(q4,{isOpen:f,onClose:()=>b(!1),onPush:Ya,completionDetails:{activityCompletionDate:((hm=t==null?void 0:t.completionDetails)==null?void 0:hm.activityCompletionDate)||((pm=t==null?void 0:t.completionDetails)==null?void 0:pm.activity_completion_date),numberOfParticipants:((gm=t==null?void 0:t.completionDetails)==null?void 0:gm.numberOfParticipants)||((fm=t==null?void 0:t.completionDetails)==null?void 0:fm.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((bm=t==null?void 0:t.completionDetails)==null?void 0:bm.closedExpenses)||((jm=t==null?void 0:t.completionDetails)==null?void 0:jm.closed_expenses),totalClosedExpenses:((ym=t==null?void 0:t.budgetTracking)==null?void 0:ym.closedExpenses)||((vm=t==null?void 0:t.budgetTracking)==null?void 0:vm.closed_expenses)||((Nm=t==null?void 0:t.completionDetails)==null?void 0:Nm.totalClosedExpenses)||((wm=t==null?void 0:t.completionDetails)==null?void 0:wm.total_closed_expenses),completionDescription:((Cm=t==null?void 0:t.completionDetails)==null?void 0:Cm.completionDescription)||((Sm=t==null?void 0:t.completionDetails)==null?void 0:Sm.completion_description)},ioDetails:{ioNumber:((Am=t==null?void 0:t.internalOrder)==null?void 0:Am.ioNumber)||((Tm=t==null?void 0:t.internalOrder)==null?void 0:Tm.io_number)||((km=t==null?void 0:t.internal_order)==null?void 0:km.ioNumber)||((Dm=t==null?void 0:t.internal_order)==null?void 0:Dm.io_number),blockedAmount:((Rm=t==null?void 0:t.internalOrder)==null?void 0:Rm.ioBlockedAmount)||((Im=t==null?void 0:t.internalOrder)==null?void 0:Im.io_blocked_amount)||((Fm=t==null?void 0:t.internal_order)==null?void 0:Fm.ioBlockedAmount)||((Pm=t==null?void 0:t.internal_order)==null?void 0:Pm.io_blocked_amount),availableBalance:((Em=t==null?void 0:t.internalOrder)==null?void 0:Em.ioAvailableBalance)||((_m=t==null?void 0:t.internalOrder)==null?void 0:_m.io_available_balance)||((Mm=t==null?void 0:t.internal_order)==null?void 0:Mm.ioAvailableBalance)||((Lm=t==null?void 0:t.internal_order)==null?void 0:Lm.io_available_balance),remainingBalance:((Om=t==null?void 0:t.internalOrder)==null?void 0:Om.ioRemainingBalance)||(($m=t==null?void 0:t.internalOrder)==null?void 0:$m.io_remaining_balance)||((Um=t==null?void 0:t.internal_order)==null?void 0:Um.ioRemainingBalance)||((Bm=t==null?void 0:t.internal_order)==null?void 0:Bm.io_remaining_balance)},completionDocuments:Ot,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:(zm=t==null?void 0:t.claimDetails)==null?void 0:zm.taxationType,onReQuotation:Pt}),e.jsx(d4,{isOpen:y,onClose:()=>j(!1),taxationType:(Vm=t==null?void 0:t.claimDetails)==null?void 0:Vm.taxationType,onDownload:async()=>{Q.info("Download functionality will be implemented")},onSendToDealer:async()=>{var K,Be;try{const De=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!De){Q.error("Request ID not found");return}await c6(De),Q.success("Credit note sent to dealer successfully. Step 8 has been approved."),n&&n()}catch(De){console.error("Failed to send credit note to dealer:",De);const pe=((Be=(K=De==null?void 0:De.response)==null?void 0:K.data)==null?void 0:Be.message)||(De==null?void 0:De.message)||"Failed to send credit note to dealer";Q.error(pe)}},creditNoteData:{creditNoteNumber:((Wm=t==null?void 0:t.creditNote)==null?void 0:Wm.creditNoteNumber)||((Hm=t==null?void 0:t.creditNote)==null?void 0:Hm.credit_note_number)||((Ym=(Gm=t==null?void 0:t.claimDetails)==null?void 0:Gm.creditNote)==null?void 0:Ym.creditNoteNumber)||((Qm=t==null?void 0:t.claimDetails)==null?void 0:Qm.creditNoteNumber)||((Km=t==null?void 0:t.claimDetails)==null?void 0:Km.credit_note_number),creditNoteDate:((Xm=t==null?void 0:t.creditNote)==null?void 0:Xm.creditNoteDate)||((Jm=t==null?void 0:t.creditNote)==null?void 0:Jm.credit_note_date)||((qm=(Zm=t==null?void 0:t.claimDetails)==null?void 0:Zm.creditNote)==null?void 0:qm.creditNoteDate)||((eu=t==null?void 0:t.claimDetails)==null?void 0:eu.creditNoteDate)||((tu=t==null?void 0:t.claimDetails)==null?void 0:tu.credit_note_date),creditNoteAmount:(su=t==null?void 0:t.creditNote)!=null&&su.creditNoteAmount?Number((au=t==null?void 0:t.creditNote)==null?void 0:au.creditNoteAmount):(ru=t==null?void 0:t.creditNote)!=null&&ru.credit_note_amount?Number((nu=t==null?void 0:t.creditNote)==null?void 0:nu.credit_note_amount):(lu=(iu=t==null?void 0:t.claimDetails)==null?void 0:iu.creditNote)!=null&&lu.creditNoteAmount?Number((cu=(ou=t==null?void 0:t.claimDetails)==null?void 0:ou.creditNote)==null?void 0:cu.creditNoteAmount):(du=t==null?void 0:t.claimDetails)!=null&&du.creditNoteAmount?Number((mu=t==null?void 0:t.claimDetails)==null?void 0:mu.creditNoteAmount):(uu=t==null?void 0:t.claimDetails)!=null&&uu.credit_note_amount?Number((xu=t==null?void 0:t.claimDetails)==null?void 0:xu.credit_note_amount):void 0,transactionNo:((hu=t==null?void 0:t.creditNote)==null?void 0:hu.transactionNo)||((pu=t==null?void 0:t.creditNote)==null?void 0:pu.transaction_no),tdsAmount:((gu=t==null?void 0:t.creditNote)==null?void 0:gu.tdsAmount)||((fu=t==null?void 0:t.creditNote)==null?void 0:fu.tds_amount),creditAmount:((bu=t==null?void 0:t.creditNote)==null?void 0:bu.creditAmount)||((ju=t==null?void 0:t.creditNote)==null?void 0:ju.credit_amount),items:((yu=t==null?void 0:t.creditNote)==null?void 0:yu.items)||[],status:((vu=t==null?void 0:t.creditNote)==null?void 0:vu.status)||((wu=(Nu=t==null?void 0:t.claimDetails)==null?void 0:Nu.creditNote)==null?void 0:wu.status)||((Cu=t==null?void 0:t.creditNote)!=null&&Cu.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((Su=t==null?void 0:t.claimDetails)==null?void 0:Su.dealerName)||((Au=t==null?void 0:t.claimDetails)==null?void 0:Au.dealer_name),dealerCode:((Tu=t==null?void 0:t.claimDetails)==null?void 0:Tu.dealerCode)||((ku=t==null?void 0:t.claimDetails)==null?void 0:ku.dealer_code),dealerEmail:((Du=t==null?void 0:t.claimDetails)==null?void 0:Du.dealerEmail)||((Ru=t==null?void 0:t.claimDetails)==null?void 0:Ru.dealer_email)},activityName:((Iu=t==null?void 0:t.claimDetails)==null?void 0:Iu.activityName)||((Fu=t==null?void 0:t.claimDetails)==null?void 0:Fu.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(e6,{isOpen:v,onClose:()=>{N(!1),A(null)},stepNumber:(T==null?void 0:T.stepNumber)||4,stepName:(T==null?void 0:T.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"}),F&&e.jsx(c4,{isOpen:k,onClose:()=>{D(!1),w(null)},onApprove:async K=>{var Be,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const pe=t.id||t.requestId,Ae=F.levelId;if(!Ae){Q.error("Approval level not found");return}await Qn(pe,Ae,K),Q.success("Request approved successfully"),J(),D(!1),w(null)}catch(pe){console.error("Failed to approve:",pe);const Ae=((De=(Be=pe==null?void 0:pe.response)==null?void 0:Be.data)==null?void 0:De.message)||(pe==null?void 0:pe.message)||"Failed to approve request. Please try again.";throw Q.error(Ae),pe}},onReject:async K=>{var Be,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const pe=t.id||t.requestId,Ae=F.levelId;if(!Ae){Q.error("Approval level not found");return}await _r(pe,Ae,"Request rejected",K),Q.success("Request rejected successfully"),J(),D(!1),w(null)}catch(pe){console.error("Failed to reject:",pe);const Ae=((De=(Be=pe==null?void 0:pe.response)==null?void 0:Be.data)==null?void 0:De.message)||(pe==null?void 0:pe.message)||"Failed to reject request. Please try again.";throw Q.error(Ae),pe}},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:F.levelName,approverName:F.approverName}),L&&L.length>0&&e.jsxs(Z,{className:"mt-6 border-amber-100 bg-amber-50/30",children:[e.jsxs(de,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ue,{className:"text-sm font-bold flex items-center gap-2 text-amber-900",children:[e.jsx(zt,{className:"w-4 h-4"}),"Revision History & Audit Trail"]}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>I(!W),className:"text-amber-700 hover:text-amber-800 hover:bg-amber-100",children:W?"Hide History":"View History"})]}),e.jsx(Te,{className:"text-xs text-amber-700",children:"Records of all revisions and actions taken on this request"})]}),W&&e.jsx(ee,{children:e.jsx("div",{className:"space-y-4",children:L.map((K,Be)=>{var De,pe,Ae,be;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 ",K.version]}),K.snapshotType&&e.jsx(oe,{className:"bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0",children:K.snapshotType}),K.levelNumber&&e.jsxs(oe,{className:"bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0",children:["Step ",K.levelNumber]})]}),e.jsx("span",{className:"text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full",children:nn(K.createdAt)})]}),e.jsx("p",{className:"text-xs font-medium text-gray-800",children:K.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:((pe=(De=K.changer)==null?void 0:De.displayName)==null?void 0:pe.charAt(0))||"U"})}),e.jsxs("span",{className:"text-xs text-gray-500",children:["By ",((Ae=K.changer)==null?void 0:Ae.displayName)||((be=K.changer)==null?void 0:be.email)||"Unknown User"]})]}),K.snapshotType==="PROPOSAL"&&K.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:"}),K.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(O,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-small flex items-center gap-1",onClick:()=>C({data:K.snapshotData,type:"PROPOSAL",title:`Historical Proposal (Version ${K.version})`}),children:["View Details",e.jsx(wt,{className:"w-2 h-2"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Budget: ₹",Number(K.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),K.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",K.snapshotData.comments.substring(0,80),K.snapshotData.comments.length>80?"...":""]})]}),K.snapshotType==="COMPLETION"&&K.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:"}),K.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(O,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-medium flex items-center gap-1",onClick:()=>C({data:K.snapshotData,type:"COMPLETION",title:`Historical Completion (Version ${K.version})`}),children:["View Details",e.jsx(wt,{className:"w-3 h-3"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Total Expenses: ₹",Number(K.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),K.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",K.snapshotData.comments.substring(0,80),K.snapshotData.comments.length>80?"...":""]})]}),K.snapshotType==="INTERNAL_ORDER"&&K.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: ",K.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-gray-600",children:["Blocked: ₹",Number(K.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),K.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-gray-600",children:["SAP Doc: ",K.snapshotData.sapDocumentNumber]})]}),K.snapshotType==="APPROVE"&&K.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:[K.snapshotData.action==="APPROVE"?"Approval":"Rejection",":"]}),e.jsxs("p",{className:"text-gray-600",children:["By: ",K.snapshotData.approverName||K.snapshotData.approverEmail||"Unknown"]}),K.snapshotData.levelName&&e.jsxs("p",{className:"text-gray-600",children:["Level: ",K.snapshotData.levelName]}),K.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",K.snapshotData.comments.substring(0,80),K.snapshotData.comments.length>80?"...":""]}),K.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-red-600 mt-1",children:["Rejection Reason: ",K.snapshotData.rejectionReason.substring(0,80),K.snapshotData.rejectionReason.length>80?"...":""]})]}),K.snapshotType==="WORKFLOW"&&K.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: ",K.snapshotData.status||"N/A"]}),K.snapshotData.currentLevel&&e.jsxs("p",{className:"text-gray-600",children:["Current Level: ",K.snapshotData.currentLevel]})]})]})]},K.historyId||Be)})})})]}),e.jsx(s6,{isOpen:!!R,onClose:()=>C(null),snapshot:R==null?void 0:R.data,type:(R==null?void 0:R.type)||"PROPOSAL",title:R==null?void 0:R.title}),P&&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:Cr}),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(Et,{className:"w-5 h-5 text-amber-600"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Invoice Preview"}),e.jsx(oe,{className:"bg-amber-100 text-amber-800 text-xs",children:t.requestNumber})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[H&&e.jsxs(O,{variant:"outline",size:"sm",onClick:sn,className:"gap-1.5 text-xs",children:[e.jsx(kt,{className:"w-3.5 h-3.5"}),"Download"]}),e.jsx(O,{variant:"ghost",size:"icon",onClick:Cr,className:"h-8 w-8 hover:bg-gray-200",children:e.jsx(vt,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:U?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3",children:[e.jsx(ze,{className:"w-8 h-8 text-amber-600 animate-spin"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading invoice..."})]}):H?e.jsx("iframe",{src:H,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 f6({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=u.useMemo(()=>{const W=(l==null?void 0:l.costBreakup)||(o==null?void 0:o.costBreakup)||[],I=Array.isArray(W)?W:typeof W=="string"?JSON.parse(W):[];return!Array.isArray(I)||I.length===0?Number((o==null?void 0:o.totalProposedTaxableAmount)||(l==null?void 0:l.totalEstimatedBudget)||(l==null?void 0:l.total_estimated_budget)||0):I.reduce(($,M)=>{const R=typeof M=="object"&&M.amount||0,C=typeof M=="object"&&M.quantity||1;return $+Number(R)*Number(C)},0)},[l==null?void 0:l.costBreakup,o==null?void 0:o.costBreakup,o==null?void 0:o.totalProposedTaxableAmount,l==null?void 0:l.totalEstimatedBudget]),m=(s==null?void 0:s.budgetTracking)||(t==null?void 0:t.budgetTracking)||{},p=(m==null?void 0:m.budgetStatus)||(m==null?void 0:m.budget_status)||"",x=(s==null?void 0:s.internalOrders)||(s==null?void 0:s.internal_orders)||(t==null?void 0:t.internalOrders)||[],h=u.useMemo(()=>x.reduce((W,I)=>W+Number(I.ioBlockedAmount||I.io_blocked_amount||0),0),[x]),g=p==="PROPOSED"&&x.length>0&&d-h>.01,[f,b]=u.useState(""),[y,j]=u.useState(!1),[v,N]=u.useState(null),[T,A]=u.useState(""),[k,D]=u.useState([]),[F,w]=u.useState(!1);u.useEffect(()=>{if(x.length>0){const W=x.map(I=>{const $=I.organizer||null,M=($==null?void 0:$.displayName)||($==null?void 0:$.display_name)||($==null?void 0:$.name)||($!=null&&$.firstName&&($!=null&&$.lastName)?`${$.firstName} ${$.lastName}`.trim():null)||($==null?void 0:$.email)||"Unknown User";return{ioNumber:I.ioNumber||I.io_number,blockedAmount:Number(I.ioBlockedAmount||I.io_blocked_amount||0),availableBalance:Number(I.ioAvailableBalance||I.io_available_balance||0),remainingBalance:Number(I.ioRemainingBalance||I.io_remaining_balance||0),blockedDate:I.organizedAt||I.organized_at||new Date().toISOString(),blockedBy:M,sapDocumentNumber:I.sapDocumentNumber||I.sap_document_number||"",status:I.status==="BLOCKED"?"blocked":I.status==="RELEASED"?"released":I.status==="PENDING"?"pending":"blocked"}});D(W),!g&&W.length>0&&b(W[W.length-1].ioNumber)}},[s,t,g,x]);const L=async()=>{var W,I;if(!f.trim()){Q.error("Please enter an IO number");return}if(!i){Q.error("Request ID not found");return}j(!0);try{const $=await l6(i,f.trim());if($.isValid&&$.availableBalance>0){N($.availableBalance);const M=k.reduce((C,H)=>C+H.blockedAmount,0),R=Math.max(0,d-M);R>0?A(String(R.toFixed(2))):d>0&&M===0?A(String(d.toFixed(2))):A(String($.availableBalance.toFixed(2))),Q.success(`IO fetched from SAP. Available balance: ₹${$.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)}else Q.error("Invalid IO number or no available balance found"),N(null),A("")}catch($){console.error("Failed to fetch IO budget:",$);const M=((I=(W=$==null?void 0:$.response)==null?void 0:W.data)==null?void 0:I.message)||($==null?void 0:$.message)||"Failed to validate IO number or fetch budget from SAP";Q.error(M),N(null)}finally{j(!1)}},_=async()=>{var R,C;if(!f.trim()||v===null){Q.error("Please fetch IO amount first");return}if(!i){Q.error("Request ID not found");return}const W=parseFloat(T);if(!T||isNaN(W)||W<=0){Q.error("Please enter a valid amount to block");return}const I=parseFloat(W.toFixed(2));if(I>v){Q.error("Amount to block exceeds available IO budget");return}const M=k.reduce((H,z)=>H+z.blockedAmount,0)+I;if(d>0){const H=parseFloat(d.toFixed(2)),z=parseFloat(M.toFixed(2));if(Math.abs(z-H)>.01){Q.error(`Total blocked amount (₹${z.toLocaleString("en-IN")}) must be exactly equal to the estimated budget (₹${H.toLocaleString("en-IN")})`);return}}w(!0);try{const H=parseFloat(v.toFixed(2)),z=parseFloat((H-I).toFixed(2)),P={ioNumber:f.trim(),ioAvailableBalance:H,ioBlockedAmount:I,ioRemainingBalance:z};await rb(i,P);const S=await r6(i),U=(S==null?void 0:S.internalOrder)||(S==null?void 0:S.internal_order);if(U){const Y=Number(U.ioBlockedAmount||U.io_blocked_amount||I),B=Number(U.ioRemainingBalance||U.io_remaining_balance||0),E=v-Y;Math.abs(Y-I)>.01&&console.warn("[IOTab] ⚠️ Amount mismatch! Sent:",I,"Saved:",Y),Math.abs(B-E)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:v,blockedAmount:Y,expectedRemaining:E,backendRemaining:B,difference:B-E});const V=n,G=(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",J={ioNumber:U.ioNumber||U.io_number||f,blockedAmount:Y,availableBalance:v,remainingBalance:B,blockedDate:U.organizedAt||U.organized_at||new Date().toISOString(),blockedBy:G,sapDocumentNumber:U.sapDocumentNumber||U.sap_document_number||"",status:"blocked"};D(q=>[...q,J]),A(""),N(null),Q.success("IO budget blocked successfully in SAP"),a==null||a()}else Q.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(H){console.error("Failed to block IO budget:",H);const z=((C=(R=H==null?void 0:H.response)==null?void 0:R.data)==null?void 0:C.message)||(H==null?void 0:H.message)||"Failed to block IO budget in SAP";Q.error(z)}finally{w(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Pa,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(Te,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_e,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:f,onChange:W=>b(W.target.value),disabled:y||k.length>0&&!g||r,className:"flex-1"}),e.jsxs(O,{onClick:L,disabled:!f.trim()||y||k.length>0&&!g||r,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),y?"Fetching...":"Fetch Amount"]})]})]}),!v&&k.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&&(k.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(Ve,{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(re,{htmlFor:"blockAmount",children:"Amount to Block *"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",children:"₹"}),e.jsx(_e,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:T,onChange:W=>{const I=W.target.value;if(parseFloat(I)<0){Q.error("Amount cannot be negative");return}A(I)},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(O,{onClick:_,disabled:F||!T||parseFloat(T)<=0||parseFloat(T)>v||d>0&&Math.abs(k.reduce((W,I)=>W+I.blockedAmount,0)+parseFloat(T)-d)>.01||r,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(ts,{className:"w-4 h-4 mr-2"}),F?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Ve,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(Te,{children:"Details of IO blocked in SAP system"})]}),e.jsx(ee,{children:k.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(Ze,{className:"w-6 h-6 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-amber-900",children:"Additional Budget Blocking Required"}),e.jsxs("p",{className:"text-sm text-amber-700 mt-1",children:["Actual expenses exceed the previously blocked amount. Please block an additional ₹",(d-k.reduce((W,I)=>W+I.blockedAmount,0)).toLocaleString("en-IN",{minimumFractionDigits:2}),"."]})]})]})}),k.slice().reverse().map((W,I)=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:`p-3 flex justify-between items-center ${I===0?"bg-green-50":"bg-gray-50"}`,children:[e.jsxs("span",{className:"font-semibold text-sm",children:["IO: ",W.ioNumber]}),e.jsx(oe,{className:W.status==="blocked"?"bg-green-100 text-green-800":W.status==="pending"?"bg-amber-100 text-amber-800":"bg-blue-100 text-blue-800",children:W.status==="blocked"?"Blocked":W.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:["₹",W.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:W.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:W.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(W.blockedDate).toLocaleString()})]})]})]},I)),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:["₹",k.reduce((W,I)=>W+I.blockedAmount,0).toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Pa,{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 b6(t){var s,a,r;try{const n=await Se.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 j6(t){var s;try{const a=await Se.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 qs=[{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 y6({formData:t,updateFormData:s,onValidationError:a,currentUserEmail:r="",currentUserId:n="",currentUserName:i="",onValidate:l,maxApprovalLevels:o,onPolicyViolation:c}){const{userSearchResults:d,userSearchLoading:m,searchUsersForIndex:p,clearSearchForIndex:x}=T0(),[h,g]=u.useState(!1),[f,b]=u.useState(""),[y,j]=u.useState(24),[v,N]=u.useState("hours"),[T,A]=u.useState(3),[k,D]=u.useState([]),[F,w]=u.useState(!1),[L,_]=u.useState(null),W=u.useRef(null),I=()=>{const E=t.approvers||[],V=[];return qs.forEach(G=>{if(G.isAuto||G.approverType==="dealer"||G.approverType==="initiator")return;const J=E.find(q=>q.level===G.level);(!J||!J.email||!J.userId||!J.tat)&&V.push(`${G.name}`)}),{isValid:V.length===0,missingSteps:V}};u.useEffect(()=>{if(l){const E=I();l(E.isValid)}},[t.approvers]),u.useEffect(()=>{const E=t.approvers||[];if(E.length>0){const V=[],G=E.filter(q=>q.isAdditional);qs.forEach(q=>{const se=E.find(ne=>ne.originalStepLevel===q.level||!ne.originalStepLevel&&!ne.isAdditional&&ne.level===q.level);if(se)V.push(se);else if(q.isAuto){const ne=q.level===8?"finance@royalenfield.com":"system@royalenfield.com",te=q.level===8?"System/Finance":"System";V.push({email:ne,name:te,level:q.level,tat:q.defaultTat,tatType:"hours",originalStepLevel:q.level})}else 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})}),G.forEach(q=>{V.push(q)}),V.sort((q,se)=>q.level-se.level),JSON.stringify(E.map(q=>({level:q.level,originalStepLevel:q.originalStepLevel})))!==JSON.stringify(V.map(q=>({level:q.level,originalStepLevel:q.originalStepLevel})))&&s("approvers",V)}else{const V=[];qs.forEach(G=>{G.isAuto||(G.approverType==="dealer"?V.push({email:t.dealerEmail||"",name:t.dealerName||"",level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level}):G.approverType==="initiator"?V.push({email:r||"",name:i||r||"User",userId:n,level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level}):V.push({email:"",name:"",level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level}))}),s("approvers",V)}},[t.dealerEmail,t.dealerName,r,n,i]);const $=(E,V)=>{const G=[...t.approvers||[]],J=G.findIndex(q=>q.originalStepLevel===E||!q.originalStepLevel&&q.level===E&&!q.isAdditional);if(J===-1){const q=qs.find(se=>se.level===E);G.push({email:V,name:"",level:E,tat:(q==null?void 0:q.defaultTat)||48,tatType:"hours",originalStepLevel:E})}else{const q=G[J];if(q){const se=q.email;G[J]={...q,email:V,name:V!==se?"":q.name,userId:V!==se?void 0:q.userId}}}if(s("approvers",G),!V||!V.startsWith("@")||V.length<2){x(E-1);return}p(E-1,V,10)},M=async(E,V)=>{var G,J;try{const q=qs.find(fe=>fe.level===E);if(q&&!q.isAuto&&q.approverType!=="initiator"&&((G=V.email)==null?void 0:G.toLowerCase())===(r==null?void 0:r.toLowerCase())){Q.error(`You cannot assign yourself as ${q.name} approver.`),a&&a({type:"self-assign",email:V.email,message:`You cannot assign yourself as ${q.name} approver.`});return}if((t.approvers||[]).some(fe=>{var ke,le;return fe.level!==E&&(fe.userId===V.userId||((ke=fe.email)==null?void 0:ke.toLowerCase())===((le=V.email)==null?void 0:le.toLowerCase()))})){Q.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 te=await wa({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}),ge=[...t.approvers||[]],we=ge.findIndex(fe=>fe.originalStepLevel===E||!fe.originalStepLevel&&fe.level===E&&!fe.isAdditional);if(we===-1){const fe=qs.find(ke=>ke.level===E);ge.push({email:V.email,name:V.displayName||[V.firstName,V.lastName].filter(Boolean).join(" "),userId:te.userId,level:E,tat:(fe==null?void 0:fe.defaultTat)||48,tatType:"hours",originalStepLevel:E})}else{const fe=ge[we];fe&&(ge[we]={...fe,email:V.email,name:V.displayName||[V.firstName,V.lastName].filter(Boolean).join(" "),userId:te.userId,originalStepLevel:fe.originalStepLevel||E})}s("approvers",ge),x(E-1),Q.success(`Approver for ${(J=qs.find(fe=>fe.level===E))==null?void 0:J.name} selected successfully.`)}catch(q){console.error("Failed to ensure user exists:",q),Q.error("Failed to validate user. Please try again."),a&&a({type:"error",email:V.email,message:"Failed to validate user. Please try again."})}},R=(E,V)=>{const G=[...t.approvers||[]],J=G.findIndex(q=>q.originalStepLevel===E||!q.originalStepLevel&&q.level===E&&!q.isAdditional);if(J!==-1){const q=G[J];q&&(G[J]={...q,tat:V},s("approvers",G))}},C=(E,V)=>{const G=[...t.approvers||[]],J=G.findIndex(q=>q.originalStepLevel===E||!q.originalStepLevel&&q.level===E&&!q.isAdditional);if(J!==-1){const q=G[J];q&&(G[J]={...q,tatType:V,tat:""},s("approvers",G))}},H=E=>{if(b(E),L&&L.email.toLowerCase()!==E.toLowerCase()&&_(null),W.current&&clearTimeout(W.current),!E||!E.startsWith("@")||E.length<2){D([]),w(!1);return}w(!0),W.current=setTimeout(async()=>{var V;try{const G=E.slice(1),q=((V=(await Sa(G,10)).data)==null?void 0:V.data)||[];D(q)}catch(G){console.error("Search failed:",G),D([])}finally{w(!1)}},300)},z=async E=>{try{await wa({userId:E.userId,email:E.email,displayName:E.displayName,firstName:E.firstName,lastName:E.lastName,department:E.department,phone:E.phone,mobilePhone:E.mobilePhone,designation:E.designation,jobTitle:E.jobTitle,manager:E.manager,employeeId:E.employeeId,employeeNumber:E.employeeNumber,secondEmail:E.secondEmail,location:E.location}),b(E.email),_(E),D([]),w(!1)}catch(V){console.error("Failed to ensure user exists:",V),Q.error("Failed to verify user. Please try again.")}},P=async()=>{var ke,le;const E=f.trim().toLowerCase();if(!E){Q.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)){Q.error("Please enter a valid email address");return}const G=typeof y=="string"?Number(y):y;if(!G||G<=0||isNaN(G)){Q.error("Please enter valid TAT (minimum 1)");return}const J=v==="days"?30:720;if((v==="days"?G*24:G)>720){Q.error(`TAT cannot exceed ${J} ${v==="days"?"days":"hours"}`);return}const se=qs.find(Ne=>Ne.name==="Requestor Claim Approval");if(se&&T>=se.level){Q.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if(E===(r==null?void 0:r.toLowerCase())){Q.error("You cannot add yourself as an additional approver.");return}const ne=t.approvers||[];if(ne.some(Ne=>{var ae;return Ne.userId&&(L==null?void 0:L.userId)&&Ne.userId===L.userId||((ae=Ne.email)==null?void 0:ae.toLowerCase())===E})){Q.error("This user is already assigned as an approver.");return}const ge=ne.find(Ne=>Ne.originalStepLevel===T||!Ne.originalStepLevel&&!Ne.isAdditional&&Ne.level===T),fe=(ge?ge.level:T)+1;if(o){const ae=new Set(ne.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):Q.error(((ke=he[0])==null?void 0:ke.message)||"Maximum approval levels exceeded");return}}if(!L||L.email.toLowerCase()!==E)try{const ae=((le=(await Sa(E,1)).data)==null?void 0:le.data)||[];if(ae.length===0){Q.error("User not found in organization directory. Please use @ to search for users.");return}const he=ae[0];await wa({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 ie={email:he.email,name:he.displayName||[he.firstName,he.lastName].filter(Boolean).join(" "),userId:he.userId,level:fe,tat:typeof y=="string"?Number(y):y,tatType:v,isAdditional:!0,insertAfterLevel:T,stepName:`Additional Approver - ${he.displayName||he.email}`},je=ne.map(Fe=>Fe.level>=fe?{...Fe,level:Fe.level+1}:Fe);je.push(ie),je.sort((Fe,Ue)=>Fe.level-Ue.level),s("approvers",je),Q.success("Additional approver added and subsequent steps shifted")}catch(Ne){console.error("Failed to validate approver:",Ne),Q.error("Failed to validate user. Please try again.");return}else{const Ne={email:L.email,name:L.displayName||[L.firstName,L.lastName].filter(Boolean).join(" "),userId:L.userId,level:fe,tat:y,tatType:v,isAdditional:!0,insertAfterLevel:T,stepName:`Additional Approver - ${L.displayName||L.email}`},ae=ne.map(he=>he.level>=fe?{...he,level:he.level+1}:he);ae.push(Ne),ae.sort((he,ie)=>he.level-ie.level),s("approvers",ae),Q.success("Additional approver added and subsequent steps shifted")}b(""),j(24),N("hours"),A(3),_(null),D([]),g(!1)},S=E=>{const V=[...t.approvers||[]];if(!V.find(se=>se.level===E))return;const q=V.filter(se=>se.level!==E).map(se=>se.level>E&&!se.isAdditional?{...se,level:se.level-1}:se);q.sort((se,ne)=>se.level-ne.level),s("approvers",q),Q.success("Additional approver removed and subsequent steps shifted back")},U=()=>[...t.approvers||[]].sort((V,G)=>V.level-G.level),Y=t.approvers||[],B=U();return e.jsxs(Gt.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(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(Jr,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsxs(Te,{className:"text-blue-700",children:['Some steps are pre-filled (Dealer, Initiator, System). You need to assign approvers for "Department Lead Approval" only. Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.',o&&e.jsxs("span",{className:"block mt-2 text-gray-600",children:["Max: ",o," level",o!==1?"s":"",(()=>{const E=t.approvers||[],G=new Set(E.map(J=>J.level)).size;return G>0?e.jsxs("span",{children:[" (",G,"/",o,")"]}):null})()]})]})]})}),e.jsxs(Z,{className:"border-2",children:[e.jsxs(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(bs,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx(Te,{children:'Define approvers and TAT for each step. Some steps are pre-filled (Dealer, Initiator, System). Only "Department Lead Approval" requires manual assignment.'})]}),e.jsxs(ee,{className:"space-y-2 pt-4",children:[e.jsxs("div",{className:"mb-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2",children:[o&&e.jsxs("p",{className:"text-sm text-gray-600",children:["Max: ",o," level",o!==1?"s":"",(()=>{const E=t.approvers||[],G=new Set(E.map(J=>J.level)).size;return G>0?e.jsxs("span",{children:[" (",G,"/",o,")"]}):null})()]}),e.jsxs(O,{type:"button",variant:"outline",onClick:()=>g(!0),className:"flex items-center gap-2",children:[e.jsx(is,{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(Wt,{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(oe,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-xs text-blue-700",children:"Creates and submits the request"})]})]})}),(()=>{const E=B.filter(G=>G.isAdditional&&G.insertAfterLevel===0);let V=E.length;return qs.filter(G=>!G.isAuto).map((G,J,q)=>{const se=Y.find(ke=>ke.originalStepLevel===G.level||!ke.originalStepLevel&&ke.level===G.level&&!ke.isAdditional)||{email:"",name:"",level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level},ne=J===q.length-1,te=G.isAuto||G.approverType==="dealer"||G.approverType==="initiator",ge=!G.isAuto,we=B.filter(ke=>ke.isAdditional&&ke.insertAfterLevel===G.level).sort((ke,le)=>ke.level-le.level),fe=V+1;return V++,V+=we.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"})}),J===0&&E.map((ke,le)=>{const Ne=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:Ne})}),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(oe,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",onClick:()=>S(ke.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(vt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:ke.name||ke.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",ke.email]}),e.jsxs("div",{children:["TAT: ",ke.tat," ",ke.tatType]})]})]})]})})]},`additional-${ke.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${se.email&&se.userId?"border-green-200 bg-green-50":te?"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 ${se.email&&se.userId?"bg-green-600":te?"bg-blue-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold text-sm",children:fe})}),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:G.name}),ne&&e.jsx(oe,{variant:"destructive",className:"text-xs",children:"FINAL"}),te&&e.jsx(oe,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:G.description}),ge&&(()=>{var Ne,ae;const ke=!!(se.email&&se.userId),le=!se.email&&!te;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs(re,{htmlFor:`approver-${G.level}`,className:`text-xs font-bold ${le?"text-blue-900":ke?"text-green-900":"text-gray-900"}`,children:["Approver Email ",!te&&"*",le&&e.jsx("span",{className:"ml-2 text-[10px] font-semibold italic text-blue-600",children:"(Required)"})]}),ke&&e.jsxs(oe,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Ve,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(_e,{id:`approver-${G.level}`,type:"text",placeholder:te?se.email:"@username or email...",value:se.email||"",onChange:he=>{const ie=he.target.value;te||$(G.level,ie)},disabled:te||G.isAuto,className:`h-9 border-2 transition-all mt-1 w-full text-sm ${te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":ke?"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"}`}),!te&&!G.isAuto&&(m[G.level-1]||(((Ne=d[G.level-1])==null?void 0:Ne.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[G.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[G.level-1])==null?void 0:ae.map(he=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>M(G.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))})})]}),se.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:se.name})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:`tat-${G.level}`,className:`text-xs font-bold ${le?"text-blue-900":ke?"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(_e,{id:`tat-${G.level}`,type:"number",placeholder:se.tatType==="days"?"7":"24",min:"1",max:se.tatType==="days"?"30":"720",value:se.tat||"",onChange:he=>R(G.level,parseInt(he.target.value)||""),disabled:G.isAuto,className:`h-9 border-2 transition-all flex-1 text-sm ${te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":ke?"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:se.tatType||"hours",onValueChange:he=>C(G.level,he),disabled:G.isAuto,children:[e.jsx(Ye,{className:`w-20 h-9 border-2 transition-all text-sm ${te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed":ke?"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(Qe,{children:[e.jsx(X,{value:"hours",children:"Hours"}),e.jsx(X,{value:"days",children:"Days"})]})]})]})]})]})})()]})]})}),we.map((ke,le)=>{const Ne=fe+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:Ne})}),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:ke.stepName||"Additional Approver"}),e.jsx(oe,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),ke.email&&ke.userId&&e.jsxs(oe,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Ve,{className:"w-3 h-3 mr-1"}),"Verified"]}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",onClick:()=>S(ke.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(vt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:ke.name||ke.email||"No approver assigned"}),ke.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",ke.email]}),ke.tat&&e.jsxs("div",{children:["TAT: ",ke.tat," ",ke.tatType]})]})]})]})})]},`additional-${ke.level}`)})]},G.level)})})()]})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(de,{children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3",children:B.map(E=>{const V=E.originalStepLevel?qs.find(se=>se.level===E.originalStepLevel):qs.find(se=>se.level===E.level&&!E.isAdditional);if(V!=null&&V.isAuto)return null;const G=Number(E.tat||0),q=(E.tatType||"hours")==="days"?G*24:G;if(!G)return null;if(E.isAdditional){const se=qs.find(ne=>ne.level===E.insertAfterLevel);return e.jsxs("div",{className:"flex items-center justify-between p-2 bg-purple-50 rounded border border-purple-200",children:[e.jsx("span",{className:"text-sm font-medium",children:E.stepName||`Additional Approver (after "${(se==null?void 0:se.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[q," hours"]})]},E.level)}return e.jsxs("div",{className:"flex items-center justify-between p-2 bg-gray-50 rounded",children:[e.jsx("span",{className:"text-sm font-medium",children:(V==null?void 0:V.name)||"Unknown"}),e.jsxs("span",{className:"text-sm text-gray-600",children:[q," hours"]})]},E.level)})})})]})]}),e.jsx(ht,{open:h,onOpenChange:g,children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(is,{className:"w-5 h-5 text-blue-600"}),"Add Additional Approver"]}),e.jsx(Mt,{children:'Add an additional approver between workflow steps. The approver will be inserted after the selected step. Additional approvers cannot be added after "Requestor Claim Approval".'})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(He,{value:T.toString(),onValueChange:E=>A(Number(E)),children:[e.jsx(Ye,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select step"})}),e.jsx(Qe,{children:qs.filter(E=>{if(E.isAuto)return!1;const V=qs.find(G=>G.name==="Requestor Claim Approval");return!(V&&E.level>=V.level)}).map(E=>e.jsx(X,{value:E.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bs,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:E.name})]})},E.level))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"The new approver will be inserted after the selected step."}),e.jsx("p",{className:"text-xs text-amber-600 font-medium",children:'⚠️ Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.'}),o&&e.jsxs("p",{className:"text-xs text-gray-600 mt-2",children:["Max: ",o," level",o!==1?"s":"",(()=>{const E=t.approvers||[],G=new Set(E.map(J=>J.level)).size;return G>0?e.jsxs("span",{children:[" (",G,"/",o,")"]}):null})()]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_e,{type:"number",min:"1",max:v==="days"?"30":"720",value:y,onChange:E=>{const V=E.target.value;if(V==="")j("");else{const G=Number(V);!isNaN(G)&&G>=0&&j(G)}},onBlur:E=>{const V=E.target.value;(!V||V===""||Number(V)<=0)&&j(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(He,{value:v,onValueChange:E=>N(E),children:[e.jsx(Ye,{className:"w-24 h-11 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Qe,{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(re,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fl,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(_e,{type:"text",placeholder:"@username or user@example.com",value:f,onChange:E=>H(E.target.value),className:"pl-10 h-11 border-gray-300",autoFocus:!0}),(F||k.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:F?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):k.length>0?e.jsx("ul",{className:"divide-y",children:k.map(E=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>z(E),children:e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:E.displayName||[E.firstName,E.lastName].filter(Boolean).join(" ")||E.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:E.email}),E.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:E.designation})]})})},E.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs(Dt,{children:[e.jsx(O,{type:"button",variant:"outline",onClick:()=>{g(!1),b(""),j(24),N("hours"),A(3),_(null),D([])},className:"flex-1",children:"Cancel"}),e.jsxs(O,{type:"button",onClick:P,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!f.trim()||!y,children:[e.jsx(is,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const Eo=[{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"}],_o=["Claim Details","Approver Selection","Review & Submit"];function v6({onBack:t,onSubmit:s}){const{user:a}=us(),[r,n]=u.useState(1),[i,l]=u.useState(!1),[o,c]=u.useState([]),[d,m]=u.useState(!1),[p,x]=u.useState(""),h=u.useRef(null),[g,f]=u.useState(!1),b=u.useRef(null),[y,j]=u.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[v,N]=u.useState({open:!1,violations:[]}),[T,A]=u.useState([]),[k,D]=u.useState(!0);u.useEffect(()=>{(async()=>{try{D(!0);const S=await DT();A(S)}catch(S){console.error("Failed to load activity types:",S),Q.error("Failed to load activity types. Please refresh the page.")}finally{D(!1)}})()},[]),u.useEffect(()=>{(async()=>{var S;try{const U=await pa("SYSTEM_SETTINGS"),Y=await pa("WORKFLOW_SHARING"),B=[...U,...Y],E={};B.forEach(V=>{E[V.configKey]=V.configValue}),j({maxApprovalLevels:parseInt(E.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(E.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((S=E.ALLOW_ADD_SPECTATOR)==null?void 0:S.toLowerCase())==="true",maxSpectators:parseInt(E.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(U){console.error("Failed to load system policy:",U)}})()},[]),u.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const[F,w]=u.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",dealerItemGroup:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),L=_o.length,_=P=>{if(x(P),h.current&&clearTimeout(h.current),!P||P.trim().length<2){c([]),m(!1);return}m(!0),h.current=setTimeout(async()=>{try{const S=await j6(P);if(S){const U={dealerId:S.dealer||S.dealer_code||P,dealerCode:S.dealer||S.dealer_code||P,dealerName:S["dealer name"]||S.dealer_name||"Unknown Dealer",displayName:S["dealer name"]||S.dealer_name||"Unknown Dealer",email:S["dealer email"]||"",phone:S["dealer phone"]||"",city:S["re city"]||S.city||"",state:S["re state code"]||S.state||"",isLoggedIn:!0,parentCode:S.parentcode||null,itemGroup:S["item group"]||null};c([U])}else c([])}catch(S){console.error("Error searching external dealer:",S),c([])}finally{m(!1)}},300)},W=(P,S)=>{w(U=>{const Y={...U,[P]:S};if(P==="periodStartDate")S&&Y.periodEndDate&&S>Y.periodEndDate&&(Y.periodEndDate=void 0,Q.error("End date must be on or after the start date. End date has been cleared."));else if(P==="periodEndDate"&&S&&Y.periodStartDate&&S<Y.periodStartDate)return Q.error("End date must be on or after the start date."),U;if(P==="activityType"&&Y.dealerCode){const B=T.find(E=>E.title===S);if(B)if(B.creditPostingOn){const E=B.creditPostingOn.toLowerCase(),V=(Y.dealerItemGroup||"").toLowerCase();if(V){let G=!1;if(((E==="vehicle"||E==="vehicles")&&(V==="vehicle"||V==="vehicles")||E==="spares"&&V==="spares"||E==="gma"&&V==="gma"||E==="apparel"&&V==="apparel"||E===V)&&(G=!0),!G)return Q.error("incorrect Delercode for selected service group",{description:`Activity requires ${B.creditPostingOn}, but already selected dealer is ${Y.dealerItemGroup}`,duration:6e3}),U}}else console.warn(`[ClaimWizard] Activity type "${S}" is missing creditPostingOn configuration.`)}return Y})},I=P=>{w(S=>({...S,...P}))},$=()=>{switch(r){case 1:return F.activityName&&F.activityType&&F.dealerCode&&F.dealerName&&F.activityDate&&F.location&&F.requestDescription;case 2:const S=(F.approvers||[]).find(U=>U.originalStepLevel===3||!U.originalStepLevel&&U.level===3&&!U.isAdditional);return(S==null?void 0:S.email)&&(S==null?void 0:S.userId)&&(S==null?void 0:S.tat);case 3:return!0;default:return!1}},M=()=>{if(r<L){if(!$()){if(r===2){const S=(F.approvers||[]).find(Y=>Y.originalStepLevel===3||!Y.originalStepLevel&&Y.level===3&&!Y.isAdditional),U=[];(!(S!=null&&S.email)||!(S!=null&&S.userId)||!(S!=null&&S.tat))&&U.push("Department Lead Approval"),U.length>0?Q.error(`Please add missing approvers: ${U.join(", ")}`):Q.error("Please complete all required approver selections (email, user verification, and TAT) before proceeding.")}else Q.error("Please complete all required fields before proceeding.");return}n(r+1)}},R=()=>{r>1&&n(r-1)},C=async P=>{l(!0);try{const S=await b6(P.dealerCode);if(!S.isLoggedIn){Q.error(`Dealer "${S.dealerName||S.displayName}" (${S.dealerCode}) is not mapped to the system.`,{duration:5e3}),x(""),c([]),W("dealerCode",""),W("dealerName",""),W("dealerEmail",""),W("dealerPhone",""),W("dealerAddress",""),l(!1);return}if(F.activityType){const U=T.find(Y=>Y.title===F.activityType);if(U&&U.creditPostingOn){const Y=U.creditPostingOn.toLowerCase(),B=(S.itemGroup||"").toLowerCase();let E=!1;if((Y==="vehicle"&&B==="vehicle"||Y==="spares"&&B==="spares"||Y==="gma"&&B==="gma"||Y==="apparel"&&B==="apparel"||Y===B)&&(E=!0),!E){Q.error("incorrect Delercode for selected service group",{description:`Activity requires ${U.creditPostingOn}, but dealer is ${S.itemGroup||"N/A"}`,duration:6e3}),x(""),c([]),l(!1);return}}}I({dealerCode:S.dealerCode,dealerName:S.dealerName||S.displayName,dealerEmail:S.email||"",dealerPhone:S.phone||"",dealerAddress:"",dealerItemGroup:S.itemGroup||""}),x(S.dealerName||S.displayName),c([]),Q.success(`Dealer "${S.dealerName||S.displayName}" verified and mapped to the System`)}catch{Q.error("Dealer is not mapped to the system",{duration:5e3}),x(""),c([]),W("dealerCode",""),W("dealerName",""),W("dealerEmail",""),W("dealerPhone",""),W("dealerAddress","")}finally{l(!1)}},H=()=>{if(g)return;const S=[...F.approvers||[]].sort((V,G)=>V.level-G.level),U=new Map,Y=[];if(S.forEach(V=>{U.has(V.level)?Y.push(V.level):U.set(V.level,V)}),Y.length>0){Q.error(`Duplicate approver levels detected: ${Y.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",Y,S);return}const B=S.map(V=>{const G={email:V.email,name:V.name,userId:V.userId,level:V.level,tat:V.tat,tatType:V.tatType};return V.isAdditional&&V.stepName&&(G.stepName=V.stepName,G.isAdditional=!0),V.originalStepLevel&&(G.originalStepLevel=V.originalStepLevel),G}),E={...F,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:B};if(f(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{f(!1),b.current=null},3e4),s)try{s(E)}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)},z=()=>{switch(r){case 1:return e.jsxs(Gt.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(Et,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Claim Details"}),e.jsx("p",{className:"text-gray-600",children:"Provide comprehensive information about your claim request"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(_e,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:F.activityName,onChange:P=>W("activityName",P.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(He,{value:F.activityType,onValueChange:P=>W("activityType",P),disabled:k,children:[e.jsx(Ye,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(Ge,{placeholder:k?"Loading activity types...":"Select activity type"})}),e.jsx(Qe,{className:"max-h-80",children:T.length>0?T.map(P=>e.jsx(X,{value:P.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:P.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:[P.creditPostingOn&&e.jsx("span",{children:P.creditPostingOn}),P.creditPostingOn&&P.taxationType&&e.jsx("span",{className:"opacity-40 select-none",children:"•"}),P.taxationType&&e.jsx("span",{children:P.taxationType})]})]})},P.activityTypeId)):e.jsx("div",{className:"px-2 py-1.5 text-sm text-gray-500 text-center",children:"No activity types available"})})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsx("div",{className:"mt-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(_e,{placeholder:"Type dealer code, name, or email to search...",value:F.dealerCode?`${F.dealerName} (${F.dealerCode})`:p,onChange:P=>{F.dealerCode?(W("dealerCode",""),W("dealerName",""),W("dealerEmail",""),W("dealerPhone",""),W("dealerAddress",""),x(P.target.value)):_(P.target.value)},onFocus:()=>{p&&p.length>=2&&_(p)},className:"h-12 border-2 border-gray-300 focus:border-blue-500",disabled:i}),F.dealerCode&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsxs(oe,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Ve,{className:"w-3 h-3 mr-1"}),"Verified"]})}),(d||o.length>0)&&!F.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(P=>e.jsx("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>C(P),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:P.dealerName||P.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:P.dealerCode}),P.email&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-40",children:"•"}),e.jsx("span",{children:P.email})]})]}),e.jsxs("div",{className:"text-[10px] text-gray-500 mt-0.5",children:[P.city,", ",P.state]}),P.itemGroup&&e.jsx("div",{className:"text-[9px] text-blue-600 font-bold uppercase tracking-wider mt-0.5",children:P.itemGroup})]}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:P.isLoggedIn?e.jsx(Ve,{className:"w-4 h-4 text-green-600"}):e.jsx(At,{className:"w-4 h-4 text-red-500"})})]})},P.dealerId))})})]})}),F.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:F.dealerName})," (",F.dealerCode,")"]}),F.dealerEmail&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Email: ",F.dealerEmail]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(na,{children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(bt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:F.activityDate?st(F.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(Xi,{mode:"single",selected:F.activityDate,onSelect:P=>W("activityDate",P),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(_e,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:F.location,onChange:P=>W("location",P.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Ci,{value:F.requestDescription||"",onChange:P=>W("requestDescription",P),placeholder:"Provide comprehensive details about your claim requirement including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(re,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(oe,{variant:"secondary",className:"text-xs",children:"Optional"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(na,{children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(bt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:F.periodStartDate?st(F.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(Xi,{mode:"single",selected:F.periodStartDate,onSelect:P=>W("periodStartDate",P),initialFocus:!0,toDate:F.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(na,{children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",disabled:!F.periodStartDate,children:[e.jsx(bt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:F.periodEndDate?st(F.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(Xi,{mode:"single",selected:F.periodEndDate,onSelect:P=>W("periodEndDate",P),initialFocus:!0,fromDate:F.periodStartDate||void 0})})]}),!F.periodStartDate&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Please select start date first"})]})]}),(F.periodStartDate||F.periodEndDate)&&e.jsx("div",{className:"mt-2",children:F.periodStartDate&&F.periodEndDate?e.jsxs("p",{className:"text-xs text-gray-600",children:["Period: ",st(F.periodStartDate,"d MMM yyyy")," - ",st(F.periodEndDate,"d MMM yyyy")]}):e.jsx("p",{className:"text-xs text-gray-500",children:F.periodStartDate?"Please select end date for the period":"Please select start date first"})})]})]})]});case 2:return e.jsx(y6,{formData:F,updateFormData:W,currentUserEmail:(a==null?void 0:a.email)||"",currentUserId:(a==null?void 0:a.userId)||"",currentUserName:(a==null?void 0:a.displayName)||(a==null?void 0:a.name)||(a!=null&&a.firstName&&(a!=null&&a.lastName)?`${a.firstName} ${a.lastName}`.trim():(a==null?void 0:a.email)||"User"),maxApprovalLevels:y.maxApprovalLevels,onPolicyViolation:P=>N({open:!0,violations:P})});case 3:return e.jsxs(Gt.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(Ve,{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(de,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Et,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F.activityName})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(oe,{variant:"secondary",className:"mt-1",children:F.activityType})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(de,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1 font-mono",children:F.dealerCode})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F.dealerName})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:F.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:F.dealerPhone})]}),F.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:F.dealerAddress})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(de,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-5 h-5 text-purple-600"}),"Selected Approvers"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsx("div",{className:"space-y-3",children:[...F.approvers||[]].filter(S=>{var U,Y;return!((U=S.email)!=null&&U.includes("system@"))&&!((Y=S.email)!=null&&Y.includes("finance@"))}).sort((S,U)=>S.level-U.level).map(S=>{const U=Number(S.tat||0),B=(S.tatType||"hours")==="days"?U*24:U;let E="Unknown",V="";if(S.isAdditional){E=S.stepName||"Additional Approver";const G=Eo.find(J=>J.level===S.insertAfterLevel);V=S.stepName||`Additional Approver (after "${(G==null?void 0:G.name)||"Unknown"}")`}else{const G=S.originalStepLevel?Eo.find(J=>J.level===S.originalStepLevel):Eo.find(J=>J.level===S.level&&!J.isAuto);E=(G==null?void 0:G.name)||"Unknown",V=E}return e.jsx("div",{className:`p-3 rounded-lg border ${S.isAdditional?"bg-purple-50 border-purple-200":"bg-gray-50 border-gray-200"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:V}),S.isAdditional&&e.jsx(oe,{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:S.name||S.email||"Not selected"}),S.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:S.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[B," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${S.level}-${S.email}`)})})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(de,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(bt,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F.activityDate?st(F.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Location"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Vc,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:F.location})]})]}),F.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Estimated Budget"}),e.jsx("p",{className:"text-xl font-bold text-blue-900 mt-1",children:F.estimatedBudget})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(de,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Brief Requirement"}),e.jsx("div",{className:"mt-2 p-4 bg-gray-50 rounded-lg border",children:e.jsx(Ls,{content:F.requestDescription||"",className:"text-sm"})})]})})]}),(F.periodStartDate||F.periodEndDate)&&e.jsxs(Z,{className:"border-2",children:[e.jsx(de,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F.periodStartDate?st(F.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F.periodEndDate?st(F.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(Jr,{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(O,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Cs,{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(oe,{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 ",L,": ",e.jsx("span",{className:"hidden sm:inline",children:_o[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(oa,{value:r/L*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:_o.map((P,S)=>e.jsx("span",{className:`text-xs sm:text-sm ${S+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:S+1},S))})]})]}),e.jsx(Z,{className:"mb-6 sm:mb-8",children:e.jsx(ee,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(Hl,{mode:"wait",children:z()})})}),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(O,{variant:"outline",onClick:R,disabled:r===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Previous"]}),r<L?e.jsxs(O,{onClick:M,className:`gap-2 w-full sm:w-auto order-1 sm:order-2 ${$()?"":"opacity-50 cursor-pointer hover:opacity-60"}`,children:["Next",e.jsx(ys,{className:"w-4 h-4"})]}):e.jsx(O,{onClick:H,disabled:!$()||g,className:"gap-2 bg-green-600 hover:bg-green-700 w-full sm:w-auto order-1 sm:order-2",children:g?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ha,{className:"w-4 h-4"}),"Submit Claim Request"]})})]})]}),e.jsx(Di,{open:v.open,onClose:()=>N({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}const{DocumentsTab:N6,ActivityTab:w6,WorkNotesTab:C6,SummaryTab:S6,RequestDetailHeader:A6,QuickActionsSidebar:T6,RequestDetailModals:k6}=B0;let D6=class extends u.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(O,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(O,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function R6({requestId:t,onBack:s,dynamicRequests:a=[]}){var Qt,As,ca,kr,Dr,Da,nr;const n=Aa().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=u.useState(l),[d,m]=u.useState(!1),[p,x]=u.useState(null),[h,g]=u.useState(null),[f,b]=u.useState(!1),[y,j]=u.useState(0),[v,N]=u.useState(!1),[T,A]=u.useState(!1),[k,D]=u.useState(!1),[F,w]=u.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[L,_]=u.useState({open:!1,violations:[]}),{user:W}=us(),{request:I,apiRequest:$,loading:M,refreshing:R,refreshDetails:C,currentApprovalLevel:H,isSpectator:z,isInitiator:P,existingParticipants:S,accessDenied:U}=Gd(n,a,W),Y=(W==null?void 0:W.userId)||"",B=(Qt=W==null?void 0:W.email)==null?void 0:Qt.toLowerCase(),E=((I==null?void 0:I.approvalFlow)||[]).some(Rt=>{var xs;return Rt.role==="Department Lead Approval"&&((xs=Rt.approverEmail)==null?void 0:xs.toLowerCase())===B}),V=(W==null?void 0:W.jobTitle)==="Dealer"||(W==null?void 0:W.designation)==="Dealer",J=((I==null?void 0:I.workflowType)==="CLAIM_MANAGEMENT"||($==null?void 0:$.workflowType)==="CLAIM_MANAGEMENT"||(I==null?void 0:I.templateType)==="claim-management")&&!V&&(P||E),{mergedMessages:q,unreadWorkNotes:se,workNoteAttachments:ne,setWorkNoteAttachments:te}=k0(n,$,o,W),{uploadingDocument:ge,triggerFileInput:we,previewDocument:fe,setPreviewDocument:ke,documentPolicy:le,documentError:Ne,setDocumentError:ae}=D0($,C),[he,ie]=u.useState(null),je=he||H,{showApproveModal:Fe,setShowApproveModal:Ue,showRejectModal:Ce,setShowRejectModal:ce,showAddApproverModal:Re,setShowAddApproverModal:qe,showAddSpectatorModal:at,setShowAddSpectatorModal:ft,showSkipApproverModal:Ft,setShowSkipApproverModal:me,showActionStatusModal:Oe,setShowActionStatusModal:xe,skipApproverData:Je,setSkipApproverData:Ke,actionStatus:rt,setActionStatus:Xe,handleApproveConfirm:lt,handleRejectConfirm:et,handleAddApprover:xt,handleSkipApprover:Hs,handleAddSpectator:ls}=I0(n,je,C),Nt=async Rt=>{await lt(Rt),ie(null)},gt=async Rt=>{await et(Rt),ie(null)},Pt=((I==null?void 0:I.status)||($==null?void 0:$.status)||"").toLowerCase(),Ss=(Pt==="approved"||Pt==="rejected")&&P,{conclusionRemark:as,setConclusionRemark:Ya,conclusionLoading:Qa,conclusionSubmitting:wr,aiGenerated:Ta,handleGenerateConclusion:Ot,handleFinalizeConclusion:ka,generationAttempts:Us,generationFailed:en,maxAttemptsReached:tn}=R0(I,n,P,C,s,Xe,xe);u.useEffect(()=>{(async()=>{var xs;try{const Js=await pa("SYSTEM_SETTINGS"),ga=await pa("WORKFLOW_SHARING"),an=[...Js,...ga],Ra={};an.forEach(ir=>{Ra[ir.configKey]=ir.configValue}),w({maxApprovalLevels:parseInt(Ra.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Ra.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((xs=Ra.ALLOW_ADD_SPECTATOR)==null?void 0:xs.toLowerCase())==="true",maxSpectators:parseInt(Ra.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Js){console.error("Failed to load system policy:",Js)}})()},[]),u.useEffect(()=>{const xs=new URLSearchParams(window.location.search).get("tab");xs&&c(xs)},[n]);const Cr=()=>{C()},sn=()=>{N(!0)},tr=()=>{A(!0)},Sr=async()=>{await C()},sr=()=>{D(!0)},Ar=async()=>{await C()},Tr=async()=>{await C()},ar=async()=>{if(!($!=null&&$.requestId)){Q.error("Request ID not found");return}if(!p){Q.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Oa=(I==null?void 0:I.status)==="closed";u.useEffect(()=>{(async()=>{if(!Oa||!($!=null&&$.requestId)){g(null),x(null);return}try{b(!0);const xs=await L0($.requestId);if(xs!=null&&xs.summaryId){x(xs.summaryId);try{const Js=await Qd(xs.summaryId);g(Js)}catch(Js){console.error("Failed to fetch summary details:",Js),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{b(!1)}})()},[Oa,$==null?void 0:$.requestId]),u.useEffect(()=>{if(!Y||!($!=null&&$.requestId))return;const Rt=Kr();if(!Rt)return;Jc(Rt,Y);const xs=Js=>{var ir,En,_n,Mn;const ga=Js==null?void 0:Js.notification;if(!ga)return;const an=ga.requestId||ga.request_id,Ra=((ir=ga.metadata)==null?void 0:ir.requestNumber)||((En=ga.metadata)==null?void 0:En.request_number);an!==$.requestId&&Ra!==n&&Ra!==$.requestNumber||((_n=ga.metadata)!=null&&_n.creditNoteNumber||(Mn=ga.metadata)!=null&&Mn.credit_note_number)&&C()};return Rt.on("notification:new",xs),()=>{Rt.off("notification:new",xs)}},[Y,$==null?void 0:$.requestId,n,C]);const rr=((I==null?void 0:I.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 M&&!I&&!$?e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(_t,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading dealer claim request details..."})]})}):U!=null&&U.denied?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"access-denied-state",children:e.jsxs("div",{className:"max-w-lg w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(Lp,{className:"w-10 h-10 text-red-500"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Access Denied"}),e.jsx("p",{className:"text-gray-600 mb-6 leading-relaxed",children:U.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(O,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(O,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):I?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(A6,{request:I,refreshing:R,onBack:s||(()=>window.history.back()),onRefresh:Cr,onShareSummary:ar,isInitiator:P,slaData:((As=I==null?void 0:I.summary)==null?void 0:As.sla)||(I==null?void 0:I.sla)||null,isPaused:((ca=I==null?void 0:I.pauseInfo)==null?void 0:ca.isPaused)||!1}),e.jsxs(Ri,{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(Ii,{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(Ut,{value:"overview",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-overview",children:[e.jsx(Op,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Oa&&h&&e.jsxs(Ut,{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(Wc,{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(Ut,{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(Ks,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),J&&e.jsxs(Ut,{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(Pa,{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(Ut,{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(Ee,{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(Ut,{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(zt,{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(Ut,{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(Qs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),se>0&&e.jsx(oe,{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:se>9?"9+":se})]})]})}),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(Bt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(o4,{request:I,apiRequest:$,currentUserId:Y,isInitiator:P,needsClosure:Ss,conclusionRemark:as,setConclusionRemark:Ya,conclusionLoading:Qa,conclusionSubmitting:wr,aiGenerated:Ta,handleGenerateConclusion:Ot,handleFinalizeConclusion:ka,generationAttempts:Us,generationFailed:en,maxAttemptsReached:tn})}),Oa&&e.jsx(Bt,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(S6,{summary:h,loading:f,onShare:ar,isInitiator:P})}),e.jsx(Bt,{value:"workflow",className:"mt-0",children:e.jsx(g6,{request:I,user:W,isInitiator:P,isSpectator:z,onSkipApprover:Rt=>{if(!Rt.levelId){alert("Level ID not available");return}Ke(Rt),me(!0)},onRefresh:C,documentPolicy:le})}),J&&e.jsx(Bt,{value:"io",className:"mt-0",children:e.jsx(f6,{request:I,apiRequest:$,onRefresh:C,isSpectator:z})}),e.jsx(Bt,{value:"documents",className:"mt-0",children:e.jsx(N6,{request:I,workNoteAttachments:ne,uploadingDocument:ge,documentPolicy:le,triggerFileInput:we,setPreviewDocument:ke,downloadDocument:$s,isSpectator:z})}),e.jsx(Bt,{value:"activity",className:"mt-0",children:e.jsx(w6,{request:I})}),e.jsx(Bt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(C6,{requestId:n,requestTitle:I.title,mergedMessages:q,setWorkNoteAttachments:te,isInitiator:P,isSpectator:z,currentLevels:rr,onAddApprover:xt,maxApprovalLevels:F.maxApprovalLevels,onPolicyViolation:Rt=>_({open:!0,violations:Rt})})})]}),o!=="worknotes"&&e.jsx(T6,{request:I,isInitiator:P,isSpectator:z,currentApprovalLevel:H,onAddApprover:()=>qe(!0),onAddSpectator:()=>ft(!0),onApprove:()=>Ue(!0),onReject:()=>ce(!0),onPause:sn,onResume:tr,onRetrigger:sr,summaryId:p,refreshTrigger:y,pausedByUserId:(Dr=(kr=I==null?void 0:I.pauseInfo)==null?void 0:kr.pausedBy)==null?void 0:Dr.userId,currentUserId:Y,apiRequest:$,hideApproveReject:V})]})]})]})}),d&&p&&e.jsx(z0,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(I==null?void 0:I.title)||"N/A",onSuccess:()=>{C(),j(Rt=>Rt+1)}}),v&&($==null?void 0:$.requestId)&&e.jsx(V0,{isOpen:v,onClose:()=>N(!1),requestId:$.requestId,levelId:(H==null?void 0:H.levelId)||null,onSuccess:Ar}),T&&($==null?void 0:$.requestId)&&e.jsx(W0,{isOpen:T,onClose:()=>A(!1),requestId:$.requestId,onSuccess:Sr}),k&&($==null?void 0:$.requestId)&&e.jsx(H0,{isOpen:k,onClose:()=>D(!1),requestId:$.requestId,approverName:(nr=(Da=I==null?void 0:I.pauseInfo)==null?void 0:Da.pausedBy)==null?void 0:nr.name,onSuccess:Tr}),e.jsx(k6,{showApproveModal:Fe,showRejectModal:Ce,showAddApproverModal:Re,showAddSpectatorModal:at,showSkipApproverModal:Ft,showActionStatusModal:Oe,previewDocument:fe,documentError:Ne,request:I,skipApproverData:Je,actionStatus:rt,existingParticipants:S,currentLevels:rr,maxApprovalLevels:F.maxApprovalLevels,onPolicyViolation:Rt=>_({open:!0,violations:Rt}),setShowApproveModal:Ue,setShowRejectModal:ce,setShowAddApproverModal:qe,setShowAddSpectatorModal:ft,setShowSkipApproverModal:me,setShowActionStatusModal:xe,setPreviewDocument:ke,setDocumentError:ae,setSkipApproverData:Ke,setActionStatus:Xe,handleApproveConfirm:Nt,handleRejectConfirm:gt,handleAddApprover:xt,handleAddSpectator:ls,handleSkipApprover:Hs,downloadDocument:$s,documentPolicy:le}),e.jsx(Di,{open:L.open,onClose:()=>_({open:!1,violations:[]}),violations:L.violations,policyDetails:{maxApprovalLevels:F.maxApprovalLevels,maxParticipants:F.maxParticipants,allowSpectators:F.allowSpectators,maxSpectators:F.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(Ee,{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(O,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(O,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function I6(t){return e.jsx(D6,{children:e.jsx(R6,{...t})})}function F6({onNavigate:t,onNewRequest:s}){const[a,r]=u.useState(!0),[n,i]=u.useState(!1),[l,o]=u.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]=u.useState([]),[m,p]=u.useState("all"),[x,h]=u.useState(),[g,f]=u.useState(),b=async(_=!1)=>{try{_?i(!0):r(!0);const W=await d6(m||"all",x,g);o(W.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(W.categoryData||[])}catch(W){console.error("[DealerDashboard] Error fetching data:",W),Q.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)}};u.useEffect(()=>{b()},[]);const y=(_,W=!1)=>{if(_==null||isNaN(_))return"₹0";const I=typeof _=="string"?parseFloat(_):Number(_);return I<=0?"₹0":W||I<1e4?`₹${Math.round(I).toLocaleString("en-IN")}`:I>=1e5?`₹${(I/1e5).toFixed(1)}L`:I>=1e3?`₹${(I/1e3).toFixed(1)}K`:`₹${Math.round(I).toLocaleString("en-IN")}`},j=_=>_.toLocaleString("en-IN"),v=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),N=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),T=u.useMemo(()=>{const _=c.reduce((W,I)=>W+I.raised,0);return _===0?[]:c.map(W=>({name:W.activityType.length>20?W.activityType.substring(0,20)+"...":W.activityType,value:W.raised,fullName:W.activityType,percentage:(W.raised/_*100).toFixed(0)}))},[c]),A=u.useMemo(()=>c.map(_=>({name:_.activityType.length>15?_.activityType.substring(0,15)+"...":_.activityType,fullName:_.activityType,Raised:_.raised,Approved:_.approved,Rejected:_.rejected,Pending:_.pending})),[c]),k=u.useMemo(()=>c.map(_=>({name:_.activityType.length>15?_.activityType.substring(0,15)+"...":_.activityType,fullName:_.activityType,Raised:_.raisedValue,Approved:_.approvedValue,Credited:_.creditedValue})),[c]),D=["#166534","#15803d","#16a34a","#22c55e","#4ade80","#86efac","#bbf7d0"],F=u.useMemo(()=>c.length===0?null:c.reduce((_,W)=>W.approvalRate>((_==null?void 0:_.approvalRate)||0)?W:_),[c]),w=u.useMemo(()=>c.length===0?null:c.reduce((_,W)=>W.raisedValue>((_==null?void 0:_.raisedValue)||0)?W:_),[c]);return a?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(_t,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):l.totalClaims===0&&c.length===0?e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(Z,{className:"border-0 shadow-xl relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(ee,{className:"relative z-10 p-8 lg:p-12",children:e.jsx("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6",children:e.jsxs("div",{className:"text-white",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-yellow-400 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(bs,{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(O,{onClick:()=>{i(!0),b(!0)},disabled:n,variant:"outline",className:"bg-white/10 hover:bg-white/20 text-white border-white/20",children:[e.jsx(_t,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh"]})})]})})})]}),e.jsx(Z,{className:"shadow-lg",children:e.jsxs(ee,{className:"flex flex-col items-center justify-center py-16 px-4",children:[e.jsx("div",{className:"w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mb-6",children:e.jsx(tc,{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(O,{onClick:()=>{i(!0),b(!0)},disabled:n,variant:"outline",children:[e.jsx(_t,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh Data"]})})]})})]}):e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(Z,{className:"border-0 shadow-xl relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(ee,{className:"relative z-10 p-8 lg:p-12",children:e.jsxs("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6",children:[e.jsxs("div",{className:"text-white",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-yellow-400 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(bs,{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(O,{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(O,{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(Ee,{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(ul,{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(de,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Raised Claims"}),e.jsx("div",{className:"p-2 rounded-lg bg-blue-50",children:e.jsx(Ee,{className:"h-4 w-4 text-blue-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:j(l.totalClaims)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(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(de,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Approved"}),e.jsx("div",{className:"p-2 rounded-lg bg-green-50",children:e.jsx(Ve,{className:"h-4 w-4 text-green-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:j(l.approved)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Ks,{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(de,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Rejected"}),e.jsx("div",{className:"p-2 rounded-lg bg-red-50",children:e.jsx(At,{className:"h-4 w-4 text-red-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:j(l.rejected)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(xy,{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(de,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Pending"}),e.jsx("div",{className:"p-2 rounded-lg bg-orange-50",children:e.jsx(it,{className:"h-4 w-4 text-orange-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:j(l.pending)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(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(de,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Credited"}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-50",children:e.jsx(hy,{className:"h-4 w-4 text-emerald-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:j(l.credited)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Ks,{className:"h-3 w-3 text-emerald-600"}),e.jsxs("p",{className:"text-xs text-emerald-600",children:[N(),"% credit rate"]})]})]})]}),e.jsxs(Z,{className:"border-l-4 border-l-amber-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(de,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Pending Credit"}),e.jsx("div",{className:"p-2 rounded-lg bg-amber-50",children:e.jsx(ss,{className:"h-4 w-4 text-amber-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:j(l.pendingCredit)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(l.pendingCreditValue)})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(Z,{className:"shadow-lg",children:[e.jsx(de,{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(tc,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Claims Distribution by Activity Type"}),e.jsx(Te,{children:"Total claims raised across activity types"})]})]})}),e.jsxs(ee,{children:[e.jsx(fn,{width:"100%",height:300,children:e.jsxs(yp,{children:[e.jsx(vp,{data:T,cx:"50%",cy:"50%",labelLine:!1,label:({name:_,percentage:W})=>`${_}: ${W}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:T.map((_,W)=>e.jsx(Np,{fill:D[W%D.length]},`cell-${W}`))}),e.jsx(bn,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:T.slice(0,3).map((_,W)=>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[W%D.length]}}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600",children:_.name}),e.jsx("p",{className:"text-sm text-gray-900",children:j(_.value)})]})]},W))})]})]}),e.jsxs(Z,{className:"shadow-lg",children:[e.jsx(de,{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(ul,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Claims Status by Activity Type"}),e.jsx(Te,{children:"Count comparison across workflow stages"})]})]})}),e.jsx(ee,{children:e.jsx(fn,{width:"100%",height:300,children:e.jsxs(Jo,{data:A,children:[e.jsx(il,{strokeDasharray:"3 3"}),e.jsx(ll,{dataKey:"name"}),e.jsx(ol,{}),e.jsx(bn,{}),e.jsx(cl,{}),e.jsx($a,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx($a,{dataKey:"Approved",fill:"#22c55e"}),e.jsx($a,{dataKey:"Rejected",fill:"#ef4444"}),e.jsx($a,{dataKey:"Pending",fill:"#f59e0b"})]})})})]})]}),e.jsxs(Z,{className:"shadow-lg",children:[e.jsx(de,{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(zt,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Detailed Activity Type Breakdown"}),e.jsx(Te,{children:"In-depth analysis of claims by type and status"})]})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg mb-4 text-gray-900",children:"Activity Type Value Comparison"}),e.jsx(fn,{width:"100%",height:350,children:e.jsxs(Jo,{data:k,children:[e.jsx(il,{strokeDasharray:"3 3"}),e.jsx(ll,{dataKey:"name"}),e.jsx(ol,{tickFormatter:_=>y(_)}),e.jsx(bn,{formatter:_=>y(_),labelFormatter:_=>_}),e.jsx(cl,{}),e.jsx($a,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx($a,{dataKey:"Approved",fill:"#22c55e"}),e.jsx($a,{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((_,W)=>e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow",children:[e.jsx(de,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-base",children:_.activityType}),e.jsxs(oe,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[_.approvalRate.toFixed(1),"% approved"]})]})}),e.jsxs(ee,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Raised:"}),e.jsxs("span",{className:"text-gray-900",children:[j(_.raised)," (",y(_.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:[j(_.approved)," (",y(_.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:[j(_.rejected)," (",y(_.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:[j(_.pending)," (",y(_.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:[j(_.credited)," (",y(_.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:[j(_.pendingCredit)," (",y(_.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:[_.creditRate.toFixed(1),"%"]})]}),e.jsx(oa,{value:_.creditRate,className:"h-2"})]})]})]},W))})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(Z,{className:"border-t-4 border-t-green-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-green-100 rounded-lg",children:e.jsx(ts,{className:"h-6 w-6 text-green-600"})}),e.jsx(Ks,{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:(F==null?void 0:F.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-green-600",children:[(F==null?void 0:F.approvalRate.toFixed(2))||0,"% approval rate"]})]})}),e.jsx(Z,{className:"border-t-4 border-t-blue-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Pa,{className:"h-6 w-6 text-blue-600"})}),e.jsx(zt,{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:(w==null?void 0:w.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-blue-600",children:[w?y(w.raisedValue,!0):"₹0"," raised"]})]})}),e.jsx(Z,{className:"border-t-4 border-t-emerald-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-emerald-100 rounded-lg",children:e.jsx(kl,{className:"h-6 w-6 text-emerald-600"})}),e.jsx(Ve,{className:"h-5 w-5 text-emerald-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Overall Credit Rate"}),e.jsxs("p",{className:"text-xl text-gray-900 mb-1",children:[N(),"%"]}),e.jsxs("p",{className:"text-sm text-emerald-600",children:[j(l.credited)," claims credited"]})]})}),e.jsx(Z,{className:"border-t-4 border-t-amber-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-amber-100 rounded-lg",children:e.jsx(Ip,{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:j(l.pendingCredit)}),e.jsxs("p",{className:"text-sm text-amber-600",children:[y(l.pendingCreditValue)," awaiting credit"]})]})})]})]})}function P6({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(de,{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(Ga,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:o>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[o," filter",o>1?"s":""," active"]})})]})]}),o>0&&e.jsxs(O,{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(vt,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ee,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Jt,{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(_e,{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(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Qe,{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(O,{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(El,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(_l,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function E6({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(de,{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(Ga,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Te,{className:"text-xs sm:text-sm",children:d>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[d," filter",d>1?"s":""," active"]})})]})]}),d>0&&e.jsxs(O,{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(vt,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ee,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Jt,{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(_e,{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(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200","data-testid":"dealer-closed-requests-status-filter",children:e.jsx(Ge,{placeholder:"Closure Type"})}),e.jsxs(Qe,{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(Ve,{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(At,{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(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200","data-testid":"dealer-closed-requests-sort-by",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Qe,{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(O,{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(El,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(_l,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function _6({searchTerm:t,statusFilter:s,initiatorFilter:a,approverFilter:r,approverFilterType:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,initiatorSearch:d,approverSearch:m,onSearchChange:p,onStatusChange:x,onInitiatorChange:h,onApproverChange:g,onApproverTypeChange:f,onDateRangeChange:b,onCustomStartDateChange:y,onCustomEndDateChange:j,onShowCustomDatePickerChange:v,onApplyCustomDate:N,onClearFilters:T,hasActiveFilters:A,...k}){return e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"dealer-user-all-requests-filters",children:e.jsx(ee,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),A&&e.jsx(oe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),A&&e.jsxs(O,{variant:"ghost",size:"sm",onClick:T,className:"gap-2",children:[e.jsx(_t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Zt,{}),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(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(_e,{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:x,children:[e.jsx(Ye,{className:"h-10","data-testid":"dealer-status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Qe,{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(re,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:d.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:d.selectedUser.displayName||d.selectedUser.email}),e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:d.handleClear,children:e.jsx(vt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{placeholder:"Search initiator...",value:d.searchQuery,onChange:D=>d.handleSearch(D.target.value),onFocus:()=>{d.searchResults.length>0&&d.setShowResults(!0)},onBlur:()=>setTimeout(()=>d.setShowResults(!1),200),className:"h-10","data-testid":"dealer-initiator-search-input"}),d.showResults&&d.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:d.searchResults.map(D=>e.jsx("button",{type:"button",onClick:()=>d.handleSelect(D),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:D.displayName||D.email}),D.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:D.email})]})},D.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r!=="all"&&f&&e.jsxs(He,{value:n,onValueChange:D=>f(D),children:[e.jsx(Ye,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Qe,{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(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:m.handleClear,children:e.jsx(vt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{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(bt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:i,onValueChange:D=>b(D),children:[e.jsx(Ye,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Qe,{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(na,{open:c,onOpenChange:v,children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(bt,{className:"w-4 h-4"}),l&&o?`${st(l,"MMM d, yyyy")} - ${st(o,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(la,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",children:"Start Date"}),e.jsx(aa,{value:l||null,onChange:D=>{const F=D?new Date(D):void 0;F?(y==null||y(F),o&&F>o&&(j==null||j(F))):y==null||y(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",children:"End Date"}),e.jsx(aa,{value:o||null,onChange:D=>{const F=D?new Date(D):void 0;F?(j==null||j(F),l&&F<l&&(y==null||y(F))):j==null||j(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(O,{size:"sm",onClick:N,disabled:!l||!o,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(O,{size:"sm",variant:"outline",onClick:()=>{v==null||v(!1),y==null||y(void 0),j==null||j(void 0),b("month")},children:"Cancel"})]})]})})]})]})]})})})}function M6(t){switch(t){case"DEALER_CLAIM":return I6;case"CUSTOM":default:return e4}}function L6(t){switch(t){case"DEALER":return P6;case"STANDARD":default:return a4}}function O6(t){switch(t){case"DEALER":return E6;case"STANDARD":default:return i4}}function $6(t){switch(t){case"DEALER":return _6;case"STANDARD":default:return l4}}const U6=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ma,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"}}},B6=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:Ze,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:At,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ve,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ze,iconColor:"text-gray-600",label:t}}};function z6({onViewRequest:t}){const[s,a]=u.useState([]),[r,n]=u.useState(!1),[i,l]=u.useState(!1),[o,c]=u.useState(1),[d,m]=u.useState(0),[p]=u.useState(10),x=u.useRef(null),h=oC(),g=u.useMemo(()=>{try{const F=nt.getUserData();return md(F)}catch(F){return console.error("[OpenRequests] Error getting user filter type:",F),"STANDARD"}},[]),f=u.useMemo(()=>L6(g),[g]),b=g==="DEALER",y=F=>{const w={search:h.searchTerm||void 0,status:F&&!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 w.templateType==="FORM_16"&&(h.form16FinancialYear&&(w.financialYear=h.form16FinancialYear),h.form16Quarter&&(w.quarter=h.form16Quarter)),w},j=u.useCallback(async(F=1,w)=>{try{F===1&&(n(!0),a([]));const L=await Xs.listOpenForMe({page:F,limit:p,search:w==null?void 0:w.search,status:w==null?void 0:w.status,priority:w==null?void 0:w.priority,templateType:w==null?void 0:w.templateType,financialYear:w==null?void 0:w.financialYear,quarter:w==null?void 0:w.quarter,sortBy:w==null?void 0:w.sortBy,sortOrder:w==null?void 0:w.sortOrder}),_=Array.isArray(L==null?void 0:L.data)?L.data:[],W=L==null?void 0:L.pagination;W&&(h.setCurrentPage(W.page||1),c(W.totalPages||1),m(W.total||0));const I=_.map($=>{var R,C,H,z;const M=$.submittedAt||$.submitted_at||$.createdAt||$.created_at;return{id:$.requestNumber||$.request_number||$.requestId,requestId:$.requestId,displayId:$.requestNumber||$.request_number||$.requestId,title:$.title,description:$.description,status:($.status||"").toString().toLowerCase().replace("_","-"),priority:($.priority||"").toString().toLowerCase(),initiator:{name:((R=$.initiator)==null?void 0:R.displayName)||((C=$.initiator)==null?void 0:C.email)||"—",avatar:(((H=$.initiator)==null?void 0:H.displayName)||((z=$.initiator)==null?void 0:z.email)||"NA").split(" ").map(P=>P[0]).join("").slice(0,2).toUpperCase()},currentApprover:$.currentApprover?{name:$.currentApprover.name||$.currentApprover.email||"—",avatar:($.currentApprover.name||$.currentApprover.email||"CA").split(" ").map(P=>P[0]).join("").slice(0,2).toUpperCase(),sla:$.currentApprover.sla}:void 0,createdAt:M||"—",approvalStep:$.currentLevel?`Step ${$.currentLevel} of ${$.totalLevels||"?"}`:void 0,department:$.department,currentLevelSLA:$.currentLevelSLA,templateType:$.templateType||$.template_type,form16Submission:$.form16Submission??null}});a(I)}finally{n(!1),l(!1)}},[p,h]);x.current=j;const v=u.useCallback(()=>{l(!0),j(h.currentPage,y(!0))},[h.currentPage,j]),N=u.useCallback(F=>{F>=1&&F<=o&&(h.setCurrentPage(F),j(F,y(!0)))},[o,h,j]),T=()=>{const F=[];let L=Math.max(1,h.currentPage-Math.floor(2.5)),_=Math.min(o,L+5-1);_-L<4&&(L=Math.max(1,_-5+1));for(let W=L;W<=_;W++)F.push(W);return F},A=u.useRef(!1);u.useEffect(()=>{if(!A.current){A.current=!0;const F=h.currentPage||1;j(F,y(!0))}},[]);const k=u.useRef({searchTerm:h.searchTerm,statusFilter:h.statusFilter,priorityFilter:h.priorityFilter,templateTypeFilter:h.templateTypeFilter,sortBy:h.sortBy,sortOrder:h.sortOrder,isDealer:b});u.useEffect(()=>{if(!A.current)return;const F=k.current;if(!(F.searchTerm!==h.searchTerm||F.statusFilter!==h.statusFilter||F.priorityFilter!==h.priorityFilter||F.templateTypeFilter!==h.templateTypeFilter||F.sortBy!==h.sortBy||F.sortOrder!==h.sortOrder||F.isDealer!==b))return;const L=setTimeout(()=>{h.setCurrentPage(1),j(1,y(!0)),k.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(L)},[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(Ee,{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(oe,{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(O,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:v,disabled:i,children:[e.jsx(_t,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:i?"Refreshing...":"Refresh"})]})]})]}),e.jsx(f,{searchTerm: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(F=>{const w=U6(F.priority),L=(F.templateType||F.template_type||"").toString().toUpperCase()==="FORM_16",_=F.form16Submission,W=_==null?void 0:_.displayStatus,I=W&&/balance mismatch|failed/i.test(String(W)),$=L&&W?{color:I?"bg-red-100 text-red-800 border-red-200":W==="Completed"?"bg-green-100 text-green-800 border-green-200":"bg-gray-100 text-gray-700 border-gray-200",icon:Ze,label:W}:B6(F.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(F.id,F.title),children:e.jsx(ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${w.color} border shadow-sm`,children:e.jsx(w.icon,{className:`w-5 h-5 ${w.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:F.displayId||F.id}),e.jsxs(oe,{variant:"outline",className:`${$.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx($.icon,{className:"w-3.5 h-3.5 mr-1"}),$.label||F.status]}),F.department&&e.jsx(oe,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:F.department}),e.jsx(oe,{variant:"outline",className:`${w.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:F.priority}),(()=>{const M=(F==null?void 0:F.templateType)||(F==null?void 0:F.template_type)||"",R=(M==null?void 0:M.toUpperCase())||"";let C="Non-Templatized",H="bg-purple-100 !text-purple-600 border-purple-200";return R==="DEALER CLAIM"?(C="Dealer Claim",H="bg-blue-100 !text-blue-700 border-blue-200"):R==="FORM_16"?(C="Form 16",H="bg-emerald-100 !text-emerald-700 border-emerald-200"):R==="TEMPLATE"&&(C="Template"),e.jsx(oe,{variant:"outline",className:`${H} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:C})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:F.title}),(F.templateType||"").toString().toUpperCase()==="FORM_16"&&F.form16Submission&&e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-600 mt-1",children:[F.form16Submission.dealerCode&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Dealer:"})," ",F.form16Submission.dealerCode]}),F.form16Submission.form16aNumber&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Form 16A:"})," ",F.form16Submission.form16aNumber]}),F.form16Submission.financialYear&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"FY:"})," ",F.form16Submission.financialYear]}),F.form16Submission.quarter&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Q:"})," ",F.form16Submission.quarter]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Total amount:"})," ",F.form16Submission.totalAmount!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(F.form16Submission.totalAmount):"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Credit note:"})," ",F.form16Submission.creditNoteNumber||"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Status:"})," ",F.form16Submission.displayStatus||F.form16Submission.status||"—"]})]}),F.currentLevelSLA&&(()=>{var z;const M=!!(F.isPaused||(z=F.pauseInfo)!=null&&z.isPaused||F.status==="paused"),R=F.currentLevelSLA.percentageUsed||0,H=M?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:R>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:R>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:R>=50?{bg:"bg-amber-50 border border-amber-200",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{bg:"bg-green-50 border border-green-200",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"};return e.jsxs("div",{className:`p-2 rounded-md ${H.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:[M?e.jsx(ur,{className:`w-3.5 h-3.5 ${H.icon}`}):e.jsx(it,{className:`w-3.5 h-3.5 ${H.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",R,"% ",M&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:F.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${H.text}`,children:[F.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(oa,{value:R,className:"h-1.5",indicatorClassName:H.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(ds,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ms,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:F.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:F.initiator.name})]}),F.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ds,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(ms,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:F.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:F.currentApprover.name})]}),F.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ze,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:F.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(bt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",F.createdAt!=="—"?_a(F.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(ys,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},F.id)})}),D.length===0&&e.jsx(Z,{className:"shadow-lg border-0",children:e.jsxs(ee,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Ee,{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(O,{variant:"outline",className:"mt-4",onClick:h.clearFilters,children:"Clear all filters"})]})}),o>1&&!r&&e.jsx(Z,{className:"shadow-md",children:e.jsx(ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(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(O,{variant:"outline",size:"sm",onClick:()=>N(h.currentPage-1),disabled:h.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(ys,{className:"h-4 w-4 rotate-180"})}),h.currentPage>3&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx(O,{variant:"outline",size:"sm",onClick:()=>N(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),T().map(F=>e.jsx(O,{variant:F===h.currentPage?"default":"outline",size:"sm",onClick:()=>N(F),className:`h-8 w-8 p-0 ${F===h.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:F},F)),h.currentPage<o-2&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>N(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>N(h.currentPage+1),disabled:h.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(ys,{className:"h-4 w-4"})})]})]})})})]})}function V6({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(Ee,{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(oe,{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(O,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:r,disabled:a,"data-testid":"closed-requests-refresh",children:[e.jsx(_t,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${a?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:a?"Refreshing...":"Refresh"})]})]})]})}function W6(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ma,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 H6(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:Ve,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:At,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ze,iconColor:"text-gray-600",label:t,description:""}}}function G6({request:t,onViewRequest:s}){var l;const a=W6(t.priority),r=H6(t.status),n=a.icon,i=r.icon;return e.jsx(Z,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>s==null?void 0:s(t.id,t.title),"data-testid":`closed-request-card-${t.id}`,children:e.jsx(ee,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-5",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${a.color} border shadow-sm`,children:e.jsx(n,{className:`w-5 h-5 ${a.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:t.displayId||t.id}),e.jsxs(oe,{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(oe,{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(oe,{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(oe,{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(ds,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ms,{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(Ve,{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(bt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?_a(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ve,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",_a(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(ys,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function Y6({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(G6,{request:r,onViewRequest:a},r.id))})}function Q6({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(Z,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(ee,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Ee,{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(O,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function K6(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 X6({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=K6(a,r);return e.jsx(Z,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(a-1)*i+1," to ",Math.min(a*i,n)," of ",n," closed requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{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(ys,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(O,{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(O,{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(O,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(O,{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(ys,{className:"h-4 w-4"})})]})]})})})}function J6(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 Z6(t){return t.map(J6)}function q6({itemsPerPage:t=10}={}){const[s,a]=u.useState([]),[r,n]=u.useState(!1),[i,l]=u.useState(!1),[o,c]=u.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=u.useCallback(async(p=1,x)=>{try{p===1&&(n(!0),a([]));const h=await Xs.listClosedByMe({page:p,limit:t,search:x==null?void 0:x.search,status:x!=null&&x.status&&x.status!=="all"?x.status:void 0,priority:x==null?void 0:x.priority,templateType:x==null?void 0:x.templateType,financialYear:x==null?void 0:x.financialYear,quarter:x==null?void 0:x.quarter,sortBy:x==null?void 0:x.sortBy,sortOrder:x==null?void 0:x.sortOrder}),g=Array.isArray(h==null?void 0:h.data)?h.data:[],f=Z6(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=u.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 eD={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},nb=An({name:"closedRequests",initialState:eD,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:tD,setStatusFilter:sD,setPriorityFilter:aD,setTemplateTypeFilter:rD,setForm16FinancialYear:nD,setForm16Quarter:iD,setSortBy:lD,setSortOrder:oD,setCurrentPage:cD,clearFilters:dD}=nb.actions;function mD({onFiltersChange:t,debounceMs:s=500}={}){const a=yi(),r=u.useRef(null),n=u.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,form16FinancialYear:d,form16Quarter:m,sortBy:p,sortOrder:x,currentPage:h}=kn(w=>w.closedRequests),g=u.useCallback(w=>a(tD(w)),[a]),f=u.useCallback(w=>a(sD(w)),[a]),b=u.useCallback(w=>a(aD(w)),[a]),y=u.useCallback(w=>a(rD(w)),[a]),j=u.useCallback(w=>a(nD(w)),[a]),v=u.useCallback(w=>a(iD(w)),[a]),N=u.useCallback(w=>a(lD(w)),[a]),T=u.useCallback(w=>a(oD(w)),[a]),A=u.useCallback(w=>a(cD(w)),[a]),k=u.useCallback(()=>({search:i,status:l,priority:o,templateType:c!=="all"?c:void 0,financialYear:c==="FORM_16"&&d?d:void 0,quarter:c==="FORM_16"&&m?m:void 0,sortBy:p,sortOrder:x}),[i,l,o,c,d,m,p,x]);u.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const w=setTimeout(()=>{t&&t(k())},i?s:0);return r.current=w,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,p,x,t,k,s]);const D=u.useCallback(()=>{a(dD())},[a]),F=[i,o!=="all"?o:null,l!=="all"?l:null,c!=="all"?c:null,c==="FORM_16"&&d?"fy":null,c==="FORM_16"&&m?"q":null].filter(Boolean).length;return{searchTerm:i,priorityFilter:o,statusFilter:l,templateTypeFilter:c,form16FinancialYear:d,form16Quarter:m,sortBy:p,sortOrder:x,currentPage:h,setSearchTerm:g,setPriorityFilter:b,setStatusFilter:f,setTemplateTypeFilter:y,setForm16FinancialYear:j,setForm16Quarter:v,setSortBy:N,setSortOrder:T,setCurrentPage:A,clearFilters:D,activeFiltersCount:F,getFilters:k}}function uD({onViewRequest:t}){const s=q6({itemsPerPage:10}),a=u.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=mD(),n=u.useMemo(()=>{try{const x=nt.getUserData();return md(x)}catch(x){return console.error("[ClosedRequests] Error getting user filter type:",x),"STANDARD"}},[]),i=u.useMemo(()=>O6(n),[n]),l=n==="DEALER",o=u.useCallback(()=>{const x=r.getFilters();return{search:x.search||void 0,status:x.status!=="all"?x.status:void 0,priority:!l&&x.priority?x.priority:void 0,templateType:x.templateType,financialYear:x.financialYear,quarter:x.quarter,sortBy:x.sortBy,sortOrder:x.sortOrder}},[r,l]),c=u.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=u.useRef(!1);u.useEffect(()=>{const x=r.currentPage||1;a.current(x,o()),d.current=!0},[l]),u.useEffect(()=>{if(!d.current)return;const x=c.current;if(!(x.searchTerm!==r.searchTerm||x.statusFilter!==r.statusFilter||x.priorityFilter!==r.priorityFilter||x.templateTypeFilter!==r.templateTypeFilter||x.form16FinancialYear!==r.form16FinancialYear||x.form16Quarter!==r.form16Quarter||x.sortBy!==r.sortBy||x.sortOrder!==r.sortOrder))return;const g=setTimeout(()=>{r.setCurrentPage(1),a.current(1,o()),c.current={searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,form16FinancialYear:r.form16FinancialYear,form16Quarter:r.form16Quarter,sortBy:r.sortBy,sortOrder:r.sortOrder}},r.searchTerm!==x.searchTerm?500:0);return()=>clearTimeout(g)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.templateTypeFilter,r.form16FinancialYear,r.form16Quarter,r.sortBy,r.sortOrder,l]);const m=u.useCallback(x=>{x>=1&&x<=s.pagination.totalPages&&(r.setCurrentPage(x),s.fetchRequests(x,o()))},[s,r,o]),p=u.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(V6,{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(Y6,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(Q6,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(X6,{pagination:s.pagination,onPageChange:m})]})}function xD(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 hD(t){return xD(t)?"DEALER_CLAIM":"CUSTOM"}function pD(t,s){return`/request/${t}`}class gD extends u.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(O,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(O,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function fD({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=Aa().requestId||t||"",{user:i}=us(),{apiRequest:l,loading:o}=Gd(n,a,i);if(o&&!l)return e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(_t,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading request details..."})]})});const c=hD(l),d=M6(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function bD(t){return e.jsx(gD,{children:e.jsx(fD,{...t})})}function jD({onViewSummary:t}){const s=gs(),[a,r]=u.useState([]),[n,i]=u.useState(!0),[l,o]=u.useState(""),[c,d]=u.useState(1),[m,p]=u.useState(1),[x,h]=u.useState(0),g=10,f=u.useCallback(async(v=1)=>{try{i(!0);const N=await Pk({page:v,limit:g});r(N.data||[]),p(N.pagination.totalPages||1),h(N.pagination.total||0),d(N.pagination.page||1)}catch(N){console.error("Failed to fetch shared summaries:",N),Q.error("Failed to load shared summaries")}finally{i(!1)}},[]);u.useEffect(()=>{f(1)},[f]);const b=async v=>{try{await M0(v),r(N=>N.map(T=>T.sharedSummaryId===v?{...T,isRead:!0,viewedAt:new Date().toISOString()}:T)),t?t(v):s(`/shared-summaries/${v}`)}catch(N){console.error("Failed to mark as viewed:",N),t?t(v):s(`/shared-summaries/${v}`)}},y=v=>{v>=1&&v<=m&&f(v)},j=a.filter(v=>{var T,A,k,D;if(!l)return!0;const N=l.toLowerCase();return((T=v.title)==null?void 0:T.toLowerCase().includes(N))||((A=v.requestNumber)==null?void 0:A.toLowerCase().includes(N))||((k=v.initiatorName)==null?void 0:k.toLowerCase().includes(N))||((D=v.sharedByName)==null?void 0:D.toLowerCase().includes(N))});return e.jsx("div",{className:"min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden",children:e.jsxs("div",{className:"max-w-7xl mx-auto w-full",children:[e.jsxs("div",{className:"mb-4 sm:mb-6",children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900 mb-1 sm:mb-2",children:"Shared Summaries"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600",children:"View summaries of closed requests shared with you"})]}),e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs("div",{className:"relative",children:[e.jsx(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(_e,{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&&j.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(Ee,{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&&j.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-3 sm:gap-4 mb-4 sm:mb-6",children:j.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(py,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(wt,{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(Wt,{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(Wt,{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(bt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",st(new Date(v.sharedAt),"MMM dd, yyyy HH:mm")]})]}),v.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(wt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",st(new Date(v.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(O,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:N=>{N.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,x)," of ",x," summaries"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(O,{variant:"outline",size:"sm",onClick:()=>y(c-1),disabled:c===1,className:"text-xs sm:text-sm",children:"Previous"}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 whitespace-nowrap",children:["Page ",c," of ",m]}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>y(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function yD(){const{sharedSummaryId:t}=Aa(),s=gs(),[a,r]=u.useState(null),[n,i]=u.useState(!0);u.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,p;try{i(!0);try{await M0(t)}catch(h){console.warn("Failed to mark as viewed:",h)}const x=await Qd(t);r(x)}catch(x){console.error("Failed to fetch summary details:",x),Q.error(((p=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:p.message)||"Failed to load summary"),s("/shared-summaries")}finally{i(!1)}})()},[t,s]);const l=d=>{const m=d.toLowerCase();return m==="approved"?e.jsx(Ve,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(At,{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(Ee,{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(O,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(Cs,{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(oe,{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(Ls,{content:a.description,className:"text-gray-700"})})]}),e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Initiator"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:st(new Date(a.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),a.approvers&&a.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),a.approvers.map((d,m)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsxs("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:["Approver ",d.levelNumber]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:d.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(d.designation,d.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[l(d.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:d.status})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:st(new Date(d.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:d.remarks})]})]},m))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),a.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(oe,{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(Ls,{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(Ee,{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(O,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function vD(){const{requestId:t}=Aa(),s=gs(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(Lt,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(_0,{requestId:t||""})})})}function ib({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(oe,{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 ma({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:l,testId:o="stats-card",onClick:c}){return e.jsx(Z,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":o,onClick:c,children:e.jsx(ee,{className:"p-3 sm:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:`text-xs sm:text-sm font-medium ${i}`,"data-testid":`${o}-label`,children:t}),e.jsx("p",{className:`text-xl sm:text-2xl font-bold ${l}`,"data-testid":`${o}-value`,children:s})]}),e.jsx(a,{className:`w-6 h-6 sm:w-8 sm:h-8 ${r}`,"data-testid":`${o}-icon`})]})})})}function ND({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(ma,{label:"Total",value:t.total,icon:Ee,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(ma,{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(ma,{label:"Paused",value:t.paused,icon:pr,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(ma,{label:"Approved",value:t.approved,icon:Ve,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(ma,{label:"Rejected",value:t.rejected,icon:At,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(ma,{label:"Draft",value:t.draft,icon:Ml,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(ma,{label:"Closed",value:t.closed,icon:Ll,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 wD({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,onSearchChange:n,onStatusChange:i,onPriorityChange:l,onTemplateTypeChange:o}){return e.jsx(Z,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(ee,{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-3 sm:gap-4 items-start md:items-center",children:[e.jsxs("div",{className:"flex-1 relative w-full",children:[e.jsx(Jt,{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(_e,{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(Ye,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"Status"})}),e.jsxs(Qe,{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(Ye,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"Priority"})}),e.jsxs(Qe,{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(Ye,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"Template Type"})}),e.jsxs(Qe,{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 CD(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ma,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 SD(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ve,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:At,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:Ve,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ml,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ze,iconColor:"text-gray-600"}}}const AD=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 TD({request:t,index:s,onViewRequest:a}){var o;const r=SD(t.status),n=CD(t.priority),i=r.icon,l=n.icon;return e.jsx(Gt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(Z,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(ee,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(oe,{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(oe,{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(pr,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(oe,{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(oe,{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:AD(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:"})," ",_a(t.submittedDate)]})]})]}),e.jsx(ys,{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(Ks,{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(Wt,{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(Ks,{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: ",_a(t.submittedDate)]})]})]})]})})})})}function kD({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(Z,{"data-testid":"loading-state",children:e.jsx(ee,{className:"p-6 text-sm text-gray-600",children:"Loading your requests…"})});if(t.length===0){const l=a||r!=="all"||n!=="all";return e.jsx(Z,{"data-testid":"empty-state",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(Ee,{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(TD,{request:l,index:o,onViewRequest:i},l.id))})}function DD(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 lb(t){return Array.isArray(t)?t.map(DD):[]}function RD({itemsPerPage:t=10}={}){const[s,a]=u.useState([]),[r,n]=u.useState(!1),[i,l]=u.useState(!1),[o,c]=u.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=u.useCallback(async(m=1,p)=>{try{m===1&&(n(!0),a([]));const x=await Xs.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(x==null?void 0:x.data)?x.data:[],g=lb(h);a(g),l(!0);const f=x==null?void 0:x.pagination;f&&c({currentPage:f.page||1,totalPages:f.totalPages||1,totalRecords:f.total||0,itemsPerPage:t})}catch(x){console.error("[MyRequests] Error fetching requests:",x),a([]),l(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:o,fetchMyRequests:d}}const ID={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},ob=An({name:"myRequests",initialState:ID,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:FD,setStatusFilter:PD,setPriorityFilter:ED,setTemplateTypeFilter:_D,setCurrentPage:MD,clearFilters:LD}=ob.actions;function OD({onFiltersChange:t,debounceMs:s=500}={}){const a=yi(),r=u.useRef(null),n=u.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d}=kn(y=>y.myRequests),m=u.useCallback(y=>a(FD(y)),[a]),p=u.useCallback(y=>a(PD(y)),[a]),x=u.useCallback(y=>a(ED(y)),[a]),h=u.useCallback(y=>a(_D(y)),[a]),g=u.useCallback(y=>a(MD(y)),[a]),f=u.useCallback(()=>({search:i,status:l,priority:o,templateType:c}),[i,l,o,c]);u.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const y=setTimeout(()=>{t&&t(f())},i?s:0);return r.current=y,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,t,f,s]);const b=u.useCallback(()=>{a(LD())},[a]);return{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d,setSearchTerm:m,setStatusFilter:p,setPriorityFilter:x,setTemplateTypeFilter:h,setCurrentPage:g,getFilters:f,resetFilters:b}}function $D({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=us(),r=RD({itemsPerPage:10}),n=u.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=OD(),l=u.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}),o=u.useRef(!1);u.useEffect(()=>{const y=i.currentPage||1;n.current(y,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),o.current=!0},[]),u.useEffect(()=>{if(!o.current)return;const y=l.current;if(!(y.searchTerm!==i.searchTerm||y.statusFilter!==i.statusFilter||y.priorityFilter!==i.priorityFilter||y.templateTypeFilter!==i.templateTypeFilter))return;const 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!==y.searchTerm?500:0);return()=>clearTimeout(v)},[i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter]);const[c,d]=u.useState(null),[m,p]=u.useState(!1),x=u.useCallback(async()=>{if(a!=null&&a.userId)try{p(!0);const y=await $t.getRequestStats("all",void 0,void 0,void 0,i.priorityFilter!=="all"?i.priorityFilter:void 0,i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0,void 0,a.userId,void 0,void 0,i.searchTerm||void 0,void 0,!0);d({total:y.totalRequests||0,pending:y.openRequests||0,paused:y.pausedRequests||0,approved:y.approvedRequests||0,rejected:y.rejectedRequests||0,draft:y.draftRequests||0,closed:y.closedRequests||0})}catch(y){console.error("Failed to fetch backend stats:",y),d(null)}finally{p(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter,i.templateTypeFilter]);u.useEffect(()=>{const y=setTimeout(()=>{x()},i.searchTerm?500:0);return()=>clearTimeout(y)},[i.searchTerm,i.priorityFilter,i.templateTypeFilter,x]);const h=lb(s),g=r.hasFetchedFromApi?r.requests:h,f=u.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=u.useCallback(y=>{y>=1&&y<=r.pagination.totalPages&&(i.setCurrentPage(y),r.fetchMyRequests(y,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}))},[r,i]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"my-requests-page",children:[e.jsx(ib,{icon:Ee,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(ND,{stats:f,onStatusFilter:y=>{i.setStatusFilter(y)}}),e.jsx(wD,{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(kD,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(Zr,{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 cb({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(ib,{icon:Ee,title:i(),description:l(),testId:"requests-header"}),e.jsx(oe,{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(O,{onClick:n,disabled:r||a,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-button",children:r?e.jsxs(e.Fragment,{children:[e.jsx(_t,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function db({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(ma,{label:"Total",value:t.total,icon:Ee,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(ma,{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(ma,{label:"Paused",value:t.paused,icon:pr,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(ma,{label:"Approved",value:t.approved,icon:Ve,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(ma,{label:"Rejected",value:t.rejected,icon:At,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(ma,{label:"Closed",value:t.closed,icon:Ll,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 UD=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ma,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"}}},Bh=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Ve,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected",icon:At,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:Ve,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"draft",icon:Ml,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:Ze,iconColor:"text-gray-600"}}},BD=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 zD(t){return t==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function VD({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:Bh(t.status).icon,label:i}:Bh(t.status),c=UD(t.priority),d=o.icon,m=c.icon;return e.jsx(Gt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(Z,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(ee,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(oe,{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(oe,{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(pr,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(oe,{variant:"outline",className:`${c.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(m,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const x=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",h=(x==null?void 0:x.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(oe,{variant:"outline",className:`${f} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:g})})(),t.department&&e.jsx(oe,{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:BD(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:"})," ",_a(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?zD(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(ys,{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(Ks,{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(Wt,{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(Ks,{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: ",_a(t.submittedDate)]})]})]})]})})})})}function mb({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(Z,{"data-testid":"loading-state",children:e.jsx(ee,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(Z,{"data-testid":"empty-state",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(Ee,{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(VD,{request:n,index:i,onViewRequest:r},n.id))})}const WD={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},ub=An({name:"requests",initialState:WD,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:HD,setStatusFilter:GD,setPriorityFilter:YD,setTemplateTypeFilter:QD,setRequestTypeFilter:KD,setForm16FinancialYear:XD,setForm16Quarter:JD,setSlaComplianceFilter:ZD,setDepartmentFilter:qD,setInitiatorFilter:eR,setApproverFilter:tR,setApproverFilterType:sR,setDateRange:zh,setCustomStartDate:Mo,setCustomEndDate:Lo,setShowCustomDatePicker:Ui,setCurrentPage:aR,clearFilters:rR}=ub.actions;function xb(){const t=yi(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,requestTypeFilter:i,form16FinancialYear:l,form16Quarter:o,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:m,approverFilter:p,approverFilterType:x,dateRange:h,customStartDate:g,customEndDate:f,showCustomDatePicker:b,currentPage:y}=kn(B=>B.requests),j=u.useCallback(B=>t(HD(B)),[t]),v=u.useCallback(B=>t(GD(B)),[t]),N=u.useCallback(B=>t(YD(B)),[t]),T=u.useCallback(B=>t(QD(B)),[t]),A=u.useCallback(B=>t(KD(B)),[t]),k=u.useCallback(B=>t(XD(B)),[t]),D=u.useCallback(B=>t(JD(B)),[t]),F=u.useCallback(B=>t(ZD(B)),[t]),w=u.useCallback(B=>t(qD(B)),[t]),L=u.useCallback(B=>t(eR(B)),[t]),_=u.useCallback(B=>t(tR(B)),[t]),W=u.useCallback(B=>t(sR(B)),[t]),I=u.useCallback(B=>t(zh(B)),[t]),$=u.useCallback(B=>t(Mo(B)),[t]),M=u.useCallback(B=>t(Lo(B)),[t]),R=u.useCallback(B=>t(Ui(B)),[t]),C=u.useCallback(B=>t(aR(B)),[t]),H=u.useCallback(()=>n==="FORM_16"?{templateType:"FORM_16",financialYear:l!=="all"?l:void 0,quarter:o!=="all"?o:void 0}:{search:s||void 0,status:a!=="all"?a:void 0,priority:r!=="all"?r:void 0,templateType:n!=="all"?n:void 0,slaCompliance:c!=="all"?c:void 0,department:d!=="all"?d:void 0,initiator:m!=="all"?m:void 0,approver:p!=="all"?p:void 0,approverType:p!=="all"?x:void 0,dateRange:h,startDate:g,endDate:f},[s,a,r,n,l,o,c,d,m,p,x,h,g,f]),z=u.useCallback(()=>{t(rR())},[t]),P=u.useCallback(B=>{const E=B;t(zh(E)),E!=="custom"?(t(Mo(void 0)),t(Lo(void 0)),t(Ui(!1))):t(Ui(!0))},[t]),S=u.useCallback(()=>{g&&f&&(g>f&&(t(Mo(f)),t(Lo(g))),t(Ui(!1)))},[g,f,t]),U=n==="FORM_16";return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,requestTypeFilter:i,form16FinancialYear:l,form16Quarter:o,isForm16:U,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:m,approverFilter:p,approverFilterType:x,dateRange:h,customStartDate:g,customEndDate:f,showCustomDatePicker:b,currentPage:y,hasActiveFilters:U?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:j,setStatusFilter:v,setPriorityFilter:N,setTemplateTypeFilter:T,setRequestTypeFilter:A,setForm16FinancialYear:k,setForm16Quarter:D,setSlaComplianceFilter:F,setDepartmentFilter:w,setInitiatorFilter:L,setApproverFilter:_,setApproverFilterType:W,setDateRange:I,setCustomStartDate:$,setCustomEndDate:M,setShowCustomDatePicker:R,setCurrentPage:C,getFilters:H,clearFilters:z,handleDateRangeChange:P,handleApplyCustomDate:S}}function yl({filterValue:t,onFilterChange:s,source:a="default"}){const[r,n]=u.useState(""),[i,l]=u.useState([]),[o,c]=u.useState(!1),[d,m]=u.useState(null),[p,x]=u.useState(!1),h=u.useRef(null);u.useEffect(()=>{async function y(){if(t!=="all"&&!d)try{const j=await ua.getUserById(t);j&&(m(j),n(j.displayName||j.email))}catch(j){console.error("Failed to fetch user detail for search:",j)}else t==="all"&&(m(null),n(""))}y()},[t]),u.useEffect(()=>()=>{h.current&&clearTimeout(h.current)},[]);const g=u.useCallback(y=>{if(n(y),h.current&&clearTimeout(h.current),!y||y.trim().length<2){l([]),c(!1);return}h.current=setTimeout(async()=>{var j;x(!0);try{const N=((j=(await ua.searchUsers(y.trim(),10,a)).data)==null?void 0:j.data)||[];l(N),c(N.length>0)}catch(v){console.error("Search API failed:",v),l([]),c(!1)}finally{x(!1)}},400)},[a]),f=u.useCallback(y=>{m(y),s(y.userId),n(y.displayName||y.email),c(!1),l([])},[s]),b=u.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 nR(t){var d,m,p,x,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(y=>{const j=(y.status||"").toString().toUpperCase();return j==="PENDING"||j==="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 j=[...t.approvals].sort((v,N)=>{const T=v.levelNumber||v.level_number||0;return(N.levelNumber||N.level_number||0)-T})[0];j&&(n=j.approverName||((x=j.approver)==null?void 0:x.name)||((h=j.approver)==null?void 0:h.displayName)||j.approverEmail||((g=j.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(y=>{const j=(y.status||"").toString().toUpperCase();return j==="PENDING"||j==="IN_PROGRESS"});if(b){const y=b.levelNumber||b.level_number||0,j=c||t.approvals.length;i=`${y} of ${j}`}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 hb(t){return Array.isArray(t)?t.map(nR):[]}function iR(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,x=t.filter(h=>(h.status||"").toString().toUpperCase()==="PAUSED").length;return{total:l,pending:o,paused:x,approved:c,rejected:d,draft:m,closed:p}}else return s&&a?{total:a.total,pending:a.pending,paused:a.paused||0,approved:a.approved,rejected:a.rejected,draft:a.draft,closed:a.closed}:{total:n||i.length,pending:i.filter(o=>o.status==="pending"||o.status==="in-progress").length,paused:i.filter(o=>o.status==="paused").length,approved:i.filter(o=>o.status==="approved").length,rejected:i.filter(o=>o.status==="rejected").length,draft:i.filter(o=>o.status==="draft").length,closed:i.filter(o=>o.status==="closed").length}}var pb={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Cl,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(pb);var lR=pb.exports;const gb=Sl(lR);var fb={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Cl,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(fb);var oR=fb.exports;const bb=Sl(oR);rs.extend(bb);rs.extend(gb);function cR(t,s){let a=[...t];if(s.search){const r=s.search.toLowerCase();a=a.filter(n=>{var i,l,o,c;return((i=n.title)==null?void 0:i.toLowerCase().includes(r))||((l=n.description)==null?void 0:l.toLowerCase().includes(r))||((o=n.requestNumber)==null?void 0:o.toLowerCase().includes(r))||((c=n.request_number)==null?void 0:c.toLowerCase().includes(r))})}if(s.status&&s.status!=="all")if(s.status.toLowerCase()==="pending")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return(n==="PENDING"||n==="IN_PROGRESS")&&!i});else if(s.status.toLowerCase()==="paused")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return n==="PAUSED"||i});else{const r=s.status.toUpperCase().replace("-","_");a=a.filter(n=>{var o;const i=(n.status||"").toString().toUpperCase(),l=((o=n.pauseInfo)==null?void 0:o.isPaused)||n.isPaused||!1;return r==="IN_PROGRESS"||r==="IN-PROGRESS"?i==="IN_PROGRESS"&&!l:i===r&&!l})}if(s.priority&&s.priority!=="all"&&(a=a.filter(r=>{var n;return(r.priority||"").toString().toLowerCase()===((n=s.priority)==null?void 0:n.toLowerCase())})),s.department&&s.department!=="all"&&(a=a.filter(r=>{var i;return(r.department||((i=r.initiator)==null?void 0:i.department)||"")===s.department})),s.initiator&&s.initiator!=="all"&&(a=a.filter(r=>{var i,l;return(r.initiatorId||r.initiator_id||((i=r.initiator)==null?void 0:i.userId)||((l=r.initiator)==null?void 0:l.user_id)||(r.initiator&&typeof r.initiator=="object"&&"userId"in r.initiator?r.initiator.userId:null))===s.initiator})),s.approver&&s.approver!=="all"&&((s.approverType||"current")==="current"?a=a.filter(n=>{var l,o,c,d,m,p;return(((l=n.currentApprover)==null?void 0:l.userId)||((o=n.currentApprover)==null?void 0:o.user_id)||((d=(c=n.approvals)==null?void 0:c.find(x=>{const h=(x.status||"").toString().toUpperCase();return h==="IN_PROGRESS"||h==="PENDING"}))==null?void 0:d.approverId)||((p=(m=n.approvals)==null?void 0:m.find(x=>{const h=(x.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,x,h,g,f,b,y,j,v;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const N=(r.status||"").toString().toUpperCase();if(!(N==="APPROVED"||N==="REJECTED"||N==="CLOSED"))return!1;const A=((c=r.currentLevelSLA)==null?void 0:c.status)||((m=(d=r.currentApprover)==null?void 0:d.sla)==null?void 0:m.status)||((p=r.sla)==null?void 0:p.status)||((h=(x=r.summary)==null?void 0:x.sla)==null?void 0:h.status);return A?A!=="breached"&&A.toLowerCase()!=="breached":!0}const i=((g=r.currentLevelSLA)==null?void 0:g.status)||((b=(f=r.currentApprover)==null?void 0:f.sla)==null?void 0:b.status)||((y=r.sla)==null?void 0:y.status)||((v=(j=r.summary)==null?void 0:j.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(),x=rs(r).startOf("day").toDate(),h=rs(n).endOf("day").toDate();return p>=x&&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(gb);rs.extend(bb);function dR(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return st(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function jb(t,s){const a=cR(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var j,v,N,T,A;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),p=((j=c.initiator)==null?void 0:j.displayName)||((v=c.initiator)==null?void 0:v.email)||c.initiatorName||"N/A",x=c.department||((N=c.initiator)==null?void 0:N.department)||"N/A",h=((T=c.currentApprover)==null?void 0:T.displayName)||((A=c.currentApprover)==null?void 0:A.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",f=dR(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),b=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),y=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${p.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,`"${h.replace(/"/g,'""')}"`,g,f,`"${b}"`];r.push(y.join(","))});const n=r.join(`
`),i=new Blob([n],{type:"text/csv;charset=utf-8;"}),l=document.createElement("a"),o=URL.createObjectURL(i);l.setAttribute("href",o),l.setAttribute("download",`requests-export-${new Date().toISOString().split("T")[0]}.csv`),l.style.visibility="hidden",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o)}async function mR({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 Xs.listWorkflows({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const p=m.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:p.length,totalPages:1};return{data:p,allData:[],filteredData:p,pagination:{page:x.page,limit:x.limit||s,total:x.total||p.length,totalPages:x.totalPages||1}}}else{const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),(a==null?void 0:a.templateType)==="FORM_16"&&(a!=null&&a.financialYear&&(c.financialYear=a.financialYear),a!=null&&a.quarter&&(c.quarter=a.quarter)),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(l=a.startDate)==null?void 0:l.toISOString()),a!=null&&a.endDate&&(c.endDate=(o=a.endDate)==null?void 0:o.toISOString());const d=await Xs.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"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:p.length,totalPages:1};return{data:p,allData:[],filteredData:p,pagination:x}}}async function uR(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const l=t?await Xs.listWorkflows({page:r,limit:100}):await Xs.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 xR({onViewRequest:t}){const{user:s}=us(),a=kn(z=>z.dashboard.viewAsUser),r=u.useMemo(()=>Ul(s),[s]),n=u.useMemo(()=>r&&!a,[r,a]),i=xb(),[l,o]=u.useState([]),[c,d]=u.useState(!1),[m,p]=u.useState(!1),[x,h]=u.useState(null),[g,f]=u.useState([]),[b,y]=u.useState(!1),[j,v]=u.useState(1),[N,T]=u.useState(0),[A]=u.useState(10),k=yl({filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter,source:"local"}),D=yl({filterValue:i.approverFilter,onFilterChange:i.setApproverFilter,source:"local"}),F=u.useCallback(async(z,P,S,U)=>{try{const Y=U==null?void 0:U.slaCompliance;if(Y&&Y!=="all"&&Y!=="breached"&&Y!=="compliant"){const E={};U!=null&&U.search&&(E.search=U.search),U!=null&&U.priority&&U.priority!=="all"&&(E.priority=U.priority),U!=null&&U.department&&U.department!=="all"&&(E.department=U.department),U!=null&&U.initiator&&U.initiator!=="all"&&(E.initiator=U.initiator),U!=null&&U.approver&&U.approver!=="all"&&(E.approver=U.approver,E.approverType=U.approverType||"current"),E.slaCompliance=Y,z&&(E.dateRange=z),P&&(E.startDate=P.toISOString()),S&&(E.endDate=S.toISOString());const V=n?await Xs.listWorkflows({page:1,limit:1e3,...E}):await Xs.listParticipantRequests({page:1,limit:1e3,...E}),G=Array.isArray(V==null?void 0:V.data)?V.data:[],J=G.length,q=G.filter(ge=>{const we=(ge.status||"").toString().toUpperCase();return we==="PENDING"||we==="IN_PROGRESS"}).length,se=G.filter(ge=>(ge.status||"").toString().toUpperCase()==="APPROVED").length,ne=G.filter(ge=>(ge.status||"").toString().toUpperCase()==="REJECTED").length,te=G.filter(ge=>(ge.status||"").toString().toUpperCase()==="CLOSED").length;h({total:J,pending:q,paused:0,approved:se,rejected:ne,draft:0,closed:te})}else{const E=await $t.getRequestStats(z,P?P.toISOString():void 0,S?S.toISOString():void 0,void 0,U==null?void 0:U.priority,U==null?void 0:U.templateType,U==null?void 0:U.department,U==null?void 0:U.initiator,U==null?void 0:U.approver,U==null?void 0:U.approverType,U==null?void 0:U.search,U==null?void 0:U.slaCompliance,!n);h({total:E.totalRequests||0,pending:E.openRequests||0,paused:E.pausedRequests||0,approved:E.approvedRequests||0,rejected:E.rejectedRequests||0,draft:E.draftRequests||0,closed:E.closedRequests||0})}}catch(Y){console.error("Failed to fetch backend stats:",Y)}finally{}},[n]),w=u.useCallback(async()=>{try{y(!0);const z=await $t.getDepartments();f(z)}catch{}finally{y(!1)}},[]),L=u.useRef(i),_=u.useRef(F);u.useEffect(()=>{L.current=i,_.current=F},[i,F]),u.useEffect(()=>{const z=new URLSearchParams(window.location.search),P=z.get("approver"),S=z.get("approverType"),U=z.get("slaCompliance"),Y=z.get("dateRange"),B=z.get("startDate"),E=z.get("endDate");P&&i.setApproverFilter(P),(S==="current"||S==="any")&&i.setApproverFilterType(S),U&&i.setSlaComplianceFilter(U),Y&&i.setDateRange(Y),B&&i.setCustomStartDate(new Date(B)),E&&i.setCustomEndDate(new Date(E))},[]);const W=u.useCallback(async(z=1)=>{try{z===1&&(d(!0),o([]));const P=L.current.getFilters(),S=await mR({page:z,itemsPerPage:A,filters:P,isOrgLevel:n});o(S.data),i.setCurrentPage(S.pagination.page),v(S.pagination.totalPages),T(S.pagination.total)}catch{o([])}finally{d(!1)}},[A,n]),I=u.useCallback(async()=>{try{p(!0);const z=await uR(n);await jb(z,i.getFilters())}catch(z){console.error("Failed to export requests:",z),alert("Failed to export requests. Please try again.")}finally{p(!1)}},[n,i]);u.useEffect(()=>{w()},[w]),u.useEffect(()=>{const z=setTimeout(()=>{const P={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},S=i.dateRange||"all";_.current(S,i.customStartDate,i.customEndDate,P)},i.searchTerm?500:0);return()=>clearTimeout(z)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.templateTypeFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const $=u.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}),M=u.useRef(!1);u.useEffect(()=>{const z=i.currentPage||1;W(z),M.current=!0},[]),u.useEffect(()=>{if(!M.current)return;const z=$.current;if(!(z.searchTerm!==i.searchTerm||z.statusFilter!==i.statusFilter||z.priorityFilter!==i.priorityFilter||z.templateTypeFilter!==i.templateTypeFilter||z.form16FinancialYear!==i.form16FinancialYear||z.form16Quarter!==i.form16Quarter||z.slaComplianceFilter!==i.slaComplianceFilter||z.departmentFilter!==i.departmentFilter||z.initiatorFilter!==i.initiatorFilter||z.approverFilter!==i.approverFilter||z.approverFilterType!==i.approverFilterType||z.dateRange!==i.dateRange||z.customStartDate!==i.customStartDate||z.customEndDate!==i.customEndDate||z.isOrgLevel!==n))return;const S=setTimeout(()=>{i.setCurrentPage(1),W(1),$.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,form16FinancialYear:i.form16FinancialYear,form16Quarter:i.form16Quarter,slaComplianceFilter:i.slaComplianceFilter,departmentFilter:i.departmentFilter,initiatorFilter:i.initiatorFilter,approverFilter:i.approverFilter,approverFilterType:i.approverFilterType,dateRange:i.dateRange,customStartDate:i.customStartDate,customEndDate:i.customEndDate,isOrgLevel:n}},i.searchTerm!==z.searchTerm?500:0);return()=>clearTimeout(S)},[n,i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter,i.form16FinancialYear,i.form16Quarter,i.slaComplianceFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.dateRange,i.customStartDate,i.customEndDate]);const R=u.useCallback(z=>{z>=1&&z<=j&&(i.setCurrentPage(z),W(z))},[j,W,i]),C=u.useMemo(()=>hb(l),[l]),H=u.useMemo(()=>x?{total:x.total||0,pending:x.pending||0,paused:x.paused||0,approved:x.approved||0,rejected:x.rejected||0,draft:x.draft||0,closed:x.closed||0}:iR([],n,x,!1,N,C),[n,x,N,C]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(cb,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:I}),e.jsx(db,{stats:H,onStatusFilter:z=>{i.setStatusFilter(z)}}),e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(ee,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(oe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(O,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx(_t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Zt,{}),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(re,{className:"text-sm font-medium text-gray-700",children:"All Templates"}),e.jsxs(He,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(Ye,{className:"h-10 w-[180px]","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Qe,{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(re,{className:"text-sm font-medium text-gray-700",children:"Financial Year"}),e.jsxs(He,{value:i.form16FinancialYear,onValueChange:i.setForm16FinancialYear,children:[e.jsx(Ye,{className:"h-10 w-[140px]","data-testid":"form16-financial-year-filter",children:e.jsx(Ge,{placeholder:"Financial Year"})}),e.jsxs(Qe,{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(re,{className:"text-sm font-medium text-gray-700",children:"Quarter"}),e.jsxs(He,{value:i.form16Quarter,onValueChange:i.setForm16Quarter,children:[e.jsx(Ye,{className:"h-10 w-[130px]","data-testid":"form16-quarter-filter",children:e.jsx(Ge,{placeholder:"Quarter"})}),e.jsxs(Qe,{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(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(_e,{placeholder:"Search requests...",value:i.searchTerm,onChange:z=>i.setSearchTerm(z.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Qe,{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(Ye,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"All Priority"})}),e.jsxs(Qe,{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(Ye,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Qe,{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(Ye,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ge,{placeholder:b?"Loading...":"All Departments"})}),e.jsxs(Qe,{children:[e.jsx(X,{value:"all",children:"All Departments"}),g.map(z=>e.jsx(X,{value:z,children:z},z))]})]}),e.jsxs(He,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"All SLA Status"})}),e.jsxs(Qe,{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(re,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:k.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:k.selectedUser.displayName||k.selectedUser.email}),e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:k.handleClear,children:e.jsx(vt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{placeholder:"Search initiator...",value:k.searchQuery,onChange:z=>k.handleSearch(z.target.value),onFocus:()=>{k.searchResults.length>0&&k.setShowResults(!0)},onBlur:()=>setTimeout(()=>k.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),k.showResults&&k.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:k.searchResults.map(z=>e.jsx("button",{type:"button",onClick:()=>k.handleSelect(z),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:z.displayName||z.email}),z.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:z.email})]})},z.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(He,{value:i.approverFilterType,onValueChange:z=>i.setApproverFilterType(z),children:[e.jsx(Ye,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Qe,{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(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:D.handleClear,children:e.jsx(vt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{placeholder:"Search approver...",value:D.searchQuery,onChange:z=>D.handleSearch(z.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(z=>e.jsx("button",{type:"button",onClick:()=>D.handleSelect(z),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:z.displayName||z.email}),z.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:z.email})]})},z.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(bt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Ye,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Qe,{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(na,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(bt,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${st(i.customStartDate,"MMM d, yyyy")} - ${st(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(la,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",children:"Start Date"}),e.jsx(aa,{value:i.customStartDate||null,onChange:z=>{const P=z?new Date(z):void 0;P?(i.setCustomStartDate(P),i.customEndDate&&P>i.customEndDate&&i.setCustomEndDate(P)):i.setCustomStartDate(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",children:"End Date"}),e.jsx(aa,{value:i.customEndDate||null,onChange:z=>{const P=z?new Date(z):void 0;P?(i.setCustomEndDate(P),i.customStartDate&&P<i.customStartDate&&i.setCustomStartDate(P)):i.setCustomEndDate(void 0)},minDate:i.customStartDate||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsx(O,{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(O,{size:"sm",variant:"outline",onClick:()=>{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})})]})})]})]})]})]})})}),e.jsx(mb,{requests:C,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(Zr,{currentPage:i.currentPage||1,totalPages:j,totalRecords:N,itemsPerPage:A,onPageChange:R,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function hR({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 Xs.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 Vh=100;async function pR(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 Xs.listParticipantRequests({page:r,limit:Vh,...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===Vh}}return s}function gR({onViewRequest:t}){const s=xb(),a=u.useMemo(()=>{try{const Y=nt.getUserData();return md(Y)}catch(Y){return console.error("[UserAllRequests] Error getting user filter type:",Y),"STANDARD"}},[]),r=u.useMemo(()=>$6(a),[a]),n=a==="DEALER",i=u.useCallback(()=>{const Y=s.getFilters();if(!n)return Y;const B=s.requestTypeFilter;if(B==="form_16")return{templateType:"FORM_16",financialYear:s.form16FinancialYear!=="all"?s.form16FinancialYear:void 0,quarter:s.form16Quarter!=="all"?s.form16Quarter:void 0};if(B==="claim_management")return{templateType:"DEALER CLAIM",search:Y.search,status:Y.status!=="all"?Y.status:void 0,dateRange:Y.dateRange,startDate:Y.startDate,endDate:Y.endDate,initiator:Y.initiator,approver:Y.approver,approverType:Y.approverType};const{priority:E,templateType:V,department:G,slaCompliance:J,...q}=Y;return q},[s,n]),l=u.useCallback(()=>{if(n){const Y=s.requestTypeFilter;return Y==="form_16"?s.form16FinancialYear!=="all"||s.form16Quarter!=="all":Y==="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]=u.useState([]),[d,m]=u.useState(!1),[p,x]=u.useState(!1),[h,g]=u.useState(null),[f,b]=u.useState([]),[y,j]=u.useState(!1),[v,N]=u.useState(!1),[T,A]=u.useState(1),[k,D]=u.useState(0),[F]=u.useState(10),w=yl({filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter,source:"local"}),L=yl({filterValue:s.approverFilter,onFilterChange:s.setApproverFilter,source:"local"}),_=u.useCallback(async(Y,B,E,V)=>{try{const G=await $t.getRequestStats(Y,B?B.toISOString():void 0,E?E.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:G.totalRequests||0,pending:G.openRequests||0,paused:G.pausedRequests||0,approved:G.approvedRequests||0,rejected:G.rejectedRequests||0,draft:G.draftRequests||0,closed:G.closedRequests||0})}catch(G){console.error("Failed to fetch backend stats:",G)}},[]),W=u.useCallback(async()=>{try{j(!0);const Y=await $t.getDepartments();b(Y)}catch{}finally{j(!1)}},[]);u.useEffect(()=>{a==="STANDARD"&&td().then(Y=>N(!!(Y.canViewForm16Submission||Y.canView26AS))).catch(()=>N(!1))},[a]);const I=u.useRef(s),$=u.useRef(_),M=u.useRef(i);u.useEffect(()=>{I.current=s,$.current=_,M.current=i},[s,_,i]);const R=u.useCallback(async(Y=1)=>{try{Y===1&&(m(!0),c([]));const B=M.current(),E=await hR({page:Y,itemsPerPage:F,filters:B});c(E.data),s.setCurrentPage(E.pagination.page),A(E.pagination.totalPages),D(E.pagination.total)}catch{c([])}finally{m(!1)}},[F,s]),C=u.useCallback(async()=>{try{x(!0);const Y=i(),B=await pR(Y);await jb(B,Y)}catch(Y){console.error("Failed to export requests:",Y),alert("Failed to export requests. Please try again.")}finally{x(!1)}},[i]);u.useEffect(()=>{W()},[W]),u.useEffect(()=>{const Y=setTimeout(()=>{const B={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"&&(B.priority=s.priorityFilter),s.templateTypeFilter!=="all"&&(B.templateType=s.templateTypeFilter),s.departmentFilter!=="all"&&(B.department=s.departmentFilter),s.slaComplianceFilter!=="all"&&(B.slaCompliance=s.slaComplianceFilter));const E=s.dateRange==="all"?"all":s.dateRange||"month";$.current(E,s.customStartDate,s.customEndDate,B)},s.searchTerm?500:0);return()=>clearTimeout(Y)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter,n]);const H=u.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}),z=u.useRef(!1);u.useEffect(()=>{const Y=s.currentPage||1;R(Y),z.current=!0},[]),u.useEffect(()=>{if(!z.current)return;const Y=H.current;if(!(Y.searchTerm!==s.searchTerm||Y.statusFilter!==s.statusFilter||Y.priorityFilter!==s.priorityFilter||Y.templateTypeFilter!==s.templateTypeFilter||Y.slaComplianceFilter!==s.slaComplianceFilter||Y.departmentFilter!==s.departmentFilter||Y.initiatorFilter!==s.initiatorFilter||Y.approverFilter!==s.approverFilter||Y.approverFilterType!==s.approverFilterType||Y.dateRange!==s.dateRange||Y.customStartDate!==s.customStartDate||Y.customEndDate!==s.customEndDate))return;const E=setTimeout(()=>{s.setCurrentPage(1),R(1),H.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!==Y.searchTerm?500:0);return()=>clearTimeout(E)},[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 P=u.useCallback(Y=>{Y>=1&&Y<=T&&(s.setCurrentPage(Y),R(Y))},[T,R,s]),S=u.useMemo(()=>hb(o),[o]),U=u.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 Y=S.filter(J=>{const q=(J.status||"").toString().toLowerCase();return q==="pending"||q==="in-progress"}).length,B=S.filter(J=>(J.status||"").toString().toLowerCase()==="paused").length,E=S.filter(J=>(J.status||"").toString().toLowerCase()==="approved").length,V=S.filter(J=>(J.status||"").toString().toLowerCase()==="rejected").length,G=S.filter(J=>(J.status||"").toString().toLowerCase()==="closed").length;return{total:k>0?k:S.length,pending:Y,paused:B,approved:E,rejected:V,draft:0,closed:G}},[h,k,S]);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(cb,{isOrgLevel:!1,isAdmin:!1,loading:d,exporting:p,onExport:C}),e.jsx(db,{stats:U,onStatusFilter:Y=>{s.setStatusFilter(Y)}}),e.jsx(r,{requestTypeFilter:s.requestTypeFilter,onRequestTypeChange:Y=>s.setRequestTypeFilter(Y),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:y,initiatorSearch:w,approverSearch:L,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(mb,{requests:S,loading:d,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(Zr,{currentPage:s.currentPage||1,totalPages:T,totalRecords:k,itemsPerPage:F,onPageChange:P,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function fR(){const t=gs();return e.jsx("div",{className:"flex-1 p-3 lg:p-6 overflow-auto min-w-0","data-testid":"approver-performance-empty",children:e.jsx("div",{className:"max-w-7xl mx-auto p-4",children:e.jsx(Z,{children:e.jsxs(ee,{className:"p-8 text-center",children:[e.jsx(Ze,{className:"w-12 h-12 text-yellow-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Approver ID Required"}),e.jsx("p",{className:"text-gray-600",children:"Please select an approver to view their performance details."}),e.jsxs(O,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(Cs,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function bR({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(O,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx(_t,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function jR({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(de,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(ee,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[s,"%"]}),e.jsx("div",{className:`p-2 rounded-lg ${s>=95?"bg-green-100":s>=90?"bg-blue-100":s>=85?"bg-orange-100":"bg-red-100"}`,children:e.jsx(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(oa,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(Z,{children:[e.jsx(de,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(ee,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.totalApproved}),e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Ve,{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(de,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(ee,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[t.avgResponseHours.toFixed(1),"h"]}),e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(Hc,{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(de,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(ee,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.pendingCount}),e.jsx("div",{className:"p-2 bg-orange-100 rounded-lg",children:e.jsx(it,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function yR({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(Z,{"data-testid":"approver-actions-stats",children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Approver's Actions"}),e.jsxs(Te,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?z1(a,r,n,""):"(all time)"]})]}),e.jsxs(ee,{children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2",children:[e.jsx(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(Ve,{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(At,{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(Ll,{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(Ee,{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(gy,{className:"w-5 h-5 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:(s==null?void 0:s.tatCompliancePercent)!==void 0?`${s.tatCompliancePercent}%`:"N/A"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:(s==null?void 0:s.withinTatCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Compliant"})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Ze,{className:"w-5 h-5 text-red-600"})}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:(s==null?void 0:s.breachedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Breached"})]}),e.jsxs("div",{className:"p-4 bg-purple-50 rounded-lg border border-purple-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(ul,{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 vR({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:l,showCustomDatePicker:o,tempCustomStartDate:c,tempCustomEndDate:d,onSearchChange:m,onStatusChange:p,onPriorityChange:x,onSlaComplianceChange:h,onDateRangeChange:g,onShowCustomDatePickerChange:f,onTempStartDateChange:b,onTempEndDateChange:y,onApplyCustomDate:j,onClearFilters:v}){return e.jsxs(Z,{"data-testid":"approver-performance-filters",children:[e.jsx(de,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Filters"}),e.jsx(O,{variant:"ghost",size:"sm",onClick:v,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(_e,{placeholder:"Search requests...",value:t,onChange:N=>m(N.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:p,children:[e.jsx(Ye,{"data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"Status"})}),e.jsxs(Qe,{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:x,children:[e.jsx(Ye,{"data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"Priority"})}),e.jsxs(Qe,{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(Ye,{"data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"SLA Compliance"})}),e.jsxs(Qe,{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(bt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:n,onValueChange:g,children:[e.jsx(Ye,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Qe,{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(na,{open:o,onOpenChange:f,children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(bt,{className:"w-4 h-4"}),c&&d?`${st(c,"MMM d")} - ${st(d,"MMM d")}`:"Select dates"]})}),e.jsx(la,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(_e,{id:"start-date",type:"date",value:c?st(c,"yyyy-MM-dd"):"",onChange:N=>{const T=N.target.value?new Date(N.target.value):void 0;T?(b(T),d&&T>d&&y(T)):b(void 0)},max:st(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(_e,{id:"end-date",type:"date",value:d?st(d,"yyyy-MM-dd"):"",onChange:N=>{const T=N.target.value?new Date(N.target.value):void 0;T?(y(T),c&&T<c&&b(T)):y(void 0)},min:c?st(c,"yyyy-MM-dd"):void 0,max:st(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(O,{size:"sm",onClick:j,disabled:!c||!d,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-date-button",children:"Apply"}),e.jsx(O,{size:"sm",variant:"outline",onClick:()=>{f(!1),b(i),y(l),(!i||!l)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const NR=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ks,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"}}},wR=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ve,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:At,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:Ve,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ee,iconColor:"text-gray-600"}}},CR=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 SR(t){if(!t)return"N/A";try{return st(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function AR(t){if(!t)return"N/A";try{return st(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function vl(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=pD(s);n(l)}function TR({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const c=gs();return e.jsxs(Z,{"data-testid":"approver-performance-request-list",children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Request Details"}),e.jsxs(Te,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(ee,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(_t,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading requests..."})]}):t.length===0?e.jsxs("div",{className:"text-center py-12 text-gray-500","data-testid":"empty-state",children:[e.jsx(Ee,{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=NR(d.priority),p=wR(d.status),x=CR(d.slaStatus||""),h=m.icon,g=p.icon;return e.jsx(Z,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{vl({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm text-blue-600 hover:underline","data-testid":"request-number",children:d.requestNumber}),e.jsxs(oe,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(h,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(oe,{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(oe,{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(Ve,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(At,{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(oe,{className:x.color,"data-testid":"sla-status-badge",children:x.label})]}),e.jsx("h3",{className:"font-medium text-gray-900 mb-1 truncate","data-testid":"request-title",children:d.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-500 mt-2",children:[e.jsxs("span",{className:"flex items-center gap-1","data-testid":"initiator-info",children:[e.jsx(Wt,{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: ",SR(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(Ve,{className:"w-3 h-3"}),"Action: ",AR(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(Hc,{className:"w-3 h-3"}),Xt(d.levelElapsedHours)," / ",Xt(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(O,{variant:"ghost",size:"sm",onClick:f=>{f.stopPropagation(),vl({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(ys,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(Zr,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function kR(){const[t]=Vp(),[s,a]=u.useState(""),[r,n]=u.useState(t.get("status")||"all"),[i,l]=u.useState(t.get("priority")||"all"),[o,c]=u.useState(t.get("slaCompliance")||"all"),[d,m]=u.useState(t.get("dateRange")||"all"),[p,x]=u.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[h,g]=u.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[f,b]=u.useState(!1),[y,j]=u.useState(void 0),[v,N]=u.useState(void 0),T=u.useCallback(()=>{a(""),n("all"),l("all"),c("all"),m("all"),x(void 0),g(void 0),j(void 0),N(void 0),b(!1)},[]),A=u.useCallback(D=>{const F=D;m(F),F!=="custom"?(x(void 0),g(void 0),j(void 0),N(void 0),b(!1)):(j(p),N(h),b(!0))},[p,h]),k=u.useCallback(()=>{if(y&&v){if(y>v){const D=y;x(v),g(D),j(v),N(D)}else x(y),g(v);b(!1)}},[y,v]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:d,customStartDate:p,customEndDate:h,showCustomDatePicker:f,tempCustomStartDate:y,tempCustomEndDate:v,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:x,setCustomEndDate:g,setShowCustomDatePicker:b,setTempCustomStartDate:j,setTempCustomEndDate:N,clearFilters:T,handleDateRangeChange:A,handleApplyCustomDate:k}}function DR({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:l,searchTerm:o,itemsPerPage:c}){const[d,m]=u.useState([]),[p,x]=u.useState(null),[h,g]=u.useState([]),[f,b]=u.useState(!0),[y,j]=u.useState(!1),[v,N]=u.useState(1),[T,A]=u.useState(1),[k,D]=u.useState(0),F=u.useRef(!0),w=u.useCallback(async()=>{if(t)try{const I=s==="all"?void 0:s,$=await $t.getSingleApproverStats(t,I,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);x($)}catch(I){console.error("[ApproverPerformance] Failed to fetch approver stats:",I),x(null)}},[t,s,a,r,i,l]),L=u.useCallback(async(I=1)=>{if(!t){b(!1);return}try{b(!0);const $=await $t.getRequestsByApprover(t,I,c,s==="all"?void 0:s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,l!=="all"?l:void 0,o||void 0);m($.requests),D($.pagination.totalRecords),A($.pagination.totalPages),N($.pagination.currentPage),g($.requests)}catch($){console.error("Failed to fetch requests:",$)}finally{b(!1),j(!1)}},[t,s,a,r,n,i,l,o,c]);u.useEffect(()=>{F.current&&(F.current=!1,w(),L(1))},[]),u.useEffect(()=>{F.current||w()},[s,a,r,i,l]),u.useEffect(()=>{F.current||L(1)},[s,a,r,n,i,l,o]);const _=u.useCallback(()=>{j(!0),w(),L(1)},[w,L]),W=u.useCallback(I=>{L(I)},[L]);return{requests:d,approverStats:p,allFilteredRequests:h,loading:f,refreshing:y,currentPage:v,totalPages:T,totalRecords:k,handleRefresh:_,handlePageChange:W}}const Wh=10;function RR(){const[t]=Vp(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=kR(),n=DR({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:Wh});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(bR,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(jR,{approverStats:n.approverStats}),n.approverStats&&e.jsx(yR,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(vR,{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(TR,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:Wh,onPageChange:n.handlePageChange})]}):e.jsx(fR,{})}function IR(){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(ee,{className:"relative z-10 p-8 lg:p-12",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-start md:items-center gap-6",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(ds,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(zl,{src:(t==null?void 0:t.picture)||""}),e.jsx(ms,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),Er(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(bs,{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:[Er(t)&&e.jsxs(oe,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(bs,{className:"w-3 h-3 mr-1"}),"Administrator"]}),On(t)&&e.jsxs(oe,{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(oe,{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(de,{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(Wt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(Te,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(ee,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Ca,{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(Wt,{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(Wt,{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(Wt,{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(bi,{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(de,{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(Ou,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(Te,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(ee,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[(t==null?void 0:t.employeeId)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Wt,{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(Uc,{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(Ou,{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(bs,{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(oe,{variant:Er(t)||On(t)?"default":"secondary",className:Er(t)?"bg-yellow-400 text-slate-900":On(t)?"bg-blue-400 text-slate-900":"",children:Er(t)?"Administrator":On(t)?"Management":"User"}),(Er(t)||On(t))&&e.jsx(Ve,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(de,{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(bt,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(Te,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-green-50 rounded-lg border border-green-200",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-green-500 rounded-full",children:e.jsx(Ve,{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(oe,{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 Bi="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",FR="https://reflow-uat.royalenfield.com/";function Oo(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 PR(){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 ER(t){if(Bi.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:Oo(Bi)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Oo(Bi)})}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:Oo(Bi)})}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(`${FR}/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 _R(){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 PR()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await ER(s)}catch(a){throw a}}function Fc({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const l=u.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(Tj,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:$e("relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",t),...i,children:[e.jsx(kj,{"data-slot":"slider-track",className:$e("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-4 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"),children:e.jsx(Dj,{"data-slot":"slider-range",className:$e("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,c)=>e.jsx(Rj,{"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 MR({onConfigUpdate:t}){const[s,a]=u.useState([]),[r,n]=u.useState(!0),[i,l]=u.useState(null),[o,c]=u.useState(null),[d,m]=u.useState({}),[p,x]=u.useState(null);u.useEffect(()=>{h()},[]);const h=async()=>{var w,L;try{n(!0),c(null);const _=await Kl();a(_)}catch(_){c(((L=(w=_.response)==null?void 0:w.data)==null?void 0:L.error)||"Failed to load configurations")}finally{n(!1)}},g=async w=>{var L,_;try{l(w.configKey),c(null);const W=d[w.configKey]??w.configValue;if(w.validationRules){const I=parseFloat(W);if(w.valueType==="NUMBER"){if(w.validationRules.min!==void 0&&I<w.validationRules.min)throw new Error(`Value must be at least ${w.validationRules.min}`);if(w.validationRules.max!==void 0&&I>w.validationRules.max)throw new Error(`Value must be at most ${w.validationRules.max}`)}}await Gs(w.configKey,W),a(I=>I.map($=>$.configKey===w.configKey?{...$,configValue:W}:$)),m(I=>{const $={...I};return delete $[w.configKey],$}),x(`${w.displayName} updated successfully`),setTimeout(()=>x(null),3e3),t&&t()}catch(W){c(W.message||((_=(L=W.response)==null?void 0:L.data)==null?void 0:_.error)||"Failed to save configuration")}finally{l(null)}},f=async w=>{var L,_;if(confirm(`Reset "${w.displayName}" to default value?`))try{l(w.configKey),c(null),await yT(w.configKey),a(W=>W.map(I=>I.configKey===w.configKey?{...I,configValue:I.defaultValue||""}:I)),m(W=>{const I={...W};return delete I[w.configKey],I}),x(`${w.displayName} reset to default`),setTimeout(()=>x(null),3e3)}catch(W){c(((_=(L=W.response)==null?void 0:L.data)==null?void 0:_.error)||"Failed to reset configuration")}finally{l(null)}},b=(w,L)=>{m(_=>({..._,[w]:L}))},y=w=>d[w.configKey]??w.configValue,j=w=>d[w.configKey]!==void 0&&d[w.configKey]!==w.configValue,v=w=>{var W,I,$,M;const L=y(w),_=i===w.configKey;if(!w.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:w.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Ze,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(w.uiComponent||w.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 ${L==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${L==="true"?"text-green-700":"text-slate-600"}`,children:L==="true"?"Enabled":"Disabled"})]}),e.jsx(cs,{checked:L==="true",onCheckedChange:z=>b(w.configKey,z?"true":"false"),disabled:_})]});case"slider":const R=parseInt(L)||0,C=((W=w.validationRules)==null?void 0:W.min)||0,H=((I=w.validationRules)==null?void 0:I.max)||100;return e.jsxs("div",{className:"space-y-3 p-3 bg-slate-50 border border-slate-200 rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-lg font-semibold text-slate-900",children:[R,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",C,"-",H]})]}),e.jsx(Fc,{value:[R],min:C,max:H,step:1,onValueChange:([z])=>{z!==void 0&&b(w.configKey,z.toString())},disabled:_,className:"w-full"})]});case"number":return e.jsx(_e,{type:"number",value:L,onChange:z=>b(w.configKey,z.target.value),disabled:_,min:($=w.validationRules)==null?void 0:$.min,max:(M=w.validationRules)==null?void 0:M.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(_e,{type:"text",value:L,onChange:z=>b(w.configKey,z.target.value),disabled:_,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},N=w=>{switch(w){case"TAT_SETTINGS":return e.jsx(it,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Ee,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(Os,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Dl,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(Sn,{className:"w-5 h-5"});default:return e.jsx(hr,{className:"w-5 h-5"})}},T=["DASHBOARD_LAYOUT"],A=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],k=s.filter(w=>!T.includes(w.configCategory)&&!A.includes(w.configKey)),D=k.reduce((w,L)=>(w[L.configCategory]||(w[L.configCategory]=[]),w[L.configCategory].push(L),w),{});if(Object.keys(D).forEach(w=>{const L=D[w];L&&L.sort((_,W)=>_.sortOrder-W.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(k.length===0)return e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(hr,{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 F=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(Ve,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:p})]}),o&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:o}),e.jsx(O,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(Ri,{defaultValue:F[0],className:"w-full",children:[e.jsx(Ii,{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:F.map(w=>e.jsx(Ut,{value:w,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:w.replace(/_/g," ")})},w))}),F.map(w=>{var L,_,W;return e.jsx(Bt,{value:w,className:"space-y-4 mt-6",children:e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(de,{className:"pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx("div",{className:"text-white",children:N(w)})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-slate-900",children:w.replace(/_/g," ")}),e.jsxs(Te,{className:"text-sm",children:[((L=D[w])==null?void 0:L.length)||0," setting",(((_=D[w])==null?void 0:_.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(ee,{className:"space-y-6",children:(W=D[w])==null?void 0:W.map(I=>e.jsxs("div",{className:"space-y-3 pb-6 border-b border-slate-100 last:border-b-0 last:pb-0 hover:bg-slate-50/50 -mx-6 px-6 py-4 rounded-md transition-colors",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[e.jsx(re,{className:"text-sm font-semibold text-slate-900",children:I.displayName}),j(I)&&e.jsx(oe,{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"}),I.requiresRestart&&e.jsx(oe,{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"})]}),I.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:I.description}),I.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:I.defaultValue})]})]})}),v(I),I.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(O,{size:"sm",onClick:()=>g(I),disabled:!j(I)||i===I.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===I.configKey?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(La,{className:"w-4 h-4"}),"Save Changes"]})}),I.defaultValue&&e.jsxs(O,{size:"sm",variant:"outline",onClick:()=>f(I),disabled:i===I.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Ep,{className:"w-4 h-4"}),"Reset to Default"]})]})]},I.configKey))})]})},w)})]})]})}function LR(){const[t,s]=u.useState([]),[a,r]=u.useState(!0),[n,i]=u.useState(new Date().getFullYear()),[l,o]=u.useState(!1),[c,d]=u.useState(null),[m,p]=u.useState(null),[x,h]=u.useState(null),[g,f]=u.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});u.useEffect(()=>{b()},[n]);const b=async()=>{var w,L;try{r(!0),p(null);const _=await ST(n);s(_)}catch(_){p(((L=(w=_.response)==null?void 0:w.data)==null?void 0:L.error)||"Failed to load holidays")}finally{r(!1)}},y=()=>{f({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),o(!0)},j=w=>{f({holidayDate:w.holidayDate,holidayName:w.holidayName,description:w.description||"",holidayType:w.holidayType,isRecurring:w.isRecurring}),d(w),o(!0)},v=()=>{if(c)return;const w=new Date;return w.setDate(w.getDate()+1),w.toISOString().split("T")[0]},N=async()=>{var w,L;try{if(p(null),!g.holidayDate||!g.holidayName){p("Holiday date and name are required");return}c?(await TT(c.holidayId,g),Q.success("Holiday updated successfully")):(await AT(g),Q.success("Holiday created successfully")),await b(),o(!1),setTimeout(()=>h(null),3e3)}catch(_){p(((L=(w=_.response)==null?void 0:w.data)==null?void 0:L.error)||"Failed to save holiday")}},T=async w=>{var L,_;if(confirm(`Delete "${w.holidayName}"?`))try{p(null),await kT(w.holidayId),Q.success("Holiday deleted successfully"),await b()}catch(W){const I=((_=(L=W.response)==null?void 0:L.data)==null?void 0:_.error)||"Failed to delete holiday";p(I),Q.error(I)}},A=w=>{switch(w){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"}},k=Array.from({length:5},(w,L)=>new Date().getFullYear()-1+L),D=t.reduce((w,L)=>{const _=new Date(L.holidayDate).toLocaleString("default",{month:"long"});return w[_]||(w[_]=[]),w[_].push(L),w},{}),F=Object.keys(D).sort((w,L)=>{const _=new Date(Date.parse(w+" 1, 2000")).getMonth(),W=new Date(Date.parse(L+" 1, 2000")).getMonth();return _-W});return e.jsxs("div",{className:"space-y-6",children:[x&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(Ve,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:x})]}),m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:m}),e.jsx(O,{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(de,{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(bt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(Te,{className:"text-sm",children:"Manage organization holidays for TAT calculations"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 w-full sm:w-auto",children:[e.jsxs(He,{value:n.toString(),onValueChange:w=>i(parseInt(w)),children:[e.jsx(Ye,{className:"w-24 sm:w-32 border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm",children:e.jsx(Ge,{})}),e.jsx(Qe,{className:"rounded-md",children:k.map(w=>e.jsx(X,{value:w.toString(),children:w},w))})]}),e.jsxs(O,{onClick:y,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(is,{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(ee,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(bt,{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(O,{onClick:y,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(is,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:F.map(w=>{var L,_,W;return e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(de,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[w," ",n]}),e.jsxs(Te,{className:"text-xs sm:text-sm",children:[((L=D[w])==null?void 0:L.length)||0," holiday",(((_=D[w])==null?void 0:_.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(bt,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(ee,{className:"space-y-3 pt-4",children:(W=D[w])==null?void 0:W.map(I=>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:I.holidayName}),e.jsx(oe,{variant:"outline",className:`${A(I.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:I.holidayType}),I.isRecurring&&e.jsx(oe,{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:zg(I.holidayDate)}),I.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:I.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(O,{size:"sm",variant:"ghost",onClick:()=>j(I),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ni,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(O,{size:"sm",variant:"ghost",onClick:()=>T(I),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(vr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},I.holidayId))})]},w)})}),e.jsx(ht,{open:l,onOpenChange:o,children:e.jsxs(mt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(pt,{className:"pb-4 border-b border-slate-100 px-6 pt-6 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg shadow-md",children:e.jsx(bt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ut,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(Mt,{className:"text-sm text-slate-600 mt-1",children:c?"Update holiday information":"Add a new holiday to the calendar for TAT calculations"})]})]})}),e.jsxs("div",{className:"space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"date",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(_e,{id:"date",type:"date",value:g.holidayDate,onChange:w=>f({...g,holidayDate:w.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(re,{htmlFor:"name",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Holiday Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(_e,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:w=>f({...g,holidayName:w.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"description",className:"text-sm font-semibold text-slate-900",children:["Description ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(_e,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:w=>f({...g,description:w.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(He,{value:g.holidayType,onValueChange:w=>f({...g,holidayType:w}),children:[e.jsx(Ye,{id:"type",className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Qe,{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:w=>f({...g,isRecurring:w.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(re,{htmlFor:"recurring",className:"font-semibold cursor-pointer text-sm text-slate-900 block mb-1",children:"Recurring Holiday"}),e.jsx("p",{className:"text-xs text-slate-600",children:"This holiday will automatically repeat every year on the same date"})]})]})]}),e.jsxs(Dt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(O,{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(O,{onClick:N,disabled:!g.holidayDate||!g.holidayName,className:"h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(bt,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function OR(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function $R(){const[t,s]=u.useState(""),[a,r]=u.useState([]),[n,i]=u.useState(!1),[l,o]=u.useState(null),[c,d]=u.useState("USER"),[m,p]=u.useState(!1),[x,h]=u.useState(null),[g,f]=u.useState([]),[b,y]=u.useState(!1),[j,v]=u.useState({admins:0,management:0,users:0}),[N,T]=u.useState("ELEVATED"),[A,k]=u.useState(1),[D,F]=u.useState(1),[w,L]=u.useState(0),_=10,W=u.useRef(null),I=u.useRef(null),$=u.useCallback(OR(async E=>{var V,G,J;if(!E||!E.startsWith("@")||E.length<2){r([]),i(!1);return}i(!0);try{const q=E.slice(1),ne=((V=(await ua.searchUsers(q,20)).data)==null?void 0:V.data)||[];r(ne)}catch(q){console.error("Search failed:",q),h({type:"error",text:((J=(G=q.response)==null?void 0:G.data)==null?void 0:J.message)||"Failed to search users"})}finally{i(!1)}},300),[]),M=E=>{const V=E.target.value;s(V),$(V)},R=async E=>{o(E),s(E.email),r([]);const V=g.find(G=>G.email.toLowerCase()===E.email.toLowerCase()||G.userId===E.userId);if(V&&V.role)d(V.role);else try{const J=(await ua.getAllUsers()).find(q=>q.email&&q.email.toLowerCase()===E.email.toLowerCase()||q.userId&&q.userId===E.userId);J&&J.role?d(J.role):d("USER")}catch(G){console.error("Failed to check user role:",G),d("USER")}},C=async()=>{var E,V;if(!l||!c){h({type:"error",text:"Please select a user and role"});return}p(!0),h(null);try{await ua.assignRole(l.email,c),h({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await H(),await z()}catch(G){console.error("Role assignment failed:",G),h({type:"error",text:((V=(E=G.response)==null?void 0:E.data)==null?void 0:V.error)||"Failed to assign role"})}finally{p(!1)}},H=async(E=A)=>{var V,G,J,q,se,ne;y(!0);try{const te=await ua.getUsersByRole(N,E,_),ge=((G=(V=te.data)==null?void 0:V.data)==null?void 0:G.users)||[],we=(q=(J=te.data)==null?void 0:J.data)==null?void 0:q.pagination,fe=(ne=(se=te.data)==null?void 0:se.data)==null?void 0:ne.summary;f(ge),we&&(k(we.currentPage),F(we.totalPages),L(we.totalUsers)),fe&&v({admins:fe.ADMIN||0,management:fe.MANAGEMENT||0,users:fe.USER||0})}catch(te){console.error("Failed to fetch users:",te)}finally{y(!1)}},z=async()=>{var E,V,G,J,q,se;try{const ne=await ua.getRoleStatistics(),te=((V=(E=ne.data)==null?void 0:E.data)==null?void 0:V.statistics)||((G=ne.data)==null?void 0:G.statistics)||[];v({admins:parseInt(((J=te.find(ge=>ge.role==="ADMIN"))==null?void 0:J.count)||"0"),management:parseInt(((q=te.find(ge=>ge.role==="MANAGEMENT"))==null?void 0:q.count)||"0"),users:parseInt(((se=te.find(ge=>ge.role==="USER"))==null?void 0:se.count)||"0")})}catch(ne){console.error("Failed to fetch statistics:",ne)}};u.useEffect(()=>{H(1),z()},[N]);const P=E=>{T(E),k(1)},S=E=>{H(E)},U=E=>{T(E),k(1),requestAnimationFrame(()=>{const V=I.current;V&&V.scrollIntoView({behavior:"smooth",block:"start"})})};u.useEffect(()=>{const E=V=>{W.current&&!W.current.contains(V.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",E),()=>{document.removeEventListener("mousedown",E)}},[a]);const Y=E=>{switch(E){case"ADMIN":return"bg-yellow-400 text-slate-800";case"MANAGEMENT":return"bg-blue-400 text-slate-800";default:return"bg-gray-400 text-slate-800"}},B=E=>{switch(E){case"ADMIN":return e.jsx(cn,{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(Wt,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(de,{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(fy,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6",children:[e.jsx(Z,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${N==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>U("ADMIN"),children:e.jsx(ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Administrators"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"admin-count",children:j.admins}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1 font-semibold",children:N==="ADMIN"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-xl shadow-md",children:e.jsx(cn,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(Z,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${N==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>U("MANAGEMENT"),children:e.jsx(ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Management"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"management-count",children:j.management}),e.jsx("p",{className:"text-xs text-blue-700 mt-1 font-semibold",children:N==="MANAGEMENT"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-blue-400 to-blue-500 rounded-xl shadow-md",children:e.jsx(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 ${N==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>U("USER"),children:e.jsx(ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Regular Users"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"user-count",children:j.users}),e.jsx("p",{className:"text-xs text-gray-700 mt-1 font-semibold",children:N==="USER"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-gray-400 to-gray-500 rounded-xl shadow-md",children:e.jsx(Wt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(Zt,{}),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:W,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(_e,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:M,className:"pl-10 pr-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"user-search-input"}),n&&e.jsx(ze,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Start with @ to search users (e.g., @john)"}),a.length>0&&e.jsxs("div",{className:"border border-purple-200 rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-purple-50 px-4 py-2 border-b border-purple-100",children:e.jsxs("p",{className:"text-xs font-semibold text-purple-700",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-2",children:a.map(E=>e.jsxs("button",{onClick:()=>R(E),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${E.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:E.displayName||E.email}),e.jsx("p",{className:"text-xs text-gray-600",children:E.email}),E.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[E.department,E.designation?` • ${E.designation}`:""]})]},E.userId))})]})]}),l&&e.jsx("div",{className:"border-2 border-slate-300 bg-gradient-to-br from-slate-100 to-slate-50 rounded-lg p-4 shadow-sm",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-gradient-to-br from-slate-700 to-slate-500 flex items-center justify-center text-white font-bold shadow-md",children:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-slate-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-slate-600",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[l.department,l.designation?` • ${l.designation}`:""]})]})]}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>{o(null),s("")},className:"hover:bg-slate-200",children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Select Role"}),e.jsxs(He,{value:c,onValueChange:E=>d(E),children:[e.jsx(Ye,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Ge,{placeholder:"Select role"})}),e.jsxs(Qe,{children:[e.jsx(X,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{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(cn,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(O,{onClick:C,disabled:!l||m,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"assign-role-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Assign Role"]})}),x&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${x.type==="success"?"border-green-200 bg-green-50":"border-red-200 bg-red-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.type==="success"?e.jsx(Ve,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Ze,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${x.type==="success"?"text-green-800":"text-red-800"}`,children:x.text})]})})]})]}),e.jsx(Zt,{}),e.jsxs("div",{ref:I,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 (",w," ",N!=="ALL"&&N!=="ELEVATED"?N.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(He,{value:N,onValueChange:P,children:[e.jsx(Ye,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Ge,{placeholder:"Filter by role"})}),e.jsxs(Qe,{children:[e.jsx(X,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bs,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",j.admins+j.management,")"]})]})}),e.jsx(X,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",j.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 (",j.management,")"]})]})}),e.jsx(X,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",j.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 (",j.admins+j.management+j.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:N==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2","data-testid":"users-list",children:g.map(E=>e.jsx("div",{className:"border border-gray-200 hover:border-re-green hover:shadow-sm transition-all rounded-lg bg-white p-4","data-testid":`user-${E.email}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg ${Y(E.role)} flex items-center justify-center shadow-sm`,children:B(E.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:E.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:E.email}),E.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[E.department,E.designation?` • ${E.designation}`:""]})]})]}),e.jsx(oe,{className:`${Y(E.role)} shrink-0`,"data-testid":`role-badge-${E.role}`,children:E.role})]})},E.userId))}),D>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(A-1)*_+1," to ",Math.min(A*_,w)," of ",w," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{variant:"outline",size:"sm",onClick:()=>S(A-1),disabled:A===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,D)},(E,V)=>{let G;return D<=5||A<=3?G=V+1:A>=D-2?G=D-4+V:G=A-2+V,e.jsx(O,{variant:A===G?"default":"outline",size:"sm",onClick:()=>S(G),className:`w-9 h-9 p-0 ${A===G?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${G}-button`,children:G},G)})}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>S(A+1),disabled:A===D,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function UR(){const[t,s]=u.useState([]),[a,r]=u.useState(!0),[n,i]=u.useState(!1),[l,o]=u.useState(null),[c,d]=u.useState(null),[m,p]=u.useState(null),[x,h]=u.useState({title:"",itemCode:"",taxationType:"",sapRefNo:"",creditPostingOn:""});u.useEffect(()=>{g()},[]);const g=async()=>{var T,A;try{r(!0),d(null);const k=await RT(!1);s(k)}catch(k){const D=((A=(T=k.response)==null?void 0:T.data)==null?void 0:A.error)||"Failed to load activity types";d(D),Q.error(D)}finally{r(!1)}},f=()=>{h({title:"",itemCode:"",taxationType:"",sapRefNo:"",creditPostingOn:""}),o(null),i(!0)},b=T=>{h({title:T.title,itemCode:T.itemCode||"",taxationType:T.taxationType||"",sapRefNo:T.sapRefNo||"",creditPostingOn:T.creditPostingOn||""}),o(T),i(!0)},y=async()=>{var T,A;try{if(d(null),!x.title.trim()||!x.taxationType.trim()||!x.sapRefNo.trim()||!x.creditPostingOn.trim()){d("Title, Taxation Type, Credit Posting On, and Claim Document Type (SAP Ref) are required"),Q.error("Please fill in all mandatory fields");return}const k={title:x.title.trim(),itemCode:x.itemCode.trim()||null,taxationType:x.taxationType.trim(),sapRefNo:x.sapRefNo.trim(),creditPostingOn:x.creditPostingOn.trim()};l?(await FT(l.activityTypeId,k),Q.success("Activity type updated successfully")):(await IT(k),Q.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>p(null),3e3)}catch(k){const D=((A=(T=k.response)==null?void 0:T.data)==null?void 0:A.error)||"Failed to save activity type";d(D),Q.error(D)}},j=async T=>{var A,k;if(confirm(`Delete "${T.title}"? This will deactivate the activity type.`))try{d(null),await PT(T.activityTypeId),Q.success("Activity type deleted successfully"),await g()}catch(D){const F=((k=(A=D.response)==null?void 0:A.data)==null?void 0:k.error)||"Failed to delete activity type";d(F),Q.error(F)}},v=t.filter(T=>T.isActive!==!1&&T.isActive!==void 0),N=t.filter(T=>T.isActive===!1);return e.jsxs("div",{className:"space-y-6",children:[m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(Ve,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:m})]}),c&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:c}),e.jsx(O,{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(de,{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(Ee,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Activity Types"}),e.jsx(Te,{className:"text-sm",children:"Manage dealer claim activity types"})]})]}),e.jsxs(O,{onClick:f,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm",children:[e.jsx(is,{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(ee,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(Ee,{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(O,{onClick:f,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(is,{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(de,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Active Activity Types"}),e.jsxs(Te,{className:"text-xs sm:text-sm",children:[v.length," active type",v.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-green-50 rounded-md",children:e.jsx(Ve,{className:"w-4 h-4 text-green-600"})})]})}),e.jsx(ee,{className:"space-y-3 pt-4",children:v.map(T=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 hover:border-slate-300 transition-all shadow-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-900 text-sm sm:text-base",children:T.title}),e.jsx(oe,{variant:"outline",className:"bg-gradient-to-r from-green-50 to-emerald-50 text-green-800 border-green-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Active"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs sm:text-sm text-slate-600",children:[T.itemCode&&e.jsxs("span",{className:"font-medium",children:["Item Code: ",e.jsx("span",{className:"text-slate-900",children:T.itemCode})]}),T.taxationType&&e.jsxs("span",{className:"font-medium",children:["Taxation: ",e.jsx("span",{className:"text-slate-900",children:T.taxationType})]}),T.sapRefNo&&e.jsxs("span",{className:"font-medium",children:["SAP Ref: ",e.jsx("span",{className:"text-slate-900",children:T.sapRefNo})]}),T.creditPostingOn&&e.jsxs("span",{className:"font-medium",children:["Credit Posting On: ",e.jsx(oe,{variant:"secondary",className:"ml-1 bg-slate-200 text-slate-800",children:T.creditPostingOn})]}),!T.itemCode&&!T.taxationType&&!T.sapRefNo&&!T.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(O,{size:"sm",variant:"ghost",onClick:()=>b(T),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ni,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(O,{size:"sm",variant:"ghost",onClick:()=>j(T),className:"gap-1.5 text-red-600 hover:text-red-700 hover:bg-red-50 border border-transparent hover:border-red-200 text-xs sm:text-sm",children:[e.jsx(vr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},T.activityTypeId))})]}),N.length>0&&e.jsxs(Z,{className:"shadow-lg border-0 rounded-md border-amber-200",children:[e.jsx(de,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Inactive Activity Types"}),e.jsxs(Te,{className:"text-xs sm:text-sm",children:[N.length," inactive type",N.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-amber-50 rounded-md",children:e.jsx(Ze,{className:"w-4 h-4 text-amber-600"})})]})}),e.jsx(ee,{className:"space-y-3 pt-4",children:N.map(T=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-amber-50/50 border border-amber-200 rounded-md hover:bg-amber-50 hover:border-amber-300 transition-all shadow-sm",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-700 text-sm sm:text-base line-through",children:T.title}),e.jsx(oe,{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(O,{size:"sm",variant:"ghost",onClick:()=>b(T),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ni,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]})})]},T.activityTypeId))})]})]}),e.jsx(ht,{open:n,onOpenChange:i,children:e.jsxs(mt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(pt,{className:"pb-4 border-b border-slate-100 px-6 pt-6 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg shadow-md",children:e.jsx(Ee,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ut,{className:"text-xl font-semibold text-slate-900",children:l?"Edit Activity Type":"Add New Activity Type"}),e.jsx(Mt,{className:"text-sm text-slate-600 mt-1",children:l?"Update activity type information":"Add a new activity type for dealer claim management"})]})]})}),e.jsxs("div",{className:"space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"title",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Title ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(_e,{id:"title",placeholder:"e.g., Riders Mania Claims, Legal Claims Reimbursement",value:x.title,onChange:T=>h({...x,title:T.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the activity type title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"itemCode",className:"text-sm font-semibold text-slate-900",children:["Item Code ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(_e,{id:"itemCode",placeholder:"e.g., 1, 2, 3",value:x.itemCode,onChange:T=>h({...x,itemCode:T.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional item code for the activity type"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{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:x.taxationType,onValueChange:T=>h({...x,taxationType:T}),children:[e.jsx(Ye,{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(Qe,{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(re,{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(_e,{id:"sapRefNo",placeholder:"e.g., ZCNS, ZRE",value:x.sapRefNo,onChange:T=>h({...x,sapRefNo:T.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Required SAP reference number for CSV generation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{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:x.creditPostingOn,onValueChange:T=>h({...x,creditPostingOn:T}),children:[e.jsx(Ye,{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(Qe,{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(O,{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(O,{onClick:y,disabled:!x.title.trim()||!x.taxationType||!x.sapRefNo.trim()||!x.creditPostingOn,className:"h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(Ee,{className:"w-4 h-4 mr-2"}),l?"Update Activity Type":"Add Activity Type"]})]})]})})]})}function Rs({className:t,...s}){return e.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:e.jsx("table",{"data-slot":"table",className:$e("w-full caption-bottom text-sm",t),...s})})}function Is({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:$e("[&_tr]:border-b",t),...s})}function Fs({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:$e("[&_tr:last-child]:border-0",t),...s})}function tt({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:$e("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function Ie({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:$e("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function ve({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:$e("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function BR(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function Hh({emails:t,onAdd:s,onRemove:a,placeholder:r}){const[n,i]=u.useState(""),l=()=>{const o=n.trim().toLowerCase();if(o){if(!BR(o)){Q.error("Please enter a valid email address");return}if(t.includes(o)){Q.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(_e,{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(O,{type:"button",variant:"outline",size:"sm",onClick:l,className:"shrink-0 gap-1",children:[e.jsx(is,{className:"w-4 h-4"}),"Add"]})]}),t.length>0?e.jsx("div",{className:"rounded-md border",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{children:[e.jsx(Ie,{children:"Email"}),e.jsx(Ie,{className:"w-[80px] text-right",children:"Actions"})]})}),e.jsx(Fs,{children:t.map(o=>e.jsxs(tt,{children:[e.jsx(ve,{className:"font-medium",children:o}),e.jsx(ve,{className:"text-right",children:e.jsx(O,{type:"button",variant:"ghost",size:"sm",onClick:()=>a(o),className:"text-destructive hover:text-destructive",children:e.jsx(vr,{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 Gh(t,s){return{enabled:t,template:s}}const $o=()=>({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 zR(){const[t,s]=u.useState(!0),[a,r]=u.useState(!1),[n,i]=u.useState([]),[l,o]=u.useState([]),[c,d]=u.useState(!0),[m,p]=u.useState(7),[x,h]=u.useState($o()),[g,f]=u.useState(!0),[b,y]=u.useState(0),[j,v]=u.useState(Gh(!0,"Form 16 submitted successfully. Credit note: [CreditNoteRef].")),[N,T]=u.useState(Gh(!0,"Form 16 submission was unsuccessful. Issue: [Issue]. Please review.")),[A,k]=u.useState(!0),[D,F]=u.useState(0),[w,L]=u.useState(7),[_,W]=u.useState(0),[I,$]=u.useState(24),[M,R]=u.useState("09:00"),[C,H]=u.useState("Dear [Name], please submit Form 16A for the pending period. Due: [DueDate]."),[z,P]=u.useState(!0),[S,U]=u.useState(0),[Y,B]=u.useState(12),[E,V]=u.useState("10:00"),[G,J]=u.useState("Reminder: Dear [Name], your Form 16A submission is pending for request [Request ID]. Please complete it.");u.useEffect(()=>{let se=!0;return vT().then(ne=>{if(se){if(i(ne.submissionViewerEmails??[]),o(ne.twentySixAsViewerEmails??[]),d(ne.reminderEnabled??!0),p(typeof ne.reminderDays=="number"?ne.reminderDays:7),ne.notification26AsDataAdded){const te=ne.notification26AsDataAdded;h({enabled:te.enabled??!0,templateRe:te.templateRe??te.template??$o().templateRe,templateDealers:te.templateDealers??$o().templateDealers})}f(ne.reminder26AsUploadEnabled??!0),y(typeof ne.reminder26AsUploadAfterQuarterEndDays=="number"?ne.reminder26AsUploadAfterQuarterEndDays:0),ne.notificationForm16SuccessCreditNote&&v(ne.notificationForm16SuccessCreditNote),ne.notificationForm16Unsuccessful&&T(ne.notificationForm16Unsuccessful),k(ne.alertSubmitForm16Enabled??!0),F(typeof ne.alertSubmitForm16AfterQuarterEndDays=="number"?ne.alertSubmitForm16AfterQuarterEndDays:0),L(typeof ne.alertSubmitForm16EveryDays=="number"?ne.alertSubmitForm16EveryDays:7),W(ne.alertSubmitForm16FrequencyDays??0),$(ne.alertSubmitForm16FrequencyHours??24),R(ne.alertSubmitForm16RunAtTime!==void 0&&ne.alertSubmitForm16RunAtTime!==null?ne.alertSubmitForm16RunAtTime:"09:00"),H(ne.alertSubmitForm16Template??"Dear [Name], please submit Form 16A for the pending period. Due: [DueDate]."),P(ne.reminderNotificationEnabled??!0),U(ne.reminderFrequencyDays??0),B(ne.reminderFrequencyHours??12),V(ne.reminderRunAtTime!==void 0&&ne.reminderRunAtTime!==null?ne.reminderRunAtTime:"10:00"),J(ne.reminderNotificationTemplate??"Reminder: Dear [Name], your Form 16A submission is pending for request [Request ID]. Please complete it.")}}).catch(()=>{se&&Q.error("Failed to load Form 16 configuration")}).finally(()=>{se&&s(!1)}),()=>{se=!1}},[]);const q=async()=>{r(!0);try{await NT({submissionViewerEmails:n,twentySixAsViewerEmails:l,reminderEnabled:c,reminderDays:Math.max(1,Math.min(365,m))||7,notification26AsDataAdded:x,reminder26AsUploadEnabled:g,reminder26AsUploadAfterQuarterEndDays:Math.max(0,Math.min(365,b)),notificationForm16SuccessCreditNote:j,notificationForm16Unsuccessful:N,alertSubmitForm16Enabled:A,alertSubmitForm16AfterQuarterEndDays:Math.max(0,Math.min(365,D)),alertSubmitForm16EveryDays:Math.max(1,Math.min(365,w)),alertSubmitForm16FrequencyDays:Math.max(0,Math.min(365,_)),alertSubmitForm16FrequencyHours:Math.max(0,Math.min(168,I)),alertSubmitForm16RunAtTime:M??"",alertSubmitForm16Template:C,reminderNotificationEnabled:z,reminderFrequencyDays:Math.max(0,Math.min(365,S)),reminderFrequencyHours:Math.max(0,Math.min(168,Y)),reminderRunAtTime:E??"",reminderNotificationTemplate:G}),Q.success("Form 16 configuration saved")}catch{Q.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:[[x==null?void 0:x.enabled,j==null?void 0:j.enabled,N==null?void 0:N.enabled,A,z].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(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx($u,{className:"w-5 h-5 text-re-green"}),"Quarter calendar (how reminders/alerts work)"]}),e.jsx(Te,{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(ee,{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(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-5 h-5"}),"Submission data who can see"]}),e.jsxs(Te,{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(ee,{children:e.jsx(Hh,{emails:n,onAdd:se=>i(ne=>[...ne,se].sort()),onRemove:se=>i(ne=>ne.filter(te=>te!==se)),placeholder:"e.g., user@royalenfield.com"})})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx($u,{className:"w-5 h-5"}),"26AS page and button who can see"]}),e.jsxs(Te,{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(ee,{children:e.jsx(Hh,{emails:l,onAdd:se=>o(ne=>[...ne,se].sort()),onRemove:se=>o(ne=>ne.filter(te=>te!==se)),placeholder:"e.g., user@royalenfield.com"})})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"w-5 h-5"}),"Reminder schedule (for dealers)"]}),e.jsx(Te,{children:"When reminders are enabled, dealers with pending Form 16 for a quarter are reminded at this interval. Set how often (in days) the system may send them a reminder to submit Form 16."})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{htmlFor:"reminder-enabled",children:"Enable reminders to dealers"}),e.jsx(cs,{id:"reminder-enabled",checked:c,onCheckedChange:d})]}),e.jsxs("div",{className:"space-y-2 max-w-xs",children:[e.jsx(re,{htmlFor:"reminder-days",children:"Remind dealers every (days)"}),e.jsx(_e,{id:"reminder-days",type:"number",min:1,max:365,value:m,onChange:se=>p(parseInt(se.target.value,10)||7)})]})]})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Email and in-app notifications"}),e.jsx(Te,{children:"Configure who receives each notification, what triggers it, and when it is sent. Templates support placeholders such as [Name], [Request ID], [DueDate]."})]}),e.jsx(ee,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Form 16 notifications recipient and trigger"}),e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0 space-y-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(re,{htmlFor:"re-26as-after-days",className:"text-sm whitespace-nowrap",children:"Start after (days):"}),e.jsx(_e,{id:"re-26as-after-days",type:"number",min:0,max:365,value:b,onChange:se=>y(parseInt(se.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(cs,{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(cs,{checked:x.enabled,onCheckedChange:se=>h(ne=>({...ne,enabled:se}))})]}),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(re,{htmlFor:"dealer-submit-after-days",className:"text-sm whitespace-nowrap",children:"Start after (days):"}),e.jsx(_e,{id:"dealer-submit-after-days",type:"number",min:0,max:365,value:D,onChange:se=>F(parseInt(se.target.value||"0",10)||0),className:"w-24"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(re,{htmlFor:"dealer-submit-every-days",className:"text-sm whitespace-nowrap",children:"Repeat every (days):"}),e.jsx(_e,{id:"dealer-submit-every-days",type:"number",min:1,max:365,value:w,onChange:se=>L(parseInt(se.target.value||"7",10)||7),className:"w-24"})]})]})]}),e.jsx(cs,{checked:A,onCheckedChange:k})]}),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(cs,{checked:j.enabled,onCheckedChange:se=>v(ne=>({...ne,enabled:se}))})]}),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(cs,{checked:N.enabled,onCheckedChange:se=>T(ne=>({...ne,enabled:se}))})]}),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(re,{htmlFor:"reminder-run-at",className:"text-sm whitespace-nowrap",children:"Run daily at (optional):"}),e.jsx(_e,{id:"reminder-run-at",type:"time",value:E,onChange:se=>V(se.target.value),className:"w-28"}),E?e.jsx(O,{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(re,{htmlFor:"reminder-freq-days",className:"text-sm whitespace-nowrap",children:"Frequency (days):"}),e.jsx(_e,{id:"reminder-freq-days",type:"number",min:0,max:365,value:S,onChange:se=>U(Math.max(0,parseInt(se.target.value,10)||0)),className:"w-20"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(re,{htmlFor:"reminder-freq-hours",className:"text-sm whitespace-nowrap",children:"Hours:"}),e.jsx(_e,{id:"reminder-freq-hours",type:"number",min:0,max:168,value:Y,onChange:se=>B(Math.max(0,parseInt(se.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(cs,{checked:z,onCheckedChange:P})]})]})})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(O,{onClick:q,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(La,{className:"w-4 h-4"}),"Save Form 16 configuration"]})})]})}function VR(){const[t,s]=u.useState([]),[a,r]=u.useState(!0),[n,i]=u.useState(!1),[l,o]=u.useState(null),[c,d]=u.useState(null),[m,p]=u.useState(1),[x,h]=u.useState(1),[g,f]=u.useState(0),[b]=u.useState(10),[y,j]=u.useState(""),[v,N]=u.useState(""),[T,A]=u.useState({code:"",type:"HSN",gstRate:"",description:"",isActive:!0});u.useEffect(()=>{const W=setTimeout(()=>{N(y),p(1)},500);return()=>clearTimeout(W)},[y]),u.useEffect(()=>{k()},[m,v]);const k=async()=>{var W,I;try{r(!0),d(null);const $=await eb(!1,m,b,v);s($.codes),h($.pagination.totalPages),f($.pagination.totalRecords)}catch($){const M=((I=(W=$.response)==null?void 0:W.data)==null?void 0:I.error)||"Failed to load HSN/SAC codes";d(M),Q.error(M)}finally{r(!1)}},D=()=>{A({code:"",type:"HSN",gstRate:"",description:"",isActive:!0}),o(null),i(!0)},F=W=>{var I;A({code:W.code,type:W.type,gstRate:((I=W.gstRate)==null?void 0:I.toString())||"",description:W.description||"",isActive:W.isActive}),o(W),i(!0)},w=async()=>{var W,I;try{if(d(null),!T.code.trim()||!T.type){d("Code and Type are required"),Q.error("Please fill in required fields");return}const{isValid:$,message:M}=va(T.code,T.type==="SAC");if(!$){d(M),Q.error(M);return}const R={code:T.code.trim(),type:T.type,gstRate:T.gstRate?parseFloat(T.gstRate):void 0,description:T.description.trim()||void 0,isActive:T.isActive};l?(await z4(l.id,R),Q.success(`${T.type} code updated successfully`)):(await B4(R),Q.success(`${T.type} code created successfully`)),await k(),i(!1)}catch($){const M=((I=(W=$.response)==null?void 0:W.data)==null?void 0:I.error)||"Failed to save code";d(M),Q.error(M)}},L=async W=>{var I,$;if(confirm(`Delete ${W.type} code "${W.code}"?`))try{d(null),await V4(W.id),Q.success("Code deleted successfully"),await k()}catch(M){const R=(($=(I=M.response)==null?void 0:I.data)==null?void 0:$.error)||"Failed to delete code";d(R),Q.error(R)}},_=async W=>{try{await W4(W),await k(),Q.success("Status updated successfully")}catch{Q.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(Ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:c}),e.jsx(O,{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(de,{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(sc,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"HSN/SAC Codes"}),e.jsxs(Te,{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(Jt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(_e,{placeholder:"Search code or description...",value:y,onChange:W=>j(W.target.value),className:"pl-9 bg-slate-50 border-slate-200 focus:bg-white transition-all text-sm"})]}),e.jsxs(O,{onClick:D,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm whitespace-nowrap",children:[e.jsx(is,{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(ee,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:v?e.jsx(by,{className:"w-10 h-10 text-slate-400"}):e.jsx(sc,{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(O,{onClick:()=>j(""),variant:"outline",children:"Clear Search"}):e.jsxs(O,{onClick:D,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50",children:[e.jsx(is,{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(W=>e.jsx(WR,{code:W,onEdit:()=>F(W),onDelete:()=>L(W),onToggle:()=>_(W.id)},W.id))}),x>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(O,{variant:"outline",size:"sm",onClick:()=>p(W=>Math.max(1,W-1)),disabled:m===1,className:"gap-1 h-9",children:[e.jsx(Nn,{className:"w-4 h-4"}),e.jsx("span",{children:"Previous"})]}),e.jsx("div",{className:"flex items-center gap-1",children:[...Array(x)].map((W,I)=>{const $=I+1;return x<=7||$===1||$===x||$>=m-1&&$<=m+1?e.jsx(O,{variant:m===$?"default":"outline",size:"sm",onClick:()=>p($),className:`w-9 h-9 p-0 ${m===$?"bg-slate-800":"text-slate-600"}`,children:$},$):$===m-2&&$>1||$===m+2&&$<x?e.jsx("span",{className:"px-1 text-slate-400",children:"..."},$):null})}),e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>p(W=>Math.min(x,W+1)),disabled:m===x,className:"gap-1 h-9",children:[e.jsx("span",{children:"Next"}),e.jsx(Wa,{className:"w-4 h-4"})]})]})]})]}),e.jsx(ht,{open:n,onOpenChange:i,children:e.jsxs(mt,{className:"sm:max-w-[500px]",children:[e.jsxs(pt,{children:[e.jsx(ut,{children:l?"Edit Code":"Add New HSN/SAC Code"}),e.jsx(Mt,{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(re,{htmlFor:"type",children:["Type ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs(He,{value:T.type,onValueChange:W=>A({...T,type:W}),children:[e.jsx(Ye,{children:e.jsx(Ge,{placeholder:"Select type"})}),e.jsxs(Qe,{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(re,{htmlFor:"code",children:["Code ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(_e,{id:"code",placeholder:"e.g., 998311",value:T.code,onChange:W=>A({...T,code:W.target.value}),className:va(T.code,T.type==="SAC").isValid?"":"border-red-500"}),!va(T.code,T.type==="SAC").isValid&&T.code&&e.jsx("p",{className:"text-[10px] text-red-500 absolute left-0 bottom-0 leading-tight",children:va(T.code,T.type==="SAC").message})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(_e,{id:"description",placeholder:"Brief description of the code",value:T.description,onChange:W=>A({...T,description:W.target.value})})]})]}),e.jsxs(Dt,{children:[e.jsx(O,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(O,{onClick:w,className:"bg-re-green hover:bg-re-green/90 text-white",children:l?"Update Code":"Create Code"})]})]})})]})}function WR({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(jy,{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(O,{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(ni,{className:"w-4 h-4"})}),e.jsx(O,{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(vr,{className:"w-4 h-4"})})]}),e.jsx(O,{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 HR(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function GR(){const[t,s]=u.useState(!0),[a,r]=u.useState(!1),[n,i]=u.useState([]),[l,o]=u.useState("");u.useEffect(()=>{let p=!0;return wT().then(x=>{p&&i(x.viewerEmails??[])}).catch(()=>{p&&Q.error("Failed to load CPC-CSD configuration")}).finally(()=>{p&&s(!1)}),()=>{p=!1}},[]);const c=()=>{const p=l.trim().toLowerCase();if(p){if(!HR(p)){Q.error("Please enter a valid email address");return}if(n.includes(p)){Q.error("This email is already in the list");return}i(x=>[...x,p].sort()),o("")}},d=p=>{i(x=>x.filter(h=>h!==p))},m=async()=>{r(!0);try{await CT({viewerEmails:n}),Q.success("CPC-CSD configuration saved")}catch{Q.error("Failed to save CPC-CSD 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:"CPC-CSD Administration"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Configure who can view and use the CPC-CSD module."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 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:"CPC-CSD viewers"}),e.jsx("p",{className:"text-2xl font-semibold",children:n.length}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"ADMIN always has full access"})]}),e.jsxs("div",{className:"p-4 bg-blue-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Access mode"}),e.jsx("p",{className:"text-lg font-semibold text-blue-700",children:n.length===0?"Restricted (no viewers configured)":"Restricted to listed viewers"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Same as Form16 viewer-based access model"})]})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-5 h-5"}),"CPC-CSD module viewers"]}),e.jsx(Te,{children:"Users with these email addresses can access the CPC-CSD sidebar and pages. Use exact login email."})]}),e.jsxs(ee,{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_e,{type:"email",placeholder:"e.g., user@royalenfield.com",value:l,onChange:p=>o(p.target.value),onKeyDown:p=>p.key==="Enter"&&(p.preventDefault(),c()),className:"flex-1"}),e.jsxs(O,{type:"button",variant:"outline",size:"sm",onClick:c,className:"shrink-0 gap-1",children:[e.jsx(is,{className:"w-4 h-4"}),"Add"]})]}),n.length>0?e.jsx("div",{className:"rounded-md border",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{children:[e.jsx(Ie,{children:"Email"}),e.jsx(Ie,{className:"w-[80px] text-right",children:"Actions"})]})}),e.jsx(Fs,{children:n.map(p=>e.jsxs(tt,{children:[e.jsx(ve,{className:"font-medium",children:p}),e.jsx(ve,{className:"text-right",children:e.jsx(O,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(p),className:"text-destructive hover:text-destructive",children:e.jsx(vr,{className:"w-4 h-4"})})})]},p))})]})}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center rounded-md border border-dashed",children:"No viewers configured. Non-admin users will not get CPC-CSD access."})]})]}),e.jsx("div",{className:"sticky bottom-4 z-10",children:e.jsx("div",{className:"bg-background/80 backdrop-blur border rounded-lg p-3 flex justify-end",children:e.jsxs(O,{onClick:m,disabled:a,className:"gap-2",children:[a?e.jsx(ze,{className:"w-4 h-4 animate-spin"}):e.jsx(La,{className:"w-4 h-4"}),"Save CPC-CSD configuration"]})})})]})}function YR({open:t,onClose:s,success:a,message:r}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(Mt,{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(Ve,{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(At,{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(O,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const QR=async()=>(await Se.get("/user/preferences/notifications")).data.data,KR=async t=>(await Se.put("/user/preferences/notifications",t)).data.data;function XR({open:t,onClose:s}){const[a,r]=u.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=u.useState(!0),[l,o]=u.useState(null),[c,d]=u.useState(null),[m,p]=u.useState(null);u.useEffect(()=>{t&&x()},[t]);const x=async()=>{var g,f;try{i(!0),p(null);const b=await QR();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,y;try{o(g),p(null),d(null);const j={[g]:f},v=await KR(j);r(v),d(`${g==="emailNotificationsEnabled"?"Email":g==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${f?"enabled":"disabled"}`),setTimeout(()=>d(null),3e3)}catch(j){console.error("[NotificationPreferences] Failed to update preference:",j),p(((y=(b=j.response)==null?void 0:b.data)==null?void 0:y.message)||"Failed to update notification preference"),x()}finally{o(null)}};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(pt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg",children:e.jsx(hr,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(ut,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(Mt,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(Zt,{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(Ve,{className:"w-4 h-4 text-green-600 shrink-0"}),e.jsx("p",{className:"text-sm text-green-800 font-medium",children:c})]}),m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-md animate-in fade-in slide-in-from-top-2",children:[e.jsx(Ze,{className:"w-4 h-4 text-red-600 shrink-0"}),e.jsx("p",{className:"text-sm text-red-800 font-medium",children:m})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(Ca,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Receive important updates and alerts via email"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="emailNotificationsEnabled"&&e.jsx(ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(cs,{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(Os,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"push-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Push Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Get instant browser notifications for real-time updates"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="pushNotificationsEnabled"&&e.jsx(ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(cs,{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(Qs,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"inapp-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"View notifications in the notification center"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="inAppNotificationsEnabled"&&e.jsx(ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(cs,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>h("inAppNotificationsEnabled",g),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx(Zt,{}),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 JR(){const t=gs(),{user:s}=us(),a=Er(s),[r,n]=u.useState(!1),[i,l]=u.useState(!1),[o,c]=u.useState(),[d,m]=u.useState(!1),[p,x]=u.useState(!1),[h,g]=u.useState(!1),[f,b]=u.useState(!0),[y,j]=u.useState(!1),[v,N]=u.useState(!1),[T,A]=u.useState(!1),[k,D]=u.useState(!1);u.useEffect(()=>{F()},[]);const F=async()=>{try{b(!0);const L=await dN();g(L.length>0)}catch(L){console.error("Failed to check subscription status:",L),g(!1)}finally{b(!1)}},w=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 L=Notification.permission;if(L==="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(L==="default"&&(L=await Notification.requestPermission(),L==="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(L!=="granted"){l(!1),c("Notification permission is required to enable push notifications. Please grant permission and try again."),n(!0),m(!1);return}await _R(),l(!0),c("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),n(!0),await F()}catch(L){console.error("[Settings] Error enabling notifications:",L),l(!1);const _=(L==null?void 0:L.message)||"Unknown error occurred";c(_.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":_.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":_.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${_}`),n(!0)}finally{m(!1)}};return e.jsxs("div",{className:"min-h-screen pb-8",children:[e.jsxs("div",{className:"max-w-7xl mx-auto space-y-6",children:[e.jsxs(Z,{className:"relative overflow-hidden shadow-2xl border-0 rounded-2xl",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,_var(--tw-gradient-stops))] from-yellow-400/20 via-transparent to-transparent"}),e.jsx(ee,{className:"relative z-10 p-6 sm:p-8 lg:p-12",children:e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[e.jsx("div",{className:"w-14 h-14 sm:w-16 sm:h-16 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-2xl flex items-center justify-center shadow-xl transform hover:scale-105 transition-transform",children:e.jsx(hr,{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(Ri,{defaultValue:"user",className:"w-full",children:[e.jsxs(Ii,{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(Ut,{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(hr,{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(Ut,{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(bs,{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(Ut,{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(Up,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(Ut,{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(bt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Holidays"}),e.jsx("span",{className:"sm:hidden",children:"Holidays"})]}),e.jsxs(Ut,{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(Ee,{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(Bt,{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(de,{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(Os,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-4",children:[f?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):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(O,{onClick:w,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(Os,{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(de,{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(ur,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:[e.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"Manage your password, API tokens, and other security preferences."}),e.jsxs(O,{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(ur,{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(de,{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(Uu,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Appearance settings will be available soon"})})})})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(de,{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(bs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(ee,{children:e.jsxs(O,{onClick:()=>x(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(Bt,{value:"roles",className:"mt-0",children:e.jsx($R,{})}),e.jsx(Bt,{value:"system",className:"mt-0",children:e.jsx(MR,{})}),e.jsx(Bt,{value:"holidays",className:"mt-0",children:e.jsx(LR,{})}),e.jsx(Bt,{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(de,{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(O,{variant:"ghost",size:"sm",onClick:()=>N(!1),className:"gap-2 hover:bg-slate-100",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]}),e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-emerald-600 to-emerald-700 rounded-md shadow-md",children:e.jsx(Ee,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Form 16 Administration"}),e.jsx(Te,{className:"text-sm",children:"Configure Form 16 access, who can view submission data and 26AS, and notification settings"})]})]})})})}),e.jsx(zR,{})]}):k?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsx(de,{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(O,{variant:"ghost",size:"sm",onClick:()=>D(!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-teal-600 to-cyan-700 rounded-md shadow-md",children:e.jsx(Ee,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"CPC-CSD Administration"}),e.jsx(Te,{className:"text-sm",children:"Configure who can access CPC-CSD module and pages"})]})]})})})}),e.jsx(GR,{})]}):y?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsx(de,{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(O,{variant:"ghost",size:"sm",onClick:()=>j(!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(Ee,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Dealer Claim Activity Settings"}),e.jsx(Te,{className:"text-sm",children:"Manage activity types for dealer claim workflows"})]})]})})})}),e.jsx(UR,{})]}):T?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsx(de,{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(O,{variant:"ghost",size:"sm",onClick:()=>A(!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(Ee,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"HSN/SAC Code Configuration"}),e.jsx(Te,{className:"text-sm",children:"Manage HSN/SAC codes and associated GST rates"})]})]})})})}),e.jsx(VR,{})]}):e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(de,{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(Ee,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Template Settings"}),e.jsx(Te,{className:"text-sm",children:"Manage templates and activity types for workflows"})]})]})}),e.jsx(ee,{className:"pt-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Z,{className:"shadow-md hover:shadow-lg transition-all duration-300 border border-slate-200 rounded-lg cursor-pointer group",onClick:()=>j(!0),children:e.jsx(ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Ee,{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:()=>D(!0),children:e.jsx(ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-teal-500 to-cyan-600 rounded-lg shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Ee,{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-teal-600 transition-colors",children:"CPC-CSD"}),e.jsx("p",{className:"text-sm text-slate-600 mt-1",children:"Configure role based access for CPC-CSD module"})]})]}),e.jsx("div",{className:"text-slate-400 group-hover:text-teal-600 transition-colors",children:e.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})})}),e.jsx(Z,{className:"shadow-md hover:shadow-lg transition-all duration-300 border border-slate-200 rounded-lg cursor-pointer group",onClick:()=>N(!0),children:e.jsx(ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-emerald-500 to-emerald-600 rounded-lg shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Ee,{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:()=>A(!0),children:e.jsx(ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-re-green to-teal-600 rounded-lg shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Ee,{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(de,{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(Os,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-4",children:[f?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):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(O,{onClick:w,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(Os,{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(de,{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(ur,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:[e.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"Manage your password, API tokens, and other security preferences."}),e.jsxs(O,{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(ur,{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(de,{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(Uu,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Appearance settings will be available soon"})})})})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(de,{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(bs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(ee,{children:e.jsxs(O,{onClick:()=>x(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(YR,{open:r,onClose:()=>n(!1),success:i,message:o}),e.jsx(XR,{open:p,onClose:()=>x(!1)})]})}const ZR=Zc("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 qR({className:t,variant:s,...a}){return e.jsx("div",{"data-slot":"alert",role:"alert",className:$e(ZR({variant:s}),t),...a})}function eI({className:t,...s}){return e.jsx("div",{"data-slot":"alert-title",className:$e("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",t),...s})}function tI({className:t,...s}){return e.jsx("div",{"data-slot":"alert-description",className:$e("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",t),...s})}function sI(){const[t,s]=u.useState([]),[a,r]=u.useState(!0),[n,i]=u.useState(!1),[l,o]=u.useState(""),[c,d]=u.useState(""),[m,p]=u.useState(null),[x,h]=u.useState(!1),[g,f]=u.useState(!1),[b,y]=u.useState(null);u.useEffect(()=>{j()},[]);const j=async()=>{try{r(!0);const D=await Se.get("/api-tokens");s(D.data.data.tokens)}catch(D){console.error("Failed to fetch API tokens:",D),Q.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 F=await Se.post("/api-tokens",D);p(F.data.data.token),Q.success("API Token created successfully"),j()}catch(D){console.error("Failed to create token:",D),Q.error("Failed to create API token")}finally{h(!1)}},N=D=>{y(D)},T=async()=>{if(b)try{await Se.delete(`/api-tokens/${b.id}`),Q.success("Token revoked successfully"),s(t.filter(D=>D.id!==b.id)),y(null)}catch(D){console.error("Failed to revoke token:",D),Q.error("Failed to revoke token")}},A=()=>{m&&(navigator.clipboard.writeText(m),f(!0),setTimeout(()=>f(!1),2e3),Q.success("Token copied to clipboard"))},k=()=>{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(O,{onClick:()=>i(!0),size:"sm",className:"bg-re-green hover:bg-re-green/90 text-white",children:[e.jsx(is,{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(Bp,{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(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{children:[e.jsx(Ie,{children:"Name"}),e.jsx(Ie,{children:"Prefix"}),e.jsx(Ie,{children:"Last Used"}),e.jsx(Ie,{children:"Expires"}),e.jsx(Ie,{className:"text-right",children:"Actions"})]})}),e.jsx(Fs,{children:t.map(D=>e.jsxs(tt,{children:[e.jsx(ve,{className:"font-medium",children:D.name}),e.jsxs(ve,{className:"font-mono text-xs bg-slate-100 rounded px-2 py-1 w-fit",children:[D.prefix,"..."]}),e.jsx(ve,{className:"text-gray-500 text-sm",children:D.lastUsedAt?st(new Date(D.lastUsedAt),"MMM d, yyyy"):"Never"}),e.jsx(ve,{className:"text-gray-500 text-sm",children:D.expiresAt?st(new Date(D.expiresAt),"MMM d, yyyy"):"No Expiry"}),e.jsx(ve,{className:"text-right",children:e.jsxs(O,{variant:"ghost",size:"sm",onClick:()=>N(D),className:"text-red-600 hover:text-red-700 hover:bg-red-50",children:[e.jsx(vr,{className:"w-4 h-4"}),e.jsx("span",{className:"sr-only",children:"Revoke"})]})})]},D.id))})]})}),e.jsx(ht,{open:n,onOpenChange:D=>!D&&k(),children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(ut,{children:"Generate API Token"}),e.jsx(Mt,{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(qR,{className:"bg-green-50 border-green-200",children:[e.jsx(Ha,{className:"h-4 w-4 text-green-600"}),e.jsx(eI,{className:"text-green-800",children:"Token Generated Successfully"}),e.jsx(tI,{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(O,{size:"icon",variant:"ghost",className:"absolute top-1 right-1 text-gray-400 hover:text-white hover:bg-slate-800",onClick:A,children:g?e.jsx(Ha,{className:"w-4 h-4 text-green-500"}):e.jsx(yy,{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(re,{htmlFor:"token-name",children:"Token Name"}),e.jsx(_e,{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(re,{htmlFor:"token-expiry",children:"Expiration (Days)"}),e.jsx(_e,{id:"token-expiry",type:"number",min:"1",placeholder:"Leave empty for no expiry",value:c,onChange:D=>{const F=D.target.value;if(F==="")d("");else{const w=parseInt(F);!isNaN(w)&&w>=1&&d(w)}}})]})]}),e.jsx(Dt,{children:m?e.jsx(O,{onClick:k,children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(O,{variant:"outline",onClick:k,children:"Cancel"}),e.jsx(O,{onClick:v,disabled:!l.trim()||x,children:x?"Generating...":"Generate Token"})]})})]})}),e.jsx(lg,{open:!!b,onOpenChange:D=>!D&&y(null),children:e.jsxs(ed,{children:[e.jsxs(cg,{children:[e.jsx(mg,{children:"Revoke API Token"}),e.jsxs(ug,{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(dg,{children:[e.jsx(hg,{children:"Cancel"}),e.jsx(xg,{onClick:T,className:"bg-red-600 hover:bg-red-700 text-white",children:"Revoke Token"})]})]})})]})}function aI(){const t=gs();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(O,{variant:"ghost",size:"icon",onClick:()=>t("/settings"),children:e.jsx(Cs,{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(de,{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(ur,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Password"}),e.jsx(Te,{children:"Manage your sign-in password"})]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"p-4 bg-gray-50 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Your password is managed through your organization's Single Sign-On (SSO) provider. Please contact your IT administrator to reset or change your password."})})})]}),e.jsxs(Z,{className:"shadow-md",children:[e.jsx(de,{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(Bp,{className:"w-5 h-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"API Tokens"}),e.jsx(Te,{children:"Manage personal access tokens for external integrations"})]})]})}),e.jsx(ee,{children:e.jsx(sI,{})})]})]})]})}function rI({onNavigate:t}){const[s,a]=u.useState([]),[r,n]=u.useState(!0),[i,l]=u.useState(1),[o,c]=u.useState(1),[d,m]=u.useState(0),[p,x]=u.useState("all"),[h,g]=u.useState(!1),f=20,b=async(F=i,w=p==="unread")=>{var L,_;try{n(F===1);const W=await xr.list({page:F,limit:f,unreadOnly:w}),I=((L=W.data)==null?void 0:L.notifications)||[],$=((_=W.data)==null?void 0:_.pagination)||{},M=$.total||0,R=$.totalPages||1;a(I),m(M),c(R),l(F)}catch(W){console.error("[Notifications] Failed to fetch:",W)}finally{n(!1),g(!1)}};u.useEffect(()=>{l(1),b(1,p==="unread")},[p]);const y=async F=>{var w;try{if(F.isRead||(await xr.markAsRead(F.notificationId),a(L=>L.map(_=>_.notificationId===F.notificationId?{..._,isRead:!0}:_))),F.actionUrl&&t){const L=(w=F.metadata)==null?void 0:w.requestNumber;if(L){let _=`request/${L}`;(F.notificationType==="mention"||F.notificationType==="comment"||F.notificationType==="worknote")&&(_+="?tab=worknotes"),F.notificationType==="document_added"&&(_+="?tab=documents"),t(_)}}}catch(L){console.error("[Notifications] Error handling notification click:",L)}},j=async()=>{try{g(!0),await xr.markAllAsRead(),await b(i,p==="unread")}catch(F){console.error("[Notifications] Error marking all as read:",F),g(!1)}},v=async F=>{try{await xr.delete(F),a(w=>w.filter(L=>L.notificationId!==F)),m(w=>w-1)}catch(w){console.error("[Notifications] Error deleting notification:",w)}},N=()=>{g(!0),b(i,p==="unread")},T=F=>{F<1||F>o||(l(F),b(F,p==="unread"))},A=F=>{const w="w-6 h-6";switch(F){case"mention":case"comment":return e.jsx(Qs,{className:`${w} text-blue-600`});case"worknote":return e.jsx(Ee,{className:`${w} text-purple-600`});case"document_added":return e.jsx(Ee,{className:`${w} text-teal-600`});case"assignment":return e.jsx(Il,{className:`${w} text-indigo-600`});case"approval":return e.jsx(Ve,{className:`${w} text-green-600`});case"rejection":return e.jsx(At,{className:`${w} text-red-600`});case"tat_alert":return e.jsx(it,{className:`${w} text-orange-600`});case"tat_breach":return e.jsx(Ze,{className:`${w} text-red-600`});case"tat_breach_initiator":return e.jsx(ss,{className:`${w} text-amber-600`});default:return e.jsx(Os,{className:`${w} text-gray-600`})}},k=F=>{switch(F==null?void 0:F.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(F=>!F.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(Os,{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(O,{variant:"outline",size:"sm",onClick:N,disabled:h,className:"gap-2",children:[e.jsx(_t,{className:`w-4 h-4 ${h?"animate-spin":""}`}),"Refresh"]}),D>0&&e.jsxs(O,{variant:"outline",size:"sm",onClick:j,disabled:h,className:"gap-2",children:[e.jsx(vy,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(O,{variant:p==="all"?"default":"outline",size:"sm",onClick:()=>{x("all"),l(1)},children:"All Notifications"}),e.jsxs(O,{variant:p==="unread"?"default":"outline",size:"sm",onClick:()=>{x("unread"),l(1)},children:["Unread",D>0&&e.jsx(oe,{className:"ml-2 bg-red-500 text-white",children:D})]})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Recent Activity"}),e.jsx(Te,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(ee,{children:r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"})}):s.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Os,{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(F=>{var w;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${F.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>y(F),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:A(F.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 ${F.isRead?"font-semibold":"font-bold"} text-gray-900`,children:F.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[F.priority&&F.priority!=="LOW"&&e.jsx(oe,{variant:"outline",className:`text-xs ${k(F.priority)}`,children:F.priority}),!F.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:F.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[wp(new Date(F.createdAt),{addSuffix:!0}),((w=F.metadata)==null?void 0:w.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",F.metadata.requestNumber]})]}),e.jsx(O,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:L=>{L.stopPropagation(),v(F.notificationId)},children:e.jsx(vr,{className:"w-3.5 h-3.5"})})]})]})]})},F.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(O,{variant:"outline",size:"sm",onClick:()=>T(i-1),disabled:i===1,children:[e.jsx(Nn,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,o)},(F,w)=>{let L;return o<=5||i<=3?L=w+1:i>=o-2?L=o-4+w:L=i-2+w,e.jsx(O,{variant:i===L?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>T(L),children:L},L)})}),e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>T(i+1),disabled:i===o,children:["Next",e.jsx(Wa,{className:"w-4 h-4"})]})]})]})]})}function nI({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(O,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(Cs,{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(Ee,{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 Jd({dateRange:t,customStartDate:s,customEndDate:a,showCustomDatePicker:r,tempCustomStartDate:n,tempCustomEndDate:i,onDateRangeChange:l,onShowCustomDatePickerChange:o,onStartDateChange:c,onEndDateChange:d,onApply:m,onCancel:p,testIdPrefix:x="date-filter"}){const h=s&&a?`${st(s,"d MMM yyyy")} - ${st(a,"d MMM yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${x}-container`,children:[e.jsx(bt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:t,onValueChange:l,"data-testid":`${x}-select`,children:[e.jsx(Ye,{className:"w-[160px]",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Qe,{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(na,{open:r,onOpenChange:o,children:[e.jsx(ia,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${x}-custom-trigger`,children:[e.jsx(bt,{className:"w-4 h-4"}),h]})}),e.jsx(la,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:`${x}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(aa,{value:n||null,onChange:g=>{const f=g?new Date(g):void 0;c(f)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full",id:`${x}-start-date`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:`${x}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(aa,{value:i||null,onChange:g=>{const f=g?new Date(g):void 0;d(f)},minDate:n||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full",id:`${x}-end-date`})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(O,{size:"sm",onClick:m,disabled:!n||!i,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":`${x}-apply-button`,children:"Apply"}),e.jsx(O,{size:"sm",variant:"outline",onClick:p,"data-testid":`${x}-cancel-button`,children:"Cancel"})]})]})})]})]})}function iI(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 yb(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 vb(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 lI(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function oI({lifecycleRequests:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,exporting:p,onDateRangeChange:x,onShowCustomDatePickerChange:h,onStartDateChange:g,onEndDateChange:f,onApplyCustomDate:b,onCancelCustomDate:y,onPageChange:j,onExport:v,onViewRequest:N}){return e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(de,{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(zt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(Te,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2",onClick:v,disabled:p,"data-testid":"export-lifecycle-button",children:[e.jsx(kt,{className:"w-4 h-4"}),p?"Exporting...":"Download CSV"]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(Jd,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:x,onShowCustomDatePickerChange:h,onStartDateChange:g,onEndDateChange:f,onApply:b,onCancel:y,testIdPrefix:"lifecycle"})})]}),e.jsxs(ee,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(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(Ze,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"lifecycle-empty",children:e.jsx("p",{className:"text-sm",children:"No lifecycle data available"})}):e.jsx("div",{className:"space-y-4",children:t.map(T=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${T.id}`,children:e.jsx("div",{className:"p-4 bg-gradient-to-r from-gray-50 to-white hover:bg-gray-100 cursor-pointer transition-all",onClick:()=>N(T.requestId||T.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("button",{onClick:A=>{A.stopPropagation(),N(T.requestId||T.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${T.id}`,children:T.id}),e.jsx(oe,{className:yb(T.priority),"data-testid":`lifecycle-priority-${T.id}`,children:T.priority}),e.jsx(oe,{className:vb(T.status),"data-testid":`lifecycle-status-${T.id}`,children:T.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:T.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:T.initiator})," on ",T.initDate]}),T.currentStage&&!T.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",T.currentStage]})]})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Current Stage"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:T.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",T.currentLevel,"/",T.totalLevels,")"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Overall TAT"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:T.overallTAT}),T.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[T.breachCount," breach",T.breachCount>1?"es":""]})]}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>N(T.requestId||T.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${T.id}`,children:e.jsx(Wa,{className:"w-4 h-4"})})]})]})})},T.id))}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"lifecycle-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(ze,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(O,{variant:"outline",size:"sm",onClick:()=>j(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>j(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function cI({activityLog:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,filterCategory:p,filterSeverity:x,exporting:h,onDateRangeChange:g,onShowCustomDatePickerChange:f,onStartDateChange:b,onEndDateChange:y,onApplyCustomDate:j,onCancelCustomDate:v,onCategoryChange:N,onSeverityChange:T,onClearFilters:A,onPageChange:k,onExport:D,onViewRequest:F}){const w=p!=="all"||x!=="all"||i!=="month"||l||o;return e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(de,{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($p,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(Te,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2",onClick:D,disabled:h,"data-testid":"export-activity-button",children:[e.jsx(kt,{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(Jd,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:g,onShowCustomDatePickerChange:f,onStartDateChange:b,onEndDateChange:y,onApply:j,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:N,"data-testid":"activity-category-filter",children:[e.jsx(Ye,{className:"w-40",children:e.jsx(Ge,{placeholder:"All Categories"})}),e.jsxs(Qe,{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:x,onValueChange:T,"data-testid":"activity-severity-filter",children:[e.jsx(Ye,{className:"w-40",children:e.jsx(Ge,{placeholder:"All Severities"})}),e.jsxs(Qe,{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"})]})]})]}),w&&e.jsx(O,{variant:"ghost",size:"sm",onClick:A,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(ee,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(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(Ze,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"activity-empty",children:e.jsx("p",{className:"text-sm",children:"No activity data available"})}):e.jsxs("div",{className:"rounded-lg border",children:[e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{className:"bg-gray-50",children:[e.jsx(Ie,{className:"font-semibold",children:"Timestamp"}),e.jsx(Ie,{className:"font-semibold",children:"User"}),e.jsx(Ie,{className:"font-semibold",children:"Action"}),e.jsx(Ie,{className:"font-semibold",children:"Details"}),e.jsx(Ie,{className:"font-semibold",children:"IP Address"}),e.jsx(Ie,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(Fs,{children:t.map((L,_)=>e.jsxs(tt,{className:"hover:bg-gray-50","data-testid":`activity-row-${_}`,children:[e.jsx(ve,{className:"text-xs font-medium",children:L.timestamp}),e.jsx(ve,{className:"text-sm",children:L.user}),e.jsx(ve,{children:e.jsx(oe,{className:iI(L.action),"data-testid":`activity-action-${_}`,children:L.action})}),e.jsx(ve,{className:"text-sm text-gray-600",children:L.details}),e.jsx(ve,{className:"text-xs font-mono text-gray-500",children:L.ip&&L.ip!=="N/A"?e.jsx("span",{title:L.userAgent||"",children:L.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(ve,{children:L.requestId!=="-"&&L.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const W=L.requestId;W&&F(W)},className:"hover:underline","data-testid":`activity-request-link-${_}`,children:e.jsx(oe,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:L.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},_))})]}),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(O,{variant:"outline",size:"sm",onClick:()=>k(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>k(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function dI({agingWorkflows:t,loading:s,loadingPage:a,error:r,pagination:n,threshold:i,thresholdError:l,dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:p,tempCustomEndDate:x,searchQuery:h,exporting:g,onThresholdChange:f,onThresholdBlur:b,onDateRangeChange:y,onShowCustomDatePickerChange:j,onStartDateChange:v,onEndDateChange:N,onApplyCustomDate:T,onCancelCustomDate:A,onSearchChange:k,onPageChange:D,onExport:F,onViewRequest:w}){return e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(de,{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(Hc,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(Te,{className:"text-gray-600",children:"Workflows exceeding aging threshold"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Threshold:"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_e,{type:"number",min:"1",value:i,onChange:L=>f(L.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(oe,{variant:"outline",className:"font-semibold","data-testid":"aging-total-badge",children:[n.totalRecords," workflows"]}),e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2",onClick:F,disabled:g,"data-testid":"export-aging-button",children:[e.jsx(kt,{className:"w-4 h-4"}),g?"Exporting...":"Download CSV"]})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(Jd,{dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:p,tempCustomEndDate:x,onDateRangeChange:y,onShowCustomDatePickerChange:j,onStartDateChange:v,onEndDateChange:N,onApply:T,onCancel:A,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(_e,{placeholder:"Search by Request ID, Title, or Initiator...",value:h,onChange:L=>k(L.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(ee,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(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(Ze,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"aging-empty",children:e.jsxs("p",{className:"text-sm",children:["No workflows found exceeding ",i," days threshold"]})}):e.jsxs("div",{className:"rounded-lg border",children:[e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{className:"bg-gray-50",children:[e.jsx(Ie,{className:"font-semibold",children:"Request ID"}),e.jsx(Ie,{className:"font-semibold",children:"Title"}),e.jsx(Ie,{className:"font-semibold",children:"Initiator"}),e.jsx(Ie,{className:"font-semibold",children:"Start Date"}),e.jsx(Ie,{className:"font-semibold",children:"Days Open"}),e.jsx(Ie,{className:"font-semibold",children:"Current Stage"}),e.jsx(Ie,{className:"font-semibold",children:"Assigned To"}),e.jsx(Ie,{className:"font-semibold",children:"Priority"}),e.jsx(Ie,{className:"font-semibold",children:"Status"})]})}),e.jsx(Fs,{children:t.map(L=>e.jsxs(tt,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${L.id}`,children:[e.jsx(ve,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>w(L.requestId||L.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${L.id}`,children:L.id})}),e.jsx(ve,{className:"text-sm",children:L.title}),e.jsx(ve,{className:"text-sm",children:L.initiator}),e.jsx(ve,{className:"text-sm text-gray-600",children:L.startDate}),e.jsx(ve,{children:e.jsxs(oe,{className:`${lI(L.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${L.id}`,children:[L.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(ve,{className:"text-sm",children:L.currentStage}),e.jsx(ve,{className:"text-sm",children:L.assignedTo&&L.assignedTo!=="N/A"?L.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(ve,{children:e.jsx(oe,{className:yb(L.priority),"data-testid":`aging-priority-${L.id}`,children:L.priority})}),e.jsx(ve,{children:e.jsx(oe,{className:vb(L.status),"data-testid":`aging-status-${L.id}`,children:L.status})})]},L.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(O,{variant:"outline",size:"sm",onClick:()=>D(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>D(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function Uo(t="month"){const[s,a]=u.useState(t),[r,n]=u.useState(void 0),[i,l]=u.useState(void 0),[o,c]=u.useState(!1),[d,m]=u.useState(void 0),[p,x]=u.useState(void 0),h=u.useCallback(N=>{const T=N;a(T),T!=="custom"?(n(void 0),l(void 0),m(void 0),x(void 0),c(!1)):(m(r),x(i),c(!0))},[r,i]),g=u.useCallback(()=>{if(d&&p){if(d>p){const N=d;n(p),l(N),m(p),x(N)}else n(d),l(p);c(!1)}},[d,p]),f=u.useCallback(()=>{c(!1),m(r),x(i),(!r||!i)&&(n(void 0),l(void 0),a("month"))},[r,i]),b=u.useCallback(N=>{N?(m(N),p&&N>p&&x(N)):m(void 0)},[p]),y=u.useCallback(N=>{N?(x(N),d&&N<d&&m(N)):x(void 0)},[d]),j=u.useCallback(()=>r&&i?`${st(r,"MMM d, yyyy")} - ${st(i,"MMM d, yyyy")}`:"Select dates",[r,i]),v=u.useCallback(()=>{a("month"),n(void 0),l(void 0),c(!1),m(void 0),x(void 0)},[]);return{dateRange:s,customStartDate:r,customEndDate:i,showCustomDatePicker:o,tempCustomStartDate:d,tempCustomEndDate:p,setShowCustomDatePicker:c,handleDateRangeChange:h,handleApplyCustomDate:g,handleCancelCustomDate:f,handleStartDateChange:b,handleEndDateChange:y,getDisplayDateRange:j,reset:v}}function mI(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 Nb(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 Or(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 wb(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 uI=10;function xI({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=u.useState([]),[i,l]=u.useState(!0),[o,c]=u.useState(!1),[d,m]=u.useState(null),[p,x]=u.useState({page:1,totalPages:1,totalRecords:0}),h=u.useRef(!0),g=u.useCallback(async(f=1)=>{const b=f===1&&h.current;try{b?l(!0):c(!0),m(null);const y=await $t.getLifecycleReport(f,uI,t,s,a),j=y.lifecycleData.map(v=>{const N=mI(v.overallTATHours);return{id:v.requestNumber,requestId:v.requestId,title:v.title,priority:v.priority||"medium",status:v.status,initiator:v.initiatorName||"Unknown",initDate:Nb(v.submissionDate),currentStage:v.currentStageName||`Level ${v.currentLevel}`,overallTAT:N,currentLevel:v.currentLevel,totalLevels:v.totalLevels,breachCount:v.breachCount||0}});n(j),x({page:y.pagination.currentPage,totalPages:y.pagination.totalPages,totalRecords:y.pagination.totalRecords})}catch(y){console.error("Failed to fetch lifecycle data:",y),m((y==null?void 0:y.message)||"Failed to load lifecycle data")}finally{b?l(!1):c(!1)}b&&(h.current=!1)},[t,s,a]);return u.useEffect(()=>{t==="custom"&&(!s||!a)||g(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:o,error:d,pagination:p,fetchData:g}}const hI=20;function pI({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,l]=u.useState([]),[o,c]=u.useState(!0),[d,m]=u.useState(!1),[p,x]=u.useState(null),[h,g]=u.useState({page:1,totalPages:1,totalRecords:0}),f=u.useRef(!0),b=u.useCallback(async(y=1)=>{const j=y===1&&f.current;try{j?c(!0):m(!0),x(null);const v=await $t.getActivityLogReport(y,hI,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),N=v.activities.map(T=>{const A=wb(T.type||"",T.details),k=(T.type||"").toLowerCase()==="login"||T.requestId==="00000000-0000-0000-0000-000000000001"||T.requestId==="SYSTEM_LOGIN",D=k?T.details||"User login":T.requestTitle||T.requestNumber||T.details||"N/A";return{timestamp:T.timestamp?Nb(T.timestamp):"N/A",user:T.userName||"Unknown",action:A,details:D,ip:T.ipAddress||"N/A",userAgent:T.userAgent||null,requestId:k?"System Login":T.requestNumber||T.requestId||"-",userId:T.userId}});l(N),g({page:v.pagination.currentPage,totalPages:v.pagination.totalPages,totalRecords:v.pagination.totalRecords})}catch(v){console.error("Failed to fetch activity data:",v),x((v==null?void 0:v.message)||"Failed to load activity data")}finally{j?c(!1):m(!1)}j&&(f.current=!1)},[r,n,t,s,a]);return u.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 gI=20;function fI({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,l]=u.useState([]),[o,c]=u.useState(!0),[d,m]=u.useState(!1),[p,x]=u.useState(null),[h,g]=u.useState({page:1,totalPages:1,totalRecords:0}),f=u.useRef(!0),b=u.useCallback(async(j=1)=>{const v=j===1&&f.current;try{v?c(!0):m(!0),x(null);const N=parseInt(t,10);if(isNaN(N)||N<1){x("Please enter a valid threshold (minimum 1 day)");return}const T=await $t.getWorkflowAgingReport(N,j,gI,s,a,r),A=T.agingData.map(k=>({id:k.requestNumber||k.requestId,requestId:k.requestId,title:k.title,initiator:k.initiatorName||"Unknown",startDate:k.submissionDate?new Date(k.submissionDate).toLocaleDateString():"N/A",daysOpen:k.daysOpen,currentStage:k.currentStageName||`Level ${k.currentLevel}`,assignedTo:k.currentApproverName||"N/A",priority:k.priority||"medium",status:k.status||"pending"}));l(A),g({page:T.pagination.currentPage,totalPages:T.pagination.totalPages,totalRecords:T.pagination.totalRecords})}catch(N){console.error("Failed to fetch aging data:",N),x((N==null?void 0:N.message)||"Failed to load aging data")}finally{v?c(!1):m(!1)}v&&(f.current=!1)},[t,s,a,r]),y=u.useMemo(()=>i.filter(j=>{var N,T,A;if(!n)return!0;const v=n.toLowerCase();return((N=j.id)==null?void 0:N.toLowerCase().includes(v))||((T=j.title)==null?void 0:T.toLowerCase().includes(v))||((A=j.initiator)==null?void 0:A.toLowerCase().includes(v))}),[i,n]);return u.useEffect(()=>{s==="custom"&&(!a||!r)||b(1)},[t,s,a,r]),{agingWorkflows:y,loading:o,loadingPage:d,error:p,pagination:h,fetchData:b}}function bI(t="7"){const[s,a]=u.useState(t),[r,n]=u.useState(null),i=u.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=u.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 jI(t,s,a){const r=await $t.getLifecycleReport(1,1e4,t,s,a),n=[["Request Number","Title","Priority","Overall Status","Initiator","Submission Date","Closure Date","Total Levels","Current Level","Overall TAT (Hours)","Overall TAT (Days)","Breach Count","Level Number","Level Name","Approver Name","Approver Email","Level Status","Level Start Date","Level Completion Date","Level TAT (Hours)","Level TAT (Days)","Level TAT Compliance","Level Elapsed Hours","Level Remaining Hours","Level TAT % Used"].join(",")];for(const i of r.lifecycleData)try{const l=await Ms(i.requestId||i.requestNumber),o=i.submissionDate?Or(i.submissionDate):"N/A",c=i.closureDate?Or(i.closureDate):"N/A",d=i.overallTATHours||0,m=d>0?(d/8).toFixed(2):"0",p=i.totalLevels||1,x=Math.min(Math.max(1,i.currentLevel||1),p),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(),x.toString(),d.toString(),m,(i.breachCount||0).toString(),"N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(g.join(","))}else h.forEach(g=>{const f=g.levelStartTime?Or(g.levelStartTime):"N/A",b=g.levelEndTime||g.completedAt?Or(g.levelEndTime||g.completedAt):"N/A",y=g.tatHours||0,j=g.tatDays||(y>0?(y/8).toFixed(2):"0");let v="N/A",N="N/A",T="N/A",A="N/A";if(g.levelStartTime){const D=new Date(g.levelStartTime);if(N=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-D.getTime())/(1e3*60*60)).toFixed(2),y>0){const L=parseFloat(N);T=Math.max(0,y-L).toFixed(2),A=(L/y*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?v=L<=y?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?v=L<=y?"On Track":"At Risk":v="N/A"}}const k=[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,y.toString(),j.toString(),v,N,T,A];n.push(k.join(","))})}catch(l){console.error(`Failed to fetch details for request ${i.requestNumber}:`,l);const o=i.submissionDate?Or(i.submissionDate):"N/A",c=i.overallTATHours||0,d=c>0?(c/8).toFixed(2):"0",m=i.totalLevels||1,p=Math.min(Math.max(1,i.currentLevel||1),m),x=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,"N/A",m.toString(),p.toString(),c.toString(),d,(i.breachCount||0).toString(),"Error","Error fetching details","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(x.join(","))}Zd(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function yI(t,s,a,r,n){const i=await $t.getActivityLogReport(1,1e4,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),l=[["Timestamp","User","Action","Details","IP Address","User Agent","Request ID"].join(",")];i.activities.forEach(o=>{const c=wb(o.type||"",o.details),m=[o.timestamp?Or(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(","))}),Zd(l,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function vI(t,s,a,r){const n=await $t.getWorkflowAgingReport(t,1,1e4,s,a,r),i=[["Request ID","Title","Initiator","Start Date","Days Open (Business)","Current Stage","Assigned To","Priority","Status"].join(",")];n.agingData.forEach(l=>{const o=l.submissionDate?Or(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(","))}),Zd(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function Zd(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 NI(){const[t,s]=u.useState(!1),[a,r]=u.useState(!1),[n,i]=u.useState(!1),l=u.useCallback(async(d,m,p)=>{try{s(!0),await jI(d,m,p)}catch(x){console.error("Failed to export lifecycle data:",x),alert("Failed to export lifecycle data. Please try again.")}finally{s(!1)}},[]),o=u.useCallback(async(d,m,p,x,h)=>{try{r(!0),await yI(d,m,p,x,h)}catch(g){console.error("Failed to export activity data:",g),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),c=u.useCallback(async(d,m,p,x)=>{try{i(!0),await vI(d,m,p,x)}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 wI({onBack:t}){const s=gs(),[a,r]=u.useState(""),[n,i]=u.useState("all"),[l,o]=u.useState("all"),c=Uo("month"),d=Uo("month"),m=Uo("month"),p=bI("7"),x=xI({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),h=pI({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:l}),g=fI({threshold:p.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),f=NI(),b=u.useCallback(()=>{t?t():s("/dashboard")},[t,s]),y=u.useCallback(A=>{vl({requestId:A,navigate:s})},[s]),j=u.useCallback(()=>{f.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[f,c]),v=u.useCallback(()=>{f.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,l)},[f,d,n,l]),N=u.useCallback(()=>{const A=parseInt(p.threshold,10);!isNaN(A)&&A>=1&&f.handleExportAging(A,m.dateRange,m.customStartDate,m.customEndDate)},[f,p.threshold,m]),T=u.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(nI,{onBack:b}),e.jsx(oI,{lifecycleRequests:x.lifecycleRequests,loading:x.loading,loadingPage:x.loadingPage,error:x.error,pagination:x.pagination,dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate,showCustomDatePicker:c.showCustomDatePicker,tempCustomStartDate:c.tempCustomStartDate,tempCustomEndDate:c.tempCustomEndDate,exporting:f.exportingLifecycle,onDateRangeChange:c.handleDateRangeChange,onShowCustomDatePickerChange:c.setShowCustomDatePicker,onStartDateChange:c.handleStartDateChange,onEndDateChange:c.handleEndDateChange,onApplyCustomDate:c.handleApplyCustomDate,onCancelCustomDate:c.handleCancelCustomDate,onPageChange:x.fetchData,onExport:j,onViewRequest:y}),e.jsx(cI,{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:T,onPageChange:h.fetchData,onExport:v,onViewRequest:y}),e.jsx(dI,{agingWorkflows:g.agingWorkflows,loading:g.loading,loadingPage:g.loadingPage,error:g.error,pagination:g.pagination,threshold:p.threshold,thresholdError:p.thresholdError,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,showCustomDatePicker:m.showCustomDatePicker,tempCustomStartDate:m.tempCustomStartDate,tempCustomEndDate:m.tempCustomEndDate,searchQuery:a,exporting:f.exportingAging,onThresholdChange:p.handleThresholdChange,onThresholdBlur:p.handleThresholdBlur,onDateRangeChange:m.handleDateRangeChange,onShowCustomDatePickerChange:m.setShowCustomDatePicker,onStartDateChange:m.handleStartDateChange,onEndDateChange:m.handleEndDateChange,onApplyCustomDate:m.handleApplyCustomDate,onCancelCustomDate:m.handleCancelCustomDate,onSearchChange:r,onPageChange:g.fetchData,onExport:N,onViewRequest:y})]})})}function zi({className:t,...s}){return e.jsx("div",{"data-slot":"skeleton",className:$e("bg-accent animate-pulse rounded-md",t),...s})}function CI(){const t=gs(),[s,a]=u.useState(()=>Ih()||[]),[r,n]=u.useState(()=>!Ih()),[i,l]=u.useState(""),o=async()=>{try{s.length===0&&n(!0);const m=await Xl();a(m||[])}catch(m){console.error("Failed to fetch templates:",m),Q.error("Failed to load templates")}finally{n(!1)}};u.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(O,{onClick:()=>t("/admin/create-template"),className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(is,{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(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(_e,{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(de,{children:[e.jsx(zi,{className:"h-6 w-3/4 mb-2"}),e.jsx(zi,{className:"h-4 w-1/2"})]}),e.jsxs(ee,{children:[e.jsx(zi,{className:"h-4 w-full mb-2"}),e.jsx(zi,{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(Ee,{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(O,{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(de,{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(Ee,{className:"w-5 h-5"})}),e.jsx(oe,{variant:"outline",className:d(m.priority),children:m.priority})]}),e.jsx(ue,{className:"line-clamp-1 text-lg",children:m.name}),e.jsx(Te,{className:"line-clamp-3 min-h-[4.5rem]",children:m.description})]}),e.jsxs(ee,{children:[e.jsxs("div",{className:"text-sm text-gray-500 mb-4 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Category:"}),e.jsx("span",{className:"font-medium text-gray-900",children:m.category})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"SLA:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[m.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Approvers:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[((p=m.approvers)==null?void 0:p.length)||0," levels"]})]})]}),e.jsx("div",{className:"flex gap-2 pt-2 border-t mt-2",children:e.jsxs(O,{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(Ny,{className:"w-4 h-4 mr-2"}),"Edit"]})})]})]},m.id)})})]})}function Yh(){const t=gs(),{templateId:s}=Aa(),a=!!s,[r,n]=u.useState(!1),[i,l]=u.useState(!1),{searchResults:o,searchLoading:c,searchUsersDebounced:d,clearSearch:m}=A0(),[p,x]=u.useState(""),[h,g]=u.useState({name:"",description:"",category:"General",priority:"medium",estimatedTime:"2 days",suggestedSLA:24,approvers:[]});u.useEffect(()=>{a&&s&&(async()=>{try{l(!0);const D=(await Xl()).find(F=>F.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||[]}):(Q.error("Template not found"),t("/admin/templates"))}catch(k){console.error("Failed to load template:",k),Q.error("Failed to load template details")}finally{l(!1)}})()},[a,s,t]);const f=A=>{const{name:k,value:D}=A.target;g(F=>({...F,[k]:D}))},b=(A,k)=>{g(D=>({...D,[A]:k}))},y=A=>{if(x(A),A.startsWith("@")&&A.slice(1).length>=1){d(A,5);return}m()},j=A=>{if(h.approvers.some(k=>k.userId===A.userId)){Q.error("Approver already added");return}g(k=>({...k,approvers:[...k.approvers,{userId:A.userId,name:A.displayName||A.email,email:A.email,level:k.approvers.length+1,tat:24,tatType:"hours"}]})),x(""),m()},v=A=>{const k=[...h.approvers];k.splice(A,1),k.forEach((D,F)=>D.level=F+1),g(D=>({...D,approvers:k}))},N=async A=>{if(A.preventDefault(),!h.name||!h.description){Q.error("Please fill in required fields");return}if(h.approvers.length===0){Q.error("Please add at least one approver");return}const k={...h,approvers:h.approvers.map(D=>({...D,tat:D.tatType==="days"?parseInt(D.tat)*24:parseInt(D.tat)}))};try{n(!0),a&&s?(await qT(s,k),Q.success("Template updated successfully")):(await ZT(k),Q.success("Template created successfully")),t("/admin/templates")}catch(D){Q.error(a?"Failed to update template":"Failed to create template"),console.error(D)}finally{n(!1)}};if(i)return e.jsx("div",{className:"flex h-96 items-center justify-center",children:e.jsx(ze,{className:"h-8 w-8 animate-spin text-gray-400"})});const T=h.name&&h.description&&h.approvers.length>0&&h.approvers.every(A=>{const k=parseInt(String(A.tat))||0,D=A.tatType==="days"?7:24;return k>=1&&k<=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(O,{variant:"ghost",size:"icon",onClick:()=>t("/admin/templates"),children:e.jsx(Cs,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:a?"Edit Workflow Template":"Create Workflow Template"}),e.jsx("p",{className:"text-gray-500",children:a?"Update existing workflow configuration":"Define a new standardized request workflow"})]})]}),e.jsxs("form",{onSubmit:N,className:"space-y-6",children:[e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Basic Information"}),e.jsx(Te,{children:"General details about the template"})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Template Name *"}),e.jsx(_e,{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(re,{htmlFor:"category",children:"Category"}),e.jsx("div",{className:"relative",children:e.jsx(_e,{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(re,{htmlFor:"description",children:"Description *"}),e.jsx(Vs,{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(re,{htmlFor:"priority",children:"Default Priority"}),e.jsxs(He,{name:"priority",value:h.priority,onValueChange:A=>b("priority",A),children:[e.jsx(Ye,{children:e.jsx(Ge,{placeholder:"Select priority"})}),e.jsxs(Qe,{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(re,{htmlFor:"estimatedTime",children:"Estimated Time"}),e.jsx(_e,{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(re,{htmlFor:"suggestedSLA",children:"SLA (Hours)"}),e.jsx(_e,{id:"suggestedSLA",name:"suggestedSLA",type:"number",placeholder:"24",value:h.suggestedSLA,onChange:f,className:"border-gray-200"})]})]})]})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Approver Workflow"}),e.jsx(Te,{children:"Define static approvers for this template"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[h.approvers.map((A,k)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsxs(oe,{variant:"outline",className:"bg-white",children:["Level ",A.level]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:A.name}),e.jsx("div",{className:"text-sm text-gray-500",children:A.email})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(re,{htmlFor:`tat-${k}`,className:"text-xs whitespace-nowrap",children:"TAT"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(_e,{id:`tat-${k}`,type:"number",className:"h-8 w-16 border-gray-200",value:A.tat||"",min:1,max:A.tatType==="days"?7:24,placeholder:A.tatType==="days"?"1":"24",onChange:D=>{if((parseInt(D.target.value)||0)<0)return;const w=[...h.approvers];w[k].tat=D.target.value,g(L=>({...L,approvers:w}))}}),e.jsxs(He,{value:A.tatType||"hours",onValueChange:D=>{const F=[...h.approvers];F[k].tatType=D,F[k].tat=1,g(w=>({...w,approvers:F}))},children:[e.jsx(Ye,{className:"h-8 w-20 text-xs px-2",children:e.jsx(Ge,{})}),e.jsxs(Qe,{children:[e.jsx(X,{value:"hours",children:"Hours"}),e.jsx(X,{value:"days",children:"Days"})]})]})]})]})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",onClick:()=>v(k),children:e.jsx(vt,{className:"w-4 h-4 text-gray-500 hover:text-red-600"})})]},k)),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(re,{children:"Add Approver"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(_e,{placeholder:"Type '@' to search user by name or email...",value:p,onChange:A=>y(A.target.value),className:"border-gray-200"})}),(c||o.length>0)&&e.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-white border rounded-lg shadow-lg z-10 max-h-60 overflow-y-auto",children:[c&&e.jsx("div",{className:"p-2 text-sm text-gray-500",children:"Searching..."}),o.map(A=>e.jsxs("div",{className:"p-2 hover:bg-gray-50 cursor-pointer flex items-center gap-3",onClick:()=>j(A),children:[e.jsx(ds,{className:"h-8 w-8",children:e.jsx(ms,{children:(A.displayName||"U").substring(0,2)})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:A.displayName}),e.jsx("div",{className:"text-xs text-gray-500",children:A.email})]})]},A.userId))]})]}),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 A=h.approvers.reduce((D,F)=>{const w=Number(F.tat||0);return(F.tatType||"hours")==="days"?D+w:D+w/24},0)||0,k=Math.ceil(A);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[k," ",k===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((A,k)=>{const D=Number(A.tat||0),w=(A.tatType||"hours")==="days"?D*24:D;return D?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",k+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[w," ",w===1?"hour":"hours"]})]})},k):null})}),(()=>{const A=h.approvers.reduce((D,F)=>{const w=Number(F.tat||0);return(F.tatType||"hours")==="days"?D+w*24:D+w},0)||0,k=Math.ceil(A/8);return A===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[A,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children:k}),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(O,{type:"button",variant:"outline",onClick:()=>t("/admin/templates"),children:"Cancel"}),e.jsx(O,{type:"submit",disabled:r||!T,className:"bg-re-green hover:bg-re-green/90",children:r?"Saving...":e.jsxs(e.Fragment,{children:[e.jsx(La,{className:"w-4 h-4 mr-2"}),a?"Update Template":"Create Template"]})})]})]})]})}function SI({template:t,formData:s,setFormData:a,documents:r,setDocuments:n}){const i=u.useRef(null),[l,o]=u.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)},x=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(ee,{className:"pt-6",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-xl font-bold text-gray-800",children:t.name}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.description})]}),e.jsxs("div",{className:"flex gap-4 text-sm text-gray-600 bg-gray-50 p-3 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-semibold",children:"Category:"})," ",t.category]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-semibold",children:"Priority:"}),e.jsx("span",{className:"capitalize",children:t.priority})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-semibold",children:"SLA:"})," ",t.suggestedSLA," Hours"]})]})]})}),e.jsx(Z,{children:e.jsxs(ee,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"requestTitle",children:"Request Title *"}),e.jsx(_e,{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(re,{htmlFor:"justification",className:"text-base font-semibold",children:"Request Detail *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Explain what you need approval for, why it's needed, and any relevant details."}),e.jsx(Ci,{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(ee,{className:"pt-6 space-y-4",children:[e.jsx(re,{children:"Supporting Documents"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>{var h;return(h=i.current)==null?void 0:h.click()},children:[e.jsx(vs,{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(Ee,{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:[x(h)&&e.jsx(O,{variant:"ghost",size:"icon",onClick:()=>m(h),children:e.jsx(wt,{className:"w-4 h-4 text-gray-500 hover:text-blue-600"})}),e.jsx(O,{variant:"ghost",size:"icon",onClick:()=>d(g),children:e.jsx(vt,{className:"w-4 h-4 text-gray-500 hover:text-red-500"})})]})]},g))})]})}),l&&e.jsx(qr,{fileName:l.file.name,fileType:l.file.type,fileUrl:l.url,fileSize:l.file.size,open:!!l,onClose:p})]})}function AI({template:t,formData:s,documents:a}){const r=t.workflowApprovers||[];return e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Ze,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900",children:"Ready to Submit?"}),e.jsx("p",{className:"text-sm text-blue-700 mt-1",children:"Please review the details below. This request will follow the standardized approval workflow defined by the administrator."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsxs(Z,{children:[e.jsx(de,{className:"pb-3",children:e.jsx(ue,{className:"text-lg",children:"Request Overview"})}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Title"}),e.jsx("p",{className:"text-base font-medium text-gray-900 mt-1",children:s.title})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Request Detail"}),e.jsx("div",{className:"text-sm text-gray-700 mt-1 prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:Ua(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(oe,{variant:"secondary",className:"pl-1 pr-2 py-1 flex items-center gap-1.5 h-auto",children:[e.jsx(Ee,{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(de,{className:"pb-3",children:e.jsx(ue,{className:"text-lg",children:"Approval Workflow"})}),e.jsx(ee,{children:e.jsx("div",{className:"relative pl-6 border-l-2 border-gray-100 space-y-8 py-2",children:r.map((n,i)=>e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute -left-[31px] top-1 w-4 h-4 rounded-full bg-white border-2 border-blue-500 flex items-center justify-center",children:e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-blue-500"})}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-3 border border-gray-100",children:[e.jsxs("div",{className:"flex justify-between items-start mb-1",children:[e.jsxs("div",{children:[e.jsx("h5",{className:"font-semibold text-gray-800 text-sm",children:n.name||n.email}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Level ",n.level," Approver"]})]}),e.jsxs(oe,{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(de,{className:"pb-3",children:e.jsx(ue,{className:"text-sm uppercase text-gray-500",children:"Properties"})}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Template"}),e.jsx("span",{className:"text-sm font-medium text-right",children:t.name})]}),e.jsx(Zt,{}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Priority"}),e.jsx(oe,{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(Zt,{}),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 TI(){const{templateId:t}=Aa(),s=gs(),{user:a}=us(),[r,n]=u.useState(!0),[i,l]=u.useState(!1),[o,c]=u.useState(null),[d,m]=u.useState(1),[p,x]=u.useState([]),[h,g]=u.useState({title:"",description:""}),f=["Request Details","Review & Submit"];u.useEffect(()=>{t&&(async()=>{try{n(!0);const v=(await Xl()).find(N=>N.id===t);if(v){const N={id:v.id,name:v.name,description:v.description,category:v.category,icon:Ee,estimatedTime:v.estimatedTime,commonApprovers:v.approvers.map(T=>T.name),workflowApprovers:v.approvers,suggestedSLA:v.suggestedSLA,priority:v.priority,fields:v.fields||{}};c(N),g({title:N.name,description:N.description})}else Q.error("Template not found")}catch(j){console.error("Error loading template:",j),Q.error("Failed to load template details")}finally{n(!1)}})()},[t,s]);const b=async()=>{var y;if(o)try{l(!0);const j={templateId:o.id,templateType:"TEMPLATE",title:h.title,description:h.description,priorityUi:o.priority==="high"?"express":"standard",approverCount:((y=o.workflowApprovers)==null?void 0:y.length)||0,approvers:(o.workflowApprovers||[]).map(N=>({email:N.email,name:N.name,tat:N.tat,tatType:"hours"})),spectators:[],ccList:[]},v=await dd(j,p);v&&v.id&&await Ug(v.id),Q.success("Request Submitted Successfully",{description:`Your request "${h.title}" has been created.`}),s("/my-requests")}catch(j){console.error("Submission failed:",j),Q.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(O,{variant:"ghost",size:"icon",onClick:()=>s("/new-request"),children:e.jsx(Cs,{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(O,{variant:"outline",onClick:()=>s("/dashboard"),children:"Cancel Request"})]}),e.jsx(S0,{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(SI,{template:o,formData:h,setFormData:g,documents:p,setDocuments:x}):e.jsx(AI,{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(O,{variant:"outline",onClick:()=>d===1?s("/new-request"):m(1),disabled:i,children:d===1?"Cancel":"Back to Details"}),e.jsx(O,{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(Wa,{className:"w-4 h-4 ml-1"})]}):e.jsxs(e.Fragment,{children:[i?"Submitting...":"Submit Request"," ",e.jsx(Ha,{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(Ee,{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(O,{variant:"outline",onClick:()=>s("/dashboard"),children:"Go to Dashboard"}),e.jsx(O,{onClick:()=>s("/new-request"),children:"Browse Templates"})]})]})})}function kI({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(re,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(He,{value:t,onValueChange:a,children:[e.jsx(Ye,{id:"default-period",children:e.jsx(Ge,{})}),e.jsx(Qe,{children:n.map(i=>e.jsx(X,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(_e,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function DI({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(cs,{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(cs,{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(cs,{checked:a,onCheckedChange:i})]})]})}const RI=["CSV","Excel","PDF","JSON"];function II({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(re,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:RI.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Kd,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(re,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function FI({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(_e,{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 PI(){const[t,s]=u.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{Q.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Analytics & Reporting Configuration"}),e.jsx(Te,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(kI,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(Zt,{}),e.jsx(DI,{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(Zt,{}),e.jsx(II,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(FI,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(O,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(La,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const EI=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"}},_I=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function MI({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{children:[e.jsx(Ie,{children:"User"}),e.jsx(Ie,{children:"Role"}),e.jsx(Ie,{children:"Department"}),e.jsx(Ie,{children:"Status"}),e.jsx(Ie,{className:"text-right",children:"Actions"})]})}),e.jsx(Fs,{children:t.length===0?e.jsx(tt,{children:e.jsx(ve,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(tt,{className:"hover:bg-muted/50",children:[e.jsx(ve,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ds,{className:"size-10",children:e.jsx(ms,{className:"bg-re-green text-white",children:_I(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(ve,{children:e.jsx(oe,{className:EI(n.role),children:n.role})}),e.jsx(ve,{children:n.department}),e.jsx(ve,{children:e.jsxs(oe,{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(ve,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx(Ml,{className:"w-4 h-4"})}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(wy,{className:"w-4 h-4"})}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(vr,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function LI({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 OI(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function $I(){const[t,s]=u.useState(""),[a,r]=u.useState([]),[n,i]=u.useState(!1),[l,o]=u.useState(null),[c,d]=u.useState("USER"),[m,p]=u.useState(!1),[x,h]=u.useState(!1),[g,f]=u.useState(null),[b,y]=u.useState([]),[j,v]=u.useState(!1),[N,T]=u.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[A,k]=u.useState("ELEVATED"),[D,F]=u.useState(1),[w,L]=u.useState(1),[_,W]=u.useState(0),I=10,$=u.useRef(null),M=u.useCallback(OI(async J=>{var q,se,ne;if(!J||!J.startsWith("@")||J.length<2){r([]),i(!1);return}i(!0);try{const te=J.slice(1),we=((q=(await ua.searchUsers(te,20)).data)==null?void 0:q.data)||[];r(we)}catch(te){console.error("Search failed:",te),f({type:"error",text:((ne=(se=te.response)==null?void 0:se.data)==null?void 0:ne.message)||"Failed to search users"})}finally{i(!1)}},300),[]),R=J=>{const q=J.target.value;s(q),M(q)},C=async J=>{var q,se;try{const ne=b.find(fe=>fe.email.toLowerCase()===J.toLowerCase());if(ne)return ne.role;const we=(((se=(q=(await ua.getUsersByRole("ALL",1,1e3)).data)==null?void 0:q.data)==null?void 0:se.users)||[]).find(fe=>{var ke;return((ke=fe.email)==null?void 0:ke.toLowerCase())===J.toLowerCase()});return we&&we.role?we.role:null}catch(ne){return console.error("Failed to fetch user role:",ne),null}},H=async J=>{o(J),s(J.email),r([]),h(!0);try{const q=await C(J.email);d(q||"USER")}catch(q){console.error("Failed to fetch user role:",q),d("USER")}finally{h(!1)}},z=async()=>{var J,q;if(!l||!c){f({type:"error",text:"Please select a user and role"});return}p(!0),f(null);try{await ua.assignRole(l.email,c),f({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await P(),await S(),Q.success("Role assigned successfully")}catch(se){console.error("Role assignment failed:",se);const ne=((q=(J=se.response)==null?void 0:J.data)==null?void 0:q.error)||"Failed to assign role";f({type:"error",text:ne}),Q.error(ne)}finally{p(!1)}},P=async(J=D)=>{var q,se,ne,te,ge,we;v(!0);try{const fe=await ua.getUsersByRole(A,J,I),ke=((se=(q=fe.data)==null?void 0:q.data)==null?void 0:se.users)||[],le=(te=(ne=fe.data)==null?void 0:ne.data)==null?void 0:te.pagination,Ne=(we=(ge=fe.data)==null?void 0:ge.data)==null?void 0:we.summary;y(ke.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&&(F(le.currentPage),L(le.totalPages),W(le.totalUsers)),Ne&&T(ae=>({...ae,admins:Ne.ADMIN||0,management:Ne.MANAGEMENT||0,users:Ne.USER||0,total:(Ne.ADMIN||0)+(Ne.MANAGEMENT||0)+(Ne.USER||0)}))}catch(fe){console.error("Failed to fetch users:",fe),Q.error("Failed to load users")}finally{v(!1)}},S=async()=>{var J,q,se,ne,te,ge;try{const we=await ua.getRoleStatistics(),fe=((q=(J=we.data)==null?void 0:J.data)==null?void 0:q.statistics)||((se=we.data)==null?void 0:se.statistics)||[],ke={admins:parseInt(((ne=fe.find(le=>le.role==="ADMIN"))==null?void 0:ne.count)||"0"),management:parseInt(((te=fe.find(le=>le.role==="MANAGEMENT"))==null?void 0:te.count)||"0"),users:parseInt(((ge=fe.find(le=>le.role==="USER"))==null?void 0:ge.count)||"0")};T(le=>({...le,...ke,total:ke.admins+ke.management+ke.users,active:le.active||ke.admins+ke.management+ke.users,inactive:le.inactive||0}))}catch(we){console.error("Failed to fetch statistics:",we)}};u.useEffect(()=>{P(1),S()},[A]);const U=J=>{k(J),F(1)},Y=J=>{P(J)},B=async(J,q)=>{var se,ne;try{await ua.updateUserRole(J,q),Q.success("User role updated successfully"),await P(),await S()}catch(te){console.error("Failed to update user role:",te),Q.error(((ne=(se=te.response)==null?void 0:se.data)==null?void 0:ne.error)||"Failed to update user role")}},E=async J=>{b.find(se=>se.userId===J)&&Q.info("User status toggle functionality coming soon")},V=async J=>{const q=b.find(se=>se.userId===J);if(q){if(q.role==="ADMIN"){Q.error("Cannot delete admin user");return}Q.info("User deletion functionality coming soon")}};u.useEffect(()=>{const J=q=>{$.current&&!$.current.contains(q.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",J),()=>{document.removeEventListener("mousedown",J)}},[a]);const G={total:N.total,active:N.active,inactive:N.inactive,admins:N.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(LI,{stats:G}),e.jsxs(Z,{children:[e.jsx(de,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Assign User Role"}),e.jsx(Te,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(O,{onClick:z,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(is,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",ref:$,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(_e,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:R,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx(ze,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Start with @ to search users (e.g., @john)"}),a.length>0&&e.jsxs("div",{className:"border rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-muted px-4 py-2 border-b",children:e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-3",children:a.map(J=>e.jsxs("button",{onClick:()=>H(J),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:J.displayName||J.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:J.email}),J.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[J.department,J.designation?` • ${J.designation}`:""]})]},J.userId))})]})]}),l&&e.jsx("div",{className:"border-2 border-re-green/20 bg-re-green/5 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-re-green flex items-center justify-center text-white font-bold shadow-md",children:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-gray-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[l.department,l.designation?` • ${l.designation}`:""]}),x&&e.jsxs("p",{className:"text-xs text-re-green mt-1 flex items-center gap-1",children:[e.jsx(ze,{className:"w-3 h-3 animate-spin"}),"Checking current role..."]})]})]}),e.jsx(O,{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:J=>d(J),disabled:x,children:[e.jsx(Ye,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ge,{placeholder:x?"Loading current role...":"Select role"})}),e.jsxs(Qe,{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(Wt,{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(cn,{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(Ve,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Ze,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${g.type==="success"?"text-green-800":"text-red-800"}`,children:g.text})]})})]})]}),e.jsxs(Z,{children:[e.jsx(de,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(Te,{children:["View and manage user accounts and roles (",_," ",A!=="ALL"&&A!=="ELEVATED"?A.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(He,{value:A,onValueChange:U,children:[e.jsx(Ye,{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(Qe,{children:[e.jsx(X,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bs,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",N.admins+N.management,")"]})]})}),e.jsx(X,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",N.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 (",N.management,")"]})]})}),e.jsx(X,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",N.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 (",N.admins+N.management+N.users,")"]})]})})]})]})})]})}),e.jsx(ee,{className:"pt-6",children:j?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:A==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(MI,{users:b.map(J=>({id:J.userId,name:J.displayName,email:J.email,role:J.role,department:J.department||"N/A",status:J.isActive?"active":"inactive"})),onEdit:J=>{const q=b.find(se=>se.userId===J);if(q){const se=q.role==="USER"?"MANAGEMENT":q.role==="MANAGEMENT"?"ADMIN":"USER";B(J,se)}},onToggleStatus:E,onDelete:V}),w>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)*I+1," to ",Math.min(D*I,_)," of ",_," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{variant:"outline",size:"sm",onClick:()=>Y(D-1),disabled:D===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,w)},(J,q)=>{let se;return w<=5||D<=3?se=q+1:D>=w-2?se=w-4+q:se=D-2+q,e.jsx(O,{variant:D===se?"default":"outline",size:"sm",onClick:()=>Y(se),className:`w-9 h-9 p-0 ${D===se?"bg-re-green hover:bg-re-green/90":""}`,children:se},se)})}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>Y(D+1),disabled:D===w,children:"Next"})]})]})]})})]})]})}function UI({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(de,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kl,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(Te,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(_e,{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(re,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(_e,{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 BI({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(de,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(Te,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(ee,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{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(Fc,{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(Os,{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(re,{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(Fc,{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 Wn=[{value:1,label:"Monday"},{value:2,label:"Tuesday"},{value:3,label:"Wednesday"},{value:4,label:"Thursday"},{value:5,label:"Friday"},{value:6,label:"Saturday"},{value:7,label:"Sunday"}];function zI({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(de,{className:"pb-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(ue,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(Te,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(_e,{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(re,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(_e,{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(re,{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(Ye,{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(Qe,{children:Wn.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(re,{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(Ye,{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(Qe,{children:Wn.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=Wn.find(p=>p.value===a))==null?void 0:c.label} only`:` ${(d=Wn.find(p=>p.value===a))==null?void 0:d.label} to ${(m=Wn.find(p=>p.value===r))==null?void 0:m.label}`]})})]})]})}function VI(){const[t,s]=u.useState(!0),[a,r]=u.useState(!1),[n,i]=u.useState({expressHours:24,standardHours:72,reminderThreshold1:50,reminderThreshold2:75,workStartHour:9,workEndHour:18,workStartDay:1,workEndDay:5});u.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await Kl("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),Q.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())]),Q.success("TAT configuration saved successfully"),await l()}catch(p){console.error("Failed to save TAT configuration:",p),Q.error(((m=(d=p.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save TAT configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(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(de,{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(ue,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(UI,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx(Zt,{}),e.jsx(zI,{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(Zt,{}),e.jsx(BI,{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(O,{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(La,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function WI({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(cs,{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(cs,{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(cs,{checked:a,onCheckedChange:i})]})]})}function HI({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(re,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(He,{value:t,onValueChange:a,children:[e.jsx(Ye,{id:"notification-frequency",children:e.jsx(Ge,{placeholder:"Select frequency"})}),e.jsxs(Qe,{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(re,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(_e,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function GI({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(Vs,{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 YI(){const[t,s]=u.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=()=>{Q.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Notification Configuration"}),e.jsx(Te,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(WI,{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(Zt,{}),e.jsx(HI,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(GI,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(O,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(La,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function QI({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(de,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(Te,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(_e,{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(vs,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(_e,{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(Ll,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const KI=[{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 XI({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(de,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wc,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(Te,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:KI.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(re,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(_e,{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 JI(){const[t,s]=u.useState(!0),[a,r]=u.useState(!1),[n,i]=u.useState({maxFileSizeMB:10,retentionDays:365,allowedFileTypes:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"});u.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await Kl("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),Q.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)]),Q.success("Document policy saved successfully"),await l()}catch(p){console.error("Failed to save document configuration:",p),Q.error(((m=(d=p.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save document configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(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(de,{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(Ee,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(QI,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx(Zt,{}),e.jsx(XI,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:d=>c({allowedFileTypes:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(O,{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(La,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function ZI(){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 qI=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],e3=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 t3({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(oe,{className:e3(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:qI.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Kd,{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 s3(){const[t,s]=u.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=()=>{Q.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(de,{children:[e.jsx(ue,{children:"Dashboard Layout Configuration"}),e.jsx(Te,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsx(ZI,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(t3,{role:i,kpis:t[i]||{},onKPIToggle:(l,o)=>r(i,l,o)},i))}),e.jsxs(O,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(La,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}function a3({aiEnabled:t,onAiEnabledChange:s}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(de,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zp,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Vertex AI Gemini Configuration"})]}),e.jsx(Te,{className:"text-sm",children:"Configure AI features. Model and region are configured via environment variables."})]}),e.jsx(ee,{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-md",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Enable AI Features"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Master toggle to enable/disable all AI-powered features"})]}),e.jsx(cs,{checked:t,onCheckedChange:s})]})})]})}function r3({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(de,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dl,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(Te,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-md hover:bg-gray-100 transition-colors",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"AI Remark Generation"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically generate conclusion remarks for workflow closures"})]}),e.jsx(cs,{checked:t,onCheckedChange:s})]})})})]})}function n3({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(de,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Up,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(Te,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(ee,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Length"}),e.jsx(_e,{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 i3(){const[t,s]=u.useState(!0),[a,r]=u.useState(!1),[n,i]=u.useState({aiEnabled:!0,aiRemarkGeneration:!0,maxRemarkChars:2e3});u.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await Kl("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),Q.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())]),Q.success("AI configuration saved successfully"),await l()}catch(p){console.error("Failed to save AI configuration:",p),Q.error(((m=(d=p.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save AI configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(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(de,{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(Dl,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(Te,{className:"text-sm text-gray-600",children:"Configure Vertex AI Gemini settings and enable/disable AI-powered features"})]})]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(a3,{aiEnabled:n.aiEnabled,onAiEnabledChange:d=>c({aiEnabled:d})}),e.jsx(Zt,{}),e.jsx(r3,{aiRemarkGeneration:n.aiRemarkGeneration,onRemarkGenerationChange:d=>c({aiRemarkGeneration:d})}),e.jsx(Zt,{}),e.jsx(n3,{maxRemarkChars:n.maxRemarkChars,onMaxRemarkCharsChange:d=>c({maxRemarkChars:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(O,{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(La,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const Qh=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function l3({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(re,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(He,{value:t,onValueChange:a,children:[e.jsx(Ye,{id:"spectator-permission",children:e.jsx(Ge,{placeholder:"Select permission"})}),e.jsx(Qe,{children:Qh.map(n=>e.jsx(X,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(He,{value:s,onValueChange:r,children:[e.jsx(Ye,{id:"link-sharing-permission",children:e.jsx(Ge,{placeholder:"Select permission"})}),e.jsx(Qe,{children:Qh.map(n=>e.jsx(X,{value:n,children:n},n))})]})]})]})}function o3({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(cs,{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(cs,{checked:s,onCheckedChange:r})]})]})}function c3(){const[t,s]=u.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{Q.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Workflow Sharing Policy"}),e.jsx(Te,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx(l3,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(Zt,{}),e.jsx(o3,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(O,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(La,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function d3(){const{user:t}=us(),[s,a]=u.useState(""),[r,n]=u.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(bs,{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(O,{variant:"outline",size:"sm",onClick:()=>Q.info("COB&NDC Coming soon"),children:"COB&NDC"}),e.jsxs(oe,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]})]}),e.jsx(Zt,{}),e.jsxs(Ri,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(Ii,{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(Ut,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(ul,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(Ut,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(Ut,{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(Ut,{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(Ut,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(Os,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(Ut,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(Ut,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(Cy,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(Ut,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(zp,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(Ut,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(Sn,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(Bt,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(Z,{children:[e.jsx(de,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"KPI Configuration"}),e.jsx(Te,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(oe,{className:"bg-blue-50 text-blue-700",children:[o," / ",o," KPIs Active"]})]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Jt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(_e,{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(zt,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:d.name}),e.jsxs(oe,{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(oe,{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(Sy,{className:"w-3 h-3"}):e.jsx(Ay,{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(oe,{className:`${c(p)} text-xs px-1.5 py-0`,children:p},p))]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Period: ",m.period]}),m.thresholdBreached&&e.jsxs("div",{className:"flex items-center gap-1 text-orange-600",children:[e.jsx(Ze,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},m.id))})]},d.name))]})]})}),e.jsx(Bt,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(PI,{})}),e.jsx(Bt,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx($I,{})}),e.jsx(Bt,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(VI,{})}),e.jsx(Bt,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(YI,{})}),e.jsx(Bt,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(JI,{})}),e.jsx(Bt,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(s3,{})}),e.jsx(Bt,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(i3,{})}),e.jsx(Bt,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(c3,{})})]})]})}function m3(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 Bo(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}const zo={totalCreditNotes:0,totalAmount:0,activeDealersCount:0};function u3(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function x3(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 h3(){const[t,s]=u.useState([]),[a,r]=u.useState(zo),[n,i]=u.useState(!0),[l,o]=u.useState(""),[c,d]=u.useState(!1),[m,p]=u.useState(!1),[x,h]=u.useState(null),g=u.useCallback(async j=>{try{i(!0);const v=await fg(j);s(v.creditNotes),r(v.summary??zo)}catch(v){console.error("[Form16CreditNotes] Failed to fetch:",v),Q.error(v instanceof Error?v.message:"Failed to load credit notes"),s([]),r(zo)}finally{i(!1)}},[]);u.useEffect(()=>{g()},[g]);const f=u.useCallback(async(j,v)=>{var N;d(!0),p(!0),h(null);try{const T=await sd(j),A=(v||`credit-note-${j}`).trim()+".csv",k=u3(T.sapResponse),D=t.find(L=>Number(L.id)===Number(j)),F=Bo((D==null?void 0:D.amount)??null),w=x3((D==null?void 0:D.issueDate)??null);h({fileName:A,row:k,meta:{amountText:F,issuedAtText:w},downloadUrl:T.url||null})}catch(T){const A=((N=T==null?void 0:T.response)==null?void 0:N.status)===409?"The credit note is being generated, wait.":T instanceof Error?T.message:"Failed to load SAP response";Q.error(String(A)),d(!1)}finally{p(!1)}},[t]),b=u.useCallback(async()=>{if(!(x!=null&&x.downloadUrl)){Q.error("CSV download link not available");return}window.open(x.downloadUrl,"_blank")},[x]),y=u.useMemo(()=>{if(!l.trim())return t;const j=l.trim().toLowerCase();return t.filter(v=>{var N;return v.creditNoteNumber&&v.creditNoteNumber.toLowerCase().includes(j)||v.dealerName&&v.dealerName.toLowerCase().includes(j)||v.dealerCode&&v.dealerCode.toLowerCase().includes(j)||((N=v.submission)==null?void 0:N.form16aNumber)&&v.submission.form16aNumber.toLowerCase().includes(j)})},[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(ht,{open:c,onOpenChange:j=>{d(j),j||h(null)},children:e.jsxs(mt,{className:"sm:max-w-2xl",children:[e.jsxs(pt,{children:[e.jsx(ut,{children:"SAP Response"}),e.jsx(Mt,{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…"]}):x?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(Ee,{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:x.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:x.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(zs,{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(zs,{className:"w-4 h-4"})," Amount"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:x.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(Ol,{className:"w-4 h-4"})," Issued Date"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:x.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:x.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:x.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:x.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(O,{variant:"outline",onClick:()=>d(!1),children:"Close"}),e.jsxs(O,{onClick:b,disabled:!x||m||!(x!=null&&x.downloadUrl),children:[e.jsx(kt,{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(de,{className:"pb-3",children:[e.jsx(Te,{children:"Total Credit Notes Issued"}),e.jsx(ue,{className:"text-3xl",children:n?"...":a.totalCreditNotes})]})}),e.jsx(Z,{children:e.jsxs(de,{className:"pb-3",children:[e.jsx(Te,{children:"Total Credit Amount"}),e.jsx(ue,{className:"text-3xl text-green-600",children:n?"...":Bo(a.totalAmount)})]})}),e.jsx(Z,{children:e.jsxs(de,{className:"pb-3",children:[e.jsx(Te,{children:"Active Dealers"}),e.jsx(ue,{className:"text-3xl",children:n?"...":a.activeDealersCount})]})})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"All Credit Notes"}),e.jsx(Te,{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(Jt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(_e,{type:"search",placeholder:"Search credit notes...",value:l,onChange:j=>o(j.target.value),className:"pl-9"})]})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{children:[e.jsx(Ie,{children:"Credit Note No."}),e.jsx(Ie,{children:"Dealer Name"}),e.jsx(Ie,{children:"Form 16A No."}),e.jsx(Ie,{children:"Amount"}),e.jsx(Ie,{children:"Issue Date"}),e.jsx(Ie,{children:"Status"}),e.jsx(Ie,{className:"text-right",children:"Actions"})]})}),e.jsx(Fs,{children:n?e.jsx(tt,{children:e.jsxs(ve,{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..."})]})}):y.length===0?e.jsx(tt,{children:e.jsxs(ve,{colSpan:7,className:"text-center py-12 text-gray-500",children:[e.jsx(Et,{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."})]})}):y.map(j=>{var v,N,T;return e.jsxs(tt,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(ve,{className:"font-medium",children:j.creditNoteNumber?j.creditNoteNumber.startsWith("CN")?j.creditNoteNumber:`CN #${j.creditNoteNumber}`:""}),e.jsx(ve,{children:j.dealerName??j.dealerCode??""}),e.jsx(ve,{children:((v=j.submission)==null?void 0:v.form16aNumber)??""}),e.jsx(ve,{children:Bo(j.amount)}),e.jsx(ve,{children:m3(j.issueDate)}),e.jsx(ve,{children:e.jsx(oe,{className:((N=j.status)==null?void 0:N.toLowerCase())==="issued"||((T=j.status)==null?void 0:T.toLowerCase())==="completed"?"bg-green-100 text-green-800 border-green-200":"bg-gray-100 text-gray-700 border-gray-200",children:j.status??""})}),e.jsx(ve,{className:"text-right",children:e.jsx("div",{className:"flex items-center justify-end gap-2",children:j.sapResponseAvailable?e.jsxs(O,{variant:"outline",size:"sm",onClick:async()=>{await f(Number(j.id),j.creditNoteNumber)},children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"View"]}):e.jsxs(O,{variant:"outline",size:"sm",onClick:async()=>{Q.loading("Pulling credit note...",{id:`pull-cn-${j.id}`});try{await Se.post("/form16/sap/pull"),await g(),Q.success("Refreshed.",{id:`pull-cn-${j.id}`})}catch{Q.error("Failed to pull credit note",{id:`pull-cn-${j.id}`})}},children:[e.jsx(_t,{className:"w-4 h-4 mr-2"}),"Pull"]})})})]},j.id)})})]})})})]})]})]})}function Vo(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 Wo(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function p3(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function g3(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 f3(){var F;const t=gs(),{id:s}=Aa(),[a,r]=u.useState(null),[n,i]=u.useState(!0),[l,o]=u.useState(!1),[c,d]=u.useState(!1),[m,p]=u.useState(!1),[x,h]=u.useState(null),[g,f]=u.useState(null);u.useEffect(()=>{const w=s?parseInt(s,10):NaN;if(Number.isNaN(w)){i(!1);return}let L=!1;return tx(w).then(_=>{L||r(_)}).catch(_=>{L||(Q.error(_ instanceof Error?_.message:"Failed to load credit note"),t("/form16/credit-notes"))}).finally(()=>{L||i(!1)}),()=>{L=!0}},[s,t]);const b=()=>{Q.info("Resend to dealer integration pending")},y=async()=>{var L;const w=s?parseInt(s,10):NaN;if(!Number.isNaN(w)){o(!0);try{const _=await tx(w);r(_),(L=_.creditNote)!=null&&L.sapResponseAvailable?Q.success("Credit note is available to download."):Q.info("Credit note is being generated. Please wait.")}catch(_){Q.error(_ instanceof Error?_.message:"Failed to pull credit note")}finally{o(!1)}}},j=async()=>{var L;const w=s?parseInt(s,10):NaN;if(!Number.isNaN(w))try{d(!0),p(!0),h(null),f(null);const _=await sd(w),W=p3(_.sapResponse);h(W),f(_.url||null)}catch(_){const W=((L=_==null?void 0:_.response)==null?void 0:L.status)===409?"The credit note is being generated, wait.":_ instanceof Error?_.message:"Failed to download";Q.error(String(W))}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:N,dealerEmail:T,dealerContact:A,dealerCreditNotes:k}=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(ht,{open:c,onOpenChange:w=>{d(w),w||(h(null),f(null))},children:e.jsxs(mt,{className:"sm:max-w-2xl",children:[e.jsxs(pt,{children:[e.jsx(ut,{children:"SAP Response"}),e.jsx(Mt,{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…"]}):x?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(Ee,{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:x.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:x.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(zs,{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(zs,{className:"w-4 h-4"})," Amount"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:Wo(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(Ol,{className:"w-4 h-4"})," Issued Date"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:g3(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:x.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:x.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:x.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(O,{variant:"outline",onClick:()=>d(!1),children:"Close"}),e.jsxs(O,{onClick:()=>{if(!g){Q.error("CSV download link not available");return}window.open(g,"_blank")},disabled:!x||m||!g,children:[e.jsx(kt,{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(O,{variant:"ghost",size:"sm",onClick:()=>t("/form16/credit-notes"),className:"text-gray-600 hover:text-gray-900",children:[e.jsx(Cs,{className:"w-4 h-4 mr-2"}),"Back to Credit Notes"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(O,{variant:"outline",size:"sm",onClick:b,children:[e.jsx(Ca,{className:"w-4 h-4 mr-2"}),"Resend to Dealer"]})})]}),e.jsx(Z,{className:"mb-6",children:e.jsxs(ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-1",children:[e.jsx("span",{className:"text-xl font-semibold text-gray-900",children:D}),e.jsx(oe,{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 ",Vo(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:Wo(v.amount)})]})]}),e.jsx("div",{className:"flex justify-end gap-2 mt-4",children:v.sapResponseAvailable?e.jsxs(O,{variant:"outline",size:"sm",onClick:j,children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Download Credit Note"]}):e.jsxs(O,{variant:"outline",size:"sm",onClick:y,disabled:l,children:[l?e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(_t,{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:N||""})]}),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:((F=v.submission)==null?void 0:F.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:T||""})]}),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:A||""})]})]})]})}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Dealer Transaction History"}),e.jsxs(Te,{children:["All credit notes issued to ",N||"this dealer"]})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{children:[e.jsx(Ie,{children:"Submission Date"}),e.jsx(Ie,{children:"Form 16A No."}),e.jsx(Ie,{children:"Amount"}),e.jsx(Ie,{children:"Credit Note Issued"}),e.jsx(Ie,{children:"Credit Note No."}),e.jsx(Ie,{children:"CN Issue Date"}),e.jsx(Ie,{children:"Status"})]})}),e.jsx(Fs,{children:k.length===0?e.jsx(tt,{children:e.jsx(ve,{colSpan:7,className:"text-center py-8 text-gray-500",children:"No other credit notes for this dealer"})}):k.map(w=>{var L,_;return e.jsxs(tt,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(ve,{children:Vo(w.submittedDate)}),e.jsx(ve,{children:w.form16aNumber??""}),e.jsx(ve,{children:Wo(w.amount)}),e.jsx(ve,{children:e.jsx(oe,{className:"bg-green-100 text-green-800 border-green-200",children:"Yes"})}),e.jsx(ve,{children:w.creditNoteNumber?w.creditNoteNumber.startsWith("CN")?w.creditNoteNumber:`CN #${w.creditNoteNumber}`:""}),e.jsx(ve,{children:Vo(w.issueDate)}),e.jsx(ve,{children:e.jsx(oe,{className:((L=w.status)==null?void 0:L.toLowerCase())==="withdrawn"?"bg-red-50 text-red-700 border-red-200":"bg-green-100 text-green-800 border-green-200",children:((_=w.status)==null?void 0:_.toLowerCase())==="withdrawn"?"Withdrawn":"Completed"})})]},w.id)})})]})})})]})]})]})}function b3(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 Ho(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function j3(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 y3(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}const Go={totalDebitNotes:0,totalAmount:0,impactedDealersCount:0};function v3(){const[t,s]=u.useState([]),[a,r]=u.useState(Go),[n,i]=u.useState(!0),[l,o]=u.useState(""),[c,d]=u.useState(!1),[m,p]=u.useState(!1),[x,h]=u.useState(null),[g,f]=u.useState(null),[b,y]=u.useState(!1),j=u.useCallback(async A=>{try{i(!0);const k=await bg(A);s(k.debitNotes),r(k.summary??Go)}catch(k){console.error("[Form16DebitNotes] Failed to fetch:",k),Q.error(k instanceof Error?k.message:"Failed to load debit notes"),s([]),r(Go)}finally{i(!1)}},[]);u.useEffect(()=>{j()},[j]);const v=u.useMemo(()=>{if(!l.trim())return t;const A=l.trim().toLowerCase();return t.filter(k=>k.debitNoteNumber&&k.debitNoteNumber.toLowerCase().includes(A)||k.creditNoteNumber&&k.creditNoteNumber.toLowerCase().includes(A)||k.dealerName&&k.dealerName.toLowerCase().includes(A)||k.dealerCode&&k.dealerCode.toLowerCase().includes(A)||k.form16aNumber&&k.form16aNumber.toLowerCase().includes(A))},[t,l]),N=u.useCallback(async A=>{var k;d(!0),p(!0),h(null),f({amountText:Ho(A.amount),issuedAtText:j3(A.issueDate)});try{const D=await jg(Number(A.id));h(y3(D.sapResponse))}catch(D){const F=((k=D==null?void 0:D.response)==null?void 0:k.status)===409?"The debit note is being generated, wait.":D instanceof Error?D.message:"Failed to load SAP response";Q.error(String(F)),d(!1)}finally{p(!1)}},[]),T=u.useCallback(async()=>{var A;y(!0),Q.loading("Pulling SAP responses...",{id:"pull-debit"});try{const k=await Se.post("/form16/sap/pull");await j();const D=(A=k.data)==null?void 0:A.data,F=typeof(D==null?void 0:D.debitProcessed)=="number"?D.debitProcessed:D==null?void 0:D.processed;typeof F=="number"&&F>0?Q.success(`Pulled. ${F} debit response(s) processed. List refreshed.`,{id:"pull-debit"}):Q.success("Pulled. List refreshed. (No new debit responses in folder.)",{id:"pull-debit"})}catch{Q.error("Failed to pull SAP responses",{id:"pull-debit"})}finally{y(!1)}},[j]);return e.jsxs("div",{className:"space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full",children:[e.jsx(ht,{open:c,onOpenChange:A=>{d(A),A||(h(null),f(null))},children:e.jsxs(mt,{className:"sm:max-w-2xl",children:[e.jsxs(pt,{children:[e.jsx(ut,{children:"SAP Response"}),e.jsx(Mt,{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…"]}):x?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(Ee,{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:x.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:x.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(zs,{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(zs,{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(Ol,{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:x.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:x.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:x.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(O,{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(de,{className:"pb-3",children:[e.jsx(Te,{children:"Total Debit Notes Issued"}),e.jsx(ue,{className:"text-3xl",children:n?"...":a.totalDebitNotes})]})}),e.jsx(Z,{children:e.jsxs(de,{className:"pb-3",children:[e.jsx(Te,{children:"Total Debit Amount"}),e.jsx(ue,{className:"text-3xl text-red-600",children:n?"...":Ho(a.totalAmount)})]})}),e.jsx(Z,{children:e.jsxs(de,{className:"pb-3",children:[e.jsx(Te,{children:"Impacted Dealers"}),e.jsx(ue,{className:"text-3xl",children:n?"...":a.impactedDealersCount})]})})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"All Debit Notes"}),e.jsx(Te,{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(Jt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(_e,{type:"search",placeholder:"Search debit notes...",value:l,onChange:A=>o(A.target.value),className:"pl-9"})]})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{children:[e.jsx(Ie,{children:"Debit Note No."}),e.jsx(Ie,{children:"Credit Note No."}),e.jsx(Ie,{children:"Dealer"}),e.jsx(Ie,{children:"Form 16A No."}),e.jsx(Ie,{children:"Amount"}),e.jsx(Ie,{children:"Issue Date"}),e.jsx(Ie,{children:"Status"}),e.jsx(Ie,{className:"text-right",children:"Actions"})]})}),e.jsx(Fs,{children:n?e.jsx(tt,{children:e.jsxs(ve,{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(tt,{children:e.jsxs(ve,{colSpan:8,className:"text-center py-12 text-gray-500",children:[e.jsx(Et,{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(A=>{var k,D;return e.jsxs(tt,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(ve,{className:"font-medium",children:A.debitNoteNumber??""}),e.jsx(ve,{className:"font-medium",children:A.creditNoteNumber??""}),e.jsx(ve,{children:A.dealerName??A.dealerCode??""}),e.jsx(ve,{children:A.form16aNumber??""}),e.jsx(ve,{children:Ho(A.amount)}),e.jsx(ve,{children:b3(A.issueDate)}),e.jsx(ve,{children:e.jsx(oe,{className:((k=A.status)==null?void 0:k.toLowerCase())==="issued"||((D=A.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:A.status??""})}),e.jsx(ve,{className:"text-right",children:e.jsx("div",{className:"flex items-center justify-end gap-2",children:A.sapResponseAvailable?e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>N(A),children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"View"]}):e.jsxs(O,{variant:"outline",size:"sm",onClick:T,disabled:b,children:[b?e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(_t,{className:"w-4 h-4 mr-2"}),"Pull"]})})})]},A.id)})})]})})})]})]})]})}function N3(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 w3(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 Kh(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function C3(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function S3(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 A3(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 T3(){const[t,s]=u.useState(!0),[a,r]=u.useState(!1),[n,i]=u.useState(""),[l,o]=u.useState([]),[c,d]=u.useState(!1),[m,p]=u.useState(!1),[x,h]=u.useState(null),g=u.useCallback(async()=>{try{s(!0);const[j,v]=await Promise.all([fg(),bg()]),N=[...j.creditNotes.map(S3),...v.debitNotes.map(A3)].sort((T,A)=>{const k=T.issueDate?new Date(T.issueDate).getTime():0;return(A.issueDate?new Date(A.issueDate).getTime():0)-k});o(N)}catch(j){console.error("[Form16Transactions] Failed to fetch:",j),Q.error(j instanceof Error?j.message:"Failed to load transactions"),o([])}finally{s(!1)}},[]);u.useEffect(()=>{g()},[g]);const f=u.useMemo(()=>{if(!n.trim())return l;const j=n.trim().toLowerCase();return l.filter(v=>v.searchText.includes(j))},[l,n]),b=u.useCallback(async j=>{d(!0),p(!0),h(null);try{const v=j.type==="credit"?await sd(j.id):await jg(j.id);h({type:j.type,referenceNumber:j.referenceNumber,amountText:Kh(j.amount),issuedAtText:w3(j.issueDate),row:C3(v.sapResponse)})}catch(v){const N=v instanceof Error?v.message:"Failed to load SAP response";Q.error(N),d(!1)}finally{p(!1)}},[]),y=u.useCallback(async()=>{r(!0),Q.loading("Pulling SAP responses...",{id:"pull-transactions"});try{await Se.post("/form16/sap/pull"),await g(),Q.success("Pulled and refreshed transactions.",{id:"pull-transactions"})}catch{Q.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(ht,{open:c,onOpenChange:j=>{d(j),j||h(null)},children:e.jsxs(mt,{className:"sm:max-w-2xl",children:[e.jsxs(pt,{children:[e.jsx(ut,{children:"SAP Response"}),e.jsx(Mt,{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..."]}):x?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(Ee,{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:x.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:x.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(zs,{className:"w-4 h-4 text-amber-700"}),e.jsx("p",{className:"text-xs font-semibold text-amber-800 tracking-wide uppercase",children:x.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(zs,{className:"w-4 h-4"})," Amount"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:x.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(Ol,{className:"w-4 h-4"})," Issued Date"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:x.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:x.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:x.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:x.row.MESSAGE||""})]})]})]}):e.jsx("div",{className:"py-8 text-sm text-gray-600",children:"No preview available."}),e.jsx(Dt,{children:e.jsx(O,{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(de,{children:[e.jsx(ue,{children:"All Transactions"}),e.jsx(Te,{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(Jt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(_e,{type:"search",placeholder:"Search transactions...",value:n,onChange:j=>i(j.target.value),className:"pl-9"})]}),e.jsxs(O,{variant:"outline",onClick:y,disabled:a,children:[a?e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(_t,{className:"w-4 h-4 mr-2"}),"Pull SAP Response"]})]})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{children:[e.jsx(Ie,{children:"TDS_TRANS_ID"}),e.jsx(Ie,{children:"Dealer"}),e.jsx(Ie,{children:"Transaction Amount"}),e.jsx(Ie,{children:"Issued Date"}),e.jsx(Ie,{children:"Status"}),e.jsx(Ie,{className:"text-right",children:"Actions"})]})}),e.jsx(Fs,{children:t?e.jsx(tt,{children:e.jsxs(ve,{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(tt,{children:e.jsxs(ve,{colSpan:6,className:"text-center py-12 text-gray-500",children:[e.jsx(Et,{className:"w-12 h-12 mx-auto mb-3 text-gray-400"}),e.jsx("p",{children:"No transactions found"})]})}):f.map(j=>e.jsxs(tt,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(ve,{className:"font-medium",children:j.referenceNumber}),e.jsx(ve,{children:j.dealer}),e.jsx(ve,{children:e.jsxs("div",{className:`inline-flex items-center gap-1.5 font-semibold ${j.type==="credit"?"text-green-600":"text-red-600"}`,children:[j.type==="credit"?e.jsx(Ty,{className:"w-4 h-4"}):e.jsx(ky,{className:"w-4 h-4"}),e.jsxs("span",{children:[j.type==="credit"?"+ ":"- ",Kh(j.amount)]})]})}),e.jsx(ve,{children:N3(j.issueDate)}),e.jsx(ve,{children:j.sapResponseAvailable?e.jsx(oe,{className:"bg-green-100 text-green-800 border-green-200",children:"Completed"}):e.jsx(oe,{className:"bg-orange-100 text-orange-800 border-orange-200",children:"OUTGOING"})}),e.jsx(ve,{className:"text-right",children:j.sapResponseAvailable?e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>b(j),children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"View"]}):e.jsxs(O,{variant:"outline",size:"sm",onClick:y,disabled:a,children:[a?e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(_t,{className:"w-4 h-4 mr-2"}),"Pull"]})})]},`${j.type}-${j.id}`))})]})})})]})]})]})}function k3({state:t="idle",onFileSelect:s,errorMessage:a,className:r="",disabled:n=!1}){const[i,l]=u.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 y=f.dataTransfer.files[0];y&&s(y)},p=f=>{const b=f.target.files,y=b==null?void 0:b[0];y&&s(y)},x={idle:{icon:vs,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:vs,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:Ze,text:"Upload failed",subtext:a||"Please try again",bgColor:"bg-red-50",borderColor:"border-red-300",iconColor:"text-red-600"}},h=x[o]??x.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 Vi=10;function D3(t){if(!t)return"—";try{return new Date(t).toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}catch{return String(t)}}function ea(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 R3(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 I3(){const t=gs(),[s,a]=u.useState([]),[r,n]=u.useState(!0),[i,l]=u.useState(0),[o,c]=u.useState(""),[d,m]=u.useState(""),[p,x]=u.useState(null),[h,g]=u.useState("idle"),[f,b]=u.useState(null),[y,j]=u.useState(null),[v,N]=u.useState(!1),[T,A]=u.useState(""),[k,D]=u.useState(""),[F,w]=u.useState(null),[L,_]=u.useState(!1);u.useEffect(()=>{let B=!1;return vg().then(E=>{B||(a(Array.isArray(E)?E:[]),l(0))}).catch(()=>{B||a([])}).finally(()=>{B||n(!1)}),()=>{B=!0}},[]);const W=Math.max(1,Math.ceil(s.length/Vi)),I=i>0,$=i<W-1,M=Math.max(0,Math.min(i-4,W-9)),R=Math.min(W-1,M+8),C=Array.from({length:R-M+1},(B,E)=>M+E),H=s.slice(i*Vi,(i+1)*Vi),z=u.useCallback(()=>{if(!p)return;const B=URL.createObjectURL(p);w(B),_(!0)},[p]),P=u.useCallback(()=>{_(!1),F&&(URL.revokeObjectURL(F),w(null))},[F]),S=u.useCallback(async B=>{if(!B.name.toLowerCase().endsWith(".pdf")){Q.error("Please upload a PDF file");return}x(B),b(null),j(null),g("extracting");try{Q.loading("Extracting data with Google Gemini...",{id:"form16-ocr"});const E=await pN(B);b(E.extractedData),j(E.ocrProvider||null),A(E.extractedData.tanNumber??E.extractedData.tanOfDeductor??""),D(E.extractedData.deductorName??E.extractedData.nameAndAddressOfDeductor??""),c(E.extractedData.financialYear??""),m(E.extractedData.quarter??""),g("success"),Q.success(E.ocrProvider?`Data extracted via ${E.ocrProvider}`:"Data extracted",{id:"form16-ocr"})}catch(E){g("error");const V=E instanceof Error?E.message:"Failed to extract data from PDF";Q.error(V,{id:"form16-ocr"})}},[]),U=async()=>{var q;if(!o||!d){Q.error("Financial year and quarter could not be extracted from the PDF. Please ensure you upload a valid Form 16A certificate.");return}if(!p){Q.error("Please upload Form 16A PDF");return}const B=((f==null?void 0:f.form16aNumber)??"").trim()||`F16-${o}-${d}-${Date.now()}`,E=(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,G=(T||((f==null?void 0:f.tanNumber)??(f==null?void 0:f.tanOfDeductor)??"")).trim(),J=(k||((f==null?void 0:f.deductorName)??(f==null?void 0:f.nameAndAddressOfDeductor)??"")).trim();if(!G||!J){Q.error("TAN and Deductor name are required. Please enter or correct them below.");return}N(!0);try{const se=await gN({financialYear:o,quarter:d,form16aNumber:B,tdsAmount:Number(E)||0,totalAmount:Number(V)||0,tanNumber:G,deductorName:J,file:p,extractedData:f??void 0}),ne=se.validationStatus,te=ne==="success"?"success":ne==="duplicate"?"duplicate":ne==="failed"?"mismatch":"error",ge=te==="duplicate"?"A credit note has already been issued for this financial year and quarter. This submission is recorded as a new version.":void 0,we=te==="mismatch"?se.validationNotes||"Form 16A details did not match with 26AS data.":void 0;Q.success(te==="success"?"Form 16A matched with 26AS. Credit note generated.":"Form 16A submitted successfully"),t("/form16/submit/result",{state:{status:te,requestId:se.requestId,requestNumber:se.requestNumber,creditNoteNumber:se.creditNoteNumber??void 0,message:ge??we}})}catch(se){const ne=se&&typeof se=="object"&&"response"in se?se.response:void 0,te=((q=ne==null?void 0:ne.data)==null?void 0:q.message)??(se instanceof Error?se.message:"Failed to submit");(ne==null?void 0:ne.status)===400&&typeof te=="string"&&(te.toLowerCase().includes("duplicate")||te.toLowerCase().includes("already exist"))?t("/form16/submit/result",{state:{status:"duplicate",requestId:"",message:te}}):Q.error(String(te))}finally{N(!1)}},Y=!!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(O,{type:"button",variant:"ghost",size:"icon",onClick:()=>t(-1),"aria-label":"Go back",children:e.jsx(Cs,{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(de,{children:[e.jsx(ue,{children:"Upload Form 16A Certificate"}),e.jsx(Te,{children:"PDF only. Financial year and quarter are taken from the certificate via OCR; no need to enter them manually."})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsx(k3,{state:h==="extracting"?"extracting":h==="error"?"error":h==="success"?"success":"idle",onFileSelect:S,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(Ze,{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(O,{type:"button",variant:"ghost",size:"sm",onClick:()=>{x(null),b(null),j(null),A(""),D(""),c(""),m(""),g("idle"),P()},disabled:h==="extracting",children:"Remove"})]}),p&&e.jsxs(O,{type:"button",variant:"outline",className:"w-full",onClick:z,disabled:h==="extracting",children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"View Uploaded Form 16A"]})]})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Quarters Pending Submission"}),e.jsx(Te,{children:"These quarters don't have completed Form 16A submissions. Please submit Form 16A for these quarters."})]}),e.jsxs(ee,{children:[e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{className:"bg-gray-50",children:[e.jsx(Ie,{children:"Dealer Name"}),e.jsx(Ie,{children:"Financial Year"}),e.jsx(Ie,{children:"Quarter"}),e.jsx(Ie,{children:"Version"}),e.jsx(Ie,{children:"Status"}),e.jsx(Ie,{children:"26AS start date"}),e.jsx(Ie,{children:"Days Status"}),e.jsx(Ie,{className:"text-right",children:"Action"})]})}),e.jsx(Fs,{children:r?e.jsx(tt,{children:e.jsxs(ve,{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(tt,{children:e.jsx(ve,{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(Ee,{className:"w-12 h-12 text-gray-300"}),e.jsx("p",{children:"No pending submissions. All quarters are complete."})]})})}):H.map(B=>e.jsxs(tt,{className:"hover:bg-gray-50",children:[e.jsx(ve,{className:"text-sm text-gray-900",children:B.dealer_name??"Your submission"}),e.jsx(ve,{children:e.jsxs("span",{className:"text-sm text-gray-900",children:["FY ",B.financial_year]})}),e.jsx(ve,{children:e.jsx(oe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:B.quarter})}),e.jsx(ve,{children:e.jsx(oe,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:B.has_submission?"V1":"—"})}),e.jsx(ve,{children:e.jsx(oe,{variant:"outline",className:B.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":B.has_submission?"bg-slate-50 text-slate-600 border-slate-200":"bg-gray-100 text-gray-600 border-gray-200",children:B.latest_submission_status==="failed"?"Failed":B.has_submission?"Under review":"Not Submitted"})}),e.jsx(ve,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-700",children:D3(B.twenty_six_as_start_date??B.audit_start_date)})]})}),e.jsx(ve,{children:B.days_since_26as_uploaded!=null&&B.days_since_26as_uploaded>=0?e.jsxs("span",{className:"text-sm font-medium text-gray-700",children:["due from ",B.days_since_26as_uploaded," days"]}):e.jsx("span",{className:"text-sm text-gray-500",children:"—"})}),e.jsx(ve,{className:"text-right",children:e.jsx(O,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>t("/form16/submit"),children:"Submit Now"})})]},`${B.financial_year}|${B.quarter}`))})]})}),!r&&s.length>Vi&&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 ",W," (",s.length," records)"]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-wrap justify-center",children:[e.jsxs(O,{variant:"outline",size:"sm",disabled:!I,onClick:()=>l(B=>B-1),children:[e.jsx(Nn,{className:"w-4 h-4"}),"Previous"]}),C.map(B=>e.jsx(O,{variant:B===i?"default":"outline",size:"sm",className:B===i?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>l(B),children:B+1},B)),e.jsxs(O,{variant:"outline",size:"sm",disabled:!$,onClick:()=>l(B=>B+1),children:["Next",e.jsx(Wa,{className:"w-4 h-4"})]})]})]})]})]}),e.jsxs(Z,{className:"border-blue-200 bg-blue-50",children:[e.jsx(de,{children:e.jsxs(ue,{className:"text-blue-900 flex items-center gap-2",children:[e.jsx(Jr,{className:"w-5 h-5"}),"Important Notes"]})}),e.jsx(ee,{className:"space-y-2 text-sm text-blue-800",children:e.jsxs("ul",{className:"list-disc list-inside space-y-1 ml-2",children:[e.jsx("li",{children:"Ensure the Form 16A certificate is issued by the correct deductor (TAN and name must match)"}),e.jsx("li",{children:"The certificate should match your Form 26AS data from the Income Tax portal"}),e.jsx("li",{children:"If you submit multiple versions for the same quarter, only the latest approved version will be processed"}),e.jsx("li",{children:"You can track all submissions in the Requests section (filter by Form 16)"}),e.jsx("li",{children:"Processing typically takes 23 business days after validation"})]})})]}),Y&&e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-5 h-5 text-blue-600"}),e.jsx(ue,{children:"Form 16A Extracted Details"})]}),e.jsx(Te,{children:h==="extracting"?"Extracting with Google Gemini (or regex fallback)...":f?y?`Extracted via ${y}. 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(ee,{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(Ze,{className:"w-8 h-8 text-amber-600 mr-3 shrink-0"}),e.jsx("p",{className:"text-gray-600",children:"Data extraction failed. Please remove the file and try uploading again."})]}):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:R3(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:ea(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?`₹ ${ea(f.totalAmountPaid??f.totalAmount)}`:ea(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?`₹ ${ea(f.totalTaxDeducted??f.tdsAmount)}`:ea(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?`₹ ${ea(f.totalTdsDeposited??f.tdsAmount)}`:ea(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:ea(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:ea(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:ea(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:ea(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:ea(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:ea(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:ea(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(re,{htmlFor:"form16-tan",children:"TAN of deductor *"}),e.jsx(_e,{id:"form16-tan",value:T,onChange:B=>A(B.target.value),placeholder:"e.g. BLRH07660C",maxLength:10})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(re,{htmlFor:"form16-deductor",children:"Deductor name *"}),e.jsx(_e,{id:"form16-deductor",value:k,onChange:B=>D(B.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(O,{type:"button",variant:"outline",onClick:()=>t(-1),disabled:v,children:"Cancel"}),e.jsxs(O,{type:"button",className:"bg-re-green hover:bg-re-green/90",onClick:U,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(ht,{open:L,onOpenChange:B=>!B&&P(),children:e.jsxs(mt,{className:"max-w-4xl max-h-[90vh] flex flex-col","aria-describedby":"form16-pdf-description",children:[e.jsxs(pt,{children:[e.jsx(ut,{children:"Form 16A Certificate"}),e.jsx(Mt,{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:F&&e.jsx("iframe",{title:"Form 16A PDF",src:F,className:"w-full h-[70vh] rounded"})})]})})]})})}const F3={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 P3({variant:t,label:s,showIcon:a=!0}){const r=t==="success"?ps:t==="failed"?At:it;return e.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm font-medium ${F3[t]}`,children:[a&&e.jsx(r,{className:"h-4 w-4 shrink-0"}),s]})}function E3({step:t,label:s,state:a,isLast:r}){const n=a==="completed"?ps:a==="failed"?At:Bc,i=a==="completed"?"text-teal-600 bg-teal-100":a==="failed"?"text-red-600 bg-red-100":"text-gray-400 bg-gray-100";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col items-center flex-1 min-w-0",children:[e.jsx("div",{className:`flex items-center justify-center w-8 h-8 rounded-full shrink-0 ${i}`,children:a==="pending"?e.jsx("span",{className:"text-xs font-medium text-gray-500",children:t}):e.jsx(n,{className:"w-4 h-4"})}),e.jsx("p",{className:"text-xs font-medium text-gray-600 mt-2 text-center max-w-[80px] truncate",title:s,children:s})]}),!r&&e.jsx("div",{className:"w-8 sm:w-12 h-0.5 bg-gray-200 self-start mt-4 shrink-0","aria-hidden":!0})]})}function _3({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."})(),x=t==="duplicate",h=t==="error";u.useEffect(()=>{if(!c)return;const f=setTimeout(i,5e3);return()=>clearTimeout(f)},[c,i]);const g=[{label:"Form 16A Uploaded",state:x?"failed":"completed"},{label:"Validation",state:x?"failed":h?"pending":"completed"},{label:"26AS Matching",state:c?"completed":d||x?"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(Gt.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":x?"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(ee,{className:"pt-12 pb-10",children:[e.jsx(Gt.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{delay:.15},className:"flex justify-center mb-6",children:e.jsx(P3,{variant:c?"success":x?"failed":h?"pending":"failed",label:c?"Matched & Credit Note Generated":x?"Duplicate Submission":d?"Value Mismatch":"Request Received",showIcon:!0})}),e.jsx(Gt.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":x?"bg-red-100":h?"bg-gray-100":"bg-amber-100"}`,children:c?e.jsx(ps,{className:"w-12 h-12 text-teal-600"}):x?e.jsx(Dy,{className:"w-12 h-12 text-red-600"}):h?e.jsx(Ze,{className:"w-12 h-12 text-gray-500"}):e.jsx(Ze,{className:"w-12 h-12 text-amber-600"})})}),e.jsx(Gt.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."})]}):x?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(Gt.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":x?"bg-red-50 border-2 border-red-200":"bg-white border border-amber-200"}`,children:[e.jsx("p",{className:`text-sm mb-1 ${x?"text-red-700":"text-gray-600"}`,children:"Request ID"}),e.jsx("p",{className:`font-mono tracking-wide ${x?"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(Gt.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(E3,{step:b+1,label:f.label,state:f.state,isLast:b===g.length-1},b))})]}),e.jsx(Gt.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(O,{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(O,{onClick:o,className:"bg-teal-600 hover:bg-teal-700",children:"View Request"}),l&&(d||x||h)&&e.jsx(O,{onClick:l,className:x?"bg-red-600 hover:bg-red-700":d?"bg-amber-600 hover:bg-amber-700":"bg-gray-600 hover:bg-gray-700",children:x?"Back to New Submission":d?"Resubmit Form 16A":"Try Again"}),e.jsx(O,{onClick:i,variant:"outline",children:"Back to My Requests"})]})})]})})})})}const Hn="form16_submission_result";function M3(){const t=gs(),a=$l().state,r=(()=>{try{const d=sessionStorage.getItem(Hn);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);u.useEffect(()=>{i&&sessionStorage.setItem(Hn,JSON.stringify(n))},[i,n]);const l=u.useCallback(()=>{sessionStorage.removeItem(Hn),t("/my-requests",{replace:!0})},[t]),o=u.useCallback(()=>{sessionStorage.removeItem(Hn),t("/form16/submit",{replace:!0})},[t]),c=u.useCallback(()=>{n!=null&&n.requestNumber&&(sessionStorage.removeItem(Hn),t(`/request/${n.requestNumber}`,{replace:!0}))},[t,n==null?void 0:n.requestNumber]);return i?e.jsx(_3,{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 Gn=50,Wi=10,L3=["Q1","Q2","Q3","Q4"],O3=[{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 Xh(t){if(!t)return"";try{const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"})}catch{return t}}function Hi(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function $3(){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 U3(t){switch((t||"").trim().toUpperCase().slice(0,1)){case"F":return e.jsx(oe,{className:"bg-green-100 text-green-700 border-green-300",children:"F"});case"O":return e.jsx(oe,{className:"bg-orange-100 text-orange-700 border-orange-300",children:"O"});case"M":return e.jsx(oe,{className:"bg-blue-100 text-blue-700 border-blue-300",children:"M"});case"U":return e.jsx(oe,{className:"bg-red-100 text-red-700 border-red-300",children:"U"});case"P":return e.jsx(oe,{className:"bg-amber-100 text-amber-700 border-amber-300",children:"P"});default:return t?e.jsx(oe,{variant:"secondary",children:t}):null}}function B3(){const[t,s]=u.useState(!1),[a,r]=u.useState({assessmentYear:"all",quarter:"all",section:"all",tanNumber:"",deductor:"",status:"all"}),[n,i]=u.useState(""),l=u.useRef(null),[o,c]=u.useState(!1),[d,m]=u.useState(!1),[p,x]=u.useState(0),[h,g]=u.useState(0),[f,b]=u.useState(null),y=u.useRef(null),j=u.useRef(null),[v,N]=u.useState([]),[T,A]=u.useState(0),[k,D]=u.useState({totalRecords:0,booked:0,notBooked:0,pending:0,totalTaxDeducted:0}),[F,w]=u.useState(!0),[L,_]=u.useState(0),[W,I]=u.useState([]),[$,M]=u.useState(0),[R,C]=u.useState(0),[H,z]=u.useState(!1),P=$3(),S=u.useCallback(async(ae=0)=>{try{z(!0);const{history:he,total:ie}=await bN({limit:Wi,offset:ae*Wi});I(he),M(ie),C(ae)}catch(he){console.error("[Form16_26AS] upload history",he),I([]),M(0),C(0)}finally{z(!1)}},[]),U=u.useCallback(async(ae=0)=>{try{w(!0);const he={limit:Gn,offset:ae*Gn};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 ie=await fN(he);N(ie.entries),A(ie.total),D(ie.summary),_(ae)}catch(he){console.error("[Form16_26AS]",he),Q.error(he instanceof Error?he.message:"Failed to load 26AS entries"),N([]),A(0),D({totalRecords:0,booked:0,notBooked:0,pending:0,totalTaxDeducted:0})}finally{w(!1)}},[a.assessmentYear,a.quarter,a.section,a.tanNumber,a.deductor,a.status]);u.useEffect(()=>{U(0)},[U]),u.useEffect(()=>{S(0)},[S]),u.useEffect(()=>(l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{r(ae=>({...ae,deductor:n.trim()}))},300),()=>{l.current&&clearTimeout(l.current)}),[n]),u.useEffect(()=>()=>{j.current&&(clearInterval(j.current),j.current=null)},[]);const Y=ae=>{var ie;const he=(ie=ae.target.files)==null?void 0:ie[0];if(he){if(he.size>50*1024*1024){Q.error("File size must be less than 50MB");return}if(!he.name.toLowerCase().endsWith(".txt")){Q.error("Only .txt files are supported");return}b(he)}},B=async()=>{var ae,he;if(!f){Q.error("Please select a file");return}m(!0),x(0),g(0),j.current&&(clearInterval(j.current),j.current=null);try{const ie=await yN(f,je=>{if(x(je),je>=100&&!j.current){g(0);let Fe=0;j.current=setInterval(()=>{Fe+=1,g(Ue=>Math.min(99,Ue+4+Math.floor(Fe/3)))},300)}});j.current&&(clearInterval(j.current),j.current=null),g(100),ie.imported>0?(Q.success(`Successfully imported ${ie.imported} entries.${(ae=ie.errors)!=null&&ae.length?` ${ie.errors.length} warnings.`:""}`),c(!1),b(null),y.current&&(y.current.value=""),U(0),S(0)):(he=ie.errors)!=null&&he.length&&Q.error(ie.errors[0]||"Upload failed")}catch(ie){j.current&&(clearInterval(j.current),j.current=null),Q.error(ie instanceof Error?ie.message:"Upload failed")}finally{m(!1),x(0),g(0)}},E=()=>{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",G=Math.max(1,Math.ceil(T/Gn)),J=L>0,q=L<G-1,se=Math.max(0,Math.min(L-4,G-9)),ne=Math.min(G-1,se+8),te=Array.from({length:ne-se+1},(ae,he)=>se+he),ge=Math.max(1,Math.ceil($/Wi)),we=R>0,fe=R<ge-1,ke=Math.max(0,Math.min(R-4,ge-9)),le=Math.min(ge-1,ke+8),Ne=Array.from({length:le-ke+1},(ae,he)=>ke+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(Jt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(_e,{placeholder:"Search...",value:n,onChange:ae=>i(ae.target.value),className:"pl-9 h-9"})]}),e.jsxs(O,{onClick:()=>c(!0),className:"gap-2 bg-teal-600 hover:bg-teal-700 text-white",children:[e.jsx(vs,{className:"w-4 h-4"}),"Upload 26AS File"]}),e.jsxs(O,{variant:"outline",onClick:()=>s(!t),className:"gap-2",children:[e.jsx(Ga,{className:"w-4 h-4"}),"Filters",V&&e.jsx(oe,{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(Al,{className:"w-4 h-4"}):e.jsx(Qr,{className:"w-4 h-4"})]})]})]}),e.jsx(ht,{open:o,onOpenChange:c,children:e.jsxs(mt,{className:"max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(vs,{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(re,{htmlFor:"file-upload",children:"Select 26AS File"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("input",{ref:y,id:"file-upload",type:"file",accept:".txt",onChange:Y,disabled:d,className:"hidden"}),e.jsxs(O,{variant:"outline",onClick:()=>{var ae;return(ae=y.current)==null?void 0:ae.click()},disabled:d,className:"gap-2",children:[e.jsx(Ee,{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(oa,{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(oa,{value:h,className:"h-2",indicatorClassName:"bg-teal-600"})]})]})]}),e.jsxs(Dt,{children:[e.jsx(O,{variant:"outline",onClick:()=>{c(!1),b(null),y.current&&(y.current.value="")},disabled:d,children:"Cancel"}),e.jsx(O,{onClick:B,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(vs,{className:"w-4 h-4"}),"Upload"]})})]})]})}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Management"}),e.jsxs(Te,{children:["History of 26AS file uploads: when and which user added or uploaded 26AS data",$>0?` (${$} total)`:""]})]}),e.jsxs(ee,{children:[e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{children:[e.jsx(Ie,{children:"Date & Time"}),e.jsx(Ie,{children:"User"}),e.jsx(Ie,{children:"File Name"}),e.jsx(Ie,{className:"text-right",children:"Records Imported"}),e.jsx(Ie,{className:"text-right",children:"Errors"})]})}),e.jsx(Fs,{children:H?e.jsx(tt,{children:e.jsxs(ve,{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..."})]})}):W.length===0?e.jsx(tt,{children:e.jsx(ve,{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."})}):W.map(ae=>e.jsxs(tt,{className:"hover:bg-gray-50",children:[e.jsx(ve,{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(ve,{className:"text-sm",children:ae.uploadedByDisplayName||ae.uploadedByEmail||ae.uploadedBy||""}),e.jsx(ve,{className:"text-sm text-gray-600 max-w-[200px] truncate",title:ae.fileName||void 0,children:ae.fileName||""}),e.jsx(ve,{className:"text-right font-medium",children:ae.recordsImported}),e.jsx(ve,{className:"text-right",children:ae.errorsCount>0?ae.errorsCount:""})]},ae.id))})]})}),!H&&$>Wi&&e.jsxs("div",{className:"flex items-center justify-between mt-4 px-6 pb-6",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Page ",R+1," of ",ge," (",$," uploads)"]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-wrap justify-center",children:[e.jsxs(O,{variant:"outline",size:"sm",disabled:!we,onClick:()=>S(R-1),children:[e.jsx(Nn,{className:"w-4 h-4"}),"Previous"]}),Ne.map(ae=>e.jsx(O,{variant:ae===R?"default":"outline",size:"sm",className:ae===R?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>S(ae),children:ae+1},ae)),e.jsxs(O,{variant:"outline",size:"sm",disabled:!fe,onClick:()=>S(R+1),children:["Next",e.jsx(Wa,{className:"w-4 h-4"})]})]})]})]})]}),t&&e.jsxs(Z,{children:[e.jsx(de,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Filter TDS Records"}),V&&e.jsxs(O,{variant:"ghost",size:"sm",onClick:E,className:"gap-2 text-gray-600",children:[e.jsx(vt,{className:"w-4 h-4"}),"Clear All"]})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Assessment Year"}),e.jsxs(He,{value:a.assessmentYear,onValueChange:ae=>r(he=>({...he,assessmentYear:ae})),children:[e.jsx(Ye,{children:e.jsx(Ge,{placeholder:"Select year"})}),e.jsxs(Qe,{children:[e.jsx(X,{value:"all",children:"All Years"}),P.map(ae=>e.jsx(X,{value:ae,children:ae},ae))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Quarter"}),e.jsxs(He,{value:a.quarter,onValueChange:ae=>r(he=>({...he,quarter:ae})),children:[e.jsx(Ye,{children:e.jsx(Ge,{placeholder:"Select quarter"})}),e.jsxs(Qe,{children:[e.jsx(X,{value:"all",children:"All Quarters"}),L3.map(ae=>e.jsx(X,{value:ae,children:ae},ae))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Section"}),e.jsxs(He,{value:a.section,onValueChange:ae=>r(he=>({...he,section:ae})),children:[e.jsx(Ye,{children:e.jsx(Ge,{placeholder:"Select section"})}),e.jsxs(Qe,{children:[e.jsx(X,{value:"all",children:"All Sections"}),O3.map(ae=>e.jsx(X,{value:ae.value,children:ae.label},ae.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"TAN"}),e.jsx(_e,{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(re,{children:"Deductor"}),e.jsx(_e,{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(re,{children:"Status"}),e.jsxs(He,{value:a.status,onValueChange:ae=>r(he=>({...he,status:ae})),children:[e.jsx(Ye,{children:e.jsx(Ge,{placeholder:"Select status"})}),e.jsxs(Qe,{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(de,{className:"pb-3",children:[e.jsx(Te,{children:"Total Records"}),e.jsx(ue,{className:"text-2xl",children:k.totalRecords})]})}),e.jsx(Z,{children:e.jsxs(de,{className:"pb-3",children:[e.jsx(Te,{children:"Booked"}),e.jsx(ue,{className:"text-2xl text-green-600",children:k.booked})]})}),e.jsx(Z,{children:e.jsxs(de,{className:"pb-3",children:[e.jsx(Te,{children:"Not Booked"}),e.jsx(ue,{className:"text-2xl text-red-600",children:k.notBooked})]})}),e.jsx(Z,{children:e.jsxs(de,{className:"pb-3",children:[e.jsx(Te,{children:"Pending"}),e.jsx(ue,{className:"text-2xl text-amber-600",children:k.pending})]})}),e.jsx(Z,{className:"lg:col-span-1",children:e.jsxs(de,{className:"pb-3",children:[e.jsx(Te,{children:"Total Tax Deducted"}),e.jsx(ue,{className:"text-xl",children:Hi(k.totalTaxDeducted)})]})})]}),e.jsxs(Z,{children:[e.jsx(de,{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(ue,{children:"TDS Records from Form 26AS"}),e.jsx(Te,{children:V?`Showing ${v.length} of ${T} records`:`Complete list of TDS deduction records (${T} total)`})]}),e.jsxs(O,{variant:"outline",size:"sm",disabled:!0,children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Export"]})]})}),e.jsxs(ee,{className:"p-0",children:[e.jsx("div",{className:"overflow-auto min-h-[320px]",style:{maxHeight:"calc(100vh - 380px)"},children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{className:"bg-gray-50",children:[e.jsx(Ie,{className:"w-14",children:"Sr No"}),e.jsx(Ie,{className:"min-w-[180px]",children:"Name of Deductor"}),e.jsx(Ie,{className:"text-right min-w-[110px]",children:"Total Amount Paid"}),e.jsx(Ie,{className:"text-right min-w-[110px]",children:"Total Tax Deducted"}),e.jsx(Ie,{className:"text-right min-w-[110px]",children:"Total TDS Deposited"}),e.jsx(Ie,{className:"min-w-[100px]",children:"TAN of Deductor"}),e.jsx(Ie,{className:"min-w-[72px]",children:"Section"}),e.jsx(Ie,{className:"min-w-[64px]",children:"Quarter"}),e.jsx(Ie,{className:"min-w-[90px]",children:"Assessment Year"}),e.jsx(Ie,{className:"min-w-[90px]",children:"Financial Year"}),e.jsx(Ie,{className:"min-w-[100px]",children:"Transaction Date"}),e.jsx(Ie,{className:"min-w-[64px]",children:"Status"}),e.jsx(Ie,{className:"min-w-[100px]",children:"Date of Booking"})]})}),e.jsx(Fs,{children:F?e.jsx(tt,{children:e.jsx(ve,{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(tt,{children:e.jsxs(ve,{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(O,{variant:"outline",size:"sm",onClick:E,className:"mt-2",children:"Clear Filters"})]})}):v.map((ae,he)=>e.jsxs(tt,{className:"hover:bg-gray-50",children:[e.jsx(ve,{className:"text-center text-sm text-gray-900",children:L*Gn+he+1}),e.jsx(ve,{className:"text-sm text-gray-900",children:ae.deductorName||""}),e.jsx(ve,{className:"text-right text-sm text-gray-900",children:Hi(ae.amountPaid??0)}),e.jsx(ve,{className:"text-right text-sm text-gray-900",children:Hi(ae.taxDeducted)}),e.jsx(ve,{className:"text-right text-sm text-gray-900",children:Hi(ae.totalTdsDeposited??0)}),e.jsx(ve,{className:"text-sm text-gray-700 font-mono",children:ae.tanNumber}),e.jsx(ve,{children:e.jsx(oe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:ae.sectionCode||""})}),e.jsx(ve,{children:e.jsx(oe,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:ae.quarter})}),e.jsx(ve,{className:"text-sm text-gray-700 font-medium",children:ae.assessmentYear||""}),e.jsx(ve,{className:"text-sm text-gray-700 font-medium",children:ae.financialYear||""}),e.jsx(ve,{className:"text-sm text-gray-700",children:Xh(ae.transactionDate)}),e.jsx(ve,{children:U3(ae.statusOltas)}),e.jsx(ve,{className:"text-sm text-gray-700",children:Xh(ae.dateOfBooking)})]},ae.id))})]})}),!F&&T>Gn&&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 ",L+1," of ",G," (",T," records)"]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-wrap justify-center",children:[e.jsxs(O,{variant:"outline",size:"sm",disabled:!J,onClick:()=>U(L-1),children:[e.jsx(Nn,{className:"w-4 h-4"}),"Previous"]}),te.map(ae=>e.jsx(O,{variant:ae===L?"default":"outline",size:"sm",className:ae===L?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>U(ae),children:ae+1},ae)),e.jsxs(O,{variant:"outline",size:"sm",disabled:!q,onClick:()=>U(L+1),children:["Next",e.jsx(Wa,{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 Jh={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 Zh({rows:t,label:s="Total"}){const a=u.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(tt,{className:"bg-gray-50 font-semibold",children:[e.jsx(ve,{children:s}),e.jsx(ve,{className:"text-right",children:ks(a.totalAmount)}),e.jsx(ve,{className:"text-right",children:ks(a.dealerCount)}),e.jsx(ve,{className:"text-right text-green-700",children:ks(a.submittedAmount)}),e.jsx(ve,{className:"text-right",children:ks(a.submittedDealerCount)}),e.jsx(ve,{className:"text-right text-red-700",children:ks(a.pendingAmount)})]})}function z3(){const[t,s]=u.useState(Jh),[a,r]=u.useState(!0);return u.useEffect(()=>{let n=!0;return(async()=>{try{r(!0);const i=await uN();if(!n)return;s(i)}catch(i){if(!n)return;console.error("[Form16Dashboard] fetch error:",i),Q.error(i instanceof Error?i.message:"Failed to load Form16A dashboard"),s(Jh)}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(ee,{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(ee,{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(ee,{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(ee,{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(de,{children:e.jsx(ue,{children:"Overall Summary"})}),e.jsxs(ee,{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(de,{children:e.jsx(ue,{children:"Year-wise Breakdown"})}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{className:"bg-gray-50",children:[e.jsx(Ie,{children:"Year"}),e.jsx(Ie,{className:"text-right",children:"Total Amount"}),e.jsx(Ie,{className:"text-right",children:"Dealer Count"}),e.jsx(Ie,{className:"text-right",children:"Submitted Amount"}),e.jsx(Ie,{className:"text-right",children:"Submitted Dealer Count"}),e.jsx(Ie,{className:"text-right",children:"Pending Amount"})]})}),e.jsx(Fs,{children:t.yearWise.length===0?e.jsx(tt,{children:e.jsx(ve,{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(tt,{children:[e.jsx(ve,{className:"font-medium",children:n.label}),e.jsx(ve,{className:"text-right",children:ks(n.totalAmount)}),e.jsx(ve,{className:"text-right",children:ks(n.dealerCount)}),e.jsx(ve,{className:"text-right text-green-700",children:ks(n.submittedAmount)}),e.jsx(ve,{className:"text-right",children:ks(n.submittedDealerCount)}),e.jsx(ve,{className:"text-right text-red-700",children:ks(n.pendingAmount)})]},n.label)),e.jsx(Zh,{rows:t.yearWise})]})})]})})})]}),e.jsxs(Z,{children:[e.jsx(de,{children:e.jsx(ue,{children:"Zone-wise Breakdown"})}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{className:"bg-gray-50",children:[e.jsx(Ie,{children:"Zone"}),e.jsx(Ie,{className:"text-right",children:"Total Amount"}),e.jsx(Ie,{className:"text-right",children:"Dealer Count"}),e.jsx(Ie,{className:"text-right",children:"Submitted Amount"}),e.jsx(Ie,{className:"text-right",children:"Submitted Dealer Count"}),e.jsx(Ie,{className:"text-right",children:"Pending Amount"})]})}),e.jsx(Fs,{children:t.zoneWise.length===0?e.jsx(tt,{children:e.jsx(ve,{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(tt,{children:[e.jsx(ve,{className:"font-medium",children:n.label}),e.jsx(ve,{className:"text-right",children:ks(n.totalAmount)}),e.jsx(ve,{className:"text-right",children:ks(n.dealerCount)}),e.jsx(ve,{className:"text-right text-green-700",children:ks(n.submittedAmount)}),e.jsx(ve,{className:"text-right",children:ks(n.submittedDealerCount)}),e.jsx(ve,{className:"text-right text-red-700",children:ks(n.pendingAmount)})]},n.label)),e.jsx(Zh,{rows:t.zoneWise})]})})]})})})]})]})})}const V3="".trim().replace(/\/$/,"");let rl="https://reflow-uat.royalenfield.com/api/v1".trim().replace(/\/$/,"");/\/cpc-(cdc|csd)$/i.test(rl)&&(rl=rl.replace(/\/cpc-(cdc|csd)$/i,""));const W3=t=>t?t.replace(/\/v1\/?$/i,""):"",H3=V3||W3(rl)||"/api",ta=fi.create({baseURL:H3,withCredentials:!0});ta.interceptors.request.use(t=>{if(t.data instanceof FormData){const s=t.headers;delete s["Content-Type"];const a=s.common,r=s.post;a&&typeof a=="object"&&delete a["Content-Type"],r&&typeof r=="object"&&delete r["Content-Type"]}return t});function pn(t){return!t||typeof t!="object"?t:{...t,id:t.id,bookingId:t.bookingId??t.booking_id??"",claimId:t.claimId??t.claim_id??"",documentType:t.documentType??t.document_type??"",validationStatus:t.validationStatus??t.validation_status??"",matchPercentage:Number(t.matchPercentage??t.match_percentage??0)||0,createdAt:t.createdAt??t.created_at,documentGcpUrl:t.documentGcpUrl??t.document_gcp_url,extractedFields:t.extractedFields??t.extracted_fields,fieldResults:t.fieldResults??t.field_results,field_results:t.field_results??t.fieldResults,msdPayload:t.msdPayload??t.msd_payload,mismatchReasons:t.mismatchReasons??t.mismatch_reasons,attemptNo:t.attemptNo!=null?t.attemptNo:t.attempt_no!=null?t.attempt_no:1,provider:t.provider,summary:t.summary}}function Cb(t){return Array.isArray(t)?t.map(pn):[]}function G3(t){if(!Array.isArray(t)||t.length===0)return[];const s=[...t].sort((n,i)=>new Date(i.createdAt)-new Date(n.createdAt)),a=new Map;for(const n of s){const i=String(n.claimId||"").trim(),l=Number(n.attemptNo??1)||1,o=i?`${i}::${l}`:`id:${n.id}`;a.has(o)||a.set(o,[]),a.get(o).push(n)}const r=[];for(const[n,i]of a){const l=[...i].sort((j,v)=>new Date(v.createdAt)-new Date(j.createdAt)),o=Math.max(...l.map(j=>new Date(j.createdAt).getTime())),d=String(l[0].claimId||"").trim()||l[0].bookingId||"",m=[...new Set(l.map(j=>j.documentType).filter(Boolean))].join(" + "),p=l.map(j=>Number(j.matchPercentage)||0),x=p.length?Math.min(...p):0,h=p.length?Math.max(...p):0,g=p.length?Math.round(p.reduce((j,v)=>j+v,0)/p.length):0,f=l.map(j=>String(j.validationStatus||"").toUpperCase());let b=l[0].validationStatus||"UNKNOWN";f.some(j=>j==="NEED_MANUAL"||j==="REVIEW")?b=f.includes("NEED_MANUAL")?"NEED_MANUAL":"REVIEW":f.some(j=>["MISMATCH","UNSUCCESSFUL","REJECTED"].includes(j))?b="MISMATCH":f.some(j=>j==="PENDING"||j==="PROCESSING")?b="PENDING":f.length&&f.every(j=>["MATCH","SUCCESSFUL","APPROVED"].includes(j))&&(b="MATCH");const y=l.length>1&&x!==h?`${x}% ${h}%`:`${g}%`;r.push({key:n,displayId:d,typesLabel:m,docs:l,aggregateStatus:b,aggregateMatchPct:l.length>1?x:g,matchPctLabel:y,sortTime:o})}return r.sort((n,i)=>i.sortTime-n.sortTime),r}var Sb={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},qh=xa.createContext&&xa.createContext(Sb),Y3=["attr","size","title"];function Q3(t,s){if(t==null)return{};var a,r,n=K3(t,s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)a=i[r],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(n[a]=t[a])}return n}function K3(t,s){if(t==null)return{};var a={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(s.indexOf(r)!==-1)continue;a[r]=t[r]}return a}function Nl(){return Nl=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var r in a)({}).hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},Nl.apply(null,arguments)}function ep(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);s&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),a.push.apply(a,r)}return a}function wl(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?ep(Object(a),!0).forEach(function(r){X3(t,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):ep(Object(a)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(a,r))})}return t}function X3(t,s,a){return(s=J3(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function J3(t){var s=Z3(t,"string");return typeof s=="symbol"?s:s+""}function Z3(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var r=a.call(t,s);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Ab(t){return t&&t.map((s,a)=>xa.createElement(s.tag,wl({key:a},s.attr),Ab(s.child)))}function Ws(t){return s=>xa.createElement(q3,Nl({attr:wl({},t.attr)},s),Ab(t.child))}function q3(t){var s=a=>{var{attr:r,size:n,title:i}=t,l=Q3(t,Y3),o=n||a.size||"1em",c;return a.className&&(c=a.className),t.className&&(c=(c?c+" ":"")+t.className),xa.createElement("svg",Nl({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},a.attr,r,l,{className:c,style:wl(wl({color:t.color||a.color},a.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),i&&xa.createElement("title",null,i),t.children)};return qh!==void 0?xa.createElement(qh.Consumer,null,a=>s(a)):s(Sb)}function Gi(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"18",y1:"6",x2:"6",y2:"18"},child:[]},{tag:"line",attr:{x1:"6",y1:"6",x2:"18",y2:"18"},child:[]}]})(t)}function Pc(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"15",y1:"9",x2:"9",y2:"15"},child:[]},{tag:"line",attr:{x1:"9",y1:"9",x2:"15",y2:"15"},child:[]}]})(t)}function eF(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"17 8 12 3 7 8"},child:[]},{tag:"line",attr:{x1:"12",y1:"3",x2:"12",y2:"15"},child:[]}]})(t)}function tF(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"6"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"2"},child:[]}]})(t)}function sF(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]}]})(t)}function tp(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]}]})(t)}function Yo(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"},child:[]},{tag:"polyline",attr:{points:"13 2 13 9 20 9"},child:[]}]})(t)}function sp(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"},child:[]},{tag:"polyline",attr:{points:"14 2 14 8 20 8"},child:[]},{tag:"line",attr:{x1:"16",y1:"13",x2:"8",y2:"13"},child:[]},{tag:"line",attr:{x1:"16",y1:"17",x2:"8",y2:"17"},child:[]},{tag:"polyline",attr:{points:"10 9 9 9 8 9"},child:[]}]})(t)}function pi(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]}]})(t)}function ap(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"7 10 12 15 17 10"},child:[]},{tag:"line",attr:{x1:"12",y1:"15",x2:"12",y2:"3"},child:[]}]})(t)}function Qo(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"polyline",attr:{points:"12 6 12 12 16 14"},child:[]}]})(t)}function rp(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(t)}function Ko(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"15 18 9 12 15 6"},child:[]}]})(t)}function aF(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"6 9 12 15 18 9"},child:[]}]})(t)}function Yr(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"},child:[]},{tag:"polyline",attr:{points:"22 4 12 14.01 9 11.01"},child:[]}]})(t)}function gi(t){return Ws({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12.01",y2:"16"},child:[]}]})(t)}const rF=()=>{var ne;const t=gs(),s=$l(),[a,r]=u.useState([]),[n,i]=u.useState(!0),[l,o]=u.useState(null),[c,d]=u.useState(!1),[m,p]=u.useState(!1),[x,h]=u.useState(""),[g,f]=u.useState([]),[b,y]=u.useState("GEMINI_VERTEX"),[j,v]=u.useState(""),[N,T]=u.useState("CPC"),A=N==="CSD"?1:2,[k,D]=u.useState(null),F=te=>te==="AADHAAR"?[{key:"customer_name",value:"",label:"Customer Name"},{key:"aadhar_number",value:"",label:"Aadhar Number"}]:te==="CPC_AUTH"?[{key:"customer_name",value:"",label:"Customer Name"},{key:"letter_number",value:"",label:"Letter Number"},{key:"letter_amount",value:"",label:"Letter Amount"},{key:"signature_and_stamp",value:"yes",label:"Signature & Stamp"}]:te==="CSD_PO"?[{key:"customer_name",value:"",label:"Customer Name"},{key:"po_number",value:"",label:"PO Number"},{key:"po_amount",value:"",label:"PO Amount"},{key:"signature_and_stamp",value:"yes",label:"Signature & Stamp"}]:te==="RETAIL_INVOICE"?[{key:"vendor_name",value:"",label:"Supplier Name"},{key:"order_or_authorisation_number",value:"",label:"Order / Authorisation Number"},{key:"invoice_value",value:"",label:"Invoice Amount"}]:[{key:"vendor_name",value:"",label:"Supplier Name"},{key:"order_or_authorisation_number",value:"",label:"PO Number"},{key:"invoice_value",value:"",label:"PO Amount"}],w=te=>{const ge=Array.from(te.target.files),we=N==="CSD"?"CSD_PO":"CPC_AUTH",fe=ge.map(ke=>({id:Math.random().toString(36).substring(7),file:ke,documentType:we,expectedFields:F(we)}));f([...g,...fe]),fe.length>0&&!k&&D(fe[0].id)},L=(te,ge)=>{f(we=>we.map(fe=>{if(fe.id===te){const ke={...fe,...ge};return ge.documentType&&ge.documentType!==fe.documentType&&(ke.expectedFields=F(ge.documentType)),ke}return fe}))},_=(te,ge,we,fe)=>{f(ke=>ke.map(le=>{if(le.id!==te)return le;const Ne=[...le.expectedFields];let ae=fe;if(we==="value"){const he=(Ne[ge].key||"").toLowerCase();he.includes("name")||he.includes("surname")?ae=fe.replace(/\b\w/g,ie=>ie.toUpperCase()):he==="gender"?ae=fe.charAt(0).toUpperCase()+fe.slice(1).toLowerCase():he==="dob"&&(ae=fe.replace(/\D/g,""))}return Ne[ge][we]=ae,{...le,expectedFields:Ne}}))},W=te=>{f(ge=>ge.map(we=>we.id===te?{...we,expectedFields:[...we.expectedFields,{key:"",value:""}]}:we))},I=(te,ge)=>{f(we=>we.map(fe=>fe.id===te?{...fe,expectedFields:fe.expectedFields.filter((ke,le)=>le!==ge)}:fe))},$=te=>{const ge=g.filter(we=>we.id!==te);f(ge),k===te&&D(ge.length>0?ge[0].id:null)},[M,R]=u.useState(null),[C,H]=u.useState(!1),[z,P]=u.useState(0),S={CSD_PO:["customer_name","order_or_authorisation_number","invoice_value","govt_signatory_and_stamp_present","vendor_name","mail_extraction"],RETAIL_INVOICE:["vendor_name","order_or_authorisation_number","invoice_value","invoice_date","customer_name"],AADHAAR:["customer_name","aadhar_number","name","aadhaar_number","dob","gender","address","mail_extraction"],CPC_AUTH:["customer_name","letter_number","letter_amount","signature_and_stamp","authority_grantor_name","valid_until","purpose","date_of_issue","mail_extraction"]};u.useEffect(()=>{U()},[]),u.useEffect(()=>{var te,ge;((te=s.state)!=null&&te.openCpcCsdNewRequest||(ge=s.state)!=null&&ge.openCpcCdcNewRequest)&&(p(!0),t(`${s.pathname}${s.search}`,{replace:!0,state:{}}))},[s.state,s.pathname,s.search,t]);const U=async()=>{var te,ge,we,fe;i(!0),o(null);try{const{data:ke}=await ta.get("/documents/recent",{params:{page:1,limit:100}}),le=Array.isArray(ke)?ke:ke.items||[];r(Cb(le))}catch(ke){console.error(ke);const le=((ge=(te=ke.response)==null?void 0:te.data)==null?void 0:ge.message)||((fe=(we=ke.response)==null?void 0:we.data)==null?void 0:fe.error)||ke.message||"Could not load CPC documents.";o(le),r([])}finally{i(!1)}},Y=async te=>{var ge;if(te.preventDefault(),g.length===0)return alert("Please select at least one file");if(g.length<A)return alert(N==="CSD"?"CSD claims need 1 file: the Purchase Order (PO). Rules you add are the reference values to check.":"CPC claims need 2 files: (1) Authorization Letter and (2) Aadhaar. Select both PDFs/images in the queue.");d(!0);try{const we=new FormData,fe=[];g.forEach(ae=>{we.append("files",ae.file);const he=ae.expectedFields.reduce((je,Fe)=>{const Ue=(Fe.key||"").trim();return Ue&&(je[Ue]=Fe.value==null?"":Fe.value),je},{}),ie=[...new Set(ae.expectedFields.map(je=>(je.key||"").trim()).filter(Boolean))];fe.push({document_type:ae.documentType,msd_payload:he,expected_field_keys:ie})});const ke=j.replace(/^(CPC|CSD)-?/i,""),le=`${N}-${ke}`;we.append("booking_id",le),we.append("booking_type",N),we.append("provider",b),we.append("metadata_queue",JSON.stringify(fe));const{data:Ne}=await ta.post("/v1/ocr/upload",we);R(Ne),P(0),p(!1),H(!0),U(),f([]),D(null),v("")}catch(we){const fe=(ge=we.response)==null?void 0:ge.data,ke=(fe==null?void 0:fe.message)||(fe==null?void 0:fe.error_message)||(fe==null?void 0:fe.error)||we.message;alert(`Process Failed: ${ke}`)}finally{d(!1)}},B=G3(a),E=te=>String(te.validationStatus||"").toUpperCase(),V={total:B.length,open:B.filter(te=>te.docs.some(ge=>["PENDING","NEED_MANUAL","REVIEW","PROCESSING"].includes(E(ge)))).length,completed:B.filter(te=>te.docs.length>0&&te.docs.every(ge=>["MATCH","SUCCESSFUL","APPROVED"].includes(E(ge)))).length,failed:B.filter(te=>te.docs.some(ge=>["MISMATCH","UNSUCCESSFUL","REJECTED"].includes(E(ge)))).length},G=(te,ge=0)=>{const we=te?te.toUpperCase():"UNKNOWN",fe=Number(ge||0);return["MISMATCH","FAILED","UNSUCCESSFUL","REJECTED"].includes(we)?e.jsxs("span",{className:"status-pill danger",children:[e.jsx(gi,{className:"status-icon"})," Mismatch"]}):["NEED_MANUAL","REVIEW"].includes(we)?e.jsxs("span",{className:"status-pill warning",children:[e.jsx(pi,{className:"status-icon"})," Needs Review"]}):["PENDING","PROCESSING"].includes(we)?e.jsxs("span",{className:"status-pill info",children:[e.jsx(Qo,{className:"status-icon ani-spin"})," Processing"]}):["MATCH","COMPLETED","SUCCESS","SUCCESSFUL","APPROVED"].includes(we)?e.jsxs("span",{className:"status-pill success",children:[e.jsx(Yr,{className:"status-icon"})," Match"]}):fe>=95?e.jsxs("span",{className:"status-pill success",children:[e.jsx(Yr,{className:"status-icon"})," Match"]}):e.jsx("span",{className:"status-pill neutral",children:te})},J=(te,ge)=>{const we=String(ge||"").toUpperCase();return["MISMATCH","UNSUCCESSFUL","REJECTED","NEED_MANUAL","REVIEW","PENDING","PROCESSING"].includes(we)?!1:["MATCH","SUCCESSFUL","APPROVED"].includes(we)?!0:Number(te||0)>=95},q=x.toLowerCase(),se=B.filter(te=>q?(te.displayId||"").toLowerCase().includes(q)||(te.typesLabel||"").toLowerCase().includes(q)||(te.aggregateStatus||"").toLowerCase().includes(q)||te.docs.some(ge=>(ge.bookingId||"").toLowerCase().includes(q)||(ge.documentType||"").toLowerCase().includes(q)||(ge.validationStatus||"").toLowerCase().includes(q)):!0);return e.jsxs("div",{className:"dashboard-container",children:[l&&e.jsxs("div",{role:"alert",style:{marginBottom:"1rem",padding:"0.75rem 1rem",borderRadius:"8px",background:"#fef2f2",border:"1px solid #fecaca",color:"#991b1b",fontSize:"0.9rem"},children:[e.jsx("strong",{children:"CPC-CSD list error:"})," ",l," ",e.jsx("button",{type:"button",onClick:()=>U(),style:{marginLeft:"0.5rem",textDecoration:"underline",cursor:"pointer",background:"none",border:"none",color:"#991b1b"},children:"Retry"})]}),e.jsxs("div",{className:"page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:"1rem"},children:[e.jsxs("div",{children:[e.jsx("h1",{className:"page-title",children:"My Requests"}),e.jsx("p",{className:"page-subtitle",children:"View and manage your document submissions"})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"1rem"},children:[e.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center"},children:[e.jsx(sF,{style:{position:"absolute",left:"12px",color:"#94a3b8",fontSize:"1.2rem",pointerEvents:"none"}}),e.jsx("input",{type:"text",placeholder:"Search requests...",value:x,onChange:te=>h(te.target.value),style:{padding:"10px 16px 10px 38px",border:"1px solid #e2e8f0",borderRadius:"8px",outline:"none",width:"250px",fontSize:"0.9rem",backgroundColor:"white",lineHeight:"normal",display:"block"}})]}),e.jsxs("button",{className:"btn-new-request",onClick:()=>p(!0),children:[e.jsx(tp,{})," New Request"]})]})]}),e.jsxs("div",{className:"stats-grid",children:[e.jsx("div",{className:"stat-card blue",children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[e.jsxs("div",{children:[e.jsx("span",{className:"stat-label",children:"Total Requests"}),e.jsx("div",{className:"stat-value",children:V.total})]}),e.jsx("div",{style:{color:"#3b82f6",background:"#eff6ff",padding:"0.75rem",borderRadius:"12px"},children:e.jsx(Yo,{className:"text-xl",style:{fontSize:"1.5rem"}})})]})}),e.jsx("div",{className:"stat-card yellow",children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[e.jsxs("div",{children:[e.jsx("span",{className:"stat-label",children:"Open / Review"}),e.jsx("div",{className:"stat-value",children:V.open})]}),e.jsx("div",{style:{color:"#f59e0b",background:"#fffbeb",padding:"0.75rem",borderRadius:"12px"},children:e.jsx(Qo,{style:{fontSize:"1.5rem"}})})]})}),e.jsx("div",{className:"stat-card green",children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[e.jsxs("div",{children:[e.jsx("span",{className:"stat-label",children:"Completed"}),e.jsx("div",{className:"stat-value",children:V.completed})]}),e.jsx("div",{style:{color:"#10b981",background:"#ecfdf5",padding:"0.75rem",borderRadius:"12px"},children:e.jsx(Yr,{style:{fontSize:"1.5rem"}})})]})}),e.jsx("div",{className:"stat-card red",children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[e.jsxs("div",{children:[e.jsx("span",{className:"stat-label",children:"Failed / Mismatch"}),e.jsx("div",{className:"stat-value",children:V.failed})]}),e.jsx("div",{style:{color:"#ef4444",background:"#fef2f2",padding:"0.75rem",borderRadius:"12px"},children:e.jsx(gi,{style:{fontSize:"1.5rem"}})})]})})]}),e.jsxs("div",{className:"table-container",children:[e.jsx("div",{className:"table-header-actions",children:e.jsx("div",{className:"table-title",children:"Recent Submissions"})}),e.jsx("div",{style:{maxHeight:"450px",overflowY:"auto"},children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{style:{position:"sticky",top:0,backgroundColor:"white",zIndex:1,boxShadow:"0 1px 0 #e5e7eb"},children:e.jsxs("tr",{children:[e.jsx("th",{children:"Booking ID"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Match %"}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:n?e.jsx("tr",{children:e.jsx("td",{colSpan:"6",style:{textAlign:"center",padding:"2rem"},children:"Loading submissions…"})}):se.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:"6",style:{textAlign:"center",padding:"2rem"},children:"No matching documents found."})}):se.map(te=>{var ge,we;return e.jsxs("tr",{children:[e.jsx("td",{style:{fontWeight:600},children:(we=(ge=te.docs)==null?void 0:ge[0])!=null&&we.id?e.jsx(ii,{to:`/cpc-csd/documents/${te.docs[0].id}`,state:{from:"/cpc-csd/dashboard",title:"CPC-CSD Dashboard"},title:te.docs.length>1?`Open review (first of ${te.docs.length} documents — use Actions for others)`:"Open review",style:{color:"#2563eb",textDecoration:"none",cursor:"pointer"},className:"dashboard-booking-id-link",children:te.displayId}):e.jsx("span",{style:{color:"#2563eb"},children:te.displayId})}),e.jsxs("td",{style:{fontSize:"0.85rem",lineHeight:1.35},children:[te.typesLabel,te.docs.length>1&&e.jsxs("span",{style:{display:"block",color:"#64748b",fontSize:"0.75rem",marginTop:"2px"},children:[te.docs.length," documents"]})]}),e.jsx("td",{children:new Date(te.sortTime).toLocaleDateString()}),e.jsx("td",{children:G(te.aggregateStatus,te.aggregateMatchPct)}),e.jsx("td",{style:{fontWeight:700,color:J(te.aggregateMatchPct,te.aggregateStatus)?"#059669":"#dc2626"},children:te.matchPctLabel}),e.jsx("td",{children:e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem",alignItems:"center"},children:te.docs.map(fe=>e.jsxs(ii,{to:`/cpc-csd/documents/${fe.id}`,state:{from:"/cpc-csd/dashboard",title:"CPC-CSD Dashboard"},title:fe.bookingId||fe.documentType,style:{color:"#059669",textDecoration:"none",fontWeight:600,display:"inline-flex",alignItems:"center",gap:"0.2rem",fontSize:te.docs.length>1?"0.8rem":"0.9rem"},children:[e.jsx(pi,{})," ",te.docs.length>1?(fe.documentType||"Doc").replace(/_/g," "):"View"]},fe.id))})})]},te.key)})})]})})]}),C&&M&&e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-content",style:{maxWidth:"700px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{className:"modal-title",style:{margin:0,border:"none",padding:0},children:"Validation Result"}),e.jsx("button",{className:"modal-close",onClick:()=>H(!1),style:{position:"static"},children:e.jsx(Gi,{})})]}),e.jsxs("div",{className:"modal-body",children:[e.jsxs("div",{style:{padding:"1.25rem",backgroundColor:"#f8fafc",borderRadius:"12px",marginBottom:"1.5rem",border:"1px solid #e2e8f0"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[e.jsx("span",{style:{fontSize:"0.9rem",fontWeight:600,color:"#64748b"},children:"Batch Identifier"}),e.jsx("span",{style:{fontSize:"1rem",fontWeight:700,color:"#2563eb"},children:M.booking_id||((ne=M.document_id)==null?void 0:ne.substring(0,8))})]}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{style:{fontSize:"0.9rem",fontWeight:600,color:"#64748b"},children:"Processing Status"}),M.results?e.jsxs("span",{className:"status-pill success",children:[M.count," Files Processed"]}):G(M.validation_status,M.overall_match_percentage||M.match_percentage)]})]}),M.results&&e.jsxs("div",{style:{marginBottom:"1rem"},children:[e.jsx("div",{style:{fontSize:"0.8rem",fontWeight:600,color:"#64748b",marginBottom:"0.4rem",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Click a document to view its details"}),e.jsx("div",{style:{maxHeight:"200px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"0.5rem"},children:M.results.map((te,ge)=>e.jsxs("div",{onClick:()=>P(ge),style:{padding:"0.6rem 0.75rem",background:z===ge?"#eff6ff":"white",border:z===ge?"2px solid #2563eb":"1px solid #e5e7eb",borderRadius:"6px",display:"flex",justifyContent:"space-between",alignItems:"center",cursor:"pointer",transition:"all 0.15s"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"0.875rem",fontWeight:600,color:z===ge?"#1d4ed8":"#111827"},children:te.filename||`Document ${ge+1}`}),e.jsxs("div",{style:{fontSize:"0.75rem",color:"#6b7280"},children:["ID: ",te.booking_id]})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[G(te.validation_status,te.overall_match_percentage||te.match_percentage),e.jsxs("span",{style:{fontWeight:700,fontSize:"0.875rem"},children:[te.overall_match_percentage,"%"]})]})]},ge))})]}),!M.results&&e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{style:{fontSize:"1.1rem",fontWeight:600},children:"Match Percentage"}),e.jsxs("span",{style:{fontSize:"1.2rem",fontWeight:700,color:J(M.overall_match_percentage||M.match_percentage,M.validation_status||M.status)?"#059669":"#dc2626"},children:[M.overall_match_percentage||M.match_percentage||0,"%"]})]}),(()=>{const te=M.results?M.results[z]:M,ge=te==null?void 0:te.mismatch_summary;return ge?e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:"0.5rem",marginBottom:"1.5rem",textAlign:"center"},children:[e.jsxs("div",{style:{padding:"0.5rem",background:"#f3f4f6",borderRadius:"6px"},children:[e.jsx("div",{style:{fontSize:"0.75rem",color:"#6b7280"},children:"Total"}),e.jsx("div",{style:{fontWeight:700},children:ge.total_expected_fields})]}),e.jsxs("div",{style:{padding:"0.5rem",background:"#ecfdf5",borderRadius:"6px",color:"#059669"},children:[e.jsx("div",{style:{fontSize:"0.75rem"},children:"Matched"}),e.jsx("div",{style:{fontWeight:700},children:ge.matched})]}),e.jsxs("div",{style:{padding:"0.5rem",background:"#fffbeb",borderRadius:"6px",color:"#b45309"},children:[e.jsx("div",{style:{fontSize:"0.75rem"},children:"Missing"}),e.jsx("div",{style:{fontWeight:700},children:ge.missing})]}),e.jsxs("div",{style:{padding:"0.5rem",background:"#fef2f2",borderRadius:"6px",color:"#dc2626"},children:[e.jsx("div",{style:{fontSize:"0.75rem"},children:"Mismatch"}),e.jsx("div",{style:{fontWeight:700},children:ge.mismatched})]})]}):null})(),(()=>{const te=M.results?M.results[z]:M;return te!=null&&te.field_results?e.jsxs(e.Fragment,{children:[e.jsxs("h3",{style:{fontSize:"1rem",fontWeight:600,marginBottom:"0.5rem",color:"#374151",display:"flex",alignItems:"center",gap:"0.5rem"},children:[e.jsx("span",{children:M.results?"Extraction Details":"Validation Details"}),M.results&&e.jsx("span",{style:{fontSize:"0.8rem",fontWeight:500,color:"#2563eb",background:"#eff6ff",border:"1px solid #bfdbfe",borderRadius:"4px",padding:"2px 8px"},children:te.filename||`Document ${z+1}`})]}),e.jsx("div",{style:{maxHeight:"250px",overflowY:"auto",border:"1px solid #e5e7eb",borderRadius:"6px",padding:"0.5rem"},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},children:[e.jsx("thead",{style:{backgroundColor:"#f9fafb"},children:e.jsxs("tr",{children:[e.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Field"}),e.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Expected"}),e.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Extracted"}),e.jsx("th",{style:{padding:"0.5rem",textAlign:"center"},children:"Status"})]})}),e.jsx("tbody",{children:(te.field_results||[]).map((ge,we)=>e.jsxs("tr",{style:{borderBottom:"1px solid #f3f4f6"},children:[e.jsx("td",{style:{padding:"0.5rem",fontWeight:500},children:ge.field||ge.key}),e.jsx("td",{style:{padding:"0.5rem"},children:ge.expected}),e.jsx("td",{style:{padding:"0.5rem",color:ge.status==="MISSING"?"#9ca3af":"inherit"},children:ge.extracted||ge.found||"N/A"}),e.jsx("td",{style:{padding:"0.5rem",textAlign:"center"},children:e.jsxs("span",{style:{padding:"2px 6px",borderRadius:"4px",fontSize:"0.75rem",backgroundColor:J(ge.match_percentage,ge.status)?"#d1fae5":"#fee2e2",color:J(ge.match_percentage,ge.status)?"#065f46":"#991b1b"},children:[ge.match_percentage,"%"]})})]},we))})]})})]}):null})(),(()=>{const te=M.results?M.results[z]:M,ge=te==null?void 0:te.mismatch_reasons;return!ge||ge.length===0?null:e.jsxs("div",{style:{marginTop:"1rem",padding:"0.75rem",backgroundColor:"#fef2f2",border:"1px solid #fca5a5",borderRadius:"6px"},children:[e.jsx("h4",{style:{margin:"0 0 0.5rem 0",color:"#991b1b",fontSize:"0.9rem"},children:"Critical Issues:"}),e.jsx("ul",{style:{margin:0,paddingLeft:"1.2rem",color:"#b91c1c",fontSize:"0.85rem"},children:ge.map((we,fe)=>e.jsx("li",{style:{whiteSpace:"pre-wrap"},children:typeof we=="string"?we:`${we.field}: ${we.reason||"Mismatch"}`},fe))})]})})(),e.jsx("div",{style:{marginTop:"1.5rem",display:"flex",gap:"1rem"},children:e.jsx("button",{onClick:()=>H(!1),style:{flex:1,padding:"0.75rem",backgroundColor:"#2563eb",color:"white",borderRadius:"6px",fontWeight:600,cursor:"pointer",border:"none"},children:"Done & Close"})})]})]})}),m&&e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-content",style:{maxWidth:g.length>0?"900px":"600px",transition:"max-width 0.3s"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{className:"modal-title",style:{margin:0,border:"none",padding:0},children:"Create New Validation Request"}),e.jsx("button",{className:"modal-close",onClick:()=>p(!1),style:{position:"static"},children:e.jsx(Gi,{})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("form",{onSubmit:Y,children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"1.5rem",marginBottom:"1.5rem"},children:[e.jsxs("div",{children:[e.jsx("label",{className:"premium-label",children:"Booking ID"}),e.jsx("input",{type:"text",className:"premium-input",value:j,onChange:te=>v(te.target.value),placeholder:"Enter ID (e.g., 40156)",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"premium-label",children:"Booking Type"}),e.jsxs("select",{className:"premium-input",value:N,onChange:te=>T(te.target.value),children:[e.jsx("option",{value:"CPC",children:"CPC"}),e.jsx("option",{value:"CSD",children:"CSD"})]})]})]}),e.jsxs("div",{className:"form-group",style:{marginBottom:"1.5rem"},children:[e.jsx("label",{className:"premium-label",children:"Add Documents to Queue"}),e.jsxs("div",{className:"file-upload-wrapper",children:[e.jsx("input",{type:"file",multiple:!0,className:"file-upload-input",onChange:w,accept:".pdf,.jpg,.jpeg,.png"}),e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx(eF,{style:{fontSize:"2rem",color:"#94a3b8",marginBottom:"0.75rem"}}),e.jsx("div",{style:{fontSize:"0.95rem",fontWeight:500,color:"#475569"},children:"Click or Drag files here"}),e.jsx("div",{style:{fontSize:"0.8rem",color:"#94a3b8",marginTop:"0.25rem"},children:"PDF, JPG, PNG up to 20 files"})]})]}),e.jsxs("div",{style:{marginTop:"0.75rem",padding:"0.65rem 0.85rem",fontSize:"0.8rem",lineHeight:1.45,color:"#334155",background:"#f1f5f9",borderRadius:"8px",border:"1px solid #e2e8f0"},children:[e.jsxs("strong",{children:["Files in queue: ",g.length]})," — ",N==="CSD"?"CSD needs 1 attachment (PO).":"CPC needs 2 attachments: Authority Letter + Aadhaar (set document type per file)."," ","“Validation rules” are the reference values compared to the document."]})]}),g.length>0&&e.jsxs("div",{className:"queue-container",children:[e.jsxs("div",{className:"queue-sidebar",children:[e.jsx("div",{style:{padding:"1rem",fontWeight:700,fontSize:"0.7rem",textTransform:"uppercase",color:"#94a3b8",borderBottom:"1px solid #e2e8f0",backgroundColor:"white",position:"sticky",top:0},children:"Upload Queue"}),g.map(te=>e.jsxs("div",{onClick:()=>D(te.id),className:`queue-item ${k===te.id?"active":""}`,children:[e.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"flex",alignItems:"center",gap:"0.5rem"},children:[e.jsx(Yo,{style:{flexShrink:0}})," ",te.file.name]}),e.jsx("button",{type:"button",onClick:ge=>{ge.stopPropagation(),$(te.id)},style:{color:"#94a3b8",border:"none",background:"none",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center"},children:e.jsx(Gi,{})})]},te.id))]}),e.jsxs("div",{style:{padding:"1.5rem",overflowY:"auto",backgroundColor:"#ffffff"},children:[k&&g.find(te=>te.id===k)&&e.jsx("div",{children:(()=>{const te=g.find(ge=>ge.id===k);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{marginBottom:"1.5rem"},children:[e.jsx("label",{className:"premium-label",children:"Select Document Type"}),e.jsxs("select",{className:"premium-input",value:te.documentType,onChange:ge=>L(te.id,{documentType:ge.target.value}),children:[e.jsx("option",{value:"CSD_PO",children:"CSD Purchase Order"}),e.jsx("option",{value:"CPC_AUTH",children:"CPC Authority Letter"}),e.jsx("option",{value:"AADHAAR",children:"Aadhaar Card"}),e.jsx("option",{value:"RETAIL_INVOICE",children:"Retail Invoice"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"premium-label",style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:["Validation Rules",e.jsxs("span",{style:{fontWeight:400,fontSize:"0.75rem",color:"#94a3b8"},children:[te.expectedFields.length," rules defined"]})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginTop:"0.5rem"},children:[te.expectedFields.map((ge,we)=>e.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[e.jsx("div",{style:{flex:1},children:ge.label?e.jsx("div",{style:{padding:"0.5rem 0.75rem",fontSize:"0.8rem",fontWeight:700,color:"#334155",backgroundColor:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:"6px"},children:ge.label}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",placeholder:"Field Key",className:"premium-input",style:{padding:"0.5rem 0.75rem",fontSize:"0.85rem"},value:ge.key,onChange:fe=>_(te.id,we,"key",fe.target.value),list:`suggestions-${te.id}-${we}`}),e.jsx("datalist",{id:`suggestions-${te.id}-${we}`,children:(S[te.documentType]||[]).map(fe=>e.jsx("option",{value:fe},fe))})]})}),e.jsx("div",{style:{flex:1.5},children:e.jsx("input",{type:"text",placeholder:"Expected Value",className:"premium-input",style:{padding:"0.5rem 0.75rem",fontSize:"0.85rem"},value:ge.value,onChange:fe=>_(te.id,we,"value",fe.target.value)})}),e.jsx("button",{type:"button",onClick:()=>I(te.id,we),style:{color:"#ef4444",border:"none",background:"none",cursor:"pointer",padding:"0.5rem"},children:e.jsx(Gi,{})})]},we)),e.jsxs("button",{type:"button",onClick:()=>W(te.id),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"0.5rem",color:"#2563eb",border:"1px dashed #bfdbfe",borderRadius:"8px",padding:"0.75rem",background:"#f8fafc",fontSize:"0.85rem",fontWeight:600,marginTop:"0.5rem",cursor:"pointer"},children:[e.jsx(tp,{})," Add New Rule"]})]})]})]})})()}),!k&&e.jsxs("div",{style:{textAlign:"center",color:"#94a3b8",marginTop:"4rem"},children:[e.jsx(Yo,{style:{fontSize:"3rem",margin:"0 auto 1rem",opacity:.3}}),e.jsx("p",{children:"Select a file from the queue to configure its validation rules."})]})]})]}),e.jsx("div",{style:{marginTop:"2rem"},children:e.jsx("button",{type:"submit",style:{width:"100%",backgroundColor:"#10b981",color:"white",padding:"1rem",border:"none",borderRadius:"12px",fontWeight:700,fontSize:"1rem",cursor:c||g.length===0||g.length<A?"not-allowed":"pointer",opacity:c||g.length===0||g.length<A?.7:1,boxShadow:"0 4px 6px -1px rgba(16, 185, 129, 0.2)",transition:"all 0.2s"},disabled:c||g.length===0||g.length<A,children:c?e.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"0.5rem"},children:[e.jsx(Qo,{className:"ani-spin"})," Processing Documents..."]}):`Submit ${g.length} file(s) (${A} required for ${N})`})})]})})]})})]})};function Tb(t){const[s,a]=u.useState(null),[r,n]=u.useState(!1),[i,l]=u.useState(null);return u.useEffect(()=>{if(!t){a(null),n(!1),l(null);return}let o=!1,c;return(async()=>{n(!0),l(null),a(null);try{const{data:m}=await ta.get(`/documents/${t}/file`,{responseType:"blob"}),p=URL.createObjectURL(m);if(o){URL.revokeObjectURL(p);return}c=p,a(c)}catch(m){o||l(m)}finally{o||n(!1)}})(),()=>{o=!0,c&&URL.revokeObjectURL(c)}},[t]),{previewUrl:s,previewLoading:r,previewError:i}}function Xo(t){const s=t==null||t===""?"-":String(t);if(s==="-"||s==="N.A."||s==="N.A")return e.jsx("span",{style:{fontSize:"12px",fontWeight:400,color:"#94a3b8"},children:s});const a=s==="Yes"||s==="YES",r=s==="No"||s==="NO",n={display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:500,padding:"3px 10px",borderRadius:"999px",lineHeight:1.25};return a?e.jsx("span",{style:{...n,color:"#166534",backgroundColor:"rgba(22, 163, 74, 0.09)",border:"1px solid rgba(22, 163, 74, 0.22)"},children:s}):r?e.jsx("span",{style:{...n,color:"#9f1239",backgroundColor:"rgba(244, 63, 94, 0.07)",border:"1px solid rgba(244, 63, 94, 0.2)"},children:s}):e.jsx("span",{style:{...n,color:"#475569",backgroundColor:"#f1f5f9",border:"1px solid #e2e8f0"},children:s})}function np(t){const s={display:"inline-flex",alignItems:"center",fontSize:"12px",fontWeight:500,padding:"4px 12px",borderRadius:"999px",letterSpacing:"0.01em",lineHeight:1.3};return t?e.jsx("span",{style:{...s,color:"#166534",backgroundColor:"rgba(22, 163, 74, 0.09)",border:"1px solid rgba(22, 163, 74, 0.22)"},children:"Successful"}):e.jsx("span",{style:{...s,color:"#9f1239",backgroundColor:"rgba(244, 63, 94, 0.07)",border:"1px solid rgba(244, 63, 94, 0.2)"},children:"Unsuccessful"})}const nF=()=>{const[t,s]=u.useState("GLOBAL"),[a,r]=u.useState([]),[n,i]=u.useState({total:0,page:1,limit:10,pages:1}),[l,o]=u.useState(""),[c,d]=u.useState(""),[m,p]=u.useState("ALL"),[x,h]=u.useState("ALL"),[g,f]=u.useState(null),[b,y]=u.useState(!1),[j,v]=u.useState(null),[N,T]=u.useState(null),[A,k]=u.useState("ALL"),D=t==="DOCUMENT_DETAIL"&&(N!=null&&N.id)?N.id:void 0,{previewUrl:F,previewLoading:w,previewError:L}=Tb(D);u.useEffect(()=>{if(t==="GLOBAL"){const H=setTimeout(()=>_(1),300);return()=>clearTimeout(H)}},[t,c,m,x]);const _=async(H=1)=>{y(!0);try{const z={page:H,limit:30};c&&(z.search=c),m!=="ALL"&&(z.type=m),x!=="ALL"&&(z.status=x);const{data:P}=await ta.get("/documents/recent",{params:z}),U=(Array.isArray(P)?P:P.items||[]).map(Y=>W(pn(Y)));r(U),P.meta&&i(P.meta)}catch(z){console.error("Failed to fetch global history:",z)}finally{y(!1)}},W=H=>{const z=H.summary||{f1:{},f2:{},f3:{},f4:{},f5:{}};return{...H,groups:{cust:z.f1,ref:z.f2,ident:z.f3,fin:z.f4,comp:z.f5},fields:{f1:z.f1,f2:z.f2,f3:z.f3,f4:z.f4,f5:z.f5},field_results:H.fieldResults||H.field_results||z.field_results||[]}},I=async()=>{try{const{data:H}=await ta.get("/v1/ocr/report/all/download",{params:{search:c,status:x,type:m},responseType:"blob"}),z=window.URL.createObjectURL(new Blob([H])),P=document.createElement("a");P.href=z,P.setAttribute("download","Master_Audit_Report.xlsx"),document.body.appendChild(P),P.click(),P.remove()}catch(H){console.error("Download failed:",H)}},$=async H=>{const z=l||(g==null?void 0:g.claimId);try{const{data:P}=await ta.get(`/v1/ocr/report/${z}/download`,{params:{attempt:H},responseType:"blob"}),S=window.URL.createObjectURL(new Blob([P])),U=document.createElement("a");U.href=S,U.setAttribute("download",`Report_${z}_Attempt_${H}.xlsx`),document.body.appendChild(U),U.click(),U.remove()}catch(P){console.error("Download failed:",P)}},M=({rows:H,showAttemptCol:z=!1})=>{const P={padding:"12px 10px",border:"1px solid #334155",fontSize:"11px",textTransform:"uppercase",backgroundColor:"#1e293b",color:"white",whiteSpace:"nowrap",textAlign:"left"},S={padding:"12px 10px",border:"1px solid #e2e8f0",fontSize:"13px",textAlign:"left",whiteSpace:"nowrap"};return e.jsx("div",{style:{overflowX:"auto",marginBottom:"2rem",border:"1px solid #e2e8f0",borderRadius:"8px",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.05)"},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",backgroundColor:"white"},children:[e.jsxs("thead",{children:[e.jsxs("tr",{children:[z&&e.jsx("th",{rowSpan:"2",style:P,children:"Attempt"}),e.jsx("th",{rowSpan:"2",style:P,children:"Booking Type"}),e.jsx("th",{rowSpan:"2",style:P,children:"Booking Number"}),e.jsx("th",{rowSpan:"2",style:P,children:"Document Count"}),e.jsx("th",{rowSpan:"2",style:P,children:"Document Name"}),e.jsx("th",{colSpan:"5",style:P,children:"Customer Name"}),e.jsx("th",{colSpan:"5",style:P,children:"PO Number /Authorisation Letter Number"}),e.jsx("th",{colSpan:"5",style:P,children:"Aadhar Number"}),e.jsx("th",{colSpan:"5",style:P,children:"PO Amount / Authorisation Letter Amount"}),e.jsx("th",{colSpan:"5",style:P,children:"Signature & Stamp Availability"}),e.jsx("th",{rowSpan:"2",style:P,children:"Final Validation"})]}),e.jsx("tr",{children:[0,1,2,3,4].map(U=>e.jsxs(xa.Fragment,{children:[e.jsx("th",{style:{...P,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"MSD"}),e.jsx("th",{style:{...P,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"OCR"}),e.jsx("th",{style:{...P,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:U===4?"Accuracy Matching Availability":"Accuracy Matching %"}),e.jsx("th",{style:{...P,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"Accuracy Criteria"}),e.jsx("th",{style:{...P,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:U===4?"Success Ratio":"Is Match the Accuracy"})]},U))})]}),e.jsx("tbody",{children:H.map((U,Y)=>e.jsxs("tr",{children:[z&&e.jsx("td",{style:{...S,fontWeight:500,backgroundColor:"#f8fafc",color:"#475569"},children:U.attempt_no}),e.jsx("td",{style:S,children:U.booking_type}),e.jsx("td",{style:S,children:U.booking_number}),e.jsx("td",{style:S,children:U.document_count}),e.jsx("td",{style:S,children:U.document_name}),U.summary?[U.summary.f1,U.summary.f2,U.summary.f3,U.summary.f4,U.summary.f5].map((B,E)=>e.jsxs(xa.Fragment,{children:[e.jsx("td",{style:{...S,color:B!=null&&B.isNA?"#94a3b8":"inherit",fontWeight:(B!=null&&B.isNA,400)},children:(B==null?void 0:B.msd)||"-"}),e.jsx("td",{style:{...S,color:B!=null&&B.isNA?"#94a3b8":"inherit",fontWeight:(B!=null&&B.isNA,400)},children:(B==null?void 0:B.ocr)||"-"}),e.jsx("td",{style:{...S,color:B!=null&&B.isNA?"#94a3b8":"inherit",fontWeight:B!=null&&B.isNA?400:500},children:(B==null?void 0:B.accuracy_pct)||(B==null?void 0:B.pct)||"0%"}),e.jsx("td",{style:{...S,color:B!=null&&B.isNA?"#94a3b8":"#64748b",fontSize:"10px",fontWeight:400},children:(B==null?void 0:B.criteria)||(B==null?void 0:B.crit)}),e.jsx("td",{style:{...S,verticalAlign:"middle"},children:Xo((B==null?void 0:B.is_match)||(B==null?void 0:B.match)||"-")})]},E)):[U.customer_name_group,U.reference_group,U.identity_group,U.financial_group,U.compliance_group].map((B,E)=>{const V=(B==null?void 0:B.msd)==="N.A."||(B==null?void 0:B.expected)==="N.A.";return e.jsxs(xa.Fragment,{children:[e.jsx("td",{style:{...S,color:V?"#94a3b8":"inherit",fontWeight:400},children:(B==null?void 0:B.msd)||(B==null?void 0:B.expected)||"-"}),e.jsx("td",{style:{...S,color:V?"#94a3b8":"inherit",fontWeight:400},children:(B==null?void 0:B.ocr)||(B==null?void 0:B.extracted)||"-"}),e.jsx("td",{style:{...S,color:V?"#94a3b8":"inherit",fontWeight:V?400:500},children:(B==null?void 0:B.accuracy_pct)||(B==null?void 0:B.pct)||"0%"}),e.jsx("td",{style:{...S,color:V?"#94a3b8":"#64748b",fontSize:"10px",fontWeight:400},children:(B==null?void 0:B.criteria)||(B==null?void 0:B.crit)}),e.jsx("td",{style:{...S,verticalAlign:"middle"},children:Xo((B==null?void 0:B.is_match)||(B==null?void 0:B.match)||"-")})]},E)}),e.jsx("td",{style:{...S,verticalAlign:"middle"},children:np(U.final_validation==="Successful"||U.final_validation==="SUCCESSFUL")})]},Y))})]})})},R=()=>{const H={padding:"12px 10px",border:"1px solid #334155",fontSize:"11px",textTransform:"uppercase",backgroundColor:"#1e293b",color:"white",whiteSpace:"nowrap",textAlign:"left"},z={padding:"12px 10px",border:"1px solid #e2e8f0",fontSize:"13px",textAlign:"left",whiteSpace:"nowrap"},P=[{id:"f1",label:"Customer Name"},{id:"f2",label:"PO Number /Authorisation Letter Number"},{id:"f3",label:"Aadhar Number"},{id:"f4",label:"PO Amount / Authorisation Letter Amount"},{id:"f5",label:"Signature & Stamp Availability"}];return e.jsxs("div",{style:{backgroundColor:"white",borderRadius:"12px",overflow:"hidden",border:"1px solid #e2e8f0",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.05)"},children:[e.jsx("div",{style:{overflowX:"auto",maxHeight:"70vh"},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[e.jsxs("thead",{style:{position:"sticky",top:0,zIndex:10},children:[e.jsxs("tr",{children:[e.jsx("th",{rowSpan:"2",style:H,children:"Booking Type"}),e.jsx("th",{rowSpan:"2",style:H,children:"Booking Number"}),e.jsx("th",{rowSpan:"2",style:H,children:"Doc Count"}),e.jsx("th",{rowSpan:"2",style:H,children:"Document Name"}),P.map(S=>e.jsx("th",{colSpan:"5",style:H,children:S.label},S.id)),e.jsx("th",{rowSpan:"2",style:H,children:"Final Validation"}),e.jsx("th",{rowSpan:"2",style:H,children:"Actions"})]}),e.jsx("tr",{children:P.map((S,U)=>e.jsxs(xa.Fragment,{children:[e.jsx("th",{style:{...H,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"MSD"}),e.jsx("th",{style:{...H,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"OCR"}),e.jsx("th",{style:{...H,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:U===4?"Accuracy Matching Availability":"Accuracy Matching %"}),e.jsx("th",{style:{...H,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"Accuracy Criteria"}),e.jsx("th",{style:{...H,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:U===4?"Success Ratio":"Is Match the Accuracy"})]},S.id))})]}),e.jsx("tbody",{children:a.map((S,U)=>{var Y,B,E,V,G,J;return e.jsxs("tr",{style:{backgroundColor:U%2===0?"white":"#f8fafc"},children:[e.jsx("td",{style:z,children:((Y=S.summary)==null?void 0:Y.booking_type)||S.booking_type||((B=S.claimId)!=null&&B.startsWith("CPC")?"CPC":"CSD")}),e.jsx("td",{style:{...z,fontWeight:500,color:"#2563eb"},children:((E=S.summary)==null?void 0:E.booking_number)||S.bookingId||S.claimId}),e.jsx("td",{style:z,children:((V=S.summary)==null?void 0:V.document_count)||1}),e.jsx("td",{style:z,children:((G=S.summary)==null?void 0:G.document_name)||((J=S.documentType)==null?void 0:J.replace(/_/g," "))}),P.map((q,se)=>{var ge,we;const ne=((ge=S.summary)==null?void 0:ge[q.id])||((we=S.groups)==null?void 0:we[q.id]),te={...z};return ne!=null&&ne.isNA&&(te.color="#94a3b8"),te.fontWeight=400,e.jsxs(xa.Fragment,{children:[e.jsx("td",{style:te,children:(ne==null?void 0:ne.msd)||"-"}),e.jsx("td",{style:te,children:(ne==null?void 0:ne.ocr)||"-"}),e.jsx("td",{style:{...te,fontWeight:ne!=null&&ne.isNA?400:500},children:(ne==null?void 0:ne.accuracy_pct)||(ne==null?void 0:ne.pct)||"-"}),e.jsx("td",{style:{...te,fontSize:"10px",opacity:ne!=null&&ne.isNA?.5:.85,fontWeight:400},children:(ne==null?void 0:ne.criteria)||(ne==null?void 0:ne.crit)||"-"}),e.jsx("td",{style:{...te,verticalAlign:"middle"},children:Xo((ne==null?void 0:ne.is_match)||(ne==null?void 0:ne.match)||"-")})]},se)}),e.jsx("td",{style:{...z,verticalAlign:"middle"},children:np(S.validationStatus==="SUCCESSFUL"||S.validationStatus==="MATCH"||S.validationStatus==="APPROVED")}),e.jsx("td",{style:z,children:e.jsxs("button",{type:"button",onClick:()=>{s("DOCUMENT_DETAIL"),T(S)},style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 12px",backgroundColor:"#fff",color:"#334155",border:"1px solid #e2e8f0",borderRadius:"8px",fontWeight:500,fontSize:"12px",cursor:"pointer",whiteSpace:"nowrap",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.04)"},children:[e.jsx(pi,{style:{opacity:.85}})," View Details"]})})]},S.id)})})]})}),e.jsxs("div",{style:{padding:"1rem",borderTop:"1px solid #e2e8f0",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsxs("span",{style:{fontSize:"0.8rem",color:"#64748b"},children:["Total documents processed: ",e.jsx("strong",{children:n.total})]}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[e.jsx("button",{disabled:n.page<=1,onClick:()=>_(n.page-1),style:{padding:"6px 12px",border:"1px solid #e2e8f0",borderRadius:"6px",cursor:"pointer",backgroundColor:"white"},children:e.jsx(Ko,{})}),e.jsxs("span",{style:{fontSize:"0.8rem",fontWeight:700,display:"flex",alignItems:"center"},children:["Page ",n.page," of ",n.pages]}),e.jsx("button",{disabled:n.page>=n.pages,onClick:()=>_(n.page+1),style:{padding:"6px 12px",border:"1px solid #e2e8f0",borderRadius:"6px",cursor:"pointer",backgroundColor:"white"},children:e.jsx(rp,{})})]})]})]})},C=({doc:H})=>{var S;const z={padding:"10px",borderBottom:"2px solid #e2e8f0",fontSize:"11px",textTransform:"uppercase",textAlign:"left",color:"#64748b"},P={padding:"12px 10px",borderBottom:"1px solid #f1f5f9",fontSize:"12px"};return e.jsxs("div",{style:{backgroundColor:"white",borderRadius:"12px",padding:"1.5rem",marginBottom:"2rem",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},children:[e.jsx("h4",{style:{margin:0,fontSize:"1rem",fontWeight:700,color:"#1e293b"},children:H.documentType.replace(/_/g," ")}),e.jsxs("span",{style:{padding:"4px 12px",borderRadius:"20px",fontSize:"11px",fontWeight:700,backgroundColor:H.validationStatus==="SUCCESSFUL"?"#dcfce7":"#fee2e2",color:H.validationStatus==="SUCCESSFUL"?"#166534":"#991b1b"},children:[H.matchPercentage,"% Batch Score"]})]}),e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:z,children:"Field"}),e.jsx("th",{style:z,children:"MSD"}),e.jsx("th",{style:z,children:"Extracted"}),e.jsx("th",{style:z,children:"Accuracy"}),e.jsx("th",{style:z,children:"Criteria"}),e.jsx("th",{style:z,children:"Status"}),e.jsx("th",{style:z,children:"Message"})]})}),e.jsx("tbody",{children:(((S=H.summary)==null?void 0:S.field_results)||H.field_results||[]).map((U,Y)=>e.jsxs("tr",{children:[e.jsx("td",{style:{...P,fontWeight:600,color:"#334155"},children:U.field.replace(/_/g," ")}),e.jsx("td",{style:P,children:U.expected}),e.jsx("td",{style:{...P,color:U.extracted===null||U.extracted==="-"?"#94a3b8":"#1e293b"},children:U.extracted||"Not extracted"}),e.jsx("td",{style:P,children:U.accuracy||U.match_percentage||(U.match_percentage!==void 0?`${U.match_percentage}%`:"0%")}),e.jsx("td",{style:{...P,fontSize:"10px",color:"#64748b"},children:U.criteria}),e.jsx("td",{style:P,children:U.pass||U.status==="SUCCESSFUL"||U.status==="MATCH"?e.jsx(Yr,{style:{color:"#16a34a"}}):e.jsx(Pc,{style:{color:"#dc2626"}})}),e.jsx("td",{style:{...P,fontSize:"11px",fontStyle:"italic",color:U.pass||U.status==="SUCCESSFUL"?"#16a34a":"#ef4444"},children:U.message})]},Y))})]})]})};return e.jsxs("div",{className:"history-page",style:{padding:"1.5rem",backgroundColor:"#f8fafc",minHeight:"100vh"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"1.5rem"},children:[e.jsxs("div",{children:[e.jsx("h1",{style:{fontSize:"1.75rem",fontWeight:800,color:"#1e293b",marginBottom:"0.25rem",letterSpacing:"-0.025em"},children:"All Submissions"}),e.jsx("p",{style:{color:"#64748b",fontSize:"0.9rem"},children:t==="GLOBAL"?"All CPC-CSD validation submissions in one place.":`Detailed chronology for Claim ID: ${l}`})]}),e.jsx("div",{style:{display:"flex",gap:"1rem"},children:t==="GLOBAL"?e.jsxs("button",{onClick:I,style:{display:"flex",alignItems:"center",gap:"8px",padding:"10px 20px",backgroundColor:"#1e293b",color:"white",border:"none",borderRadius:"8px",fontWeight:700,cursor:"pointer",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.1)"},children:[e.jsx(ap,{})," Download Master Excel"]}):e.jsxs("button",{onClick:()=>{s("GLOBAL"),f(null),o(""),d("")},style:{padding:"10px 20px",backgroundColor:"white",border:"1px solid #e2e8f0",borderRadius:"8px",fontWeight:700,cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",transition:"all 0.2s"},children:[e.jsx(Ko,{})," Back to all submissions"]})})]}),e.jsx("div",{style:{backgroundColor:"white",padding:"1.25rem",borderRadius:"12px",border:"1px solid #e2e8f0",boxShadow:"0 1px 3px rgba(0,0,0,0.05)",marginBottom:"2rem",display:"flex",flexDirection:"column",gap:"0.75rem"},children:t==="GLOBAL"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",gap:"1rem",alignItems:"center",flexWrap:"wrap"},children:[e.jsxs("select",{value:m,onChange:H=>p(H.target.value),style:{padding:"0.6rem 1rem",border:"1px solid #e2e8f0",borderRadius:"8px",fontWeight:600,color:"#475569",backgroundColor:"#f8fafc"},children:[e.jsx("option",{value:"ALL",children:"All Documents"}),e.jsx("option",{value:"AADHAAR",children:"Aadhaar Card"}),e.jsx("option",{value:"AUTHORITY_LETTER",children:"Authority Letter"}),e.jsx("option",{value:"GENERIC_INVOICE",children:"Retail Invoice"})]}),e.jsxs("select",{value:x,onChange:H=>h(H.target.value),style:{padding:"0.6rem 1rem",border:"1px solid #e2e8f0",borderRadius:"8px",fontWeight:600,color:"#475569",backgroundColor:"#f8fafc"},children:[e.jsx("option",{value:"ALL",children:"All Status"}),e.jsx("option",{value:"SUCCESSFUL",children:"Successful"}),e.jsx("option",{value:"UNSUCCESSFUL",children:"Unsuccessful"})]})]}),x==="UNSUCCESSFUL"&&e.jsxs("p",{style:{margin:0,fontSize:"0.8rem",color:"#64748b",lineHeight:1.45,maxWidth:"960px"},children:[e.jsx("strong",{style:{color:"#334155"},children:"Note:"})," This filter uses the ",e.jsx("strong",{children:"overall"})," validation result for each document (e.g. mismatch, rejected, or needs manual review). You can still see ",e.jsx("strong",{children:'green "Yes"'})," or ",e.jsx("strong",{children:"100%"})," in a column when that ",e.jsx("strong",{children:"single field"})," matched MSD — other fields or the overall rule may still have failed."]})]})}),b&&e.jsx("div",{style:{textAlign:"center",padding:"3rem"},children:"Processing record retrieval..."}),!b&&t==="GLOBAL"&&e.jsx(R,{}),!b&&t==="DOCUMENT_DETAIL"&&N&&(()=>{var B;const H=((B=N.summary)==null?void 0:B.field_results)||N.field_results||[],z=H.filter(E=>E.pass).length,P=H.filter(E=>!E.pass&&E.extracted!=="N/A"&&E.extracted!=="-").length,S=H.filter(E=>!E.pass&&(E.extracted==="N/A"||E.extracted==="-"||!E.extracted)).length,U=H.length||1,Y=Math.round(z/U*100);return e.jsxs("div",{style:{animation:"fadeIn 0.4s cubic-bezier(0.4, 0, 0.2, 1)",height:"calc(100vh - 180px)",display:"flex",flexDirection:"column",gap:"1.25rem"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"1rem"},children:[e.jsxs("button",{onClick:()=>s("GLOBAL"),style:{display:"flex",alignItems:"center",gap:"8px",padding:"10px 18px",backgroundColor:"white",border:"1px solid #e2e8f0",borderRadius:"12px",fontWeight:800,cursor:"pointer",color:"#1e293b",transition:"all 0.2s",boxShadow:"0 1px 2px rgba(0,0,0,0.05)"},onMouseOver:E=>E.currentTarget.style.backgroundColor="#f8fafc",onMouseOut:E=>E.currentTarget.style.backgroundColor="white",children:[e.jsx(Ko,{})," Back to all submissions"]}),e.jsx("div",{style:{height:"24px",width:"1px",backgroundColor:"#e2e8f0"}}),e.jsxs("div",{style:{display:"flex",gap:"0.75rem"},children:[e.jsxs("div",{style:{padding:"6px 12px",background:"#eff6ff",border:"1px solid #dbeafe",borderRadius:"8px",fontSize:"11px",fontWeight:700,color:"#2563eb",display:"flex",alignItems:"center",gap:"6px"},children:[e.jsx(sp,{})," ",N.document_name||N.documentType]}),e.jsxs("div",{style:{padding:"6px 12px",background:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:"8px",fontSize:"11px",fontWeight:700,color:"#475569",display:"flex",alignItems:"center",gap:"6px"},children:[e.jsx(tF,{})," ID: ",N.booking_number||N.bookingId||l]})]})]}),e.jsx("span",{style:{padding:"8px 20px",borderRadius:"12px",fontSize:"13px",fontWeight:800,backgroundColor:Y>=90?"#10b981":"#ef4444",color:"white",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.1)",textTransform:"uppercase",letterSpacing:"0.025em"},children:Y>=90?"✅ Successful":"❌ Discrepancy Found"})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1.2fr) minmax(0, 0.85fr)",gap:"1.5rem",flex:1,overflow:"hidden",minWidth:0,width:"100%"},children:[e.jsxs("div",{style:{minWidth:0,backgroundColor:"white",borderRadius:"12px",border:"1px solid #e8ecf0",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.04)"},children:[e.jsxs("div",{style:{padding:"0.75rem 1rem",borderBottom:"1px solid #f1f5f9",background:"#fafbfc",fontWeight:500,color:"#475569",fontSize:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{children:"Audit evidence"}),e.jsx("span",{style:{fontSize:"10px",color:"#94a3b8",fontWeight:400},children:"Secure preview"})]}),e.jsxs("div",{style:{flex:1,backgroundColor:"#1e293b",position:"relative"},children:[w&&e.jsx("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#94a3b8",fontSize:"0.9rem"},children:"Loading document preview…"}),!w&&L&&e.jsx("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:"0.9rem",padding:"1rem",textAlign:"center"},children:"Could not load the file. Re-upload if this is an old record."}),!w&&F&&e.jsx("iframe",{src:F,style:{width:"100%",height:"100%",border:"none"},title:"Audit Evidence Viewer"}),!w&&!F&&!L&&e.jsx("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#94a3b8",fontSize:"0.9rem"},children:"Evidence binary not found in storage"})]})]}),e.jsxs("div",{style:{minWidth:0,display:"flex",flexDirection:"column",gap:"1.25rem",overflowY:"auto",overflowX:"hidden",paddingRight:"0.5rem"},children:[e.jsxs("div",{style:{flexShrink:0,backgroundColor:"white",borderRadius:"12px",padding:"1.25rem",border:"1px solid #e8ecf0",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.04)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"1.25rem",marginBottom:"1.1rem"},children:[e.jsxs("div",{style:{position:"relative",width:"80px",height:"80px",display:"flex",alignItems:"center",justifyContent:"center"},children:[e.jsxs("svg",{width:"80",height:"80",viewBox:"0 0 100 100",children:[e.jsx("circle",{cx:"50",cy:"50",r:"42",fill:"none",stroke:"#f1f5f9",strokeWidth:"6"}),e.jsx("circle",{cx:"50",cy:"50",r:"42",fill:"none",stroke:Y>=75?"#34d399":"#fb7185",strokeWidth:"6",strokeDasharray:`${2*Math.PI*42}`,strokeDashoffset:`${2*Math.PI*42*(1-Y/100)}`,strokeLinecap:"round",transform:"rotate(-90 50 50)",style:{transition:"stroke-dashoffset 1s ease-out"}})]}),e.jsx("div",{style:{position:"absolute",display:"flex",flexDirection:"column",alignItems:"center"},children:e.jsxs("span",{style:{fontWeight:600,fontSize:"1.125rem",color:"#334155",lineHeight:1,fontVariantNumeric:"tabular-nums"},children:[Y,"%"]})})]}),e.jsxs("div",{style:{flex:1},children:[e.jsx("h3",{style:{margin:"0 0 0.35rem 0",fontSize:"1rem",fontWeight:600,color:"#334155",letterSpacing:"-0.01em"},children:"Audit reconciliation"}),e.jsx("p",{style:{margin:0,fontSize:"0.8125rem",color:"#64748b",fontWeight:400,lineHeight:1.5},children:"Validation from OCR extraction compared to expected fields."})]})]}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:"0.65rem"},children:[{label:"Matched",val:z,color:"#166534",bg:"#f0fdf4",border:"#d1fae5"},{label:"Mismatch",val:P,color:"#b91c4c",bg:"#fdf2f5",border:"#fce7ec"},{label:"Missing",val:S,color:"#b45309",bg:"#fffbeb",border:"#fde68a"}].map(E=>e.jsxs("div",{style:{padding:"10px 8px",backgroundColor:E.bg,borderRadius:"10px",border:`1px solid ${E.border}`,textAlign:"center"},children:[e.jsx("div",{style:{fontSize:"0.625rem",fontWeight:500,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"6px"},children:E.label}),e.jsx("div",{style:{fontSize:"1.25rem",fontWeight:600,color:E.color,fontVariantNumeric:"tabular-nums"},children:E.val})]},E.label))})]}),e.jsxs("div",{style:{flexShrink:0,minWidth:0,backgroundColor:"white",borderRadius:"12px",border:"1px solid #e8ecf0",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.04)",overflow:"hidden"},children:[e.jsx("div",{style:{padding:"1rem 1.25rem",borderBottom:"1px solid #f1f5f9",background:"#fafbfc",fontWeight:600,color:"#475569",fontSize:"0.875rem"},children:"Field extraction matrix"}),e.jsx("div",{style:{width:"100%",minWidth:0,boxSizing:"border-box"},children:e.jsxs("table",{style:{width:"100%",maxWidth:"100%",borderCollapse:"collapse",tableLayout:"fixed"},children:[e.jsxs("colgroup",{children:[e.jsx("col",{style:{width:"28%"}}),e.jsx("col",{style:{width:"44%"}}),e.jsx("col",{style:{width:"28%"}})]}),e.jsx("thead",{children:e.jsxs("tr",{style:{borderBottom:"1px solid #f1f5f9"},children:[e.jsx("th",{style:{textAlign:"left",padding:"0.65rem 0.75rem",color:"#94a3b8",fontSize:"10px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Field name"}),e.jsx("th",{style:{textAlign:"left",padding:"0.65rem 0.75rem",color:"#94a3b8",fontSize:"10px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Extracted (AI)"}),e.jsx("th",{style:{textAlign:"center",padding:"0.65rem 0.75rem",color:"#94a3b8",fontSize:"10px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Status"})]})}),e.jsx("tbody",{children:H.map((E,V)=>{const G=E.extracted==="undefined"||E.extracted==="null"||!E.extracted?"-":E.extracted,J=E.pass?"MATCH":G==="-"||G==="N/A"?"MISSING":"MISMATCH";let q="#166534",se="#ecfdf5",ne=e.jsx(Yr,{style:{opacity:.82}});J==="MISMATCH"?(q="#b91c4c",se="#fdf2f5",ne=e.jsx(Pc,{style:{opacity:.8}})):J==="MISSING"&&(q="#b45309",se="#fffbeb",ne=e.jsx(gi,{style:{opacity:.8}}));const te=J==="MATCH"?"#166534":J==="MISSING"?"#92400e":"#9f1239";return e.jsxs("tr",{style:{borderBottom:"1px solid #f8fafc",backgroundColor:V%2===0?"white":"#fafbfc"},children:[e.jsxs("td",{style:{padding:"0.75rem 0.75rem",verticalAlign:"top",minWidth:0,wordBreak:"break-word"},children:[e.jsx("div",{style:{fontWeight:500,color:"#334155",fontSize:"0.8125rem",textTransform:"capitalize",overflowWrap:"anywhere"},children:E.field.replace(/_/g," ")}),e.jsxs("div",{style:{fontSize:"10px",color:"#94a3b8",marginTop:"6px",fontWeight:400},children:["Accuracy ",e.jsx("span",{style:{color:"#64748b",fontWeight:500},children:E.accuracy||"0%"})]})]}),e.jsxs("td",{style:{padding:"0.75rem 0.75rem",verticalAlign:"top",minWidth:0,wordBreak:"break-word"},children:[e.jsxs("div",{style:{fontSize:"10px",color:"#94a3b8",marginBottom:"6px"},children:["MSD ",e.jsx("span",{style:{color:"#64748b"},children:E.expected})]}),e.jsx("div",{style:{fontSize:"0.8125rem",fontWeight:500,color:te,overflowWrap:"anywhere",lineHeight:1.45},children:G})]}),e.jsx("td",{style:{padding:"0.75rem 0.5rem",textAlign:"center",verticalAlign:"middle",minWidth:0},children:e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"4px",padding:"4px 8px",borderRadius:"9999px",backgroundColor:se,color:q,fontSize:"10px",fontWeight:500,letterSpacing:"0.03em",border:"1px solid rgba(148, 163, 184, 0.22)",maxWidth:"100%",boxSizing:"border-box",flexWrap:"wrap",wordBreak:"break-word"},children:[ne," ",e.jsx("span",{style:{flexShrink:0},children:J})]})})]},V)})})]})})]}),e.jsxs("div",{style:{flexShrink:0,display:"grid",gridTemplateColumns:"1fr 1fr",gap:"1rem"},children:[e.jsxs("div",{style:{background:"white",padding:"1rem",borderRadius:"16px",border:"1px solid #e2e8f0",boxShadow:"0 1px 2px rgba(0,0,0,0.05)"},children:[e.jsx("div",{style:{fontSize:"10px",color:"#94a3b8",textTransform:"uppercase",fontWeight:500,letterSpacing:"0.05em",marginBottom:"0.5rem"},children:"Audit meta"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"11px"},children:[e.jsx("span",{style:{color:"#64748b"},children:"Validation mode"}),e.jsx("span",{style:{color:"#475569",fontWeight:500},children:"AI hybrid reconcile"})]}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"11px"},children:[e.jsx("span",{style:{color:"#64748b"},children:"Timestamp"}),e.jsx("span",{style:{color:"#475569",fontWeight:500},children:new Date(N.createdAt).toLocaleDateString()})]})]})]}),e.jsxs("div",{style:{background:"white",padding:"1rem",borderRadius:"16px",border:"1px solid #e2e8f0",boxShadow:"0 1px 2px rgba(0,0,0,0.05)"},children:[e.jsx("div",{style:{fontSize:"10px",color:"#94a3b8",textTransform:"uppercase",fontWeight:500,letterSpacing:"0.05em",marginBottom:"0.5rem"},children:"System health"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"11px"},children:[e.jsx("span",{style:{color:"#64748b"},children:"OCR engine"}),e.jsx("span",{style:{color:"#15803d",fontWeight:500},children:"Operational"})]}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"11px"},children:[e.jsx("span",{style:{color:"#64748b"},children:"AI model"}),e.jsx("span",{style:{color:"#7c3aed",fontWeight:500},children:"Gemini Pro Vision"})]})]})]})]})]})]})]})})(),!b&&t==="CLAIM_DETAIL"&&g&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"3rem"},children:[e.jsxs("section",{children:[e.jsxs("h2",{style:{fontSize:"1.1rem",fontWeight:800,color:"#1e293b",marginBottom:"1.25rem",display:"flex",alignItems:"center",gap:"10px"},children:[e.jsx(sp,{style:{color:"#3b82f6"}})," Multi-Attempt Audit Summary: ",l]}),e.jsx(M,{rows:g.allAttemptsRows,showAttemptCol:!0})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"260px 1fr",gap:"2rem",borderTop:"2px solid #e2e8f0",paddingTop:"3rem"},children:[e.jsxs("div",{children:[e.jsx("h3",{style:{fontSize:"0.8rem",fontWeight:800,color:"#64748b",textTransform:"uppercase",marginBottom:"1.25rem",letterSpacing:"0.05em"},children:"Chronological Attempts"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:g.attempts.map(H=>e.jsxs("button",{onClick:()=>v(H),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"1.25rem",backgroundColor:(j==null?void 0:j.attempt_no)===H.attempt_no?"#1e293b":"white",color:(j==null?void 0:j.attempt_no)===H.attempt_no?"white":"#1e293b",border:"1px solid #e2e8f0",borderRadius:"12px",cursor:"pointer",textAlign:"left",boxShadow:(j==null?void 0:j.attempt_no)===H.attempt_no?"0 10px 15px -3px rgba(30, 41, 59, 0.2)":"none"},children:[e.jsxs("div",{children:[e.jsxs("div",{style:{fontWeight:800,fontSize:"0.9rem"},children:["Attempt ",H.attempt_no]}),e.jsx("div",{style:{fontSize:"10px",opacity:.6,marginTop:"2px"},children:new Date(H.created_at).toLocaleString()})]}),(j==null?void 0:j.attempt_no)===H.attempt_no?e.jsx(rp,{}):e.jsx(aF,{style:{opacity:.2}})]},H.attempt_no))})]}),j&&e.jsxs("div",{style:{animation:"fadeIn 0.3s ease-in"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[e.jsxs("h2",{style:{margin:0,fontSize:"1rem",fontWeight:800,color:"#1e293b"},children:["Visual Report - Attempt ",j.attempt_no]}),e.jsxs("button",{onClick:()=>$(j.attempt_no),style:{display:"flex",alignItems:"center",gap:"8px",padding:"10px 20px",border:"1px solid #e2e8f0",borderRadius:"10px",backgroundColor:"white",fontWeight:700,cursor:"pointer"},children:[e.jsx(ap,{})," Export Attempt ",j.attempt_no]})]}),e.jsx(M,{rows:j.summary_report_rows}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem",marginTop:"4rem"},children:[e.jsx("h3",{style:{margin:0,fontSize:"0.85rem",fontWeight:800,color:"#64748b",textTransform:"uppercase"},children:"Extraction Evidence"}),e.jsx("div",{style:{display:"flex",gap:"0.4rem"},children:["ALL","AADHAAR","GENERIC_INVOICE","AUTHORITY_LETTER"].map(H=>e.jsx("button",{onClick:()=>k(H),style:{padding:"6px 14px",fontSize:"10px",fontWeight:800,borderRadius:"8px",border:"1px solid #e2e8f0",backgroundColor:A===H?"#1e293b":"white",color:A===H?"white":"#64748b",cursor:"pointer"},children:H==="ALL"?"All":H.split("_")[0]},H))})]}),j.documents.filter(H=>A==="ALL"||H.documentType===A).map((H,z)=>e.jsx(C,{doc:H},z))]})]})]})]})},iF=()=>{var I,$;const{id:t}=Aa(),s=$l(),a=gs(),[r,n]=u.useState(null),[i,l]=u.useState(!0),[o,c]=u.useState([]),[d,m]=u.useState({}),[p,x]=u.useState(!1),{previewUrl:h,previewLoading:g,previewError:f}=Tb(t),b=((I=s.state)==null?void 0:I.from)||"/cpc-csd/dashboard",y=(($=s.state)==null?void 0:$.title)||"Dashboard";if(u.useEffect(()=>{let M=!1;return(async()=>{l(!0),n(null),c([]);try{const{data:C}=await ta.get(`/documents/${t}`);if(M)return;const H=pn(C);n(H),m(H.extractedFields||{}),x(!1);const z=String(H.claimId||"").trim();if(z)try{const{data:P}=await ta.get("/documents/history",{params:{claimId:z}});if(M)return;const S=Number(H.attemptNo??1)||1,U=(P.attempts||[]).find(G=>Number(G.attempt_no)===S),B=((U==null?void 0:U.documents)||[]).map(G=>pn(G)).filter(G=>G==null?void 0:G.id),E=new Set,V=B.filter(G=>{const J=String(G.id);return E.has(J)?!1:(E.add(J),!0)});V.sort((G,J)=>new Date(J.createdAt||0)-new Date(G.createdAt||0)),M||c(V.length?V:[H])}catch{M||c([H])}else M||c([H])}catch(C){console.error(C),M||n(null)}finally{M||l(!1)}})(),()=>{M=!0}},[t]),i)return e.jsx("div",{className:"container",style:{padding:"4rem",textAlign:"center"},children:e.jsx("div",{style:{fontSize:"1.5rem",fontWeight:600,color:"#6b7280"},children:"Loading Document..."})});if(!r)return e.jsxs("div",{className:"container",style:{padding:"4rem",textAlign:"center"},children:[e.jsx("div",{style:{fontSize:"1.5rem",fontWeight:600,color:"#ef4444"},children:"Document not found"}),e.jsx(ii,{to:"/cpc-csd/dashboard",style:{color:"#2563eb",marginTop:"1rem",display:"inline-block"},children:"Return to Dashboard"})]});const j=()=>x(!p),v=(M,R)=>{m(C=>({...C,[M]:R}))},N=async()=>{try{await ta.put(`/documents/${t}/status`,{status:r.validationStatus,correctedFields:d});const{data:M}=await ta.get(`/documents/${t}`);n(pn(M)),x(!1),alert("Changes saved!")}catch{alert("Failed to save changes")}},T=async M=>{if(confirm(`Are you sure you want to mark this document as ${M}?`))try{const R={status:M};(M==="APPROVED"||M==="MATCH")&&(R.correctedFields=d),await ta.put(`/documents/${t}/status`,R);const{data:C}=await ta.get(`/documents/${t}`);n(pn(C)),x(!1)}catch{alert("Failed to update status")}},A=r.field_results||[],k=M=>M.pass===!0||M.status==="SUCCESSFUL"||M.status==="MATCH",D=M=>{const R=M.match_percentage??M.matchPercentage;if(R!=null&&R!==""&&!Number.isNaN(Number(R)))return Math.round(Number(R));if(typeof M.accuracy=="string"){const C=M.accuracy.trim().match(/^(\d+(?:\.\d+)?)\s*%?$/);if(C)return Math.round(Number(C[1]))}return null},F=A.filter(k).length,w=A.filter(M=>!k(M)&&M.extracted!=="N/A"&&M.extracted!=="-").length,L=A.filter(M=>!k(M)&&(M.extracted==="N/A"||M.extracted==="-"||!M.extracted)).length,_=A.length||1,W=Math.round(F/_*100);return e.jsxs("div",{className:"container dashboard-container",style:{maxWidth:"100%",padding:"1rem 2rem"},children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs(ii,{to:b,className:"inline-block",style:{textDecoration:"none",color:"#6b7280",display:"flex",alignItems:"center",gap:"0.5rem",fontWeight:500},children:["← Back to ",y]}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center",flexWrap:"wrap"},children:[e.jsxs("button",{onClick:j,style:{padding:"0.45rem 0.9rem",borderRadius:"8px",border:"1px solid #e2e8f0",backgroundColor:p?"#f8fafc":"#fff",cursor:"pointer",fontWeight:500,fontSize:"0.8125rem",color:"#475569",display:"flex",alignItems:"center",gap:"0.4rem"},children:["✏️ ",p?"Cancel Edit":"Edit Data"]}),!p&&(r.validationStatus==="PENDING"||r.validationStatus==="MISMATCH"||r.validationStatus==="MATCH"||r.validationStatus==="UNSUCCESSFUL"||r.validationStatus==="SUCCESSFUL")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>T("APPROVED"),style:{padding:"0.45rem 0.9rem",borderRadius:"8px",border:"1px solid #c4e8d4",backgroundColor:"#f0fdf4",color:"#166534",cursor:"pointer",fontWeight:500,fontSize:"0.8125rem",display:"flex",alignItems:"center",gap:"0.4rem"},children:"Approve"}),e.jsx("button",{onClick:()=>T("REJECTED"),style:{padding:"0.45rem 0.9rem",borderRadius:"8px",border:"1px solid #fbcfe8",backgroundColor:"#fdf2f8",color:"#be185d",cursor:"pointer",fontWeight:500,fontSize:"0.8125rem",display:"flex",alignItems:"center",gap:"0.4rem"},children:"Reject"})]}),p&&e.jsx("button",{onClick:N,style:{padding:"0.45rem 0.9rem",borderRadius:"8px",border:"none",backgroundColor:"#475569",color:"white",cursor:"pointer",fontWeight:500,fontSize:"0.8125rem"},children:"Save changes"}),e.jsxs("span",{style:{padding:"0.35rem 0.75rem",borderRadius:"9999px",fontWeight:500,fontSize:"0.75rem",letterSpacing:"0.02em",display:"flex",alignItems:"center",gap:"0.4rem",backgroundColor:["MATCH","SUCCESSFUL","APPROVED"].includes(r.validationStatus)?"#ecfdf5":["MISMATCH","UNSUCCESSFUL","REJECTED"].includes(r.validationStatus)?"#fdf2f5":"#fffbeb",color:["MATCH","SUCCESSFUL","APPROVED"].includes(r.validationStatus)?"#166534":["MISMATCH","UNSUCCESSFUL","REJECTED"].includes(r.validationStatus)?"#b91c4c":"#a16207",border:"1px solid rgba(148, 163, 184, 0.3)"},children:[e.jsx("span",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"currentColor",opacity:.85}}),r.validationStatus||"PENDING"]})]})]}),o.length>1&&r&&e.jsxs("div",{style:{marginBottom:"1rem",padding:"0.65rem 1rem",backgroundColor:"white",borderRadius:"12px",border:"1px solid #e8ecf0",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.04)"},children:[e.jsxs("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"#94a3b8",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"0.5rem"},children:["Documents in this submission (",o.length,")"]}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem",alignItems:"center"},children:o.map(M=>{const R=String(M.id)===String(t),C=o.filter(P=>P.documentType===M.documentType).length>1,H=(M.documentType||"Document").replace(/_/g," "),z=C&&M.bookingId?`${H} · ${M.bookingId}`:H;return e.jsxs("button",{type:"button",onClick:()=>{R||a(`/cpc-csd/documents/${M.id}`,{state:s.state,replace:!0})},style:{display:"inline-flex",alignItems:"center",gap:"0.35rem",padding:"0.45rem 0.85rem",borderRadius:"8px",fontSize:"0.8125rem",fontWeight:600,cursor:R?"default":"pointer",border:R?"1px solid #166534":"1px solid #e2e8f0",backgroundColor:R?"#ecfdf5":"#fff",color:R?"#166534":"#475569",transition:"background-color 0.15s, border-color 0.15s"},children:[e.jsx(pi,{style:{opacity:R?1:.65}}),z]},M.id)})})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1.2fr) minmax(0, 0.85fr)",gap:"1.25rem",height:"calc(100vh - 120px)",width:"100%",minWidth:0},children:[e.jsxs("div",{style:{minWidth:0,backgroundColor:"white",borderRadius:"12px",border:"1px solid #e8ecf0",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.04)"},children:[e.jsxs("div",{style:{padding:"0.75rem 1rem",borderBottom:"1px solid #f1f5f9",background:"#fafbfc",fontWeight:500,color:"#475569",fontSize:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{children:"Audit evidence"}),e.jsx("span",{style:{fontSize:"10px",color:"#94a3b8",fontWeight:400},children:(()=>{const M=o.findIndex(R=>String(R.id)===String(t));return o.length>1&&M>=0?`${M+1} of ${o.length}`:"Secure preview"})()})]}),e.jsxs("div",{style:{flex:1,backgroundColor:"#1e293b",position:"relative"},children:[g&&e.jsx("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#94a3b8",fontSize:"0.9rem"},children:"Loading document preview…"}),!g&&f&&e.jsx("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#fca5a5",fontSize:"0.9rem",padding:"1rem",textAlign:"center"},children:"Could not load the file (missing storage or no access). Re-upload if this is an old record."}),!g&&h&&e.jsx("iframe",{src:h,style:{width:"100%",height:"100%",border:"none"},title:"Audit Evidence Viewer"}),!g&&!h&&!f&&e.jsx("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#94a3b8",fontSize:"0.9rem"},children:"Evidence binary not found in storage"})]})]}),e.jsxs("div",{style:{minWidth:0,overflowY:"auto",overflowX:"hidden",paddingRight:"0.5rem",display:"flex",flexDirection:"column",gap:"1.25rem"},children:[e.jsxs("div",{style:{flexShrink:0,backgroundColor:"white",borderRadius:"12px",padding:"1.25rem",border:"1px solid #e8ecf0",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.04)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"1.25rem",marginBottom:"1.1rem"},children:[e.jsxs("div",{style:{position:"relative",width:"80px",height:"80px",display:"flex",alignItems:"center",justifyContent:"center"},children:[e.jsxs("svg",{width:"80",height:"80",viewBox:"0 0 100 100",children:[e.jsx("circle",{cx:"50",cy:"50",r:"42",fill:"none",stroke:"#f1f5f9",strokeWidth:"6"}),e.jsx("circle",{cx:"50",cy:"50",r:"42",fill:"none",stroke:W>=75?"#34d399":"#fb7185",strokeWidth:"6",strokeDasharray:`${2*Math.PI*42}`,strokeDashoffset:`${2*Math.PI*42*(1-W/100)}`,strokeLinecap:"round",transform:"rotate(-90 50 50)",style:{transition:"stroke-dashoffset 1s ease-out"}})]}),e.jsx("div",{style:{position:"absolute",display:"flex",flexDirection:"column",alignItems:"center"},children:e.jsxs("span",{style:{fontWeight:600,fontSize:"1.125rem",color:"#334155",lineHeight:1,fontVariantNumeric:"tabular-nums"},children:[W,"%"]})})]}),e.jsxs("div",{style:{flex:1},children:[e.jsx("h3",{style:{margin:"0 0 0.35rem 0",fontSize:"1rem",fontWeight:600,color:"#334155",letterSpacing:"-0.01em"},children:"Audit reconciliation"}),e.jsx("p",{style:{margin:0,fontSize:"0.8125rem",color:"#64748b",fontWeight:400,lineHeight:1.5},children:"Validation from OCR extraction compared to expected fields."})]})]}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:"0.65rem"},children:[{label:"Matched",val:F,color:"#166534",bg:"#f0fdf4",border:"#d1fae5"},{label:"Mismatch",val:w,color:"#b91c4c",bg:"#fdf2f5",border:"#fce7ec"},{label:"Missing",val:L,color:"#b45309",bg:"#fffbeb",border:"#fde68a"}].map(M=>e.jsxs("div",{style:{padding:"10px 8px",backgroundColor:M.bg,borderRadius:"10px",border:`1px solid ${M.border}`,textAlign:"center"},children:[e.jsx("div",{style:{fontSize:"0.625rem",fontWeight:500,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"6px"},children:M.label}),e.jsx("div",{style:{fontSize:"1.25rem",fontWeight:600,color:M.color,fontVariantNumeric:"tabular-nums"},children:M.val})]},M.label))})]}),e.jsxs("div",{style:{flexShrink:0,minWidth:0,backgroundColor:"white",borderRadius:"12px",border:"1px solid #e8ecf0",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.04)",overflow:"hidden"},children:[e.jsx("div",{style:{padding:"1rem 1.25rem",borderBottom:"1px solid #f1f5f9",background:"#fafbfc",fontWeight:600,color:"#475569",fontSize:"0.875rem"},children:"Field extraction matrix"}),e.jsx("div",{style:{width:"100%",minWidth:0,boxSizing:"border-box"},children:e.jsxs("table",{style:{width:"100%",maxWidth:"100%",borderCollapse:"collapse",tableLayout:"fixed"},children:[e.jsxs("colgroup",{children:[e.jsx("col",{style:{width:"20%"}}),e.jsx("col",{style:{width:"44%"}}),e.jsx("col",{style:{width:"13%"}}),e.jsx("col",{style:{width:"23%"}})]}),e.jsx("thead",{children:e.jsxs("tr",{style:{borderBottom:"1px solid #f1f5f9"},children:[e.jsx("th",{style:{textAlign:"left",padding:"0.65rem 0.6rem",color:"#94a3b8",fontSize:"10px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Field name"}),e.jsx("th",{style:{textAlign:"left",padding:"0.65rem 0.6rem",color:"#94a3b8",fontSize:"10px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Extracted (AI)"}),e.jsx("th",{style:{textAlign:"center",padding:"0.65rem 0.35rem",color:"#94a3b8",fontSize:"10px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Match %"}),e.jsx("th",{style:{textAlign:"center",padding:"0.65rem 0.5rem",color:"#94a3b8",fontSize:"10px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Status"})]})}),e.jsx("tbody",{children:A.map((M,R)=>{const C=M.extracted==="undefined"||M.extracted==="null"||!M.extracted?"-":M.extracted,H=k(M),z=String(M.status||"").toUpperCase(),P=z==="MISSING"?"MISSING":H||z==="SUCCESSFUL"||z==="MATCH"?"MATCH":C==="-"||C==="N/A"||C==="N/A."?"MISSING":"MISMATCH",S=D(M);let U="#166534",Y="#ecfdf5",B=e.jsx(Yr,{style:{opacity:.82}});P==="MISMATCH"?(U="#b91c4c",Y="#fdf2f5",B=e.jsx(Pc,{style:{opacity:.8}})):P==="MISSING"?(U="#b45309",Y="#fffbeb",B=e.jsx(gi,{style:{opacity:.8}})):B=e.jsx(Yr,{style:{opacity:.82}});const E=P==="MATCH"?"#166534":P==="MISSING"?"#92400e":"#9f1239",V=S==null?"#94a3b8":P==="MATCH"?"#15803d":P==="MISSING"?"#b45309":"#be185d";return e.jsxs("tr",{style:{borderBottom:"1px solid #f8fafc",backgroundColor:R%2===0?"white":"#fafbfc"},children:[e.jsx("td",{style:{padding:"0.75rem 0.6rem",verticalAlign:"top",minWidth:0,wordBreak:"break-word"},children:e.jsx("div",{style:{fontWeight:500,color:"#334155",fontSize:"0.8125rem",overflowWrap:"anywhere",textTransform:"capitalize"},children:M.field.replace(/_/g," ")})}),e.jsxs("td",{style:{padding:"0.75rem 0.6rem",verticalAlign:"top",minWidth:0,wordBreak:"break-word"},children:[e.jsxs("div",{style:{fontSize:"10px",color:"#94a3b8",marginBottom:"6px",fontWeight:400},children:["Expected ",e.jsx("span",{style:{color:"#64748b"},children:M.expected})]}),e.jsx("div",{style:{fontSize:"0.8125rem",fontWeight:500,color:E,wordBreak:"break-word",overflowWrap:"anywhere",lineHeight:1.45},children:p?e.jsx("input",{type:"text",value:d[M.field]!==void 0?d[M.field]:C==="-"?"":C,onChange:G=>v(M.field,G.target.value),style:{width:"100%",padding:"0.45rem 0.5rem",border:"1px solid #e2e8f0",borderRadius:"8px",fontSize:"0.8125rem",fontWeight:500,color:"#334155"}}):C})]}),e.jsx("td",{style:{padding:"0.75rem 0.35rem",textAlign:"center",verticalAlign:"top",fontVariantNumeric:"tabular-nums"},children:e.jsx("span",{style:{fontWeight:500,fontSize:"0.75rem",color:V},children:S!=null?`${S}%`:"—"})}),e.jsx("td",{style:{padding:"0.75rem 0.45rem",textAlign:"center",verticalAlign:"middle",minWidth:0},children:e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"4px",padding:"4px 8px",borderRadius:"9999px",backgroundColor:Y,color:U,fontSize:"10px",fontWeight:500,letterSpacing:"0.03em",border:"1px solid rgba(148, 163, 184, 0.22)",maxWidth:"100%",boxSizing:"border-box",lineHeight:1.25,flexWrap:"wrap",wordBreak:"break-word",textAlign:"center"},children:[B,e.jsx("span",{style:{flexShrink:0},children:P})]})})]},R)})})]})}),(r.validationStatus==="NEED_MANUAL"||r.validationStatus==="MISMATCH"||p)&&e.jsxs("div",{style:{flexShrink:0,padding:"1.1rem 1.25rem",backgroundColor:"#fffbeb",borderTop:"1px solid #fde68a"},children:[e.jsx("p",{style:{margin:"0 0 0.85rem 0",color:"#a16207",fontSize:"0.8125rem",fontWeight:500,lineHeight:1.55},children:"Manual review suggested — confirm or correct before approving."}),e.jsxs("div",{style:{display:"flex",gap:"0.65rem",flexWrap:"wrap"},children:[e.jsx("button",{onClick:()=>T("APPROVED"),style:{padding:"0.5rem 1rem",backgroundColor:"#15803d",color:"white",border:"none",borderRadius:"8px",fontWeight:500,fontSize:"0.8125rem",cursor:"pointer",boxShadow:"0 1px 2px rgba(21, 128, 61, 0.2)"},children:"Approve & mark correct"}),e.jsx("button",{onClick:()=>T("REJECTED"),style:{padding:"0.5rem 1rem",backgroundColor:"white",color:"#be185d",border:"1px solid #fbcfe8",borderRadius:"8px",fontWeight:500,fontSize:"0.8125rem",cursor:"pointer"},children:"Reject document"})]})]})]})]})]})]})},lF=()=>{const[t,s]=u.useState([]),[a,r]=u.useState(!0);u.useEffect(()=>{n()},[]);const n=async()=>{try{const{data:i}=await ta.get("/documents/recent",{params:{page:1,limit:200,status:"UNSUCCESSFUL"}}),l=Array.isArray(i)?i:i.items||[];s(Cb(l))}catch(i){console.error(i)}finally{r(!1)}};return e.jsxs("div",{className:"dashboard-container",children:[e.jsx("div",{className:"page-header",children:e.jsxs("div",{children:[e.jsx("h1",{className:"page-title",style:{color:"#dc2626"},children:"Rejected / Mismatch Documents"}),e.jsx("p",{className:"page-subtitle",children:"Documents that failed validation or were manually rejected"})]})}),e.jsx("div",{className:"table-container",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Booking ID"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:a?e.jsx("tr",{children:e.jsx("td",{colSpan:"5",style:{textAlign:"center",padding:"2rem"},children:"Loading..."})}):t.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:"5",style:{textAlign:"center",padding:"2rem"},children:"No rejected documents found."})}):t.map(i=>{var l;return e.jsxs("tr",{children:[e.jsx("td",{style:{fontWeight:600,color:"#dc2626"},children:i.bookingId}),e.jsx("td",{style:{textTransform:"capitalize"},children:(l=i.documentType)==null?void 0:l.replace("_"," ")}),e.jsx("td",{children:new Date(i.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.25rem",padding:"0.25rem 0.75rem",borderRadius:"9999px",backgroundColor:"#fee2e2",color:"#b91c1c",fontSize:"0.75rem",fontWeight:600,border:"1px solid #fecaca"},children:[e.jsx(gi,{})," ",i.validationStatus]})}),e.jsx("td",{children:e.jsxs(ii,{to:`/cpc-csd/documents/${i.id}`,state:{from:"/cpc-csd/rejected",title:"Rejected Docs"},style:{color:"#dc2626",textDecoration:"none",fontWeight:600,display:"flex",alignItems:"center",gap:"0.25rem"},children:[e.jsx(pi,{})," Review"]})})]},i.id)})})]})})]})};function ip(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 oF=[{value:"2024-25",label:"2024-25"},{value:"2023-24",label:"2023-24"},{value:"2022-23",label:"2022-23"},{value:"",label:"All Years"}];function cF(){const[t,s]=u.useState(null),[a,r]=u.useState([]),[n,i]=u.useState({totalDealers:0,nonSubmittedCount:0,neverSubmittedCount:0,overdue90Count:0}),[l,o]=u.useState(!0),[c,d]=u.useState("2024-25");u.useEffect(()=>{m()},[c]);const m=async()=>{try{o(!0);const x=await vN(c||void 0);r(x.dealers),i(x.summary)}catch(x){console.error("Error fetching non-submitted dealers:",x),Q.error("Failed to load non-submitted dealers"),r([]),i({totalDealers:0,nonSubmittedCount:0,neverSubmittedCount:0,overdue90Count:0})}finally{o(!1)}},p=async x=>{s(x.id);try{await NN({dealerCode:x.dealerCode,dealerId:x.id,email:x.email,financialYear:c||void 0}),Q.success(`Notification sent to ${x.dealerName}`,{description:`Reminder sent for missing quarters: ${x.missingQuarters.join(", ")}. Last notified column updated.`}),await m()}catch(h){console.error("Notify dealer error:",h),Q.error("Failed to send notification")}finally{s(null)}};return e.jsx("div",{className:"space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full",children:e.jsxs("div",{className:"w-full min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-2",children:"Non-Submitted Dealers"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Dealers who have not submitted Form 16A for one or more quarters"})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("select",{value:c,onChange:x=>d(x.target.value),className:"px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 bg-white",children:oF.map(x=>e.jsx("option",{value:x.value,children:x.value?`FY ${x.label}`:x.label},x.value||"all"))})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(Z,{children:e.jsxs(de,{className:"pb-3",children:[e.jsx(Te,{children:"Non-Submitted / Total Dealers"}),e.jsx(ue,{className:"text-3xl text-red-600",children:l?"...":`${n.nonSubmittedCount}/${n.totalDealers}`})]})}),e.jsx(Z,{children:e.jsxs(de,{className:"pb-3",children:[e.jsx(Te,{children:"Never Submitted"}),e.jsx(ue,{className:"text-3xl text-amber-600",children:l?"...":n.neverSubmittedCount})]})}),e.jsx(Z,{children:e.jsxs(de,{className:"pb-3",children:[e.jsx(Te,{children:"Overdue (90+ days)"}),e.jsx(ue,{className:"text-3xl text-orange-600",children:l?"...":n.overdue90Count})]})})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Dealer List"}),e.jsx(Te,{children:"Dealers with missing Form 16A submissions"})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{children:[e.jsx(Ie,{children:"Dealer Details"}),e.jsx(Ie,{children:"Contact Information"}),e.jsx(Ie,{children:"Location"}),e.jsx(Ie,{children:"Missing Quarters"}),e.jsx(Ie,{children:"Last Submission"}),e.jsx(Ie,{children:"Last Notified"}),e.jsx(Ie,{className:"text-right",children:"Action"})]})}),e.jsx(Fs,{children:l?e.jsx(tt,{children:e.jsxs(ve,{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(tt,{children:e.jsxs(ve,{colSpan:7,className:"text-center py-12 text-gray-500",children:[e.jsx("p",{children:"No dealers with missing quarters found"}),e.jsx("p",{className:"text-sm mt-1",children:"All dealers have submitted Form 16A for the selected period"})]})}):a.map(x=>{var h;return e.jsxs(tt,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(ve,{children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:x.dealerName}),e.jsx("p",{className:"text-xs text-gray-500",children:x.dealerCode})]})}),e.jsx(ve,{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(Ca,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:x.email||"—"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-600",children:[e.jsx(bi,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:x.phone||"—"})]})]})}),e.jsx(ve,{className:"text-sm",children:x.location||"—"}),e.jsx(ve,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:x.missingQuarters.map((g,f)=>e.jsx(oe,{variant:"destructive",className:"text-xs",children:g},f))})}),e.jsx(ve,{children:x.lastSubmissionDate?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:ip(x.lastSubmissionDate)}),e.jsxs("p",{className:`text-xs ${x.daysSinceLastSubmission!=null&&x.daysSinceLastSubmission>90?"text-red-600":"text-gray-500"}`,children:[x.daysSinceLastSubmission," days ago"]})]}):e.jsx(oe,{variant:"outline",className:"text-xs bg-red-50 text-red-700 border-red-200",children:"Never Submitted"})}),e.jsx(ve,{children:x.lastNotifiedDate?e.jsx(Jn,{children:e.jsxs(Ji,{children:[e.jsx(Zi,{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(bt,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:ip(x.lastNotifiedDate)})]}),x.notificationCount>1&&e.jsxs(oe,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[x.notificationCount,"x"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-600",children:[e.jsx(Wt,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:x.lastNotifiedBy})]})]})}),e.jsx(qi,{side:"left",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium",children:["Notification History (",x.notificationCount,")"]}),e.jsx("div",{className:"space-y-1.5",children:(h=x.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(oe,{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(oe,{variant:"outline",className:"text-xs bg-gray-50 text-gray-600 border-gray-200",children:"Never Notified"})}),e.jsx(ve,{className:"text-right",children:e.jsxs(O,{size:"sm",onClick:()=>p(x),disabled:t===x.id,className:"bg-teal-600 hover:bg-teal-700 text-white",children:[e.jsx(Os,{className:"w-4 h-4 mr-1"}),t===x.id?"Sending...":"Notify"]})})]},x.id)})})]})})})]})]})})}function dF(){const t=gs(),[s,a]=u.useState([]),[r,n]=u.useState([]),[i,l]=u.useState(!0),[o,c]=u.useState(!1),[d,m]=u.useState({financialYear:"all",quarter:"all"});u.useEffect(()=>{let A=!1;return(async()=>{l(!0);try{const[k,D]=await Promise.all([vg(),wN({status:"pending,failed,completed"})]);A||(a(Array.isArray(k)?k:[]),n(Array.isArray(D)?D:[]))}catch{A||(Q.error("Failed to load pending submissions"),a([]),n([]))}finally{A||l(!1)}})(),()=>{A=!0}},[]);const p=s.filter(A=>!(d.financialYear!=="all"&&A.financial_year!==d.financialYear||d.quarter!=="all"&&A.quarter!==d.quarter)),x=p.length,h=p.filter(A=>(A.days_overdue??0)>0).length,g=p.filter(A=>(A.days_remaining??0)>0).length,f=()=>m({financialYear:"all",quarter:"all"}),b=d.financialYear!=="all"||d.quarter!=="all",y=A=>{if(!A)return"—";try{return new Date(A).toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}catch{return A}},j=A=>A==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(A),v=A=>{const k=(A||"").toLowerCase();return k==="completed"?"bg-emerald-50 text-emerald-700 border-emerald-200":k==="balance mismatch"||k==="failed"?"bg-red-50 text-red-700 border-red-200":k==="resubmission needed"||k==="duplicate"||k==="duplicate submission"?"bg-amber-50 text-amber-700 border-amber-200":"bg-slate-50 text-slate-600 border-slate-200"},N=A=>{t("/form16/submit")},T=[...new Set(s.map(A=>A.financial_year))].sort();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Pending Submissions"}),e.jsx("p",{className:"text-gray-600 mt-1",children:"Quarters for which Form 16A has not been submitted."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"bg-teal-600 hover:bg-teal-700",onClick:()=>t("/form16/submit"),children:"New Submission"}),e.jsxs(O,{variant:"outline",onClick:()=>c(!o),className:"gap-2",children:[e.jsx(Ga,{className:"w-4 h-4"}),"Filters",b&&e.jsx(oe,{variant:"default",className:"ml-1 bg-teal-600 hover:bg-teal-700",children:[d.financialYear,d.quarter].filter(A=>A!=="all").length}),o?e.jsx(Al,{className:"w-4 h-4"}):e.jsx(Qr,{className:"w-4 h-4"})]})]})]}),o&&e.jsxs(Z,{children:[e.jsx(de,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-base",children:"Filter"}),b&&e.jsxs(O,{variant:"ghost",size:"sm",onClick:f,className:"gap-2 text-gray-600 hover:text-gray-900",children:[e.jsx(vt,{className:"w-4 h-4"}),"Clear All"]})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Financial Year"}),e.jsxs(He,{value:d.financialYear,onValueChange:A=>m(k=>({...k,financialYear:A})),children:[e.jsx(Ye,{children:e.jsx(Ge,{placeholder:"All years"})}),e.jsxs(Qe,{children:[e.jsx(X,{value:"all",children:"All Years"}),T.map(A=>e.jsx(X,{value:A,children:A},A))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Quarter"}),e.jsxs(He,{value:d.quarter,onValueChange:A=>m(k=>({...k,quarter:A})),children:[e.jsx(Ye,{children:e.jsx(Ge,{placeholder:"All quarters"})}),e.jsxs(Qe,{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(ee,{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(ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500 mb-1",children:"Total Pending"}),e.jsx("p",{className:"text-2xl font-semibold text-gray-900",children:x})]}),e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center",children:e.jsx(Ee,{className:"w-6 h-6 text-gray-600"})})]})})}),e.jsx(Z,{children:e.jsx(ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500 mb-1",children:"Overdue"}),e.jsx("p",{className:"text-2xl font-semibold text-red-600",children: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(ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500 mb-1",children:"Upcoming"}),e.jsx("p",{className:"text-2xl font-semibold text-amber-600",children:g})]}),e.jsx("div",{className:"w-12 h-12 bg-amber-100 rounded-lg flex items-center justify-center",children:e.jsx(bt,{className:"w-6 h-6 text-amber-600"})})]})})})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Pending Form 16A Submissions"}),e.jsx(Te,{children:"Complete list of quarters awaiting submission."})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{className:"bg-gray-50",children:[e.jsx(Ie,{children:"Dealer Name"}),e.jsx(Ie,{children:"Financial Year"}),e.jsx(Ie,{children:"Quarter"}),e.jsx(Ie,{children:"Version"}),e.jsx(Ie,{children:"Status"}),e.jsx(Ie,{children:"26AS start date"}),e.jsx(Ie,{children:"Days Status"}),e.jsx(Ie,{className:"text-right",children:"Action"})]})}),e.jsx(Fs,{children:i?e.jsx(tt,{children:e.jsxs(ve,{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(tt,{children:e.jsx(ve,{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(Ee,{className:"w-12 h-12 text-gray-300"}),e.jsx("p",{children:b?"No quarters match your filters":"No pending submissions"}),b&&e.jsx(O,{variant:"outline",size:"sm",onClick:f,className:"mt-2",children:"Clear Filters"}),!b&&e.jsx(O,{size:"sm",className:"bg-teal-600 hover:bg-teal-700 mt-2",onClick:()=>t("/form16/submit"),children:"New Submission"})]})})}):p.map(A=>e.jsxs(tt,{className:"hover:bg-gray-50",children:[e.jsx(ve,{className:"text-sm text-gray-900",children:A.dealer_name??"Your submission"}),e.jsx(ve,{children:e.jsxs("span",{className:"text-sm text-gray-900",children:["FY ",A.financial_year]})}),e.jsx(ve,{children:e.jsx(oe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:A.quarter})}),e.jsx(ve,{children:e.jsx(oe,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:A.has_submission?"V1":"—"})}),e.jsx(ve,{children:e.jsx(oe,{variant:"outline",className:A.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":A.has_submission?"bg-slate-50 text-slate-600 border-slate-200":"bg-gray-100 text-gray-600 border-gray-200",children:A.latest_submission_status==="failed"?"Failed":A.has_submission?"Under review":"Not Submitted"})}),e.jsx(ve,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-700",children:y(A.twenty_six_as_start_date??A.audit_start_date)})]})}),e.jsx(ve,{children:A.days_since_26as_uploaded!=null&&A.days_since_26as_uploaded>=0?e.jsxs("span",{className:"text-sm font-medium text-gray-700",children:["due from ",A.days_since_26as_uploaded," days"]}):e.jsx("span",{className:"text-sm text-gray-500",children:"—"})}),e.jsx(ve,{className:"text-right",children:e.jsx(O,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>N(),children:"Submit Now"})})]},`${A.financial_year}|${A.quarter}`))})]})})})]}),e.jsxs(Z,{children:[e.jsxs(de,{children:[e.jsx(ue,{children:"Your Form 16 Submissions"}),e.jsx(Te,{children:"Requests you have submitted. Total amount and credit note (when issued) are shown. Status is never shown as Pending."})]}),e.jsx(ee,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Rs,{children:[e.jsx(Is,{children:e.jsxs(tt,{className:"bg-gray-50",children:[e.jsx(Ie,{children:"Request ID"}),e.jsx(Ie,{children:"Financial Year"}),e.jsx(Ie,{children:"Quarter"}),e.jsx(Ie,{className:"text-right",children:"Total Amount"}),e.jsx(Ie,{children:"Credit Note No."}),e.jsx(Ie,{children:"Status"}),e.jsx(Ie,{children:"Submitted"}),e.jsx(Ie,{className:"text-right",children:"Action"})]})}),e.jsx(Fs,{children:i?e.jsx(tt,{children:e.jsx(ve,{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(tt,{children:e.jsx(ve,{colSpan:8,className:"text-center py-8 text-gray-500",children:'No Form 16 submissions yet. Use "New Submission" to submit.'})}):r.map(A=>e.jsxs(tt,{className:"hover:bg-gray-50",children:[e.jsx(ve,{className:"font-mono text-sm",children:A.requestId?String(A.requestId).slice(0,8)+"…":"—"}),e.jsxs(ve,{children:["FY ",A.financial_year]}),e.jsx(ve,{children:e.jsx(oe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:A.quarter})}),e.jsx(ve,{className:"text-right font-medium",children:j(A.total_amount)}),e.jsx(ve,{children:A.credit_note_number??"—"}),e.jsx(ve,{children:e.jsx(oe,{variant:"outline",className:v(A.display_status),children:A.display_status??(A.status==="completed"?"Completed":A.status==="failed"?"Failed":"Under review")})}),e.jsx(ve,{className:"text-sm text-gray-600",children:y(A.submitted_date)}),e.jsx(ve,{className:"text-right",children:e.jsx(O,{variant:"outline",size:"sm",onClick:()=>t(`/request/${A.requestId}`),children:"View Request"})})]},A.id))})]})})})]}),s.length>0&&e.jsxs(Z,{className:"border-amber-200 bg-amber-50/50",children:[e.jsxs(de,{children:[e.jsx(ue,{className:"text-amber-900",children:"Quarters Pending Submission"}),e.jsx(Te,{className:"text-amber-700",children:"These quarters don't have completed Form 16A submissions. Please submit Form 16A for these quarters."})]}),e.jsx(ee,{children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:s.slice(0,8).map(A=>e.jsx("div",{className:"p-3 bg-white rounded-lg border border-amber-200",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-gray-900",children:A.quarter}),e.jsx("p",{className:"text-sm text-gray-600",children:A.financial_year}),A.has_submission&&A.latest_submission_status&&e.jsx(oe,{variant:"outline",className:`mt-1 text-xs ${A.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":"bg-slate-50 text-slate-600 border-slate-200"}`,children:A.latest_submission_status==="failed"?"Failed":"Under review"})]}),e.jsx(O,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>t("/form16/submit"),children:"Submit"})]})},`${A.financial_year}|${A.quarter}`))})})]})]})}function mF({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[l,o]=u.useState(""),[c,d]=u.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:Ve,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:At,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(ht,{open:t,onOpenChange:p,children:e.jsxs(mt,{className:"max-w-2xl bg-white",children:[e.jsxs(pt,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:`p-2 rounded-lg ${a==="approve"?"bg-green-100":"bg-red-100"}`,children:e.jsx(g,{className:`w-6 h-6 ${h.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ut,{className:"text-xl",children:h.title}),e.jsx(Mt,{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(oe,{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(oe,{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(re,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(Vs,{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(Ve,{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(O,{variant:"outline",onClick:p,disabled:c,children:"Cancel"}),e.jsx(O,{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 uF=(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(y=>i[y]||y):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 x(){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"?x():h;m(g)}catch{}},xF=u.createContext(void 0),hF={setTheme:t=>{},themes:[]},pF=()=>{var t;return(t=u.useContext(xF))!=null?t:hF};u.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 u.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${uF.toString()})(${m})`}})});const gF=({...t})=>{const{theme:s="system"}=pF();return e.jsx(Ry,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function fF({open:t,onClose:s,onSelect:a,managers:r=[],errorType:n,message:i,isLoading:l=!1}){const o=c=>{a(c)};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-[600px]",children:[e.jsxs(pt,{children:[e.jsx(ut,{className:"flex items-center gap-2",children:n==="NO_MANAGER_FOUND"?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-amber-500"}),"Manager Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ps,{className:"w-5 h-5 text-blue-500"}),"Select Your Manager"]})}),e.jsx(Mt,{children:n==="NO_MANAGER_FOUND"?e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-sm text-gray-600",children:i||"No reporting manager found in the system. Please ensure your manager is correctly configured in your profile."}),e.jsx("p",{className:"text-sm text-gray-500 mt-2",children:"Please contact your administrator to update your manager information, or try again later."})]}):e.jsx("div",{className:"mt-2",children:e.jsx("p",{className:"text-sm text-gray-600",children:i||"Multiple managers were found with the same name. Please select the correct manager from the list below."})})})]}),e.jsx("div",{className:"mt-4",children:n==="NO_MANAGER_FOUND"?e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ze,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-amber-900",children:"Unable to Proceed"}),e.jsx("p",{className:"text-sm text-amber-700 mt-1",children:"We couldn't find your reporting manager in the system. The claim request cannot be created without a valid manager assigned."})]})]})}):e.jsx("div",{className:"space-y-3 max-h-[400px] overflow-y-auto",children:r.map(c=>e.jsx("div",{className:"border rounded-lg p-4 hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>!l&&o(c.email),children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-1",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Wt,{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(Ca,{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(Uc,{className:"w-4 h-4"}),e.jsx("span",{children:c.department})]})]})]})]}),e.jsx(O,{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(O,{onClick:s,variant:"outline",children:"Close"}):e.jsx(e.Fragment,{children:e.jsx(O,{onClick:s,variant:"outline",disabled:l,children:"Cancel"})})})]})})}function bF(){const{id:t}=Aa();return e.jsx(dr,{to:`/cpc-csd/documents/${encodeURIComponent(t??"")}`,replace:!0})}function lp({children:t}){const[s,a]=u.useState(!0),[r,n]=u.useState(!1);return u.useEffect(()=>{let i=!0;return(async()=>{try{const l=await td();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 Yi({children:t}){const[s,a]=u.useState(!0),[r,n]=u.useState(!1);return u.useEffect(()=>{let i=!0;return(async()=>{try{const l=await Ng();if(!i)return;n(!!l.canViewCpcCsd)}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 CPC-CSD module."})]})})}function jF({onViewRequest:t}){const{user:s}=us();return Ul(s)?e.jsx(xR,{onViewRequest:t}):e.jsx(gR,{onViewRequest:t})}function op({onNavigate:t,onNewRequest:s}){const[a,r]=u.useState(!1),[n,i]=u.useState(!0);return u.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(F6,{onNavigate:t,onNewRequest:s}):e.jsx(X1,{onNavigate:t,onNewRequest:s})}function yF({onLogout:t}){const s=gs(),a=$l(),[r,n]=u.useState(null),[i,l]=u.useState([]),[o,c]=u.useState(""),[d,m]=u.useState(""),[p,x]=u.useState(!1),[h,g]=u.useState(null);u.useEffect(()=>{const k=localStorage.getItem("dynamicRequests");if(k)try{const D=JSON.parse(k);l(D)}catch(D){console.error("Error parsing dynamic requests:",D)}},[]),u.useEffect(()=>{i.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(i))},[i]);const f=k=>{if(k==="profile"){s("/profile");return}if(k==="settings"){s("/settings");return}k.startsWith("/")?s(k):s(`/${k}`)},b=(k,D,F,w)=>{c(k),m(D||"Unknown Request"),vl({requestId:k,status:F,request:w,navigate:s})},y=()=>{s(-1)},j=()=>{if(a.pathname.startsWith("/cpc-csd")||a.pathname.startsWith("/cpc-cdc")){s("/cpc-csd/dashboard",{state:{openCpcCsdNewRequest:!0}});return}s("/new-request")},v=k=>{var w,L,_,W,I,$,M,R,C,H,z;if(k.templateType){k.templateType==="claim-management"&&s("/claim-management");return}if(k.backendId){s("/my-requests");return}const F={id:`RE-REQ-2024-${String(i.length+1).padStart(3,"0")}`,title:k.title,description:k.description||"",category:k.category||"General",subcategory:k.subcategory||"",status:"pending",priority:k.priority||"standard",amount:k.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:((w=k.approvers)==null?void 0:w.length)||1,currentApprover:((_=(L=k.approvers)==null?void 0:L[0])==null?void 0:_.name)||(($=(I=(W=k.approvers)==null?void 0:W[0])==null?void 0:I.email)==null?void 0:$.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((M=k.approvers)==null?void 0:M.length)||1}`,template:"custom",initiator:{name:"Current User",role:k.initiatorRole||"Employee",department:k.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:k.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:(k.approvers||[]).filter(P=>P).map((P,S)=>{var B;const U=(P==null?void 0:P.name)||((B=P==null?void 0:P.email)==null?void 0:B.split("@")[0])||`Approver ${S+1}`,Y=(P==null?void 0:P.email)||"";return{step:S+1,approver:`${U}${Y?` (${Y})`:""}`,role:(P==null?void 0:P.role)||`Level ${(P==null?void 0:P.level)||S+1} Approver`,status:S===0?"pending":"waiting",tatHours:P!=null&&P.tat?typeof P.tat=="string"?parseInt(P.tat):P.tat:48,elapsedHours:0,assignedAt:S===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(k.spectators||[]).filter(P=>P&&(P.name||P.email)).map(P=>{var U;const S=(P==null?void 0:P.name)||((U=P==null?void 0:P.email)==null?void 0:U.split("@")[0])||"Observer";return{name:S,role:(P==null?void 0:P.role)||(P==null?void 0:P.department)||"Observer",avatar:S.split(" ").map(Y=>Y[0]).join("").toUpperCase().slice(0,2)||"OB"}}),auditTrail:[{type:"created",action:"Request Created",details:`Custom request "${k.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 ${((C=(R=k.approvers)==null?void 0:R[0])==null?void 0:C.name)||((z=(H=k.approvers)==null?void 0:H[0])==null?void 0:z.email)||"first approver"}`,user:"System",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}],tags:k.tags||["custom-request"]};l([...i,F]),s("/my-requests")},N=(k,D)=>new Promise(F=>{setTimeout(()=>{k==="approve"?Q.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):Q.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),n(null),F(!0)},1e3)}),T=()=>{n(null)},A=async(k,D)=>{var F,w,L,_,W,I,$;try{const M={activityName:k.activityName,activityType:k.activityType,dealerCode:k.dealerCode,dealerName:k.dealerName,dealerEmail:k.dealerEmail||void 0,dealerPhone:k.dealerPhone||void 0,dealerAddress:k.dealerAddress||void 0,activityDate:k.activityDate?new Date(k.activityDate).toISOString():void 0,location:k.location,requestDescription:k.requestDescription,periodStartDate:k.periodStartDate?new Date(k.periodStartDate).toISOString():void 0,periodEndDate:k.periodEndDate?new Date(k.periodEndDate).toISOString():void 0,estimatedBudget:k.estimatedBudget||void 0,approvers:k.approvers||[]},R=await a6(M);if(!R||!R.request)throw new Error("Invalid response from server: Request object not found");const C=R.request;if(!C.requestNumber&&!C.requestId)throw new Error("Invalid response from server: Request identifier not found");x(!1),g(null),Q.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),C.requestNumber?s(`/request/${C.requestNumber}`):C.requestId?s(`/request/${C.requestId}`):s("/my-requests")}catch(M){console.error("[App] Error creating claim request:",M);const R=(F=M==null?void 0:M.response)==null?void 0:F.data,C=(R==null?void 0:R.code)||((w=R==null?void 0:R.error)==null?void 0:w.code);if(C==="NO_MANAGER_FOUND"){g({errorType:"NO_MANAGER_FOUND",message:(R==null?void 0:R.message)||((L=R==null?void 0:R.error)==null?void 0:L.message)||"No reporting manager found. Please ensure your manager is correctly configured in the system.",pendingClaimData:k}),x(!0);return}if(C==="MULTIPLE_MANAGERS_FOUND"){const z=(R==null?void 0:R.managers)||((_=R==null?void 0:R.error)==null?void 0:_.managers)||[];g({errorType:"MULTIPLE_MANAGERS_FOUND",managers:z,message:(R==null?void 0:R.message)||((W=R==null?void 0:R.error)==null?void 0:W.message)||"Multiple managers found. Please select one.",pendingClaimData:k}),x(!0);return}const H=(($=(I=M==null?void 0:M.response)==null?void 0:I.data)==null?void 0:$.message)||(M==null?void 0:M.message)||"Failed to create claim request";Q.error("Failed to Submit Claim Request",{description:H})}};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(Ey,{children:[e.jsx(ot,{path:"/login/callback",element:e.jsx(ig,{})}),e.jsx(ot,{path:"/",element:e.jsx(Lt,{currentPage:"dashboard",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(op,{onNavigate:f,onNewRequest:j})})}),e.jsx(ot,{path:"/dashboard",element:e.jsx(Lt,{currentPage:"dashboard",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(op,{onNavigate:f,onNewRequest:j})})}),e.jsxs(ot,{element:e.jsx(Lt,{currentPage:"admin",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(_y,{})}),children:[e.jsx(ot,{path:"/admin",element:e.jsx(d3,{})}),e.jsx(ot,{path:"/admin/create-template",element:e.jsx(Yh,{})}),e.jsx(ot,{path:"/admin/edit-template/:templateId",element:e.jsx(Yh,{})}),e.jsx(ot,{path:"/admin/templates",element:e.jsx(CI,{})})]}),e.jsx(ot,{path:"/create-admin-request/:templateId",element:e.jsx(TI,{})}),e.jsx(ot,{path:"/open-requests",element:e.jsx(Lt,{currentPage:"open-requests",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(z6,{onViewRequest:b})})}),e.jsx(ot,{path:"/closed-requests",element:e.jsx(Lt,{currentPage:"closed-requests",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(uD,{onViewRequest:b})})}),e.jsx(ot,{path:"/shared-summaries",element:e.jsx(Lt,{currentPage:"shared-summaries",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(jD,{})})}),e.jsx(ot,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(Lt,{currentPage:"shared-summaries",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(yD,{})})}),e.jsx(ot,{path:"/form16/credit-notes",element:e.jsx(Lt,{currentPage:"form16-credit-notes",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(h3,{})})}),e.jsx(ot,{path:"/form16/credit-notes/:id",element:e.jsx(Lt,{currentPage:"form16-credit-notes",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(f3,{})})}),e.jsx(ot,{path:"/form16/debit-notes",element:e.jsx(Lt,{currentPage:"form16-debit-notes",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(v3,{})})}),e.jsx(ot,{path:"/form16/transactions",element:e.jsx(Lt,{currentPage:"form16-transactions",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(T3,{})})}),e.jsx(ot,{path:"/form16/submit",element:e.jsx(Lt,{currentPage:"form16-submit",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(I3,{})})}),e.jsx(ot,{path:"/form16/submit/result",element:e.jsx(Lt,{currentPage:"form16-submit",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(M3,{})})}),e.jsx(ot,{path:"/form16/dashboard",element:e.jsx(Lt,{currentPage:"form16-dashboard",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(lp,{children:e.jsx(z3,{})})})}),e.jsx(ot,{path:"/form16/26as",element:e.jsx(Lt,{currentPage:"form16-26as",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(lp,{children:e.jsx(B3,{})})})}),e.jsx(ot,{path:"/form16/pending-submissions",element:e.jsx(Lt,{currentPage:"form16-pending-submissions",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(dF,{})})}),e.jsx(ot,{path:"/form16/non-submitted-dealers",element:e.jsx(Lt,{currentPage:"form16-non-submitted-dealers",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(cF,{})})}),e.jsx(ot,{path:"/cpc-csd/dashboard",element:e.jsx(Lt,{currentPage:"cpc-csd-dashboard",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(Yi,{children:e.jsx(rF,{})})})}),e.jsx(ot,{path:"/cpc-csd/history",element:e.jsx(Lt,{currentPage:"cpc-csd-history",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(Yi,{children:e.jsx(nF,{})})})}),e.jsx(ot,{path:"/cpc-csd/analytics",element:e.jsx(dr,{to:"/cpc-csd/dashboard",replace:!0})}),e.jsx(ot,{path:"/cpc-csd/submissions",element:e.jsx(dr,{to:"/cpc-csd/history",replace:!0})}),e.jsx(ot,{path:"/cpc-csd/rejected",element:e.jsx(Lt,{currentPage:"cpc-csd-rejected",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(Yi,{children:e.jsx(lF,{})})})}),e.jsx(ot,{path:"/cpc-csd/documents/:id",element:e.jsx(Lt,{currentPage:"cpc-csd-detail",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(Yi,{children:e.jsx(iF,{})})})}),e.jsx(ot,{path:"/cpc-cdc/dashboard",element:e.jsx(dr,{to:"/cpc-csd/dashboard",replace:!0})}),e.jsx(ot,{path:"/cpc-cdc/history",element:e.jsx(dr,{to:"/cpc-csd/history",replace:!0})}),e.jsx(ot,{path:"/cpc-cdc/analytics",element:e.jsx(dr,{to:"/cpc-csd/dashboard",replace:!0})}),e.jsx(ot,{path:"/cpc-cdc/submissions",element:e.jsx(dr,{to:"/cpc-csd/history",replace:!0})}),e.jsx(ot,{path:"/cpc-cdc/rejected",element:e.jsx(dr,{to:"/cpc-csd/rejected",replace:!0})}),e.jsx(ot,{path:"/cpc-cdc/documents/:id",element:e.jsx(bF,{})}),e.jsx(ot,{path:"/my-requests",element:e.jsx(Lt,{currentPage:"my-requests",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx($D,{onViewRequest:b,dynamicRequests:i})})}),e.jsx(ot,{path:"/requests",element:e.jsx(Lt,{currentPage:"requests",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(jF,{onViewRequest:b})})}),e.jsx(ot,{path:"/approver-performance",element:e.jsx(Lt,{currentPage:"approver-performance",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(RR,{})})}),e.jsx(ot,{path:"/request/:requestId",element:e.jsx(Lt,{currentPage:"request-detail",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(bD,{requestId:"",onBack:y,dynamicRequests:i})})}),e.jsx(ot,{path:"/work-notes/:requestId",element:e.jsx(vD,{})}),e.jsx(ot,{path:"/new-request",element:e.jsx(Eh,{onBack:y,onSubmit:v})}),e.jsx(ot,{path:"/edit-request/:requestId",element:e.jsx(Eh,{onBack:y,onSubmit:v,requestId:void 0,isEditMode:!0})}),e.jsx(ot,{path:"/claim-management",element:e.jsx(v6,{onBack:y,onSubmit:A})}),e.jsx(ot,{path:"/profile",element:e.jsx(Lt,{currentPage:"profile",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(IR,{})})}),e.jsx(ot,{path:"/settings",element:e.jsx(Lt,{currentPage:"settings",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(JR,{})})}),e.jsx(ot,{path:"/settings/security",element:e.jsx(Lt,{currentPage:"settings",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(aI,{})})}),e.jsx(ot,{path:"/notifications",element:e.jsx(Lt,{currentPage:"notifications",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(rI,{onNavigate:f})})}),e.jsx(ot,{path:"/detailed-reports",element:e.jsx(Lt,{currentPage:"detailed-reports",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(wI,{})})})]}),e.jsx(gF,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),e.jsx(fF,{open:p,onClose:()=>{x(!1),g(null)},onSelect:async k=>{h!=null&&h.pendingClaimData&&await A(h.pendingClaimData)},managers:h==null?void 0:h.managers,errorType:(h==null?void 0:h.errorType)||"NO_MANAGER_FOUND",message:h==null?void 0:h.message,isLoading:!1}),r&&e.jsx(mF,{isOpen:!!r,onClose:T,action:r,requestId:o,requestTitle:d,onSubmit:N})]})}function vF(t){const{onLogout:s}=t||{};return e.jsx(Py,{children:e.jsx(yF,{onLogout:s})})}function NF(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=us(),[i,l]=u.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(x){console.error("🔵 Logout error in handleLogout:",x);try{localStorage.clear(),sessionStorage.clear(),window.location.href="/"}catch(h){console.error("🔵 Error during emergency cleanup:",h)}}};u.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(iN,{}):e.jsx(ig,{}):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(vF,{onLogout:c}),i&&e.jsx(oN,{isOpen:i,onClose:()=>l(!1)})]}):e.jsx(nN,{})}const nl=()=>{try{return!0}catch{return!1}},wF=()=>{if(nl())return null;try{return localStorage.getItem("token")}catch{return null}},CF={user:null,token:wF(),isAuthenticated:!1,isLoading:!1,error:null},kb=An({name:"auth",initialState:CF,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,!nl())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,!nl())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!nl())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:LF,loginSuccess:OF,loginFailure:$F,logout:UF,clearError:BF,updateUser:zF}=kb.actions,SF=Fy({reducer:{auth:kb.reducer,dashboard:wg.reducer,requests:ub.reducer,myRequests:ob.reducer,openRequests:_g.reducer,closedRequests:nb.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});ac.createRoot(document.getElementById("root")).render(e.jsx(xa.StrictMode,{children:e.jsx(tv,{store:SF,children:e.jsx(Av,{children:e.jsx(NF,{})})})}));export{Se as a};