Re_Backend/build/assets/index-r8G8cQlR.js
2026-04-20 20:18:54 +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-Dwb-WsdL.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 Fb=Object.defineProperty;var Pb=(t,s,a)=>s in t?Fb(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var to=(t,s,a)=>Pb(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as dp,R as mp,I as up,F as xp,a as Eb,T as _b,P as Mb,C as Lb,b as Ob,O as hp,c as pp,d as $b,e as Ub,f as Bb,D as zb,g as Vb,A as Wb,h as Hb,i as Gb,k as Yb,l as Kb,m as Qb,n as Xb,V as Jb,o as Zb,p as qb,q as ej,r as tj,s as sj,t as aj,u as rj,v as nj,w as ij,x as lj,y as oj,z as cj,B as dj,E as mj,G as uj,H as xj,J as hj,K as pj,L as gj,M as fj,N as bj,Q as Mc,U as Lc,W as jj,X as gp,Y as fp,Z as bp,_ as jp,$ as yj,a0 as vj,a1 as Nj,a2 as wj,a3 as Cj,a4 as Sj,a5 as Aj,a6 as Tj,a7 as kj,a8 as gn,a9 as vr,aa as ri,ab as Dj,ac as Rj,ad as Ij,ae as Fj}from"./radix-vendor-CLtqm-Ae.js";import{a as Pj,r as u,d as yp,e as fn,B as qo,C as ll,X as ol,Y as cl,T as bn,L as dl,f as $a,P as vp,g as Np,h as wp,i as Ej,j as _u,k as Tl,l as kl,b as ua}from"./charts-vendor-CmYZJIYl.js";import{a as bi,f as Cp,s as xa,e as Oc,b as Mu,c as _j,d as Va,g as ni,i as $c,h as Sp,j as ta,k as ca,l as so,m as Za,n as Mj,o as ec,p as Lj,q as it,r as tc,t as Oj,u as $j,v as Uj,w as Bj,x as ao,y as Lu,z as zj,A as Ap,B as Tp,C as Uc,D as Bc,E as Vj,F as Wj,G as kp,H as nn,I as ro,J as Hj,K as Gj,L as Yj}from"./utils-vendor-BTBPSQfW.js";import{u as Y,A as vs,S as js,C as tt,a as gs,L as We,X as Nt,H as Ou,b as sc,U as Ht,F as Pe,c as He,d as Sn,R as Et,e as Qr,f as Wa,P as os,g as Kj,h as Qj,B as $s,i as pr,j as no,k as zc,l as Ha,m as Dl,n as Nn,o as jt,p as Ga,q as _t,I as Zr,T as ss,r as ot,s as Ma,t as Xj,v as as,M as Ks,w as Rl,x as Vt,y as ac,D as kt,Z as Il,z as es,E as Jj,G as Zj,J as qj,K as ey,N as ty,O as sy,Q as ay,V as ry,W as ny,Y as Dp,_ as iy,$ as ly,a0 as Rp,a1 as wa,a2 as ji,a3 as gr,a4 as ml,a5 as $u,a6 as Ei,a7 as ul,a8 as Ip,a9 as At,aa as oy,ab as Qs,ac as Vc,ad as Ss,ae as Fl,af as Fp,ag as wt,ah as cy,ai as dy,aj as Pp,ak as Pl,al as Ep,am as my,an as Wc,ao as Ns,ap as Fa,aq as _p,ar as El,as as _l,at as Zt,au as uy,av as xy,aw as Mp,ax as Lp,ay as Qi,az as xr,aA as Hc,aB as Ml,aC as ii,aD as Op,aE as $p,aF as Gc,aG as Ll,aH as Ol,aI as rc,aJ as hy,aK as Vs,aL as Up,aM as xl,aN as py,aO as gy,aP as fy,aQ as $l,aR as Ul,aS as Yc,aT as by,aU as Uu,aV as La,aW as Nr,aX as jy,aY as dn,aZ as Bu,a_ as yy,a$ as vy,b0 as Bp,b1 as zu,b2 as zp,b3 as Ny,b4 as wy,b5 as Cy,b6 as Sy,b7 as Vp,b8 as Ay,b9 as Ty,ba as ky,bb as Bl,bc as Dy,bd as Ry,be as Iy,bf as Fy}from"./ui-vendor-DgwXkk2Y.js";import{l as Py}from"./socket-vendor-TjCxX7sJ.js";import{c as An,a as Ey}from"./redux-vendor-tbZCm13o.js";import{u as fs,a as Sa,b as Wp,c as zl,L as li,B as _y,R as My,d as dt,O as Ly,N as mr}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 nc={},Vu=Pj;nc.createRoot=Vu.createRoot,nc.hydrateRoot=Vu.hydrateRoot;var Hp={exports:{}},Gp={};var yi=u;function Oy(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var $y=typeof Object.is=="function"?Object.is:Oy,Uy=yi.useSyncExternalStore,By=yi.useRef,zy=yi.useEffect,Vy=yi.useMemo,Wy=yi.useDebugValue;Gp.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=By(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=Vy(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,$y(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=Uy(t,i[0],i[1]);return zy(function(){l.hasValue=!0,l.value=o},[o]),Wy(o),o};Hp.exports=Gp;var Hy=Hp.exports;function Gy(t){t()}function Yy(){let t=null,s=null;return{clear(){t=null,s=null},notify(){Gy(()=>{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 Wu={notify(){},get:()=>[]};function Ky(t,s){let a,r=Wu,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=Yy())}function p(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Wu)}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 Qy=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Xy=Qy(),Jy=()=>typeof navigator<"u"&&navigator.product==="ReactNative",Zy=Jy(),qy=()=>Xy||Zy?u.useLayoutEffect:u.useEffect,ev=qy(),io=Symbol.for("react-redux-context"),lo=typeof globalThis<"u"?globalThis:{};function tv(){if(!u.createContext)return{};const t=lo[io]??(lo[io]=new Map);let s=t.get(u.createContext);return s||(s=u.createContext(null),t.set(u.createContext,s)),s}var fr=tv();function sv(t){const{children:s,context:a,serverState:r,store:n}=t,i=u.useMemo(()=>{const c=Ky(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=u.useMemo(()=>n.getState(),[n]);ev(()=>{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||fr;return u.createElement(o.Provider,{value:i},s)}var av=sv;function Kc(t=fr){return function(){return u.useContext(t)}}var Yp=Kc();function Kp(t=fr){const s=t===fr?Yp:Kc(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var rv=Kp();function nv(t=fr){const s=t===fr?rv:Kp(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var iv=nv(),lv=(t,s)=>t===s;function ov(t=fr){const s=t===fr?Yp:Kc(t),a=(r,n={})=>{const{equalityFn:i=lv}=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=Hy.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return u.useDebugValue(p),p};return Object.assign(a,{withTypes:()=>a}),a}var cv=ov(),ic=function(t,s){return ic=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])},ic(t,s)};function dv(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");ic(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var hl=function(){return hl=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},hl.apply(this,arguments)};var Or=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Qc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Xc(t,s){return t(s={exports:{}},s.exports),s.exports}var Er=Xc(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()}});Qc(Er);var mv=Qc(Xc(function(t,s){var a=Or&&Or.__awaiter||function(m,p,x,h){return new(x||(x=Promise))(function(g,f){function b(v){try{j(h.next(v))}catch(w){f(w)}}function y(v){try{j(h.throw(v))}catch(w){f(w)}}function j(v){v.done?g(v.value):new x(function(w){w(v.value)}).then(b,y)}j((h=h.apply(m,p||[])).next())})},r=Or&&Or.__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(w){if(x)throw new TypeError("Generator is already executing.");for(;b;)try{if(x=1,h&&(g=2&w[0]?h.return:w[0]?h.throw||((g=h.return)&&g.call(h),0):h.next)&&!(g=g.call(h,w[1])).done)return g;switch(h=0,g&&(w=[2&w[0],g.value]),w[0]){case 0:case 1:g=w;break;case 4:return b.label++,{value:w[1],done:!1};case 5:b.label++,h=w[1],w=[0];continue;case 7:w=b.ops.pop(),b.trys.pop();continue;default:if(g=b.trys,!((g=g.length>0&&g[g.length-1])||w[0]!==6&&w[0]!==2)){b=0;continue}if(w[0]===3&&(!g||w[1]>g[0]&&w[1]<g[3])){b.label=w[1];break}if(w[0]===6&&b.label<g[1]){b.label=g[1],g=w;break}if(g&&b.label<g[2]){b.label=g[2],b.ops.push(w);break}g[2]&&b.ops.pop(),b.trys.pop();continue}w=p.call(m,b)}catch(S){w=[6,S],h=0}finally{x=g=0}if(5&w[0])throw w[1];return{value:w[0]?w[1]:void 0,done:!0}}([j,v])}}},n=Or;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(w){switch(w.label){case 0:h=Date.now()+c(4),g=Date.now()+x,f=i+"-"+p,b=this.storageHandler===void 0?l:this.storageHandler,w.label=1;case 1:return Date.now()<g?[4,o(30)]:[3,8];case 2:return w.sent(),b.getItemSync(f)!==null?[3,5]:(y=this.id+"-"+p+"-"+h,[4,o(Math.floor(25*Math.random()))]);case 3:return w.sent(),b.setItemSync(f,JSON.stringify({id:this.id,iat:h,timeoutKey:y,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,o(30)];case 4:return w.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:w.sent(),w.label=7;case 7:return h=Date.now()+c(4),[3,1];case 8:return[2,!1]}})})},m.prototype.refreshLockWhileAcquired=function(p,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,Er.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?(Er.default().unlock(x),[2]):((y=JSON.parse(b)).timeRefreshed=Date.now(),f.setItemSync(p,JSON.stringify(y)),Er.default().unlock(x),this.refreshLockWhileAcquired(p,x),[2])):(Er.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,Er.default().lock(f.iat)];case 1:b.sent(),this.acquiredIatSet.delete(f.iat),x.removeItemSync(h),Er.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 w=h.getItemSync(v);if(w!==null){var S=JSON.parse(w);(S.timeRefreshed===void 0&&S.timeAcquired<x||S.timeRefreshed!==void 0&&S.timeRefreshed<x)&&(h.removeItemSync(v),y=!0)}}}y&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var Ur=Xc(function(t,s){var a=Or&&Or.__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}))}});Qc(Ur),Ur.encode,Ur.parse,Ur.getAll;Ur.get;Ur.set;Ur.remove;var Hu;(function(t){t.Code="code",t.ConnectCode="connect_code"})(Hu||(Hu={}));var Gu;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(Gu||(Gu={}));new mv;var uv={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Zs=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},xv=hl(hl({},uv),{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}),hv=u.createContext(xv);(function(t){dv(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 pv=function(t){return t===void 0&&(t=hv),u.useContext(t)};const oo="idToken",co="userData",gv=()=>!0;class lt{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(oo,s)}static getIdToken(){return sessionStorage.getItem(oo)}static setUserData(s){localStorage.setItem(co,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(co);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(co),sessionStorage.removeItem(oo)}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 gv()}static setAuthError(s){s?sessionStorage.setItem("__auth_error__",s):sessionStorage.removeItem("__auth_error__")}static getAuthError(){return sessionStorage.getItem("__auth_error__")}}function _i(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 lc(){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 oc="https://ssodev.rebridge.co.in/realms/RE",Qp="REFLOW",Jc=`${window.location.origin}/login/callback`;function fv(){const t=oc.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(Jc)}&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 bv(t,s){var r,n,i;const a="https://reflow-uat.royalenfield.com/api/v1";try{const l=await bi.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:Jc,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),o=((r=l.data)==null?void 0:r.data)||l.data;return o.accessToken&&lt.setAccessToken(o.accessToken),o.refreshToken&&lt.setRefreshToken(o.refreshToken),o.idToken&&lt.setIdToken(o.idToken),o.user&&lt.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 Xp(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=Jc,a=new URL(`${oc}/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:`${oc}/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 Jp(t){const s="https://dev-830839.oktapreview.com",a=lc();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 Yu="https://reflow-uat.royalenfield.com/api/v1".trim(),jv=typeof window<"u"&&/^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname),Zc=(!jv&&/localhost:5000/i.test(Yu)?"":Yu.replace(/\/$/,""))||"/api/v1",we=bi.create({baseURL:Zc,headers:{"Content-Type":"application/json"},withCredentials:!0});we.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));we.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=lt.getIdToken(),o=sessionStorage.getItem("auth_provider")||(l!=null&&l.includes("tanflow")?"tanflow":"okta");return lt.setAuthError("SESSION_SUPERSEDED"),Y.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?Xp(l):Jp(l||void 0)},1e3),Promise.reject(t)}if(!s._retry){s._retry=!0;const l=!0;try{const o=lt.getRefreshToken(),c=await bi.post(`${Zc}/auth/refresh`,l?{}:{refreshToken:o},{withCredentials:!0}),m=(c.data.data||c.data).accessToken;return we(s)}catch(o){return lt.clearAll(),window.location.href="/",Promise.reject(o)}}}return Promise.reject(t)});async function yv(t,s){var a,r;try{const n=await we.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&&lt.setUserData(l.user),l.idToken&&lt.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(lt.setAccessToken(l.accessToken),lt.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 vv(){var r;const t={},a=(await we.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 we.get("/auth/me")).data;return s.data||s}async function Nv(){var t,s;try{await bi.post(`${Zc}/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 Ir=null;function wv(){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 Xr(t){const s=wv();return Ir||(Ir=Py(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),Ir.on("connect",()=>{}),Ir.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),Ir.on("disconnect",a=>{}),Ir)}function cc(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function Zp(t,s){t.emit("leave:request",s)}function qc(t,s){t.emit("join:user",{userId:s})}const Cv=/^(localhost|127\.0\.0\.1)$/i;function Sv(){return typeof window>"u"?"":window.location.hostname||""}function qp(){return Cv.test(Sv())}function Ln(){return!qp()}function lr(t){return String(t||"").trim()}function Av(t){const s=(t||"").toLowerCase();return s.includes("uat")||s.includes("dev")}function eg(){const t=typeof window<"u"?window.location.hostname:"",s=qp(),a=!s&&Av(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 tg=u.createContext(void 0);function Tv({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__"),w=sessionStorage.getItem("__force_logout__");if(v==="true"||w==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),lt.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(R){console.error("Error clearing storage:",R)}a(!1),l(null),n(!1),c(null);return}const S=new URLSearchParams(window.location.search),D=S.has("code"),k=sessionStorage.getItem("__logout_type__");if((S.has("logout")||S.has("okta_logged_out")||S.has("tanflow_logged_out")||k)&&!D){console.log("🚪 Logout parameter detected in URL, clearing all tokens and backend session"),Nv().catch(R=>console.warn("🚪 Final backend logout cleanup failed:",R)),lt.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(R){console.warn("Could not set force reauth flag:",R)}window.history.replaceState({},document.title,"/");return}if(window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback")return;const F=lt.getAccessToken(),N=lt.getRefreshToken(),E=lt.getUserData(),_=F||N||E;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(),w=async()=>{if(v)try{await y()}catch(k){console.error("Silent refresh failed:",k)}else{const k=lt.getAccessToken();if(k&&_i(k,5))try{await y()}catch(C){console.error("Silent refresh failed:",C)}}},S=v?10*60*1e3:5*60*1e3,D=setInterval(w,S);return()=>clearInterval(D)},[s]),u.useEffect(()=>{if(!s||!(i!=null&&i.userId))return;const v=Xr();qc(v,i.userId);const w=S=>{console.log("📡 [Socket] Session superseded event received:",S),lt.setAuthError("SESSION_SUPERSEDED"),Y.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",w),()=>{v.off("SESSION_SUPERSEDED",w)}},[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 E,_,z,R;const w=new URLSearchParams(window.location.search);if(sessionStorage.getItem("auth_provider")==="tanflow")return;const D=sessionStorage.getItem("__logout_type__");if((w.has("logout")||w.has("tanflow_logged_out")||w.has("okta_logged_out")||D)&&!w.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const L=new URLSearchParams;(w.has("tanflow_logged_out")||D==="tanflow")&&L.set("tanflow_logged_out","true"),(w.has("okta_logged_out")||D==="okta")&&L.set("okta_logged_out","true"),w.has("logout")&&L.set("logout",w.get("logout")||Date.now().toString());const V=L.toString()?`/?${L.toString()}`:"/?logout="+Date.now();window.location.replace(V);return}p.current=!0;const C=w.get("code"),F=w.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(!C){n(!1),sessionStorage.removeItem("auth_provider");return}const N=sessionStorage.getItem("__okta_auth_code_consumed__");if(N&&N===C){c(new Error("Authorization code already used. Please login again.")),n(!1),sessionStorage.removeItem("auth_provider");return}if(x.current!==C){x.current=C,sessionStorage.setItem("__okta_auth_code_consumed__",C);try{n(!0),a(!1),c(null);const L=lc(),V=await yv(C,L);l(V.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(L){console.error("❌ Token exchange error in AuthContext:",L);const V=String(((_=(E=L==null?void 0:L.response)==null?void 0:E.data)==null?void 0:_.error)||"").toUpperCase(),I=String(((R=(z=L==null?void 0:L.response)==null?void 0:z.data)==null?void 0:R.message)||(L==null?void 0:L.message)||"").toLowerCase();if(V==="RELOGIN_REQUIRED"||I.includes("invalid or has expired")||I.includes("invalid_grant")||I.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(L),a(!1),l(null),sessionStorage.removeItem("auth_provider"),p.current=!1}finally{n(!1)}}})()},[]);const h=async()=>{var w;if(d){n(!1);return}const v=Ln();try{if(n(!0),v){const k=lt.getUserData();try{const C=await Yn();l(C),lt.setUserData(C),a(!0)}catch(C){if(((w=C==null?void 0:C.response)==null?void 0:w.status)===401)try{await y();const F=await Yn();l(F),lt.setUserData(F),a(!0)}catch{lt.clearAll(),a(!1),l(null)}else C!=null&&C.isConnectionError?k?(l(k),a(!0)):(a(!1),l(null)):(lt.clearAll(),a(!1),l(null))}return}const S=lt.getAccessToken(),D=lt.getUserData();if(!S){a(!1),l(null),n(!1);return}if(_i(S))try{await y();const k=lt.getAccessToken();if(k&&!_i(k)){const C=lt.getUserData();if(C)l(C),a(!0);else try{const F=await Yn();l(F),lt.setUserData(F),a(!0)}catch{lt.clearAll(),a(!1),l(null)}}else lt.clearAll(),a(!1),l(null)}catch{lt.clearAll(),a(!1),l(null)}else if(D)l(D),a(!0);else try{const k=await Yn();l(k),lt.setUserData(k),a(!0)}catch{lt.clearAll(),a(!1),l(null)}}catch(S){console.error("Error checking auth status:",S),c(S),lt.clearAll(),a(!1),l(null)}finally{n(!1)}},g=async()=>{try{c(null);const{domain:v,clientId:w}=eg();if(!v||!w)throw new Error("Missing Okta configuration (VITE_OKTA_DOMAIN / VITE_OKTA_CLIENT_ID). Set them and rebuild the frontend.");const S=lc(),D="code",k="openid profile email",C=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const F=new URLSearchParams(window.location.search),N=F.has("logout")||F.has("okta_logged_out")||F.has("tanflow_logged_out"),E=sessionStorage.getItem("__force_reauth_after_logout__")==="true",_=N||E;let z=`${v}/oauth2/default/v1/authorize?client_id=${w}&redirect_uri=${encodeURIComponent(S)}&response_type=${D}&scope=${encodeURIComponent(k)}&state=${C}`;_&&(z+="&prompt=login",sessionStorage.removeItem("__force_reauth_after_logout__")),window.location.href=z}catch(v){throw c(v),v}},f=async()=>{try{const v=lt.getIdToken(),w=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 S=sessionStorage.getItem("__logout_in_progress__"),D=sessionStorage.getItem("__force_logout__"),k=sessionStorage.getItem("auth_provider");if(lt.clearAll(),S&&sessionStorage.setItem("__logout_in_progress__",S),D&&sessionStorage.setItem("__force_logout__",D),v&&lt.setIdToken(v),k&&sessionStorage.setItem("auth_provider",k),await new Promise(C=>setTimeout(C,100)),w==="tanflow"&&v){console.log("🚪 Initiating Tanflow logout...");try{Xp(v);return}catch(C){console.error("🚪 Tanflow logout error:",C)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),Jp(v||void 0)}catch(v){console.error("🚪 Logout error:",v);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const S=`${"https://reflow-uat.royalenfield.com/".trim().replace(/\/$/,"")}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(S)}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 w=lt.getAccessToken();if(w&&!_i(w))return w;try{return await y(),lt.getAccessToken()}catch{return null}},y=async()=>{const v=Ln();try{const w=await vv();if(v||w)return;throw new Error("Failed to refresh token")}catch(w){throw lt.clearAll(),a(!1),l(null),w}},j={isAuthenticated:s,isLoading:r,user:i,error:o,login:g,logout:f,getAccessTokenSilently:b,refreshTokenSilently:y};return e.jsx(tg.Provider,{value:j,children:t})}function kv({children:t}){return e.jsx(Tv,{children:t})}function xs(){const t=u.useContext(tg);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function _r(t){return(t==null?void 0:t.role)==="ADMIN"}function On(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function Vl(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Ku=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,Qu=yp,ed=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return Qu(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=Ku(m)||Ku(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 Qu(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},td="-",Dv=t=>{const s=Iv(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(td);return o[0]===""&&o.length!==1&&o.shift(),sg(o,s)||Rv(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},sg=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?sg(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(td);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Xu=/^\[(.+)\]$/,Rv=t=>{if(Xu.test(t)){const s=Xu.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Iv=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Pv(Object.entries(t.classGroups),a).forEach(([i,l])=>{dc(l,r,i,s)}),r},dc=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:Ju(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Fv(n)){dc(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{dc(l,Ju(s,i),a,r)})})},Ju=(t,s)=>{let a=t;return s.split(td).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Fv=t=>t.isThemeGetter,Pv=(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,Ev=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)}}},ag="!",_v=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(ag),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},Mv=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},Lv=t=>({cache:Ev(t.cacheSize),parseClassName:_v(t),...Dv(t)}),Ov=/\s+/,$v=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(Ov);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=Mv(m).join(":"),y=p?b+ag:b,j=y+f;if(i.includes(j))continue;i.push(j);const v=n(f,g);for(let w=0;w<v.length;++w){const S=v[w];i.push(y+S)}o=d+(o.length>0?" "+o:o)}return o};function Uv(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=rg(s))&&(r&&(r+=" "),r+=a);return r}const rg=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=rg(t[r]))&&(a&&(a+=" "),a+=s);return a};function Bv(t,...s){let a,r,n,i=l;function l(c){const d=s.reduce((m,p)=>p(m),t());return a=Lv(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=$v(c,a);return n(c,m),m}return function(){return i(Uv.apply(null,arguments))}}const Xt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},ng=/^\[(?:([a-z-]+):)?(.+)\]$/i,zv=/^\d+\/\d+$/,Vv=new Set(["px","full","screen"]),Wv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Hv=/\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$/,Gv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Yv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Kv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Qa=t=>jn(t)||Vv.has(t)||zv.test(t),or=t=>Tn(t,"length",sN),jn=t=>!!t&&!Number.isNaN(Number(t)),mo=t=>Tn(t,"number",jn),$n=t=>!!t&&Number.isInteger(Number(t)),Qv=t=>t.endsWith("%")&&jn(t.slice(0,-1)),vt=t=>ng.test(t),cr=t=>Wv.test(t),Xv=new Set(["length","size","percentage"]),Jv=t=>Tn(t,Xv,ig),Zv=t=>Tn(t,"position",ig),qv=new Set(["image","url"]),eN=t=>Tn(t,qv,rN),tN=t=>Tn(t,"",aN),Un=()=>!0,Tn=(t,s,a)=>{const r=ng.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},sN=t=>Hv.test(t)&&!Gv.test(t),ig=()=>!1,aN=t=>Yv.test(t),rN=t=>Kv.test(t),nN=()=>{const t=Xt("colors"),s=Xt("spacing"),a=Xt("blur"),r=Xt("brightness"),n=Xt("borderColor"),i=Xt("borderRadius"),l=Xt("borderSpacing"),o=Xt("borderWidth"),c=Xt("contrast"),d=Xt("grayscale"),m=Xt("hueRotate"),p=Xt("invert"),x=Xt("gap"),h=Xt("gradientColorStops"),g=Xt("gradientColorStopPositions"),f=Xt("inset"),b=Xt("margin"),y=Xt("opacity"),j=Xt("padding"),v=Xt("saturate"),w=Xt("scale"),S=Xt("sepia"),D=Xt("skew"),k=Xt("space"),C=Xt("translate"),F=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],E=()=>["auto",vt,s],_=()=>[vt,s],z=()=>["",Qa,or],R=()=>["auto",jn,vt],L=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],V=()=>["solid","dashed","dotted","double","none"],I=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],A=()=>["start","end","center","between","around","evenly","stretch"],G=()=>["","0",vt],$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],M=()=>[jn,vt];return{cacheSize:500,separator:":",theme:{colors:[Un],spacing:[Qa,or],blur:["none","",cr,vt],brightness:M(),borderColor:[t],borderRadius:["none","","full",cr,vt],borderSpacing:_(),borderWidth:z(),contrast:M(),grayscale:G(),hueRotate:M(),invert:G(),gap:_(),gradientColorStops:[t],gradientColorStopPositions:[Qv,or],inset:E(),margin:E(),opacity:M(),padding:_(),saturate:M(),scale:M(),sepia:G(),skew:M(),space:_(),translate:_()},classGroups:{aspect:[{aspect:["auto","square","video",vt]}],container:["container"],columns:[{columns:[cr]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...L(),vt]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],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,vt]}],basis:[{basis:E()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",vt]}],grow:[{grow:G()}],shrink:[{shrink:G()}],order:[{order:["first","last","none",$n,vt]}],"grid-cols":[{"grid-cols":[Un]}],"col-start-end":[{col:["auto",{span:["full",$n,vt]},vt]}],"col-start":[{"col-start":R()}],"col-end":[{"col-end":R()}],"grid-rows":[{"grid-rows":[Un]}],"row-start-end":[{row:["auto",{span:[$n,vt]},vt]}],"row-start":[{"row-start":R()}],"row-end":[{"row-end":R()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",vt]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",vt]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...A()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...A(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...A(),"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",vt,s]}],"min-w":[{"min-w":[vt,s,"min","max","fit"]}],"max-w":[{"max-w":[vt,s,"none","full","min","max","fit","prose",{screen:[cr]},cr]}],h:[{h:[vt,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[vt,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[vt,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[vt,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",mo]}],"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",vt]}],"line-clamp":[{"line-clamp":["none",jn,mo]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Qa,vt]}],"list-image":[{"list-image":["none",vt]}],"list-style-type":[{list:["none","disc","decimal",vt]}],"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:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Qa,or]}],"underline-offset":[{"underline-offset":["auto",Qa,vt]}],"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",vt]}],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",vt]}],"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:[...L(),Zv]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Jv]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eN]}],"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:[...V(),"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:V()}],"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:["",...V()]}],"outline-offset":[{"outline-offset":[Qa,vt]}],"outline-w":[{outline:[Qa,or]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[Qa,or]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",cr,tN]}],"shadow-color":[{shadow:[Un]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...I(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":I()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",cr,vt]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[v]}],sepia:[{sepia:[S]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[v]}],"backdrop-sepia":[{"backdrop-sepia":[S]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",vt]}],duration:[{duration:M()}],ease:[{ease:["linear","in","out","in-out",vt]}],delay:[{delay:M()}],animate:[{animate:["none","spin","ping","pulse","bounce",vt]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[w]}],"scale-x":[{"scale-x":[w]}],"scale-y":[{"scale-y":[w]}],rotate:[{rotate:[$n,vt]}],"translate-x":[{"translate-x":[C]}],"translate-y":[{"translate-y":[C]}],"skew-x":[{"skew-x":[D]}],"skew-y":[{"skew-y":[D]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",vt]}],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",vt]}],"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",vt]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Qa,or,mo]}],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"]}}},iN=Bv(nN);function Oe(...t){return iN(yp(t))}const oi=ed("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?dp:"button";return e.jsx(l,{"data-slot":"button",className:Oe(oi({variant:s,size:a,className:t})),ref:i,...n})});O.displayName="Button";function q({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:Oe("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function me({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:Oe("@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:Oe("leading-none",t),...s})}function Se({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:Oe("text-muted-foreground",t),...s})}function se({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:Oe("px-6 [&:last-child]:pb-6",t),...s})}const Wl="/assets/Re_Logo-By51taPS.png",Zu="/assets/landing_page_image-ClTD-4qZ.jpg";function lN(){var g,f;const{login:t,isLoading:s,error:a}=xs(),{domain:r,clientId:n}=eg(),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=Zu,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{fv()}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(${Zu})`:"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(q,{className:"w-full max-w-md shadow-2xl relative z-10 bg-gray-900/95 border border-gray-700 text-white",children:[e.jsx(me,{className:"space-y-1 text-center pb-6 pt-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Wl,alt:"Royal Enfield",className:"h-9 w-auto max-w-[180px] object-contain mb-2"}),e.jsx("p",{className:"text-sm text-gray-400",children:"Approval Portal"})]})}),e.jsxs(se,{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(vs,{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(js,{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 lg(){const{isAuthenticated:t,isLoading:s,error:a,user:r,login:n}=xs(),[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:Wl,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:i==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(tt,{className:"w-16 h-16 text-red-500"})}),e.jsx(tt,{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(gs,{className:"w-16 h-16 text-green-500"})}),e.jsx(gs,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(We,{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 oN(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=xs(),[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 w=await bv(b,y||"");sessionStorage.removeItem("tanflow_auth_state"),i("fetching");const S=w.user||await Yn();if(S)lt.setUserData(S),i("complete"),setTimeout(()=>{window.history.replaceState({},document.title,"/"),window.location.href="/"},1e3);else throw new Error("User data not received")}catch(w){console.error("Tanflow callback error:",w),i("error"),o(w.message||"Authentication failed"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state")}})()},[]);const d=()=>{switch(n){case"exchanging":return"Exchanging authorization code...";case"fetching":return"Fetching your profile...";case"complete":return"Authentication successful!";case"error":return"Authentication failed";default:return"Completing authentication..."}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"}),e.jsxs("div",{className:"relative z-10 text-center px-4 max-w-md w-full",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Wl,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:n==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(tt,{className:"w-16 h-16 text-red-500"})}),e.jsx(tt,{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(gs,{className:"w-16 h-16 text-green-500"})}),e.jsx(gs,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(We,{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 cN=ed("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 le({className:t,variant:s,asChild:a=!1,...r}){const n=a?dp:"span";return e.jsx(n,{"data-slot":"badge",className:Oe(cN({variant:s}),t),...r})}function dN({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=pv();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(q,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Authentication Debug Information"}),e.jsx(O,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(Nt,{className:"h-4 w-4"})})]})}),e.jsxs(se,{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(le,{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 ms=u.forwardRef(({className:t,...s},a)=>e.jsx(mp,{ref:a,"data-slot":"avatar",className:Oe("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));ms.displayName=mp.displayName;const Hl=u.forwardRef(({className:t,...s},a)=>e.jsx(up,{ref:a,"data-slot":"avatar-image",className:Oe("aspect-square size-full",t),...s}));Hl.displayName=up.displayName;const us=u.forwardRef(({className:t,...s},a)=>e.jsx(xp,{ref:a,"data-slot":"avatar-fallback",className:Oe("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));us.displayName=xp.displayName;function qu({...t}){return e.jsx(Eb,{"data-slot":"dropdown-menu",...t})}function ex({...t}){return e.jsx(_b,{"data-slot":"dropdown-menu-trigger",...t})}function tx({className:t,sideOffset:s=4,...a}){return e.jsx(Mb,{children:e.jsx(Lb,{"data-slot":"dropdown-menu-content",sideOffset:s,className:Oe("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 uo({className:t,inset:s,variant:a="default",...r}){return e.jsx(Ob,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:Oe("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 og({...t}){return e.jsx(Ub,{"data-slot":"alert-dialog",...t})}function mN({...t}){return e.jsx($b,{"data-slot":"alert-dialog-portal",...t})}const cg=u.forwardRef(({className:t,...s},a)=>e.jsx(hp,{"data-slot":"alert-dialog-overlay",className:Oe("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}));cg.displayName=hp.displayName;const sd=u.forwardRef(({className:t,...s},a)=>e.jsxs(mN,{children:[e.jsx(cg,{}),e.jsx(pp,{"data-slot":"alert-dialog-content",ref:a,className:Oe("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})]}));sd.displayName=pp.displayName;function dg({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:Oe("flex flex-col gap-2 text-center sm:text-left",t),...s})}function mg({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:Oe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function ug({className:t,...s}){return e.jsx(Bb,{"data-slot":"alert-dialog-title",className:Oe("text-lg font-semibold",t),...s})}function xg({className:t,...s}){return e.jsx(zb,{"data-slot":"alert-dialog-description",className:Oe("text-muted-foreground text-sm",t),...s})}function hg({className:t,...s}){return e.jsx(Wb,{className:Oe(oi(),t),...s})}function pg({className:t,...s}){return e.jsx(Vb,{className:Oe(oi({variant:"outline"}),t),...s})}const hr={async list(t){return(await we.get("/notifications",{params:t})).data},async getUnreadCount(){return(await we.get("/notifications/unread-count")).data},async markAsRead(t){return(await we.patch(`/notifications/${t}/read`)).data},async markAllAsRead(){return(await we.post("/notifications/mark-all-read")).data},async delete(t){return(await we.delete(`/notifications/${t}`)).data}},uN=async()=>(await we.get("/notifications/subscriptions")).data.data.subscriptions,sx="https://reflow-uat.royalenfield.com/api/v1".trim(),xN=typeof window<"u"&&/^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname),gg=(!xN&&/localhost:5000/i.test(sx)?"":sx.replace(/\/$/,""))||"/api/v1";async function fg(t,s={}){const a=lt.getAccessToken(),r={...s.headers||{}};s.body instanceof FormData||(r["Content-Type"]="application/json"),a&&(r.Authorization=`Bearer ${a}`);const n=await fetch(`${gg}${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 ad(){var a;const t=await we.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 hN(){const{data:t}=await we.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 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/credit-notes?${a}`:"/form16/credit-notes",{data:n}=await we.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 jg(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 we.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 yg(t){const{data:s}=await we.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 rd(t){const{data:s}=await we.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 vg(t){const{data:s}=await we.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 pN(t){await we.post(`/form16/requests/${encodeURIComponent(t)}/cancel-submission`)}async function gN(t){await we.post(`/form16/requests/${encodeURIComponent(t)}/resubmission-needed`)}async function ax(t){const{data:s}=await we.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 fN(t){const s=new FormData;s.append("document",t);const a=await fg("/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 bN(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 fg("/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 jN(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 we.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 yN(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 we.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 vN=5*60*1e3;function NN(t,s){return new Promise((a,r)=>{const n=new FormData;n.append("file",t);const i=new XMLHttpRequest,l=`${gg}/form16/26as/upload`,o=lt.getAccessToken(),c=setTimeout(()=>{i.abort(),r(new Error("Upload timed out. Try a smaller file or try again."))},vN);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 wN(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 we.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 CN(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 we.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 SN(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 we.get(r),i=(n==null?void 0:n.data)??n;return Array.isArray(i)?i:[]}async function Ng(){const{data:t}=await we.get("/form16/dealer/pending-quarters"),s=(t==null?void 0:t.data)??t;return Array.isArray(s)?s:[]}async function wg(){var r;const t=await we.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,w]=u.useState(null),[S,D]=u.useState(null),{user:k}=xs(),C=u.useMemo(()=>{try{const U=lt.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",N=()=>{var U,H;try{if(k!=null&&k.displayName&&typeof k.displayName=="string"){const W=k.displayName.split(" ").filter(Boolean);return W.length>=2?`${((U=W[0])==null?void 0:U[0])||""}${((H=W[W.length-1])==null?void 0:H[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(W){return console.error("[PageLayout] Error getting user initials:",W),"U"}},E=u.useMemo(()=>{const U=[{id:"dashboard",label:"Dashboard",icon:Ou},{id:"requests",label:"All Requests",icon:sc,adminOnly:!1}];return C||U.push({id:"my-requests",label:"My Requests",icon:Ht}),U.push({id:"open-requests",label:"Open Requests",icon:Pe},{id:"closed-requests",label:"Closed Requests",icon:He},{id:"shared-summaries",label:"Shared Summary",icon:Sn}),U},[C,F]);u.useEffect(()=>{if(!(k!=null&&k.userId)){w(null);return}let U=!0;return ad().then(H=>{U&&w(H)}).catch(H=>{U&&(w({canViewForm16Submission:!1,canView26AS:!1}),console.warn("[PageLayout] Form 16 permissions could not be loaded Form 16 menu will be hidden.",H))}),()=>{U=!1}},[k==null?void 0:k.userId]),u.useEffect(()=>{if(!(k!=null&&k.userId)){D(null);return}let U=!0;return wg().then(H=>{U&&D(H)}).catch(H=>{U&&(D({canViewCpcCsd:!1}),console.warn("[PageLayout] CPC-CSD permissions could not be loaded CPC-CSD menu will be hidden.",H))}),()=>{U=!1}},[k==null?void 0:k.userId]);const _=!!v&&(C?!!v.canViewForm16Submission:!!v.canView26AS),z=!!(v!=null&&v.canViewForm16Submission),R=!!(v!=null&&v.canView26AS),L=!!(S!=null&&S.canViewCpcCsd),V=s==="form16-credit-notes"||s==="form16-debit-notes"||s==="form16-transactions"||s==="form16-submit"||s==="form16-pending-submissions"||s==="form16-dashboard"||s==="form16-26as"||s==="form16-non-submitted-dealers",I=o||V,A=!!(s!=null&&s.startsWith("cpc-csd"))||!!(s!=null&&s.startsWith("cpc-cdc")),G=d||A,$=()=>{l(!i)},M=async U=>{var H;try{if(U.isRead||(await hr.markAsRead(U.notificationId),g(W=>W.map(P=>P.notificationId===U.notificationId?{...P,isRead:!0}:P)),b(W=>Math.max(0,W-1))),U.actionUrl&&a){const W=(H=U.metadata)==null?void 0:H.requestNumber;if(W){let P=`request/${W}`;(U.notificationType==="mention"||U.notificationType==="comment"||U.notificationType==="worknote")&&(P+="?tab=worknotes"),a(P)}}j(!1)}catch(W){console.error("[PageLayout] Error handling notification click:",W)}},T=async()=>{try{await hr.markAllAsRead(),g(U=>U.map(H=>({...H,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 H=!0;(async()=>{var B,K;try{const Z=await hr.list({page:1,limit:4,unreadOnly:!1});if(!H)return;const te=((B=Z.data)==null?void 0:B.notifications)||[];g(te),b(((K=Z.data)==null?void 0:K.unreadCount)||0)}catch(Z){console.error("[PageLayout] Failed to fetch notifications:",Z)}})();const P=Xr();if(P){qc(P,U);const B=K=>{H&&(g(Z=>[K.notification,...Z].slice(0,4)),b(Z=>Z+1))};return P.on("notification:new",B),()=>{H=!1,P.off("notification:new",B)}}return()=>{H=!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:Wl,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain"}),e.jsx("p",{className:"text-xs text-gray-400 text-center mt-1 truncate",children:"RE Flow"})]})}),e.jsxs("div",{className:"p-3 flex-1 overflow-y-auto",children:[e.jsxs("div",{className:"space-y-2",children:[E.filter(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(!I),className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${V?"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"}),I?e.jsx(Qr,{className:"w-4 h-4 shrink-0"}):e.jsx(Wa,{className:"w-4 h-4 shrink-0"})]}),I&&e.jsx("div",{className:"mt-1 ml-4 pl-2 border-l border-gray-700 space-y-0.5",children:C?e.jsx(e.Fragment,{children:z&&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(Pe,{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(Pe,{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:[R&&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(Pe,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Form16A Dashboard"})]}),R&&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(Pe,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"26AS Management"})]}),z&&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"})]})]})]})})]}),L&&e.jsxs("div",{className:"pt-2 border-t border-gray-800",children:[e.jsxs("button",{type:"button",onClick:()=>m(!G),className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${A?"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"}),G?e.jsx(Qr,{className:"w-4 h-4 shrink-0"}):e.jsx(Wa,{className:"w-4 h-4 shrink-0"})]}),G&&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(Ou,{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(sc,{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(tt,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Rejected Docs"})]})]})]})]}),!C&&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(os,{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:$,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(Kj,{className:"w-5 h-5 text-gray-600"}):e.jsx(Qj,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[!C&&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(os,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(qu,{open:y,onOpenChange:j,children:[e.jsx(ex,{asChild:!0,children:e.jsxs(O,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx($s,{className:"w-5 h-5"}),f>0&&e.jsx(le,{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(tx,{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(),T()},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($s,{className:"w-12 h-12 text-gray-300 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No notifications yet"})]}):e.jsx("div",{className:"divide-y",children:h.map(U=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${U.isRead?"":"bg-blue-50"}`,onClick:()=>M(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:Cp(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(qu,{children:[e.jsx(ex,{asChild:!0,children:e.jsxs(ms,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Hl,{src:(k==null?void 0:k.picture)||""}),e.jsx(us,{className:"bg-re-green text-white text-sm",children:N()})]})}),e.jsxs(tx,{align:"end",children:[e.jsxs(uo,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(Ht,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(uo,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(pr,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(uo,{onClick:()=>x(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(no,{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(og,{open:p,onOpenChange:x,children:e.jsxs(sd,{children:[e.jsxs(dg,{children:[e.jsxs(ug,{className:"flex items-center gap-2",children:[e.jsx(no,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(xg,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(mg,{children:[e.jsx(pg,{onClick:()=>x(!1),children:"Cancel"}),e.jsxs(hg,{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(no,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const vi=()=>iv(),kn=cv,AN=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},TN={viewAsUser:AN()},Cg=An({name:"dashboard",initialState:TN,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:kN}=Cg.actions;function DN(){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 RN(){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 IN{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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 we.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 Ut=new IN;function FN({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,w]=u.useState(null),[S,D]=u.useState([]),[k,C]=u.useState(!0),[F,N]=u.useState(!1),E=u.useRef(l);E.current=l;const _=u.useCallback(async(I=!1)=>{try{I?N(!0):C(!0);const A=[Ut.getKPIs(r,n,i,s),Ut.getRecentActivity(1,10,s),Ut.getCriticalRequests(1,10,s),Ut.getUpcomingDeadlines(1,10,s)],G=!t&&a?Ut.getRequestStats(r,n==null?void 0:n.toISOString(),i==null?void 0:i.toISOString(),void 0,void 0,void 0,void 0,a,void 0,void 0,void 0,void 0,s):null,$=t?[Ut.getDepartmentStats(r,n,i),Ut.getPriorityDistribution(r,n,i),Ut.getAIRemarkUtilization(r,n,i),Ut.getApproverPerformance(r,1,10,n,i)]:[],[M,T,U]=await Promise.all([Promise.all(A),G,Promise.all($)]),H=M[0],W=M[1],P=M[2],B=M[3];if(!t&&T&&(H.requestVolume=T),c(H),m(W.activities),E.current.activity(W.pagination.currentPage,W.pagination.totalPages,W.pagination.totalRecords),x(P.criticalRequests),E.current.critical(P.pagination.currentPage,P.pagination.totalPages,P.pagination.totalRecords),j(B.deadlines),E.current.deadlines(B.pagination.currentPage,B.pagination.totalPages,B.pagination.totalRecords),t&&U.length>=4){const K=U[0],Z=U[1],te=U[2],ae=U[3];g(K),b(Z),w(te),D(ae.performance),E.current.approver(ae.pagination.currentPage,ae.pagination.totalPages,ae.pagination.totalRecords)}else t||(g([]),b([]),w(null),D([]))}catch(A){console.error("Failed to fetch dashboard data:",A)}finally{C(!1),N(!1)}},[t,s,a,r,n,i]),z=u.useCallback(async(I=1)=>{try{const A=await Ut.getRecentActivity(I,10,s);m(A.activities),E.current.activity(A.pagination.currentPage,A.pagination.totalPages,A.pagination.totalRecords)}catch(A){console.error("Failed to fetch recent activities:",A)}},[s]),R=u.useCallback(async(I=1)=>{try{const A=await Ut.getCriticalRequests(I,10,s);x(A.criticalRequests),E.current.critical(A.pagination.currentPage,A.pagination.totalPages,A.pagination.totalRecords)}catch(A){console.error("Failed to fetch critical requests:",A)}},[s]),L=u.useCallback(async(I=1)=>{try{const A=await Ut.getUpcomingDeadlines(I,10,s);j(A.deadlines),E.current.deadlines(A.pagination.currentPage,A.pagination.totalPages,A.pagination.totalRecords)}catch(A){console.error("Failed to fetch upcoming deadlines:",A)}},[s]),V=u.useCallback(async(I=1)=>{try{const A=await Ut.getApproverPerformance(r,I,10,n,i);D(A.performance),E.current.approver(A.pagination.currentPage,A.pagination.totalPages,A.pagination.totalRecords)}catch(A){console.error("Failed to fetch approver performance:",A)}},[r,n,i]);return{kpis:o,recentActivity:d,criticalRequests:p,departmentStats:h,priorityDistribution:f,upcomingDeadlines:y,aiRemarkUtilization:v,approverPerformance:S,loading:k,refreshing:F,fetchDashboardData:_,fetchRecentActivities:z,fetchCriticalRequests:R,fetchUpcomingDeadlines:L,fetchApproverPerformance:V}}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 PN{constructor(){to(this,"config",null);to(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 we.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 EN=new PN;let _N=9,MN=18,LN=1,ON=5,rx=!1;async function $N(){if(!rx)try{const t=await EN.getConfig();_N=t.workingHours.START_HOUR,MN=t.workingHours.END_HOUR,LN=t.workingHours.START_DAY,ON=t.workingHours.END_DAY,rx=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}$N().catch(()=>{});function Jt(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 UN(t,s,a){const r=[];let n=1,i=!0;const l=100;for(;i&&n<=l;){const x=await Ut.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,Jt(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 BN(t,s,a){const r=await Ut.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 zN(){const[t,s]=u.useState(!1),[a,r]=u.useState(!1),n=u.useCallback(async(l,o,c)=>{try{s(!0),await BN(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 UN(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 ds({className:t,...s}){return e.jsx(Hb,{"data-slot":"switch",className:Oe("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(Gb,{"data-slot":"switch-thumb",className:Oe("bg-card dark:data-[state=unchecked]:bg-card-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}function ne({className:t,...s}){return e.jsx(Yb,{"data-slot":"label",className:Oe("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 VN({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(q,{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(se,{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(zc,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(ne,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-gray-300":"text-red-600"}`,children:"Org"})]}),e.jsx(ds,{id:"view-toggle-switch",checked:a,onCheckedChange:r,className:"data-[state=checked]:bg-red-600 data-[state=unchecked]:bg-gray-600 shrink-0 scale-90 sm:scale-100","data-testid":"view-toggle-switch"}),e.jsxs("div",{className:`flex items-center gap-1 sm:gap-1.5 px-1.5 sm:px-2 py-0.5 sm:py-1 rounded transition-all cursor-pointer ${a?"bg-red-600/20 border border-red-600/50":"opacity-60 hover:opacity-80"}`,onClick:()=>r(!0),children:[e.jsx(Ht,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(ne,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-red-600":"text-gray-300"}`,children:"Personal"})]})]})}),e.jsx("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 sm:gap-6",children:e.jsxs("div",{className:`text-white w-full lg:w-auto ${t?"pt-12 sm:pt-0":""}`,children:[e.jsx("div",{className:"flex items-center gap-3 sm:gap-4 mb-4 sm:mb-6",children:e.jsxs("div",{className:"pr-2 sm:pr-0",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl lg:text-4xl font-bold mb-1 sm:mb-2 text-white","data-testid":"hero-title",children:["Welcome, ",o,"!"]}),e.jsx("p",{className:"text-sm sm:text-lg lg:text-xl text-gray-200","data-testid":"hero-subtitle",children:s?"Organization-wide analytics and insights":"Track your requests and approvals"})]})}),e.jsx("div",{className:"flex flex-wrap gap-2 sm:gap-4 mt-4 sm:mt-8","data-testid":"quick-actions",children:n.map((c,d)=>e.jsxs(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 Ke({...t}){return e.jsx(Kb,{"data-slot":"select",...t})}function Qe({...t}){return e.jsx(Jb,{"data-slot":"select-value",...t})}function Xe({className:t,size:s="default",children:a,...r}){return e.jsxs(Qb,{"data-slot":"select-trigger","data-size":s,className:Oe("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(Xb,{asChild:!0,children:e.jsx(Qr,{className:"size-4 opacity-50"})})]})}function Je({className:t,children:s,position:a="popper",...r}){return e.jsx(Zb,{children:e.jsxs(qb,{"data-slot":"select-content",className:Oe("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(WN,{}),e.jsx(ej,{className:Oe("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(HN,{})]})})}function J({className:t,children:s,...a}){return e.jsxs(tj,{"data-slot":"select-item",className:Oe("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(sj,{children:e.jsx(Ha,{className:"size-4"})})}),e.jsx(aj,{children:s})]})}function WN({className:t,...s}){return e.jsx(rj,{"data-slot":"select-scroll-up-button",className:Oe("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Dl,{className:"size-4"})})}function HN({className:t,...s}){return e.jsx(nj,{"data-slot":"select-scroll-down-button",className:Oe("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Qr,{className:"size-4"})})}function qt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(ij,{"data-slot":"separator-root",decorative:a,orientation:s,className:Oe("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",t),...r})}function ra({...t}){return e.jsx(lj,{"data-slot":"popover",...t})}function na({...t}){return e.jsx(oj,{"data-slot":"popover-trigger",...t})}function ia({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(cj,{children:e.jsx(dj,{"data-slot":"popover-content",align:s,sideOffset:a,className:Oe("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 ut=function(){return ut=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},ut.apply(this,arguments)};function GN(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 Sg(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 Ni(t){return t.mode==="multiple"}function wi(t){return t.mode==="range"}function Gl(t){return t.mode==="single"}var YN={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 KN(t,s){return it(t,"LLLL y",s)}function QN(t,s){return it(t,"d",s)}function XN(t,s){return it(t,"LLLL",s)}function JN(t){return"".concat(t)}function ZN(t,s){return it(t,"cccccc",s)}function qN(t,s){return it(t,"yyyy",s)}var ew=Object.freeze({__proto__:null,formatCaption:KN,formatDay:QN,formatMonthCaption:XN,formatWeekNumber:JN,formatWeekdayName:ZN,formatYearCaption:qN}),tw=function(t,s,a){return it(t,"do MMMM (EEEE)",a)},sw=function(){return"Month: "},aw=function(){return"Go to next month"},rw=function(){return"Go to previous month"},nw=function(t,s){return it(t,"cccc",s)},iw=function(t){return"Week n. ".concat(t)},lw=function(){return"Year: "},ow=Object.freeze({__proto__:null,labelDay:tw,labelMonthDropdown:sw,labelNext:aw,labelPrevious:rw,labelWeekNumber:iw,labelWeekday:nw,labelYearDropdown:lw});function cw(){var t="buttons",s=YN,a=_j,r={},n={},i=1,l={},o=new Date;return{captionLayout:t,classNames:s,formatters:ew,labels:ow,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:l,today:o,mode:"default"}}function dw(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,l=t.toDate;return r?i=xa(r):s&&(i=new Date(s,0,1)),n?l=Oc(n):a&&(l=new Date(a,11,31)),{fromDate:i?Mu(i):void 0,toDate:l?Mu(l):void 0}}var Ag=u.createContext(void 0);function mw(t){var s,a=t.initialProps,r=cw(),n=dw(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;(Gl(a)||Ni(a)||wi(a))&&(c=a.onSelect);var d=ut(ut(ut({},r),a),{captionLayout:o,classNames:ut(ut({},r.classNames),a.classNames),components:ut({},a.components),formatters:ut(ut({},r.formatters),a.formatters),fromDate:i,labels:ut(ut({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:ut(ut({},r.modifiers),a.modifiers),modifiersClassNames:ut(ut({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:ut(ut({},r.styles),a.styles),toDate:l});return e.jsx(Ag.Provider,{value:d,children:t.children})}function Kt(){var t=u.useContext(Ag);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function Tg(t){var s=Kt(),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 uw(t){return e.jsx("svg",ut({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 kg(t){var s,a,r=t.onChange,n=t.value,i=t.children,l=t.caption,o=t.className,c=t.style,d=Kt(),m=(a=(s=d.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:uw;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 xw(t){var s,a=Kt(),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(Bj(r,n))for(var x=xa(r),h=r.getMonth();h<=n.getMonth();h++)p.push(ao(x,h));else for(var x=xa(new Date),h=0;h<=11;h++)p.push(ao(x,h));var g=function(b){var y=Number(b.target.value),j=ao(xa(t.displayMonth),y);t.onChange(j)},f=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:kg;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 hw(t){var s,a=t.displayMonth,r=Kt(),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(Lu(zj(new Date),f));var b=function(j){var v=Lu(xa(a),Number(j.target.value));t.onChange(v)},y=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:kg;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 pw(t,s){var a=u.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function gw(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&&ni(i,n)<0){var d=-1*(c-1);n=Va(i,d)}return l&&ni(n,l)<0&&(n=l),xa(n)}function fw(){var t=Kt(),s=gw(t),a=pw(s,t.month),r=a[0],n=a[1],i=function(l){var o;if(!t.disableNavigation){var c=xa(l);n(c),(o=t.onMonthChange)===null||o===void 0||o.call(t,c)}};return[r,i]}function bw(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=xa(t),i=xa(Va(n,r)),l=ni(i,n),o=[],c=0;c<l;c++){var d=Va(n,c);o.push(d)}return a&&(o=o.reverse()),o}function jw(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=xa(t);if(!a)return Va(o,l);var c=ni(a,t);if(!(c<i))return Va(o,l)}}function yw(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=xa(t);if(!a)return Va(o,-l);var c=ni(o,a);if(!(c<=0))return Va(o,-l)}}var Dg=u.createContext(void 0);function vw(t){var s=Kt(),a=fw(),r=a[0],n=a[1],i=bw(r,s),l=jw(r,s),o=yw(r,s),c=function(p){return i.some(function(x){return $c(p,x)})},d=function(p,x){c(p)||(x&&Sp(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(Dg.Provider,{value:m,children:t.children})}function Ci(){var t=u.useContext(Dg);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function nx(t){var s,a=Kt(),r=a.classNames,n=a.styles,i=a.components,l=Ci().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:Tg,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(xw,{onChange:o,displayMonth:t.displayMonth}),e.jsx(hw,{onChange:o,displayMonth:t.displayMonth})]})}function Nw(t){return e.jsx("svg",ut({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 ww(t){return e.jsx("svg",ut({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 pl=u.forwardRef(function(t,s){var a=Kt(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var l=i.join(" "),o=ut(ut({},n.button_reset),n.button);return t.style&&Object.assign(o,t.style),e.jsx("button",ut({},t,{ref:s,type:"button",className:l,style:o}))});function Cw(t){var s,a,r=Kt(),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:ww,y=(a=p==null?void 0:p.IconLeft)!==null&&a!==void 0?a:Nw;return e.jsxs("div",{className:l.nav,style:o.nav,children:[!t.hidePrevious&&e.jsx(pl,{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(pl,{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 ix(t){var s=Kt().numberOfMonths,a=Ci(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,l=a.displayMonths,o=l.findIndex(function(g){return $c(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(Cw,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:p,nextMonth:n,previousMonth:r,onPreviousClick:x,onNextClick:h})}function Sw(t){var s,a=Kt(),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:Tg,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):l==="dropdown"?d=e.jsx(nx,{displayMonth:t.displayMonth,id:t.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(nx,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(ix,{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(ix,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function Aw(t){var s=Kt(),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 Tw(t,s,a){for(var r=a?Uc(new Date):Bc(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var l=ca(r,i);n.push(l)}return n}function kw(){var t=Kt(),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=Tw(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 Dw(){var t,s=Kt(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:kw;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function Rw(t){var s=Kt(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var nd=u.createContext(void 0);function Iw(t){if(!Ni(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(nd.Provider,{value:s,children:t.children})}return e.jsx(Fw,{initialProps:t.initialProps,children:t.children})}function Fw(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?Sg([],r):[];if(m.selected){var y=b.findIndex(function(j){return ta(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 ta(x,d)});return!!(m&&!p)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(nd.Provider,{value:c,children:a})}function id(){var t=u.useContext(nd);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function Pw(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?ta(n,t)&&ta(r,t)?void 0:ta(n,t)?{from:n,to:void 0}:ta(r,t)?void 0:tc(r,t)?{from:t,to:n}:{from:r,to:t}:n?tc(t,n)?{from:n,to:t}:{from:t,to:n}:r?Sp(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var ld=u.createContext(void 0);function Ew(t){if(!wi(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(ld.Provider,{value:s,children:t.children})}return e.jsx(_w,{initialProps:t.initialProps,children:t.children})}function _w(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=Pw(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],ta(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:so(i,o-1),before:ca(i,o-1)}),i&&l&&m.disabled.push({after:i,before:ca(i,o-1)}),!i&&l&&m.disabled.push({after:so(l,o-1),before:ca(l,o-1)})),c){if(i&&!l&&(m.disabled.push({before:ca(i,-c+1)}),m.disabled.push({after:ca(i,c-1)})),i&&l){var p=Za(l,i)+1,x=c-p;m.disabled.push({before:so(i,x)}),m.disabled.push({after:ca(l,x)})}!i&&l&&(m.disabled.push({before:ca(l,-c+1)}),m.disabled.push({after:ca(l,c-1)}))}return e.jsx(ld.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function od(){var t=u.useContext(ld);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function Xi(t){return Array.isArray(t)?Sg([],t):t!==void 0?[t]:[]}function Mw(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=Xi(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 Lw=Ea.Selected,Ja=Ea.Disabled,Ow=Ea.Hidden,$w=Ea.Today,xo=Ea.RangeEnd,ho=Ea.RangeMiddle,po=Ea.RangeStart,Uw=Ea.Outside;function Bw(t,s,a){var r,n=(r={},r[Lw]=Xi(t.selected),r[Ja]=Xi(t.disabled),r[Ow]=Xi(t.hidden),r[$w]=[t.today],r[xo]=[],r[ho]=[],r[po]=[],r[Uw]=[],r);return t.fromDate&&n[Ja].push({before:t.fromDate}),t.toDate&&n[Ja].push({after:t.toDate}),Ni(t)?n[Ja]=n[Ja].concat(s.modifiers[Ja]):wi(t)&&(n[Ja]=n[Ja].concat(a.modifiers[Ja]),n[po]=a.modifiers[po],n[ho]=a.modifiers[ho],n[xo]=a.modifiers[xo]),n}var Rg=u.createContext(void 0);function zw(t){var s=Kt(),a=id(),r=od(),n=Bw(s,a,r),i=Mw(s.modifiers),l=ut(ut({},n),i);return e.jsx(Rg.Provider,{value:l,children:t.children})}function Ig(){var t=u.useContext(Rg);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function Vw(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function Ww(t){return!!(t&&typeof t=="object"&&"from"in t)}function Hw(t){return!!(t&&typeof t=="object"&&"after"in t)}function Gw(t){return!!(t&&typeof t=="object"&&"before"in t)}function Yw(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function Kw(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?ta(n,t):r?ta(r,t):!1}function Qw(t){return kp(t)}function Xw(t){return Array.isArray(t)&&t.every(kp)}function Jw(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(Qw(a))return ta(t,a);if(Xw(a))return a.includes(t);if(Ww(a))return Kw(t,a);if(Yw(a))return a.dayOfWeek.includes(t.getDay());if(Vw(a)){var r=Za(a.before,t),n=Za(a.after,t),i=r>0,l=n<0,o=tc(a.before,a.after);return o?l&&i:i||l}return Hw(a)?Za(t,a.after)>0:Gw(a)?Za(a.before,t)>0:typeof a=="function"?a(t):!1})}function cd(t,s,a){var r=Object.keys(s).reduce(function(i,l){var o=s[l];return Jw(t,o)&&i.push(l),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!$c(t,a)&&(n.outside=!0),n}function Zw(t,s){for(var a=xa(t[0]),r=Oc(t[t.length-1]),n,i,l=a;l<=r;){var o=cd(l,s),c=!o.disabled&&!o.hidden;if(!c){l=ca(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),n||(n=l),l=ca(l,1)}return i||n}var qw=365;function Fg(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:ca,week:ec,month:Va,year:Oj,startOfWeek:function(b){return n.ISOWeek?Uc(b):Bc(b,{locale:p,weekStartsOn:c})},endOfWeek:function(b){return n.ISOWeek?Ap(b):Tp(b,{locale:p,weekStartsOn:c})}},h=x[a](t,r==="after"?1:-1);r==="before"&&d?h=$j([d,h]):r==="after"&&m&&(h=Uj([m,h]));var g=!0;if(i){var f=cd(h,i);g=!f.disabled&&!f.hidden}return g?h:o.count>qw?o.lastFocused:Fg(h,{moveBy:a,direction:r,context:n,modifiers:i,retry:ut(ut({},o),{count:o.count+1})})}var Pg=u.createContext(void 0);function e1(t){var s=Ci(),a=Ig(),r=u.useState(),n=r[0],i=r[1],l=u.useState(),o=l[0],c=l[1],d=Zw(s.displayMonths,a),m=n??(o&&s.isDateDisplayed(o))?o:d,p=function(){c(n),i(void 0)},x=function(b){i(b)},h=Kt(),g=function(b,y){if(n){var j=Fg(n,{moveBy:b,direction:y,context:h,modifiers:a});ta(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(Pg.Provider,{value:f,children:t.children})}function dd(){var t=u.useContext(Pg);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function t1(t,s){var a=Ig(),r=cd(t,a,s);return r}var md=u.createContext(void 0);function s1(t){if(!Gl(t.initialProps)){var s={selected:void 0};return e.jsx(md.Provider,{value:s,children:t.children})}return e.jsx(a1,{initialProps:t.initialProps,children:t.children})}function a1(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(md.Provider,{value:n,children:a})}function Eg(){var t=u.useContext(md);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function r1(t,s){var a=Kt(),r=Eg(),n=id(),i=od(),l=dd(),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(I){var A,G,$,M;Gl(a)?(A=r.onDayClick)===null||A===void 0||A.call(r,t,s,I):Ni(a)?(G=n.onDayClick)===null||G===void 0||G.call(n,t,s,I):wi(a)?($=i.onDayClick)===null||$===void 0||$.call(i,t,s,I):(M=a.onDayClick)===null||M===void 0||M.call(a,t,s,I)},w=function(I){var A;x(t),(A=a.onDayFocus)===null||A===void 0||A.call(a,t,s,I)},S=function(I){var A;p(),(A=a.onDayBlur)===null||A===void 0||A.call(a,t,s,I)},D=function(I){var A;(A=a.onDayMouseEnter)===null||A===void 0||A.call(a,t,s,I)},k=function(I){var A;(A=a.onDayMouseLeave)===null||A===void 0||A.call(a,t,s,I)},C=function(I){var A;(A=a.onDayPointerEnter)===null||A===void 0||A.call(a,t,s,I)},F=function(I){var A;(A=a.onDayPointerLeave)===null||A===void 0||A.call(a,t,s,I)},N=function(I){var A;(A=a.onDayTouchCancel)===null||A===void 0||A.call(a,t,s,I)},E=function(I){var A;(A=a.onDayTouchEnd)===null||A===void 0||A.call(a,t,s,I)},_=function(I){var A;(A=a.onDayTouchMove)===null||A===void 0||A.call(a,t,s,I)},z=function(I){var A;(A=a.onDayTouchStart)===null||A===void 0||A.call(a,t,s,I)},R=function(I){var A;(A=a.onDayKeyUp)===null||A===void 0||A.call(a,t,s,I)},L=function(I){var A;switch(I.key){case"ArrowLeft":I.preventDefault(),I.stopPropagation(),a.dir==="rtl"?o():c();break;case"ArrowRight":I.preventDefault(),I.stopPropagation(),a.dir==="rtl"?c():o();break;case"ArrowDown":I.preventDefault(),I.stopPropagation(),d();break;case"ArrowUp":I.preventDefault(),I.stopPropagation(),m();break;case"PageUp":I.preventDefault(),I.stopPropagation(),I.shiftKey?f():h();break;case"PageDown":I.preventDefault(),I.stopPropagation(),I.shiftKey?b():g();break;case"Home":I.preventDefault(),I.stopPropagation(),y();break;case"End":I.preventDefault(),I.stopPropagation(),j();break}(A=a.onDayKeyDown)===null||A===void 0||A.call(a,t,s,I)},V={onClick:v,onFocus:w,onBlur:S,onKeyDown:L,onKeyUp:R,onMouseEnter:D,onMouseLeave:k,onPointerEnter:C,onPointerLeave:F,onTouchCancel:N,onTouchEnd:E,onTouchMove:_,onTouchStart:z};return V}function n1(){var t=Kt(),s=Eg(),a=id(),r=od(),n=Gl(t)?s.selected:Ni(t)?a.selected:wi(t)?r.selected:void 0;return n}function i1(t){return Object.values(Ea).includes(t)}function l1(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(i1(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function o1(t,s){var a=ut({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=ut(ut({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function c1(t,s,a){var r,n,i,l=Kt(),o=dd(),c=t1(t,s),d=r1(t,c),m=n1(),p=!!(l.onDayClick||l.mode!=="default");u.useEffect(function(){var D;c.outside||o.focusedDay&&p&&ta(o.focusedDay,t)&&((D=a.current)===null||D===void 0||D.focus())},[o.focusedDay,t,a,p,c.outside]);var x=l1(l,c).join(" "),h=o1(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:Rw,b=e.jsx(f,{date:t,displayMonth:s,activeModifiers:c}),y={style:h,className:x,children:b,role:"gridcell"},j=o.focusTarget&&ta(o.focusTarget,t)&&!c.outside,v=o.focusedDay&&ta(o.focusedDay,t),w=ut(ut(ut({},y),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=v||j?0:-1,r)),d),S={isButton:p,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:w,divProps:y};return S}function d1(t){var s=u.useRef(null),a=c1(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(pl,ut({name:"day",ref:s},a.buttonProps)):e.jsx("div",ut({},a.divProps))}function m1(t){var s=t.number,a=t.dates,r=Kt(),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(pl,{name:"week-number","aria-label":p,className:l.weeknumber,style:i.weeknumber,onClick:x,children:m})}function u1(t){var s,a,r=Kt(),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:d1,d=(a=o==null?void 0:o.WeekNumber)!==null&&a!==void 0?a:m1,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})},Lj(p))})]})}function lx(t,s,a){for(var r=a!=null&&a.ISOWeek?Ap(s):Tp(s,a),n=a!=null&&a.ISOWeek?Uc(t):Bc(t,a),i=Za(r,n),l=[],o=0;o<=i;o++)l.push(ca(n,o));var c=l.reduce(function(d,m){var p=a!=null&&a.ISOWeek?Vj(m):Wj(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 x1(t,s){var a=lx(xa(t),Oc(t),s);if(s!=null&&s.useFixedWeeks){var r=Mj(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],l=ec(i,6-r),o=lx(ec(i,1),l,s);a.push.apply(a,o)}}return a}function h1(t){var s,a,r,n=Kt(),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=x1(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:Dw,b=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:u1,y=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:Aw;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 p1(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var g1=p1()?u.useLayoutEffect:u.useEffect,go=!1,f1=0;function ox(){return"react-day-picker-".concat(++f1)}function b1(t){var s,a=t??(go?ox():null),r=u.useState(a),n=r[0],i=r[1];return g1(function(){n===null&&i(ox())},[]),u.useEffect(function(){go===!1&&(go=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function j1(t){var s,a,r=Kt(),n=r.dir,i=r.classNames,l=r.styles,o=r.components,c=Ci().displayMonths,d=b1(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=ut(ut({},x),l.caption_start)),g&&(p.push(i.caption_end),x=ut(ut({},x),l.caption_end)),f&&(p.push(i.caption_between),x=ut(ut({},x),l.caption_between));var b=(a=o==null?void 0:o.Caption)!==null&&a!==void 0?a:Sw;return e.jsxs("div",{className:p.join(" "),style:x,children:[e.jsx(b,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(h1,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function y1(t){var s=Kt(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function v1(t){var s,a,r=t.initialProps,n=Kt(),i=dd(),l=Ci(),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=ut(ut({},n.styles.root),n.style),x=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,f){var b;return ut(ut({},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:y1;return e.jsx("div",ut({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(j1,{displayIndex:f,displayMonth:g},f)})})}))}function N1(t){var s=t.children,a=GN(t,["children"]);return e.jsx(mw,{initialProps:a,children:e.jsx(vw,{children:e.jsx(s1,{initialProps:a,children:e.jsx(Iw,{initialProps:a,children:e.jsx(Ew,{initialProps:a,children:e.jsx(zw,{children:e.jsx(e1,{children:s})})})})})})})}function w1(t){return e.jsx(N1,ut({},t,{children:e.jsx(v1,{initialProps:t})}))}function Ji({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(w1,{showOutsideDays:a,className:Oe("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:Oe(oi({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:Oe("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:Oe(oi({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:Oe("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(Wa,{className:Oe("size-4",n),...i})},...r})}function sa({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 nn(t)?t:void 0;if(typeof t=="string")try{const y=ro(t,"yyyy-MM-dd",new Date);return nn(y)?y:void 0}catch{return}}},[t]),g=u.useMemo(()=>{if(a){if(a instanceof Date)return nn(a)?a:void 0;if(typeof a=="string"){const y=ro(a,"yyyy-MM-dd",new Date);return nn(y)?y:void 0}}},[a]),f=u.useMemo(()=>{if(r){if(r instanceof Date)return nn(r)?r:void 0;if(typeof r=="string"){const y=ro(r,"yyyy-MM-dd",new Date);return nn(y)?y:void 0}}},[r]),b=y=>{if(x(!1),!!s){if(!y){s(null);return}s(it(y,"yyyy-MM-dd"))}};return e.jsx("div",{className:Oe("relative",o),children:e.jsxs(ra,{open:p,onOpenChange:x,children:[e.jsx(na,{asChild:!0,children:e.jsxs(O,{id:m,disabled:i,variant:"outline",className:Oe("w-full justify-start text-left font-normal",!h&&"text-muted-foreground",c&&"border-destructive ring-destructive/20",l),children:[e.jsx(jt,{className:"mr-2 h-4 w-4"}),h?it(h,d):e.jsx("span",{children:n})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(Ji,{mode:"single",selected:h,onSelect:b,disabled:y=>!!(g&&y<g||f&&y>f),initialFocus:!0})})]})})}function C1({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(q,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(se,{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(le,{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(jt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:s,onValueChange:l,"data-testid":"date-range-select",children:[e.jsx(Xe,{className:"w-[140px]",children:e.jsx(Qe,{placeholder:"Select period"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(ra,{open:n,onOpenChange:d,children:[e.jsx(na,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(jt,{className:"w-4 h-4"}),a&&r?`${it(a,"MMM d, yyyy")} - ${it(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",sideOffset:8,"data-testid":"custom-date-picker",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(sa,{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(ne,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(sa,{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(jt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:s,onValueChange:h=>l(h),"data-testid":"date-range-select-user",children:[e.jsx(Xe,{className:"w-[140px]",children:e.jsx(Qe,{placeholder:"Select period"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(ra,{open:n,onOpenChange:d,children:[e.jsx(na,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(jt,{className:"w-4 h-4"}),a&&r?`${it(a,"MMM d, yyyy")} - ${it(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",sideOffset:8,"data-testid":"custom-date-picker",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date-user",className:"text-sm font-medium",children:"Start Date"}),e.jsx(sa,{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(ne,{htmlFor:"end-date-user",className:"text-sm font-medium",children:"End Date"}),e.jsx(sa,{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(qt,{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 Br({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(q,{className:"hover:shadow-lg transition-all duration-200 shadow-md cursor-pointer h-full flex flex-col",onClick:c,"data-testid":o,children:[e.jsxs(me,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ue,{className:"text-sm font-medium text-muted-foreground","data-testid":`${o}-title`,children:t}),e.jsxs("div",{className:"flex items-center gap-2",children:[m&&d&&e.jsx("button",{type:"button",onClick:p,className:"p-1.5 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-colors","data-testid":`${o}-justify-button`,title:"View detailed breakdown of numbers","aria-label":"View detailed breakdown",children:e.jsx(Zr,{className:"h-4 w-4"})}),e.jsx("div",{className:`p-1.5 sm:p-2 rounded-lg ${r}`,"data-testid":`${o}-icon-wrapper`,children:e.jsx(a,{className:`h-4 w-4 sm:h-4 sm:w-4 ${n}`,"data-testid":`${o}-icon`})})]})]}),e.jsxs(se,{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 Rs({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 la({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(mj,{"data-slot":"progress",className:Oe("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(uj,{"data-slot":"progress-indicator",className:Oe("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function S1({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(Br,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Pe,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(Rs,{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(Rs,{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(Rs,{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(Rs,{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(Rs,{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(Br,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:ss,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(la,{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(Rs,{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(Rs,{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(Br,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?Jt(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:ot,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(Rs,{label:"Express",value:(()=>{const o=s.find(d=>d.priority==="express"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Jt(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(Rs,{label:"Standard",value:(()=>{const o=s.find(d=>d.priority==="standard"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Jt(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:o=>{o.stopPropagation(),i({...l(),priority:"standard"})}})]})})})]})}function A1({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(Br,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Pe,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(Rs,{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(Rs,{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(Rs,{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(Rs,{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(Rs,{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(Br,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:ot,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(Rs,{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(Rs,{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(Br,{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(Rs,{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(Rs,{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(Br,{title:"Success Rate",value:`${p.toFixed(0)}%`,icon:He,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(la,{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 T1=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)))},k1=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 D1({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=T1(t);return e.jsxs("div",{className:"p-3 sm:p-4 bg-red-50 rounded-lg sm:rounded-xl border border-red-100 hover:shadow-md transition-all duration-200 cursor-pointer",onClick:()=>s==null?void 0:s(t.requestNumber),"data-testid":`${a}-${t.requestId}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2 sm:mb-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 mb-1 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-xs sm:text-sm text-gray-900","data-testid":`${a}-request-number`,children:t.requestNumber}),t.priority==="express"&&e.jsx(Xj,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(le,{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(le,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:k1(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(la,{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 R1(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 I1(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function F1(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 P1(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 _g(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 E1({isAdmin:t,breachedRequests:s,pagination:a,onPageChange:r,onNavigate:n}){return e.jsxs(q,{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(me,{className:"pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-red-100 rounded-lg",children:e.jsx(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(Se,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(le,{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(se,{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(He,{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(D1,{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(vs,{className:"h-3 w-3 rotate-180"})}),_g(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(vs,{className:"h-3 w-3"})})]})]})})]})}const _1=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"}},M1=t=>{const s=new Date,a=new Date(t),r=Hj(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=Gj(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=Yj(s,a);return`${i} day${i>1?"s":""} ago`},L1=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()},O1=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(He,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-green-600"}):s.includes("reject")?e.jsx(as,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-red-600"}):s.includes("comment")?e.jsx(Ks,{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(Pe,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(Rl,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(Vt,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function $1({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(ms,{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(Hl,{src:""}),e.jsx(us,{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:O1(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(le,{variant:"outline",className:`text-xs ${_1(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:L1(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:M1(t.timestamp)})]})]}),e.jsx(vs,{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 U1({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:l,currentUserId:o,currentUserDisplayName:c,currentUserEmail:d}){return e.jsxs(q,{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(me,{className:"pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-blue-100 rounded-lg",children:e.jsx(Vt,{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(Se,{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(se,{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(Vt,{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($1,{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(vs,{className:"h-3 w-3 rotate-180"})}),_g(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(vs,{className:"h-3 w-3"})})]})]})})]})}function B1({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(q,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Vt,{className:"h-4 w-4 text-blue-600"})}),e.jsx(ue,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl sm:text-3xl font-bold text-blue-600",children:s.length}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"levels"})]}),e.jsx(qt,{}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg Time/Level"}),e.jsxs("span",{className:"font-semibold",children:[s.length>0?(t.tatEfficiency.avgCycleTimeHours/s.length).toFixed(1):"0","h"]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"At Risk"}),e.jsx("span",{className:"font-semibold text-red-600",children:a.filter(p=>p.breachCount>0).length})]})]})]})})]}),e.jsxs(q,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(Ks,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ue,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center p-2 bg-indigo-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-indigo-600",children:t.engagement.workNotesAdded})]}),e.jsxs("div",{className:"text-center p-2 bg-purple-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Files"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-purple-600",children:t.engagement.attachmentsUploaded})]})]}),e.jsx(qt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[t.requestVolume.totalRequests>0?(t.engagement.workNotesAdded/t.requestVolume.totalRequests).toFixed(1):"0"," ","avg notes per request"]})]})})]})]}),r.length>0&&e.jsxs(q,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-blue-50 p-2 sm:p-3 rounded-lg",children:e.jsx(ac,{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(Se,{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(se,{children:e.jsx(fn,{width:"100%",height:400,children:e.jsxs(qo,{data:r,children:[e.jsx(ll,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ol,{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(cl,{stroke:"#999",tick:{fontSize:11}}),e.jsx(bn,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(dl,{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 z1({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(q,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(Ks,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ue,{className:"text-sm",children:"My Activity"})]})}),e.jsx(se,{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(q,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(ot,{className:"h-4 w-4 text-purple-600"})}),e.jsx(ue,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(se,{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:Jt(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(qt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function V1({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(q,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-green-50 p-2 sm:p-3 rounded-lg",children:e.jsx(ss,{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(Se,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(se,{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: ",Jt(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(fn,{width:"100%",height:300,children:e.jsxs(vp,{children:[e.jsx(Np,{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(wp,{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 qr({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(q,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(se,{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(q,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(se,{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(vs,{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(vs,{className:"h-4 w-4"})})]})]})})})}function W1(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${it(s,"MMM d, yyyy")} - ${it(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 H1(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${it(s,"MMM d, yyyy")} to ${it(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 G1({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(q,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-red-50 p-2 sm:p-3 rounded-lg",children:e.jsx(as,{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(Se,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",H1(a,r,n)]})]})]}),e.jsxs(le,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[s.totalRecords," ",s.totalRecords===1?"Breach":"Breaches"]})]})}),e.jsxs(se,{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:F1(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(le,{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(qr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function Y1({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(q,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(me,{children:e.jsx("div",{className:"flex items-center justify-between gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{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(Se,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(se,{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(le,{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(le,{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(la,{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:[Jt(c)," elapsed"]}),e.jsxs("span",{children:[Jt(d)," left"]})]})]})]},l)})}),e.jsx("div",{className:"mt-4",children:e.jsx(qr,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function K1({aiRemarkUtilization:t}){return t?e.jsxs(q,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-purple-50 p-2 sm:p-3 rounded-lg",children:e.jsx(Il,{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(Se,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(se,{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(Ej,{data:t.monthlyTrends,children:[e.jsx(ll,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ol,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(cl,{stroke:"#999",tick:{fontSize:11}}),e.jsx(bn,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(dl,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(_u,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(_u,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function Q1({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(q,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-yellow-50 p-2 sm:p-3 rounded-lg",children:e.jsx(es,{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(Se,{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(se,{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 ${P1(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:Jt(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(qr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:o,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function X1(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 J1(t,s,a,r){const n=[];return r||n.push({label:"New Request",icon:Pe,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"}),n.push({label:"View Pending",icon:ot,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:pr,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:Vt,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),n}function Z1({onNavigate:t,onNewRequest:s}){const{user:a}=xs(),r=vi(),n=kn(ke=>ke.dashboard.viewAsUser),i=u.useMemo(()=>Vl(a),[a]),l=i&&!n,o=u.useCallback(ke=>{r(kN(ke))},[r]),c=DN(),{dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:x,handleDateRangeChange:h,handleApplyCustomDate:g,resetCustomDates:f,setCustomStartDate:b,setCustomEndDate:y,setShowCustomDatePicker:j}=c,v=RN(),{activity:w,critical:S,deadlines:D,approver:k,updateActivityPagination:C,updateCriticalPagination:F,updateDeadlinesPagination:N,updateApproverPagination:E,handleActivityPageChange:_,handleCriticalPageChange:z,handleDeadlinesPageChange:R,handleApproverPageChange:L}=v,V=FN({isAdmin:l,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:p,onPaginationUpdate:{activity:C,critical:F,deadlines:N,approver:E}}),{kpis:I,recentActivity:A,criticalRequests:G,departmentStats:$,priorityDistribution:M,upcomingDeadlines:T,aiRemarkUtilization:U,approverPerformance:H,loading:W,refreshing:P,fetchDashboardData:B,fetchRecentActivities:K,fetchCriticalRequests:Z,fetchUpcomingDeadlines:te,fetchApproverPerformance:ae}=V,xe=zN(),{exportingDeptStats:be,exportingApproverPerformance:Ge,handleExportDepartmentStats:Be,handleExportApproverPerformance:_e}=xe,Re=u.useMemo(()=>R1(G),[G]),ce=u.useMemo(()=>I1(T),[T]),je=u.useCallback(()=>{B(!0)},[d,m,p,B]),re=u.useCallback(()=>{g(()=>{m&&p&&B(!1)})},[m,p,g,B]),pe=u.useCallback(ke=>{_(ke,K)},[_,K]),ie=u.useCallback(ke=>{z(ke,Z)},[z,Z]),fe=u.useCallback(ke=>{R(ke,te)},[R,te]),Ie=u.useCallback(ke=>{L(ke,()=>ae(ke))},[L,ae]);u.useEffect(()=>{d==="custom"?m&&p&&B(!1):B(!1)},[d,m,p,n]);const $e=u.useMemo(()=>{try{const ke=lt.getUserData();return(ke==null?void 0:ke.jobTitle)==="Dealer"}catch(ke){return console.error("[Dashboard] Error checking dealer status:",ke),!1}},[]),ye=u.useMemo(()=>J1(i,s,t,$e),[i,s,t,$e]),oe=u.useCallback(ke=>{const st=X1(ke);t==null||t(st)},[t]);return W?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(VN,{isAdmin:i,effectiveIsAdmin:l,viewAsUser:n,onToggleView:o,quickActions:ye,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(C1,{isAdmin:l,dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:x,refreshing:P,onDateRangeChange:h,onCustomStartDateChange:b,onCustomEndDateChange:y,onShowCustomDatePickerChange:j,onApplyCustomDate:re,onResetCustomDates:f,onRefresh:je}),l?e.jsx(S1,{kpis:I,priorityDistribution:M,dateRange:d,customStartDate:m,customEndDate:p,onKPIClick:oe}):e.jsx(A1,{kpis:I,criticalRequests:G,dateRange:d,customStartDate:m,customEndDate:p,onKPIClick:oe,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(E1,{isAdmin:l,breachedRequests:Re,pagination:S,onPageChange:ie,onNavigate:t}),e.jsx(U1,{isAdmin:l,recentActivity:A,pagination:w,refreshing:P,onPageChange:pe,onRefresh:je,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),l&&I&&e.jsx(B1,{kpis:I,upcomingDeadlines:T,criticalRequests:G,departmentStats:$,dateRange:d,customStartDate:m,customEndDate:p,exportingDeptStats:be,onKPIClick:oe,onExportDepartmentStats:Be}),!l&&I&&e.jsx(z1,{kpis:I}),l&&M.length>0&&e.jsx(V1,{priorityDistribution:M,onNavigate:t}),l&&Re.length>0&&e.jsx(G1,{breachedRequests:Re,pagination:S,dateRange:d,customStartDate:m,customEndDate:p,onPageChange:ie,onKPIClick:oe,onNavigate:t}),ce.length>0&&e.jsx(Y1,{isAdmin:l,upcomingDeadlines:ce,pagination:D,onPageChange:fe,onNavigate:t}),l&&U&&e.jsx(K1,{aiRemarkUtilization:U}),l&&H.length>0&&e.jsx(Q1,{approverPerformance:H,pagination:k,dateRange:d,customStartDate:m,customEndDate:p,loading:W,exportingApproverPerformance:Ge,onPageChange:Ie,onExport:_e,onNavigate:t})]})}const q1={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},Mg=An({name:"openRequests",initialState:q1,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:eC,setStatusFilter:tC,setPriorityFilter:sC,setTemplateTypeFilter:aC,setForm16FinancialYear:rC,setForm16Quarter:nC,setSortBy:iC,setSortOrder:lC,setCurrentPage:oC,clearFilters:cC}=Mg.actions;function dC(){const t=vi(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,form16FinancialYear:i,form16Quarter:l,sortBy:o,sortOrder:c,currentPage:d}=kn(S=>S.openRequests),m=u.useCallback(S=>t(eC(S)),[t]),p=u.useCallback(S=>t(tC(S)),[t]),x=u.useCallback(S=>t(sC(S)),[t]),h=u.useCallback(S=>t(aC(S)),[t]),g=u.useCallback(S=>t(rC(S)),[t]),f=u.useCallback(S=>t(nC(S)),[t]),b=u.useCallback(S=>t(iC(S)),[t]),y=u.useCallback(S=>t(lC(S)),[t]),j=u.useCallback(S=>t(oC(S)),[t]),v=u.useCallback(()=>t(cC()),[t]),w=[s,r!=="all"?r:null,a!=="all"?a:null,n!=="all"?n:null,n==="FORM_16"&&i?"fy":null,n==="FORM_16"&&l?"q":null].filter(Boolean).length;return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,form16FinancialYear:i,form16Quarter:l,sortBy:o,sortOrder:c,currentPage:d,setSearchTerm:m,setStatusFilter:p,setPriorityFilter:x,setTemplateTypeFilter:h,setForm16FinancialYear:g,setForm16Quarter:f,setSortBy:b,setSortOrder:y,setCurrentPage:j,clearFilters:v,activeFiltersCount:w}}function fo(){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 mC(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:fo(),approverEmail:f,approverName:b,tatHours:g>0?g:24,isFinalApprover:x===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:fo(),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:fo(),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 we.post("/workflows",n),l=((o=i.data)==null?void 0:o.data)||i.data;return{id:l.id||l.workflowId||""}}async function ud(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 we.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 uC(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 we.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 xC(t={}){var j,v,w,S,D;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 we.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)||((w=y.data)==null?void 0:w.data)||[],pagination:((D=(S=y.data)==null?void 0:S.data)==null?void 0:D.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function hC(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 we.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 pC(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 we.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 gC(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 we.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 fC(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 we.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 Ls(t,s){var r;const a=await we.get(`/workflows/${t}/details`);return((r=a.data)==null?void 0:r.data)||a.data}async function yn(t){var a;const s=await we.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function Lg(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 we.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 Og(t,s,a,r){var i;const n=await we.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 bC(t,s,a){var n;const r=await we.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function $g(t,s){var r;const a=await we.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function jC(t,s,a,r){var i;const n=await we.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function yC(t,s){var r;const a=await we.post(`/workflows/${t}/resume`,{notes:s});return((r=a.data)==null?void 0:r.data)||a.data}async function vC(t){var a;const s=await we.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function cx(t){var a;const s=await we.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function NC(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 Ug(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 Us(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=Ug(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 dx(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=Ug(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:mC,createWorkflowMultipart:ud,listWorkflows:uC,listParticipantRequests:xC,listMyWorkflows:hC,listMyInitiatedWorkflows:pC,listOpenForMe:gC,listClosedByMe:fC,submitWorkflow:Bg,getWorkflowDetails:Ls,getWorkNotes:yn,createWorkNoteMultipart:Lg,handleInitiatorAction:zg};async function Bg(t){var a;const s=await we.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function wC(t,s){var r;const a=await we.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function CC(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 we.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((o=l.data)==null?void 0:o.data)||l.data}async function Kn(t,s,a){var n;const r=await we.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function Mr(t,s,a,r){var i;const n=await we.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 SC(t,s){const a=await we.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}async function zg(t,s,a){var n;const r=await we.post(`/workflows/${t}/initiator-action`,{action:s,...a});return((n=r.data)==null?void 0:n.data)||r.data}async function AC(t){var a;return((a=(await we.get(`/workflows/${t}/history`)).data)==null?void 0:a.data)||[]}function ys(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 Vg(t){return ys(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 TC(t){return t?t.jobTitle==="Dealer"||t.jobTitle==="DEALER":!1}function xd(t){return TC(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 Mi=[{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 Si({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,w]=u.useState(null),[S,D]=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(I=>(I=I.replace(/<!--[\s\S]*?-->/g,""),I=I.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),I=I.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),I=I.replace(/<meta[^>]*>/gi,""),I=I.replace(/\s*class="Mso[^"]*"/gi,""),I=I.replace(/\s*class="mso[^"]*"/gi,""),I=I.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),I=I.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),I=I.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),I=I.replace(/<\/?o:p[^>]*>/gi,""),I=I.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),I=I.replace(/<v:[^>]*\/>/gi,""),I=I.replace(/<p[^>]*>\s*<\/p>/gi,""),I=I.replace(/<div[^>]*>\s*<\/div>/gi,""),I=I.replace(/\s+/g," "),I=I.trim(),I),[]),C=u.useCallback(I=>{I.preventDefault();const A=I.clipboardData;let G=A.getData("text/html")||A.getData("text/plain");if((G.includes("<!--")||G.includes("<style")||G.includes("MsoNormal"))&&(G=k(G)),!l.current)return;const $=window.getSelection();if(!$||$.rangeCount===0)return;const M=$.getRangeAt(0);M.deleteContents();const T=document.createElement("div");T.innerHTML=G;const U=document.createDocumentFragment();Array.from(T.childNodes).forEach(H=>{if(H.nodeType===Node.ELEMENT_NODE){const W=H;if(W.tagName==="UL"||W.tagName==="OL"){const P=W.cloneNode(!0);P.removeAttribute("style"),P.removeAttribute("class"),P.querySelectorAll("li").forEach(B=>{B.removeAttribute("style"),B.removeAttribute("class");const K=B.textContent||"";K.trim()&&(B.textContent=K.trim())}),U.appendChild(P)}else if(W.tagName==="TABLE"){const P=W.cloneNode(!0);P.removeAttribute("style"),P.removeAttribute("class"),P.querySelectorAll("td, th").forEach(K=>{K.removeAttribute("style"),K.removeAttribute("class")});const B=document.createElement("div");B.className="table-wrapper",B.appendChild(P),U.appendChild(B)}else if(W.tagName==="P"||W.tagName==="DIV"){const P=document.createElement("p"),K=W.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");P.innerHTML=K,P.removeAttribute("style"),P.removeAttribute("class"),U.appendChild(P)}else if(W.tagName==="BR")U.appendChild(W.cloneNode(!0));else{const P=W.textContent||"";if(P.trim()){const B=document.createElement("p");B.textContent=P.trim(),U.appendChild(B)}}}else if(H.nodeType===Node.TEXT_NODE){const W=H.textContent||"";if(W.trim()){const P=document.createElement("p");P.textContent=W.trim(),U.appendChild(P)}}}),U.childNodes.length===0&&A.getData("text/plain").split(`
`).forEach(P=>{if(P.trim()){const B=document.createElement("p");B.textContent=P.trim(),U.appendChild(B)}else U.appendChild(document.createElement("br"))}),M.insertNode(U),M.collapse(!1),$.removeAllRanges(),$.addRange(M),l.current&&s(Ua(l.current.innerHTML))},[s,k]),F=u.useCallback(()=>{if(!l.current||!o)return;const I=new Set,A=window.getSelection();if(A&&A.rangeCount>0){const $=A.getRangeAt(0).commonAncestorContainer;let M=null;for($.nodeType===Node.TEXT_NODE?M=$.parentElement:M=$;M&&M!==l.current;){const T=M.tagName.toLowerCase();(T==="strong"||T==="b")&&I.add("bold"),(T==="em"||T==="i")&&I.add("italic"),T==="u"&&I.add("underline"),T==="h1"&&I.add("h1"),T==="h2"&&I.add("h2"),T==="h3"&&I.add("h3"),T==="ul"&&I.add("ul"),T==="ol"&&I.add("ol");const U=window.getComputedStyle(M);U.textAlign==="center"&&I.add("center"),U.textAlign==="right"&&I.add("right"),U.textAlign==="left"&&I.add("left");const H=K=>{if(K.startsWith("#"))return K.toUpperCase();const Z=K.match(/\d+/g);if(!Z||Z.length<3)return null;const te=Z[0],ae=Z[1],xe=Z[2];if(!te||!ae||!xe)return null;const be=parseInt(te).toString(16).padStart(2,"0"),Ge=parseInt(ae).toString(16).padStart(2,"0"),Be=parseInt(xe).toString(16).padStart(2,"0");return`#${be}${Ge}${Be}`.toUpperCase()},W=U.backgroundColor;if(W&&W!=="rgba(0, 0, 0, 0)"&&W!=="transparent"&&W!=="rgb(255, 255, 255)"&&W!=="#ffffff"&&W!=="#FFFFFF"){I.add("highlight");const K=H(W);if(K){const Z=Mi.find(te=>te.value==="transparent"?!1:te.value.toUpperCase()===K);g(Z?Z.value:K)}}else I.has("highlight")||g(null);const P=U.color,B=H(P);if(P&&B&&P!=="rgba(0, 0, 0, 0)"&&B!=="#000000"){I.add("textColor");const K=Mi.find(Z=>Z.value==="transparent"?!1:Z.value.toUpperCase()===B);w(K?K.value:B)}else I.has("textColor")||w(B==="#000000"||!B?"#000000":null);M=M.parentElement}}m(I)},[o]),N=u.useCallback((I,A)=>{if(!l.current)return;o||l.current.focus();const G=window.getSelection();if(!G||G.rangeCount===0){l.current.focus();return}document.execCommand(I,!1,A),l.current&&s(Ua(l.current.innerHTML)),setTimeout(F,10)},[o,s,F]),E=u.useCallback(I=>{if(!l.current)return;o||l.current.focus();const A=window.getSelection();if(!A||A.rangeCount===0){l.current.focus();return}let G=!1;if(A.rangeCount>0){const T=A.getRangeAt(0).commonAncestorContainer;let U=null;for(T.nodeType===Node.TEXT_NODE?U=T.parentElement:U=T;U&&U!==l.current;){const W=window.getComputedStyle(U).backgroundColor;if(W&&W!=="rgba(0, 0, 0, 0)"&&W!=="transparent"&&W!=="rgb(255, 255, 255)"&&W!=="#ffffff"&&W!=="#FFFFFF"){const B=(K=>{if(K.startsWith("#"))return K.toUpperCase();const Z=K.match(/\d+/g);if(!Z||Z.length<3)return null;const te=Z[0],ae=Z[1],xe=Z[2];if(!te||!ae||!xe)return null;const be=parseInt(te).toString(16).padStart(2,"0"),Ge=parseInt(ae).toString(16).padStart(2,"0"),Be=parseInt(xe).toString(16).padStart(2,"0");return`#${be}${Ge}${Be}`.toUpperCase()})(W);if(B&&B===I.toUpperCase()){G=!0;break}}U=U.parentElement}}if(I==="transparent"||G){const M=A.getRangeAt(0);if(M.collapsed)document.execCommand("removeFormat",!1);else{const T=M.extractContents(),U=document.createDocumentFragment(),H=W=>{if(W.nodeType===Node.TEXT_NODE)return W.cloneNode(!0);if(W.nodeType===Node.ELEMENT_NODE){const P=W,B=document.createElement(P.tagName.toLowerCase());return Array.from(P.attributes).forEach(K=>{K.name!=="style"&&K.name!=="class"&&B.setAttribute(K.name,K.value)}),Array.from(P.childNodes).forEach(K=>{const Z=H(K);Z&&B.appendChild(Z)}),P.style.backgroundColor&&(B.style.backgroundColor=""),B}return null};Array.from(T.childNodes).forEach(W=>{const P=H(W);P&&U.appendChild(P)}),M.insertNode(U),document.execCommand("removeFormat",!1)}g(null),b("#FFEB3B")}else if(A.rangeCount>0&&!A.getRangeAt(0).collapsed)document.execCommand("backColor",!1,I),g(I),I!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(I)&&b(I);else return;const $=window.getSelection();$&&$.removeAllRanges(),l.current&&s(Ua(l.current.innerHTML)),x(!1),setTimeout(()=>{l.current&&l.current.focus(),F()},50)},[o,s,F]),_=u.useCallback(I=>{if(!l.current)return;o||l.current.focus();const A=window.getSelection();if(!A||A.rangeCount===0){l.current.focus();return}let G=!1;if(A.rangeCount>0){const M=A.getRangeAt(0).commonAncestorContainer;let T=null;for(M.nodeType===Node.TEXT_NODE?T=M.parentElement:T=M;T&&T!==l.current;){const H=window.getComputedStyle(T).color;if(H){const P=(B=>{if(B.startsWith("#"))return B.toUpperCase();const K=B.match(/\d+/g);if(!K||K.length<3)return null;const Z=K[0],te=K[1],ae=K[2];if(!Z||!te||!ae)return null;const xe=parseInt(Z).toString(16).padStart(2,"0"),be=parseInt(te).toString(16).padStart(2,"0"),Ge=parseInt(ae).toString(16).padStart(2,"0");return`#${xe}${be}${Ge}`.toUpperCase()})(H);if(I==="#000000"){if(P==="#000000"||!P){G=!0;break}}else if(P&&P===I.toUpperCase()){G=!0;break}}T=T.parentElement}}if(I==="transparent"||I==="default"||G){if(I==="#000000"&&G){j(!1);return}document.execCommand("removeFormat",!1),w(null),D("#000000")}else document.execCommand("foreColor",!1,I),w(I),I!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(I)&&D(I);l.current&&s(Ua(l.current.innerHTML)),j(!1),setTimeout(F,10)},[o,s,F]),z=u.useCallback(()=>{l.current&&s(Ua(l.current.innerHTML)),F()},[s,F]),R=u.useCallback(I=>{if(I.ctrlKey&&I.key==="b"){I.preventDefault(),N("bold");return}if(I.ctrlKey&&I.key==="i"){I.preventDefault(),N("italic");return}if(I.ctrlKey&&I.key==="u"){I.preventDefault(),N("underline");return}},[N]),L=u.useCallback(()=>{c(!0)},[]),V=u.useCallback(()=>{c(!1),l.current&&s(Ua(l.current.innerHTML))},[s]);return u.useEffect(()=>{if(!o)return;const I=()=>{F()};return document.addEventListener("selectionchange",I),()=>{document.removeEventListener("selectionchange",I)}},[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:Oe("h-7 w-7 p-0",d.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>N("bold"),title:"Bold (Ctrl+B)",children:e.jsx(Jj,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:Oe("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>N("italic"),title:"Italic (Ctrl+I)",children:e.jsx(Zj,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:Oe("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>N("underline"),title:"Underline (Ctrl+U)",children:e.jsx(qj,{className:"h-4 w-4"})}),e.jsxs(ra,{open:p,onOpenChange:x,children:[e.jsx(na,{asChild:!0,children:e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:Oe("h-7 w-7 p-0",d.has("highlight")&&"bg-blue-100 text-blue-700"),title:"Text Highlight",children:e.jsx(ey,{className:"h-4 w-4"})})}),e.jsx(ia,{className:"w-auto p-2",align:"start",onPointerDownOutside:I=>{I.target.closest("[data-popover-content]")&&I.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:I=>I.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:I=>{I.stopPropagation(),x(!1)},title:"Close",children:e.jsx(Nt,{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:Mi.map(I=>{const A=h===I.value,G=I.value==="transparent";return e.jsxs("button",{type:"button",onClick:$=>{$.preventDefault(),$.stopPropagation(),E(A&&!G?"transparent":I.value)},className:Oe("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",I.class,A&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",G&&"border-gray-400 bg-white",!G&&!A&&"border-gray-300"),title:A&&!G?`${I.name} (Click to remove)`:I.name,style:G?{}:{backgroundColor:I.value},children:[G&&e.jsx("span",{className:"text-[10px] text-gray-600 font-bold",children:"×"}),A&&!G&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]},I.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:I=>{I.stopPropagation(),E("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:I=>{const A=I.target.value;b(A);const G=window.getSelection();G&&G.rangeCount>0&&!G.getRangeAt(0).collapsed&&E(A)},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:I=>{I.stopPropagation();const A=I.target.value;b(A)},onKeyDown:I=>{if(I.stopPropagation(),I.key==="Enter"){I.preventDefault();const A=I.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(A)&&E(A)}},onPaste:I=>{I.stopPropagation();const A=I.clipboardData.getData("text").trim();I.preventDefault(),setTimeout(()=>{if(/^#[0-9A-Fa-f]{6}$/i.test(A)){b(A);const G=window.getSelection();G&&G.rangeCount>0&&!G.getRangeAt(0).collapsed&&E(A)}else{const G=A.match(/^([0-9A-Fa-f]{6})$/);if(G){const $=`#${G[1]}`;b($);const M=window.getSelection();M&&M.rangeCount>0&&!M.getRangeAt(0).collapsed&&E($)}}},0)},onClick:I=>{I.stopPropagation()},onFocus:I=>{I.stopPropagation(),I.target.select()},onBlur:I=>{const A=I.target.value.trim();if(/^#[0-9A-Fa-f]{6}$/i.test(A)){const G=window.getSelection();G&&G.rangeCount>0&&!G.getRangeAt(0).collapsed&&E(A)}else b(A===""?h||"#FFEB3B":A)},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 I=f.trim();/^#[0-9A-Fa-f]{6}$/i.test(I)?E(I):b(h||"#FFEB3B")},title:"Apply custom color",children:"Apply"})]})]})]})})]}),e.jsxs(ra,{open:y,onOpenChange:j,children:[e.jsx(na,{asChild:!0,children:e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:Oe("h-7 w-7 p-0",d.has("textColor")&&"bg-blue-100 text-blue-700"),title:"Text Color",children:e.jsx(ty,{className:"h-4 w-4"})})}),e.jsx(ia,{className:"w-auto p-2",align:"start",onPointerDownOutside:I=>{I.target.closest("[data-popover-content]")&&I.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:I=>I.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:I=>{I.stopPropagation(),j(!1)},title:"Close",children:e.jsx(Nt,{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:I=>{I.preventDefault(),I.stopPropagation(),v==="#000000"||!v&&!d.has("textColor")||_("#000000")},className:Oe("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"})})]}),Mi.filter(I=>I.value!=="transparent").map(I=>{const A=v===I.value;return e.jsxs("button",{type:"button",onClick:G=>{G.preventDefault(),G.stopPropagation(),_(A?"#000000":I.value)},className:Oe("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center relative",A&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",!A&&"border-gray-300"),title:A?`${I.name} (Click to reset to default)`:I.name,style:{color:I.value,borderColor:A?"#2563eb":I.value},children:[e.jsx("span",{className:"text-xs font-bold",children:"A"}),A&&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-${I.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:I=>{I.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||S,onChange:I=>{const A=I.target.value;D(A),_(A)},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||S,onChange:I=>{const A=I.target.value;D(A)},onKeyDown:I=>{if(I.key==="Enter"){I.preventDefault();const A=I.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(A)&&_(A)}},onBlur:I=>{const A=I.target.value;/^#[0-9A-Fa-f]{6}$/.test(A)?_(A):A===""&&D(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:()=>_(S),title:"Apply custom text color",children:"Apply"})]})]})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:Oe("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>N("formatBlock","<h1>"),title:"Heading 1",children:e.jsx(sy,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:Oe("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>N("formatBlock","<h2>"),title:"Heading 2",children:e.jsx(ay,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:Oe("h-7 w-7 p-0",d.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>N("formatBlock","<h3>"),title:"Heading 3",children:e.jsx(ry,{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:Oe("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>N("insertUnorderedList"),title:"Bullet List",children:e.jsx(sc,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:Oe("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>N("insertOrderedList"),title:"Numbered List",children:e.jsx(ny,{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:Oe("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>N("justifyLeft"),title:"Align Left",children:e.jsx(Dp,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:Oe("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>N("justifyCenter"),title:"Align Center",children:e.jsx(iy,{className:"h-4 w-4"})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:Oe("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>N("justifyRight"),title:"Align Right",children:e.jsx(ly,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:l,contentEditable:!0,onPaste:C,onInput:z,onFocus:L,onBlur:V,onKeyDown:R,onMouseUp:F,onKeyUp:F,"data-placeholder":a,className:Oe("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 Os({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:Oe("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 Wg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Tl,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(R){var L=["th","st","nd","rd"],V=R%100;return"["+R+(L[(V-20)%10]||L[V]||L[0])+"]"}},v=function(R,L,V){var I=String(R);return!I||I.length>=L?R:""+Array(L+1-I.length).join(V)+R},w={s:v,z:function(R){var L=-R.utcOffset(),V=Math.abs(L),I=Math.floor(V/60),A=V%60;return(L<=0?"+":"-")+v(I,2,"0")+":"+v(A,2,"0")},m:function R(L,V){if(L.date()<V.date())return-R(V,L);var I=12*(V.year()-L.year())+(V.month()-L.month()),A=L.clone().add(I,p),G=V-A<0,$=L.clone().add(I+(G?-1:1),p);return+(-(I+(V-A)/(G?A-$:$-A))||0)},a:function(R){return R<0?Math.ceil(R)||0:Math.floor(R)},p:function(R){return{M:p,y:h,w:m,d,D:g,h:c,m:o,s:l,ms:i,Q:x}[R]||String(R||"").toLowerCase().replace(/s$/,"")},u:function(R){return R===void 0}},S="en",D={};D[S]=j;var k="$isDayjsObject",C=function(R){return R instanceof _||!(!R||!R[k])},F=function R(L,V,I){var A;if(!L)return S;if(typeof L=="string"){var G=L.toLowerCase();D[G]&&(A=G),V&&(D[G]=V,A=G);var $=L.split("-");if(!A&&$.length>1)return R($[0])}else{var M=L.name;D[M]=L,A=M}return!I&&A&&(S=A),A||!I&&S},N=function(R,L){if(C(R))return R.clone();var V=typeof L=="object"?L:{};return V.date=R,V.args=arguments,new _(V)},E=w;E.l=F,E.i=C,E.w=function(R,L){return N(R,{locale:L.$L,utc:L.$u,x:L.$x,$offset:L.$offset})};var _=function(){function R(V){this.$L=F(V.locale,null,!0),this.parse(V),this.$x=this.$x||V.x||{},this[k]=!0}var L=R.prototype;return L.parse=function(V){this.$d=function(I){var A=I.date,G=I.utc;if(A===null)return new Date(NaN);if(E.u(A))return new Date;if(A instanceof Date)return new Date(A);if(typeof A=="string"&&!/Z$/i.test(A)){var $=A.match(b);if($){var M=$[2]-1||0,T=($[7]||"0").substring(0,3);return G?new Date(Date.UTC($[1],M,$[3]||1,$[4]||0,$[5]||0,$[6]||0,T)):new Date($[1],M,$[3]||1,$[4]||0,$[5]||0,$[6]||0,T)}}return new Date(A)}(V),this.init()},L.init=function(){var V=this.$d;this.$y=V.getFullYear(),this.$M=V.getMonth(),this.$D=V.getDate(),this.$W=V.getDay(),this.$H=V.getHours(),this.$m=V.getMinutes(),this.$s=V.getSeconds(),this.$ms=V.getMilliseconds()},L.$utils=function(){return E},L.isValid=function(){return this.$d.toString()!==f},L.isSame=function(V,I){var A=N(V);return this.startOf(I)<=A&&A<=this.endOf(I)},L.isAfter=function(V,I){return N(V)<this.startOf(I)},L.isBefore=function(V,I){return this.endOf(I)<N(V)},L.$g=function(V,I,A){return E.u(V)?this[I]:this.set(A,V)},L.unix=function(){return Math.floor(this.valueOf()/1e3)},L.valueOf=function(){return this.$d.getTime()},L.startOf=function(V,I){var A=this,G=!!E.u(I)||I,$=E.p(V),M=function(Z,te){var ae=E.w(A.$u?Date.UTC(A.$y,te,Z):new Date(A.$y,te,Z),A);return G?ae:ae.endOf(d)},T=function(Z,te){return E.w(A.toDate()[Z].apply(A.toDate("s"),(G?[0,0,0,0]:[23,59,59,999]).slice(te)),A)},U=this.$W,H=this.$M,W=this.$D,P="set"+(this.$u?"UTC":"");switch($){case h:return G?M(1,0):M(31,11);case p:return G?M(1,H):M(0,H+1);case m:var B=this.$locale().weekStart||0,K=(U<B?U+7:U)-B;return M(G?W-K:W+(6-K),H);case d:case g:return T(P+"Hours",0);case c:return T(P+"Minutes",1);case o:return T(P+"Seconds",2);case l:return T(P+"Milliseconds",3);default:return this.clone()}},L.endOf=function(V){return this.startOf(V,!1)},L.$set=function(V,I){var A,G=E.p(V),$="set"+(this.$u?"UTC":""),M=(A={},A[d]=$+"Date",A[g]=$+"Date",A[p]=$+"Month",A[h]=$+"FullYear",A[c]=$+"Hours",A[o]=$+"Minutes",A[l]=$+"Seconds",A[i]=$+"Milliseconds",A)[G],T=G===d?this.$D+(I-this.$W):I;if(G===p||G===h){var U=this.clone().set(g,1);U.$d[M](T),U.init(),this.$d=U.set(g,Math.min(this.$D,U.daysInMonth())).$d}else M&&this.$d[M](T);return this.init(),this},L.set=function(V,I){return this.clone().$set(V,I)},L.get=function(V){return this[E.p(V)]()},L.add=function(V,I){var A,G=this;V=Number(V);var $=E.p(I),M=function(H){var W=N(G);return E.w(W.date(W.date()+Math.round(H*V)),G)};if($===p)return this.set(p,this.$M+V);if($===h)return this.set(h,this.$y+V);if($===d)return M(1);if($===m)return M(7);var T=(A={},A[o]=r,A[c]=n,A[l]=a,A)[$]||1,U=this.$d.getTime()+V*T;return E.w(U,this)},L.subtract=function(V,I){return this.add(-1*V,I)},L.format=function(V){var I=this,A=this.$locale();if(!this.isValid())return A.invalidDate||f;var G=V||"YYYY-MM-DDTHH:mm:ssZ",$=E.z(this),M=this.$H,T=this.$m,U=this.$M,H=A.weekdays,W=A.months,P=A.meridiem,B=function(te,ae,xe,be){return te&&(te[ae]||te(I,G))||xe[ae].slice(0,be)},K=function(te){return E.s(M%12||12,te,"0")},Z=P||function(te,ae,xe){var be=te<12?"AM":"PM";return xe?be.toLowerCase():be};return G.replace(y,function(te,ae){return ae||function(xe){switch(xe){case"YY":return String(I.$y).slice(-2);case"YYYY":return E.s(I.$y,4,"0");case"M":return U+1;case"MM":return E.s(U+1,2,"0");case"MMM":return B(A.monthsShort,U,W,3);case"MMMM":return B(W,U);case"D":return I.$D;case"DD":return E.s(I.$D,2,"0");case"d":return String(I.$W);case"dd":return B(A.weekdaysMin,I.$W,H,2);case"ddd":return B(A.weekdaysShort,I.$W,H,3);case"dddd":return H[I.$W];case"H":return String(M);case"HH":return E.s(M,2,"0");case"h":return K(1);case"hh":return K(2);case"a":return Z(M,T,!0);case"A":return Z(M,T,!1);case"m":return String(T);case"mm":return E.s(T,2,"0");case"s":return String(I.$s);case"ss":return E.s(I.$s,2,"0");case"SSS":return E.s(I.$ms,3,"0");case"Z":return $}return null}(te)||$.replace(":","")})},L.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},L.diff=function(V,I,A){var G,$=this,M=E.p(I),T=N(V),U=(T.utcOffset()-this.utcOffset())*r,H=this-T,W=function(){return E.m($,T)};switch(M){case h:G=W()/12;break;case p:G=W();break;case x:G=W()/3;break;case m:G=(H-U)/6048e5;break;case d:G=(H-U)/864e5;break;case c:G=H/n;break;case o:G=H/r;break;case l:G=H/a;break;default:G=H}return A?G:E.a(G)},L.daysInMonth=function(){return this.endOf(p).$D},L.$locale=function(){return D[this.$L]},L.locale=function(V,I){if(!V)return this.$L;var A=this.clone(),G=F(V,I,!0);return G&&(A.$L=G),A},L.clone=function(){return E.w(this.$d,this)},L.toDate=function(){return new Date(this.valueOf())},L.toJSON=function(){return this.isValid()?this.toISOString():null},L.toISOString=function(){return this.$d.toISOString()},L.toString=function(){return this.$d.toUTCString()},R}(),z=_.prototype;return N.prototype=z,[["$ms",i],["$s",l],["$m",o],["$H",c],["$W",d],["$M",p],["$y",h],["$D",g]].forEach(function(R){z[R[1]]=function(L){return this.$g(L,R[0],R[1])}}),N.extend=function(R,L){return R.$i||(R(L,_,N),R.$i=!0),N},N.locale=F,N.isDayjs=C,N.unix=function(R){return N(1e3*R)},N.en=D[S],N.Ls=D,N.p={},N})})(Wg);var kC=Wg.exports;const is=kl(kC);var Hg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Tl,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,w=0;w<v;w+=1){var S=j[w];S.d&&(g=x?n(d).diff(p,S.d,!0):p.diff(d,S.d,!0));var D=(a.rounding||Math.round)(Math.abs(g));if(b=g>0,D<=S.r||!S.r){D<=1&&w>0&&(S=j[w-1]);var k=y[S.l];h&&(D=h(""+D)),f=typeof k=="string"?k.replace("%d",D):k(D,m,S.l,b);break}}if(m)return f;var C=b?y.future:y.past;return typeof C=="function"?C(f):C.replace("%s",f)},i.to=function(d,m){return o(d,m,this,!0)},i.from=function(d,m){return o(d,m,this)};var c=function(d){return d.$u?n.utc():n()};i.toNow=function(d){return this.to(c(this),d)},i.fromNow=function(d){return this.from(c(this),d)}}})})(Hg);var DC=Hg.exports;const RC=kl(DC);is.extend(RC);function IC({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 G,$,M,T,U,H,W,P;const{user:v}=xs(),w=t==null?void 0:t.pauseInfo,S=(w==null?void 0:w.isPaused)||!1,D=(G=w==null?void 0:w.pausedBy)==null?void 0:G.userId,k=(v==null?void 0:v.userId)||"",C=S&&p&&(h||s),F=S&&s&&D&&D!==k&&x,E=((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,z=E&&(_!=null&&_.ocrExtractedData)&&typeof _.ocrExtractedData=="object"?_.ocrExtractedData:null,R=E&&z&&Object.keys(z).length>0?z:E&&_?{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,L=B=>B!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(Number(B)):"",V=B=>B==null||B===""?"":String(B),I=B=>{const K=(B||"").toLowerCase();return K==="completed"?"bg-emerald-100 text-emerald-800 border-emerald-200":K==="duplicate"||K==="duplicate submission"?"bg-amber-100 text-amber-800 border-amber-200":K==="balance mismatch"||K==="failed"?"bg-red-100 text-red-800 border-red-200":K==="resubmission needed"||K==="partial extracted data"?"bg-amber-50 text-amber-700 border-amber-200":"bg-gray-100 text-gray-700 border-gray-200"},A=B=>{const K=((B==null?void 0:B.displayStatus)||"").toLowerCase(),Z=((B==null?void 0:B.validationNotes)||"").toLowerCase();return K==="balance mismatch"||K==="failed"&&(Z.includes("mismatch")||Z.includes("26as")||Z.includes("value"))?"Failed - data mismatch with 26AS, submit the form 16 with correct data":K==="duplicate"||K==="duplicate submission"?"Duplicate. A submission for this FY and quarter already exists.":K==="resubmission needed"?(B==null?void 0:B.validationNotes)||"Resubmission needed. Please submit again with correct data.":K==="failed"?(B==null?void 0:B.validationNotes)||"Submission failed. Please resubmit.":null};return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[E&&(_==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(le,{variant:"outline",className:I(_.displayStatus),children:_.displayStatus})]}),A(_)&&e.jsx("p",{className:`text-sm ${(_.displayStatus||"").toLowerCase()==="balance mismatch"||(_.displayStatus||"").toLowerCase()==="failed"?"text-red-700 font-medium":"text-gray-600"}`,children:A(_)})]}),E&&e.jsxs(q,{"data-testid":"form16-certificate-details",className:"border-emerald-200 bg-emerald-50/30",children:[e.jsxs(me,{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(Pe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-emerald-600"}),"Form 16A Certificate Details"]}),e.jsx(Se,{className:"text-xs text-gray-600",children:"TDS Certificate as per Income Tax Act, 1961"})]}),e.jsx(se,{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:"})," ",L(_.totalAmount??_.amountPaid)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TDS Deducted:"})," ",L(_.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:"})," ",L(_.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:L(_.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(Os,{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."})]})})]}),E&&R&&Object.keys(R).length>0&&e.jsxs(q,{"data-testid":"form16-ocr-extracted-data",className:"border-slate-200 bg-slate-50/50",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base text-slate-800",children:[e.jsx(Rp,{className:"w-4 h-4 text-slate-600"}),"OCR extracted data"]}),e.jsx(Se,{className:"text-xs text-gray-600",children:"Data extracted from the uploaded Form 16A PDF."})]}),e.jsx(se,{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)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Deductor name"}),e.jsx("p",{className:"font-medium",children:V(R.deductorName??R.deductor_name??R.nameAndAddressOfDeductor)})]}),(R.tanNumber??R.tan_number??R.tanOfDeductor)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500",children:"TAN"}),e.jsx("p",{className:"font-medium",children:V(R.tanNumber??R.tan_number??R.tanOfDeductor)})]}),(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:V(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:V(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:V(R.form16aNumber??R.form16a_number)})]}),(R.totalAmount??R.total_amount??R.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:L(R.totalAmount??R.total_amount??R.totalAmountPaid)})]}),(R.totalTaxDeducted??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:L(R.totalTaxDeducted??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:V(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:V(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:V(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:V(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:V(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:V(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:V(R.deduceePan??R.deducee_pan)})]})]})})]}),e.jsxs(q,{"data-testid":"initiator-card",children:[e.jsx(me,{className:"pb-3 sm:pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ht,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(se,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(ms,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(us,{className:"bg-gray-700 text-white font-semibold text-sm",children:(($=t.initiator)==null?void 0:$.avatar)||"U"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:((M=t.initiator)==null?void 0:M.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((T=t.initiator)==null?void 0:T.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(wa,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((H=t.initiator)==null?void 0:H.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(ji,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((W=t.initiator)==null?void 0:W.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(q,{"data-testid":"request-details-card",children:[e.jsx(me,{className:"pb-3 sm:pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Pe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(se,{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(Os,{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:ys(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:ys(t.updatedAt)})]})]})]})]}),S&&w&&e.jsxs(q,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(me,{className:"pb-3 sm:pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(gr,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(se,{className:"space-y-3 sm:space-y-4",children:[e.jsx("div",{className:"bg-white rounded-lg p-3 sm:p-4 border border-orange-200",children:e.jsxs("div",{className:"space-y-2 sm:space-y-3",children:[w.pauseReason&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Reason"}),e.jsx(Os,{content:w.pauseReason,className:"text-sm text-gray-900 mt-1"})]}),w.pausedBy&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused By"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:w.pausedBy.name||w.pausedBy.email})]}),w.pauseResumeDate&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Auto-Resume Date"}),e.jsxs("p",{className:"text-sm text-gray-900 mt-1",children:[ys(w.pauseResumeDate),is(w.pauseResumeDate).isAfter(is())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",is(w.pauseResumeDate).fromNow(),")"]})]})]}),w.pausedAt&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused At"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:ys(w.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[C&&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(ml,{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(tt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Request Resume"]})]})]})]}),t.claimDetails&&e.jsxs(q,{children:[e.jsx(me,{className:"pb-4",children:e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(Pe,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(se,{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?Vg(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(Os,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(q,{children:[e.jsxs(me,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(He,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(Se,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(se,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Os,{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 ",ys(t.closureDate)]}),e.jsxs("span",{children:["By ",((P=t.initiator)==null?void 0:P.name)||"Initiator"]})]})]})]}),a&&e.jsxs(q,{"data-testid":"conclusion-remark-card",children:[e.jsx(me,{className:`bg-gradient-to-r border-b ${t.status==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(He,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(Se,{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(se,{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(We,{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(Si,{value:r,onChange:B=>n(B),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(We,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function Jn({delayDuration:t=0,...s}){return e.jsx(xj,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function Zi({...t}){return e.jsx(Jn,{children:e.jsx(hj,{"data-slot":"tooltip",...t})})}function qi({...t}){return e.jsx(pj,{"data-slot":"tooltip-trigger",...t})}function el({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(gj,{children:e.jsxs(fj,{"data-slot":"tooltip-content",sideOffset:s,className:Oe("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(bj,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function gt({...t}){return e.jsx(jp,{"data-slot":"dialog",...t})}function FC({...t}){return e.jsx(bp,{"data-slot":"dialog-portal",...t})}const Gg=u.forwardRef(({className:t,...s},a)=>e.jsx(Mc,{ref:a,"data-slot":"dialog-overlay",className:Oe("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}));Gg.displayName=Mc.displayName;const ht=u.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(FC,{"data-slot":"dialog-portal",children:[e.jsx(Gg,{}),e.jsxs(Lc,{ref:r,"data-slot":"dialog-content",className:Oe("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(jj,{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(Nt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));ht.displayName=Lc.displayName;const ft=u.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:Oe("flex flex-col gap-2 text-center sm:text-left",t),...s}));ft.displayName="DialogHeader";const Rt=u.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:Oe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));Rt.displayName="DialogFooter";const pt=u.forwardRef(({className:t,...s},a)=>e.jsx(gp,{ref:a,"data-slot":"dialog-title",className:Oe("text-lg leading-none font-semibold",t),...s}));pt.displayName=gp.displayName;const Mt=u.forwardRef(({className:t,...s},a)=>e.jsx(fp,{ref:a,"data-slot":"dialog-description",className:Oe("text-muted-foreground text-sm",t),...s}));Mt.displayName=fp.displayName;function Ws({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:Oe("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 mx=t=>{if(t<8)return Jt(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${Jt(r)}`:`${a}d`},PC=(t,s)=>{if(s)return e.jsx(tt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(He,{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(Ip,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(ot,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(ot,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(ot,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function EC({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}=xs(),[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",w=t.status==="waiting",S=t.status==="paused",D=Number(t.tatHours||0),k=t.actualHours??0,C=j&&k?Math.max(0,D-k):0,F=D>0?k/D*100:0,N=F>=100,E=(d==null?void 0:d.role)==="ADMIN",_=Vl(d),z=t.approverId===(d==null?void 0:d.userId),R=E||_||z,L=async()=>{var V,I;if(!x.trim()){Y.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}f(!0);try{await SC(t.levelId,x.trim()),p(!1),h(""),Y.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(A){console.error("Error updating breach reason:",A);const G=((I=(V=A==null?void 0:A.response)==null?void 0:V.data)==null?void 0:I.error)||(A==null?void 0:A.message)||"Failed to update breach reason. Please try again.";Y.error("Failed to Update Breach Reason",{description:G,duration:5e3})}finally{f(!1)}};return e.jsxs("div",{className:`relative p-3 sm:p-4 md:p-5 rounded-lg border-2 transition-all ${t.isSkipped?"border-orange-500 bg-orange-50":y?"border-blue-500 bg-blue-50 shadow-md":j?"border-green-500 bg-green-50":v?"border-red-500 bg-red-50":w?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${c}-${t.step}`,children:[e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 md:gap-4",children:[e.jsx("div",{className:`p-2 sm:p-2.5 md:p-3 rounded-xl flex-shrink-0 ${t.isSkipped?"bg-orange-100":S?"bg-yellow-100":y?"bg-blue-100":j?"bg-green-100":v?"bg-red-100":w?"bg-gray-200":"bg-gray-100"}`,children:PC(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(le,{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":w?"bg-gray-200 text-gray-600 border-gray-300":"bg-gray-100 text-gray-800 border-gray-200"}`,"data-testid":`${c}-status-badge`,children:t.isSkipped?"skipped":t.status}),t.isSkipped&&t.skipReason&&e.jsx(Jn,{delayDuration:200,children:e.jsxs(Zi,{children:[e.jsx(qi,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:V=>V.stopPropagation(),children:e.jsx(tt,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(el,{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($u,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),j&&k&&e.jsx(le,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:mx(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:[D," 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?ys(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:mx(k)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const V=Math.min(100,F),I=()=>N?"bg-red-600":F>=75?"bg-orange-500":F>=50?"bg-amber-500":"bg-green-600",A=()=>N?"text-red-600":F>=75?"text-orange-600":F>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(la,{value:V,className:"h-2 bg-gray-200",indicatorClassName:I(),"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 ${A()}`,children:[Math.round(V),"% of TAT used"]}),N&&R&&e.jsx(Jn,{children:e.jsxs(Zi,{children:[e.jsx(qi,{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(Ei,{className:"w-3 h-3"})})}),e.jsx(el,{children:e.jsx("p",{children:b?"Edit breach reason":"Add breach reason"})})]})})]}),C>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",Jt(C)]})]})]})})()}),N&&b&&e.jsxs("div",{className:"mt-4 p-3 sm:p-4 bg-red-50 border-l-4 border-red-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 mb-2 flex items-center gap-1.5",children:[e.jsx(Ei,{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(Ks,{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||S)&&(a==null?void 0:a.sla)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Due by:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.deadline?_a(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${S?"bg-gray-100 border-gray-300":(a.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(a.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(a.sla.percentageUsed||0)>=50?"bg-amber-50 border-amber-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(ot,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",S&&"(Paused)"]}),e.jsxs("div",{className:"space-y-2 text-xs mb-3",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time elapsed since assigned:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.elapsedText})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time used:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[a.sla.elapsedText," / ",Jt(D)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const V=a.sla.percentageUsed||0,I=()=>S?"bg-gray-500":V>=100?"bg-red-600":V>=75?"bg-orange-500":V>=50?"bg-amber-500":"bg-green-600",A=()=>S?"text-gray-600":V>=100?"text-red-600":V>=75?"text-orange-600":V>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(la,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:I(),"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 ${A()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&R&&e.jsx(Jn,{children:e.jsxs(Zi,{children:[e.jsx(qi,{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(Ei,{className:"w-3 h-3"})})}),e.jsx(el,{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(ul,{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(Ei,{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(as,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),w&&e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"bg-gray-100 border border-gray-300 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-gray-600 mb-1 flex items-center gap-1.5",children:[e.jsx(Ip,{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 ",D," 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($u,{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 ",ys(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((V,I)=>{var A,G,$,M,T,U;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${V.isBreached?"bg-red-50 border-red-200":(V.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${I}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(V.thresholdPercentage||0)===50&&e.jsx(oy,{className:"w-5 h-5 text-yellow-600"}),(V.thresholdPercentage||0)===75&&e.jsx(as,{className:"w-5 h-5 text-orange-600"}),(V.thresholdPercentage||0)===100&&e.jsx(ul,{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 ",I+1," - ",V.thresholdPercentage||0,"% TAT"]}),e.jsx(le,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${V.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:V.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[V.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:Jt(Number(V.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:[Jt(Number(V.tatHoursElapsed||0)),((A=V.metadata)==null?void 0:A.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(V.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 ${(V.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[Jt(Number(V.tatHoursRemaining||0)),((G=V.metadata)==null?void 0:G.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(V.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:V.expectedCompletionTime?_a(V.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"}),((($=V.metadata)==null?void 0:$.testMode)||((M=V.metadata)==null?void 0:M.tatTestMode))&&e.jsx(le,{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: ",V.alertSentAt?ys(V.alertSentAt):"N/A"]}),(((T=V.metadata)==null?void 0:T.testMode)||((U=V.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)"})]})]})]})},I)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[j?"Approved":v?"Rejected":"Actioned"," on ",ys(t.timestamp)]}),n&&!S&&(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(tt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Skip This Approver"]}),e.jsx("p",{className:"text-[10px] sm:text-xs text-gray-500 mt-1 text-center",children:S?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(gt,{open:m,onOpenChange:p,children:e.jsxs(ht,{className:"sm:max-w-[500px]",children:[e.jsxs(ft,{children:[e.jsx(pt,{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(Ws,{placeholder:"Enter the reason for the breach...",value:x,onChange:V=>h(V.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(Rt,{children:[e.jsx(O,{variant:"outline",onClick:()=>{p(!1),h("")},disabled:g,children:"Cancel"}),e.jsx(O,{onClick:L,disabled:!x.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function _C({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(q,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Qs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(Se,{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(le,{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(le,{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(le,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",x," of ",i," - ",o," completed"]})})()]})}),e.jsx(se,{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(EC,{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 Fr(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(Number(t))}function ga(t){return t==null||t===""?"":String(t)}function MC(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 ux="Failed - data mismatch with 26AS, submit the Form 16 with correct data.";function LC(t){const s=(t||"").toLowerCase();return/notnull|violation|sequelize|econnrefused|database|error\./i.test(s)}function xx(t){const s=((t==null?void 0:t.displayStatus)||"").toLowerCase(),a=String((t==null?void 0:t.validationNotes)||"");return s==="balance mismatch"||s==="failed"?LC(a)?ux:a.trim()||ux: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 OC({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(le,{variant:"outline",className:MC(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:"})," ",Fr(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]})]}),xx(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:xx(s)})]}),e.jsxs(q,{"data-testid":"form16-certificate-details",className:"border-emerald-200 bg-emerald-50/30",children:[e.jsxs(me,{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(Pe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-emerald-600"}),"Form 16A Certificate Details"]}),e.jsx(Se,{className:"text-xs text-gray-600",children:"TDS Certificate as per Income Tax Act, 1961"})]}),e.jsx(se,{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:"})," ",Fr(s.totalAmount??s.amountPaid)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"TDS Deducted:"})," ",Fr(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:"})," ",Fr(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:Fr(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(Os,{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(q,{"data-testid":"form16-ocr-extracted-data",className:"border-slate-200 bg-slate-50/50",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base text-slate-800",children:[e.jsx(Rp,{className:"w-4 h-4 text-slate-600"}),"OCR extracted data"]}),e.jsx(Se,{className:"text-xs text-gray-600",children:"Data extracted from the uploaded Form 16A PDF (shown for all submission outcomes)."})]}),e.jsx(se,{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:ga(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:ga(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:ga(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:ga(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:ga(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:Fr(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:Fr(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:ga(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:ga(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:ga(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:ga(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:ga(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:ga(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:ga(r.deduceePan??r.deducee_pan)})]})]})})]}),e.jsxs(q,{"data-testid":"form16-submission-context",children:[e.jsx(me,{className:"pb-3",children:e.jsxs(ue,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-emerald-600"}),"Submitted by"]})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ms,{className:"h-10 w-10 rounded-full flex-shrink-0",children:e.jsx(us,{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(wa,{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(Os,{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 $C=[{key:"submit",label:"Dealer submits Form 16",icon:Pe},{key:"ocr",label:"OCR extracts",icon:Pe},{key:"match",label:"Matching with 26AS",icon:_t},{key:"success",label:"Successfully match",icon:He},{key:"credit",label:"Credit note generated",icon:Et}];function UC({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 vg(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(q,{className:"border-emerald-200",children:[e.jsx(me,{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(se,{className:"space-y-4",children:$C.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(He,{className:"w-4 h-4"}):e.jsx(Vc,{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(We,{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 hd=u.createContext({});function pd(t){const s=u.useRef(null);return s.current===null&&(s.current=t()),s.current}const gd=typeof window<"u",Yg=gd?u.useLayoutEffect:u.useEffect,Yl=u.createContext(null);function fd(t,s){t.indexOf(s)===-1&&t.push(s)}function bd(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 jd=()=>{};const er={},Kg=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Qg(t){return typeof t=="object"&&t!==null}const Xg=t=>/^0[^.\s]+$/u.test(t);function yd(t){let s;return()=>(s===void 0&&(s=t()),s)}const va=t=>t,BC=(t,s)=>a=>s(t(a)),Ai=(...t)=>t.reduce(BC),ci=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class vd{constructor(){this.subscriptions=[]}add(s){return fd(this.subscriptions,s),()=>bd(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,ja=t=>t/1e3;function Jg(t,s){return s?t*(1e3/s):0}const Zg=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,zC=1e-7,VC=12;function WC(t,s,a,r,n){let i,l,o=0;do l=s+(a-s)/2,i=Zg(l,r,n)-t,i>0?a=l:s=l;while(Math.abs(i)>zC&&++o<VC);return l}function Ti(t,s,a,r){if(t===s&&a===r)return va;const n=i=>WC(i,0,1,t,a);return i=>i===0||i===1?i:Zg(n(i),s,r)}const qg=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,ef=t=>s=>1-t(1-s),tf=Ti(.33,1.53,.69,.99),Nd=ef(tf),sf=qg(Nd),af=t=>(t*=2)<1?.5*Nd(t):.5*(2-Math.pow(2,-10*(t-1))),wd=t=>1-Math.sin(Math.acos(t)),rf=ef(wd),nf=qg(wd),HC=Ti(.42,0,1,1),GC=Ti(0,0,.58,1),lf=Ti(.42,0,.58,1),YC=t=>Array.isArray(t)&&typeof t[0]!="number",of=t=>Array.isArray(t)&&typeof t[0]=="number",KC={linear:va,easeIn:HC,easeInOut:lf,easeOut:GC,circIn:wd,circInOut:nf,circOut:rf,backIn:Nd,backInOut:sf,backOut:tf,anticipate:af},QC=t=>typeof t=="string",hx=t=>{if(of(t)){jd(t.length===4);const[s,a,r,n]=t;return Ti(s,a,r,n)}else if(QC(t))return KC[t];return t},Li=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function XC(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 JC=40;function cf(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,l=Li.reduce((v,w)=>(v[w]=XC(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,JC),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:Li.reduce((v,w)=>{const S=l[w];return v[w]=(D,k=!1,C=!1)=>(a||b(),S.schedule(D,k,C)),v},{}),cancel:v=>{for(let w=0;w<Li.length;w++)l[Li[w]].cancel(v)},state:n,steps:l}}const{schedule:ts,cancel:br,state:Ms,steps:bo}=cf(typeof requestAnimationFrame<"u"?requestAnimationFrame:va,!0);let tl;function ZC(){tl=void 0}const aa={now:()=>(tl===void 0&&aa.set(Ms.isProcessing||er.useManualTiming?Ms.timestamp:performance.now()),tl),set:t=>{tl=t,queueMicrotask(ZC)}},df=t=>s=>typeof s=="string"&&s.startsWith(t),Cd=df("--"),qC=df("var(--"),Sd=t=>qC(t)?e2.test(t.split("/*")[0].trim()):!1,e2=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Rn={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},di={...Rn,transform:t=>qa(0,1,t)},Oi={...Rn,default:1},Zn=t=>Math.round(t*1e5)/1e5,Ad=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function t2(t){return t==null}const s2=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Td=(t,s)=>a=>!!(typeof a=="string"&&s2.test(a)&&a.startsWith(t)||s&&!t2(a)&&Object.prototype.hasOwnProperty.call(a,s)),mf=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,l,o]=r.match(Ad);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},a2=t=>qa(0,255,t),jo={...Rn,transform:t=>Math.round(a2(t))},zr={test:Td("rgb","red"),parse:mf("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+jo.transform(t)+", "+jo.transform(s)+", "+jo.transform(a)+", "+Zn(di.transform(r))+")"};function r2(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 mc={test:Td("#"),parse:r2,transform:zr.transform},ki=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),ur=ki("deg"),za=ki("%"),mt=ki("px"),n2=ki("vh"),i2=ki("vw"),px={...za,parse:t=>za.parse(t)/100,transform:t=>za.transform(t*100)},mn={test:Td("hsl","hue"),parse:mf("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(di.transform(r))+")"},bs={test:t=>zr.test(t)||mc.test(t)||mn.test(t),parse:t=>zr.test(t)?zr.parse(t):mn.test(t)?mn.parse(t):mc.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?zr.transform(t):mn.transform(t),getAnimatableNone:t=>{const s=bs.parse(t);return s.alpha=0,bs.transform(s)}},l2=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function o2(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(Ad))==null?void 0:s.length)||0)+(((a=t.match(l2))==null?void 0:a.length)||0)>0}const uf="number",xf="color",c2="var",d2="var(",gx="${}",m2=/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 mi(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const o=s.replace(m2,c=>(bs.test(c)?(r.color.push(i),n.push(xf),a.push(bs.parse(c))):c.startsWith(d2)?(r.var.push(i),n.push(c2),a.push(c)):(r.number.push(i),n.push(uf),a.push(parseFloat(c))),++i,gx)).split(gx);return{values:a,split:o,indexes:r,types:n}}function hf(t){return mi(t).values}function pf(t){const{split:s,types:a}=mi(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===uf?i+=Zn(n[l]):o===xf?i+=bs.transform(n[l]):i+=n[l]}return i}}const u2=t=>typeof t=="number"?0:bs.test(t)?bs.getAnimatableNone(t):t;function x2(t){const s=hf(t);return pf(t)(s.map(u2))}const jr={test:o2,parse:hf,createTransformer:pf,getAnimatableNone:x2};function yo(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 h2({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=yo(c,o,t+1/3),i=yo(c,o,t),l=yo(c,o,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function gl(t,s){return a=>a>0?s:t}const ls=(t,s,a)=>t+(s-t)*a,vo=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},p2=[mc,zr,mn],g2=t=>p2.find(s=>s.test(t));function fx(t){const s=g2(t);if(!s)return!1;let a=s.parse(t);return s===mn&&(a=h2(a)),a}const bx=(t,s)=>{const a=fx(t),r=fx(s);if(!a||!r)return gl(t,s);const n={...a};return i=>(n.red=vo(a.red,r.red,i),n.green=vo(a.green,r.green,i),n.blue=vo(a.blue,r.blue,i),n.alpha=ls(a.alpha,r.alpha,i),zr.transform(n))},uc=new Set(["none","hidden"]);function f2(t,s){return uc.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function b2(t,s){return a=>ls(t,s,a)}function kd(t){return typeof t=="number"?b2:typeof t=="string"?Sd(t)?gl:bs.test(t)?bx:v2:Array.isArray(t)?gf:typeof t=="object"?bs.test(t)?bx:j2:gl}function gf(t,s){const a=[...t],r=a.length,n=t.map((i,l)=>kd(i)(i,s[l]));return i=>{for(let l=0;l<r;l++)a[l]=n[l](i);return a}}function j2(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=kd(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function y2(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 v2=(t,s)=>{const a=jr.createTransformer(s),r=mi(t),n=mi(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?uc.has(t)&&!n.values.length||uc.has(s)&&!r.values.length?f2(t,s):Ai(gf(y2(r,n),n.values),a):gl(t,s)};function ff(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?ls(t,s,a):kd(t)(t,s)}const N2=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>ts.update(s,a),stop:()=>br(s),now:()=>Ms.isProcessing?Ms.timestamp:aa.now()}},bf=(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)})`},fl=2e4;function Dd(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<fl;)s+=a,r=t.next(s);return s>=fl?1/0:s}function w2(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(Dd(r),fl);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:ja(n)}}const C2=5;function jf(t,s,a){const r=Math.max(s-C2,0);return Jg(a-t(r),s-r)}const cs={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},No=.001;function S2({duration:t=cs.duration,bounce:s=cs.bounce,velocity:a=cs.velocity,mass:r=cs.mass}){let n,i,l=1-s;l=qa(cs.minDamping,cs.maxDamping,l),t=qa(cs.minDuration,cs.maxDuration,ja(t)),l<1?(n=d=>{const m=d*l,p=m*t,x=m-a,h=xc(d,l),g=Math.exp(-p);return No-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=xc(Math.pow(d,2),l);return(-n(d)+No>0?-1:1)*((x-h)*g)/f}):(n=d=>{const m=Math.exp(-d*t),p=(d-a)*t+1;return-No+m*p},i=d=>{const m=Math.exp(-d*t),p=(a-d)*(t*t);return m*p});const o=5/t,c=T2(n,i,o);if(t=Ba(t),isNaN(c))return{stiffness:cs.stiffness,damping:cs.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:t}}}const A2=12;function T2(t,s,a){let r=a;for(let n=1;n<A2;n++)r=r-t(r)/s(r);return r}function xc(t,s){return t*Math.sqrt(1-s*s)}const k2=["duration","bounce"],D2=["stiffness","damping","mass"];function jx(t,s){return s.some(a=>t[a]!==void 0)}function R2(t){let s={velocity:cs.velocity,stiffness:cs.stiffness,damping:cs.damping,mass:cs.mass,isResolvedFromDuration:!1,...t};if(!jx(t,D2)&&jx(t,k2))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:cs.mass,stiffness:n,damping:i}}else{const a=S2(t);s={...s,...a,mass:cs.mass},s.isResolvedFromDuration=!0}return s}function bl(t=cs.visualDuration,s=cs.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}=R2({...a,velocity:-ja(a.velocity||0)}),g=x||0,f=d/(2*Math.sqrt(c*m)),b=l-i,y=ja(Math.sqrt(c/m)),j=Math.abs(b)<5;r||(r=j?cs.restSpeed.granular:cs.restSpeed.default),n||(n=j?cs.restDelta.granular:cs.restDelta.default);let v;if(f<1){const S=xc(y,f);v=D=>{const k=Math.exp(-f*y*D);return l-k*((g+f*y*b)/S*Math.sin(S*D)+b*Math.cos(S*D))}}else if(f===1)v=S=>l-Math.exp(-y*S)*(b+(g+y*b)*S);else{const S=y*Math.sqrt(f*f-1);v=D=>{const k=Math.exp(-f*y*D),C=Math.min(S*D,300);return l-k*((g+f*y*b)*Math.sinh(C)+S*b*Math.cosh(C))/S}}const w={calculatedDuration:h&&p||null,next:S=>{const D=v(S);if(h)o.done=S>=p;else{let k=S===0?g:0;f<1&&(k=S===0?Ba(g):jf(v,S,D));const C=Math.abs(k)<=r,F=Math.abs(l-D)<=n;o.done=C&&F}return o.value=o.done?l:D,o},toString:()=>{const S=Math.min(Dd(w),fl),D=bf(k=>w.next(S*k).value,S,30);return S+"ms "+D},toTransition:()=>{}};return w}bl.applyToOptions=t=>{const s=w2(t,100,bl);return t.ease=s.ease,t.duration=Ba(s.duration),t.type="keyframes",t};function hc({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=C=>o!==void 0&&C<o||c!==void 0&&C>c,g=C=>o===void 0?c:c===void 0||Math.abs(o-C)<Math.abs(c-C)?o:c;let f=a*s;const b=p+f,y=l===void 0?b:l(b);y!==b&&(f=y-p);const j=C=>-f*Math.exp(-C/r),v=C=>y+j(C),w=C=>{const F=j(C),N=v(C);x.done=Math.abs(F)<=d,x.value=x.done?y:N};let S,D;const k=C=>{h(x.value)&&(S=C,D=bl({keyframes:[x.value,g(x.value)],velocity:jf(v,C,x.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return k(0),{calculatedDuration:null,next:C=>{let F=!1;return!D&&S===void 0&&(F=!0,w(C),k(C)),S!==void 0&&C>=S?D.next(C-S):(!F&&w(C),x)}}}function I2(t,s,a){const r=[],n=a||er.mix||ff,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]||va:s;o=Ai(c,o)}r.push(o)}return r}function F2(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(jd(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=I2(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=ci(t[p],t[p+1],m);return o[p](x)};return a?m=>d(qa(t[0],t[i-1],m)):d}function P2(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=ci(0,s,r);t.push(ls(a,1,n))}}function E2(t){const s=[0];return P2(s,t.length-1),s}function _2(t,s){return t.map(a=>a*s)}function M2(t,s){return t.map(()=>s||lf).splice(0,t.length-1)}function qn({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=YC(r)?r.map(hx):hx(r),i={done:!1,value:s[0]},l=_2(a&&a.length===s.length?a:E2(s),t),o=F2(l,s,{ease:Array.isArray(n)?n:M2(s,n)});return{calculatedDuration:t,next:c=>(i.value=o(c),i.done=c>=t,i)}}const L2=t=>t!==null;function Rd(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(L2),o=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const O2={decay:hc,inertia:hc,tween:qn,keyframes:qn,spring:bl};function yf(t){typeof t.type=="string"&&(t.type=O2[t.type])}class Id{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 $2=t=>t/100;class Fd extends Id{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!==aa.now()&&this.tick(aa.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;yf(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=Ai($2,ff(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=Dd(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,w=r;if(p){const C=Math.min(this.currentTime,n)/o;let F=Math.floor(C),N=C%1;!N&&C>=1&&(N=1),N===1&&F--,F=Math.min(F,p+1),!!(F%2)&&(x==="reverse"?(N=1-N,h&&(N-=h/o)):x==="mirror"&&(w=l)),v=qa(0,1,N)*o}const S=j?{done:!1,value:m[0]}:w.next(v);i&&(S.value=i(S.value));let{done:D}=S;!j&&c!==null&&(D=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const k=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return k&&g!==hc&&(S.value=Rd(m,this.options,b,this.speed)),f&&f(S.value),k&&this.finish(),S}then(s,a){return this.finished.then(s,a)}get duration(){return ja(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ja(s)}get time(){return ja(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(aa.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=ja(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=N2,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(aa.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 U2(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const Vr=t=>t*180/Math.PI,pc=t=>{const s=Vr(Math.atan2(t[1],t[0]));return gc(s)},B2={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:pc,rotateZ:pc,skewX:t=>Vr(Math.atan(t[1])),skewY:t=>Vr(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},gc=t=>(t=t%360,t<0&&(t+=360),t),yx=pc,vx=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Nx=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),z2={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:vx,scaleY:Nx,scale:t=>(vx(t)+Nx(t))/2,rotateX:t=>gc(Vr(Math.atan2(t[6],t[5]))),rotateY:t=>gc(Vr(Math.atan2(-t[2],t[0]))),rotateZ:yx,rotate:yx,skewX:t=>Vr(Math.atan(t[4])),skewY:t=>Vr(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function fc(t){return t.includes("scale")?1:0}function bc(t,s){if(!t||t==="none")return fc(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=z2,n=a;else{const o=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=B2,n=o}if(!n)return fc(s);const i=r[s],l=n[1].split(",").map(W2);return typeof i=="function"?i(l):l[i]}const V2=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return bc(a,s)};function W2(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),wx=t=>t===Rn||t===mt,H2=new Set(["x","y","z"]),G2=In.filter(t=>!H2.has(t));function Y2(t){const s=[];return G2.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const Wr={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})=>bc(s,"x"),y:(t,{transform:s})=>bc(s,"y")};Wr.translateX=Wr.x;Wr.translateY=Wr.y;const Hr=new Set;let jc=!1,yc=!1,vc=!1;function vf(){if(yc){const t=Array.from(Hr).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=Y2(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)})}yc=!1,jc=!1,Hr.forEach(t=>t.complete(vc)),Hr.clear()}function Nf(){Hr.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(yc=!0)})}function K2(){vc=!0,Nf(),vf(),vc=!1}class Pd{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?(Hr.add(this),jc||(jc=!0,ts.read(Nf),ts.resolveKeyframes(vf))):(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])}U2(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),Hr.delete(this)}cancel(){this.state==="scheduled"&&(Hr.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Q2=t=>t.startsWith("--");function X2(t,s,a){Q2(s)?t.style.setProperty(s,a):t.style[s]=a}const J2=yd(()=>window.ScrollTimeline!==void 0),Z2={};function q2(t,s){const a=yd(t);return()=>Z2[s]??a()}const wf=q2(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Qn=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,Cx={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Qn([0,.65,.55,1]),circOut:Qn([.55,0,1,.45]),backIn:Qn([.31,.01,.66,-.59]),backOut:Qn([.33,1.53,.69,.99])};function Cf(t,s){if(t)return typeof t=="function"?wf()?bf(t,s):"ease-out":of(t)?Qn(t):Array.isArray(t)?t.map(a=>Cf(a,s)||Cx.easeOut):Cx[t]}function eS(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=Cf(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 Sf(t){return typeof t=="function"&&"applyToOptions"in t}function tS({type:t,...s}){return Sf(t)&&wf()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class sS extends Id{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,jd(typeof s.type!="string");const d=tS(s);this.animation=eS(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=Rd(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(m):X2(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 ja(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ja(s)}get time(){return ja(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&&J2()?(this.animation.timeline=s,va):a(this)}}const Af={anticipate:af,backInOut:sf,circInOut:nf};function aS(t){return t in Af}function rS(t){typeof t.ease=="string"&&aS(t.ease)&&(t.ease=Af[t.ease])}const Sx=10;class nS extends sS{constructor(s){rS(s),yf(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 Fd({...l,autoplay:!1}),c=Ba(this.finishedTime??this.time);a.setWithVelocity(o.sample(c-Sx).value,o.sample(c).value,Sx),o.stop()}}const Ax=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(jr.test(t)||t==="0")&&!t.startsWith("url("));function iS(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 lS(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=Ax(n,s),o=Ax(i,s);return!l||!o?!1:iS(t)||(a==="spring"||Sf(a))&&r}function Nc(t){t.duration=0,t.type="keyframes"}const oS=new Set(["opacity","clipPath","filter","transform"]),cS=yd(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function dS(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 cS()&&a&&oS.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&l!=="inertia"}const mS=40;class uS extends Id{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=aa.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)||Pd;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=aa.now(),lS(s,i,l,o)||((er.instantAnimations||!c)&&(m==null||m(Rd(s,r,a))),s[0]=s[s.length-1],Nc(r),r.repeat=0);const x={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>mS?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},h=!d&&dS(x)?new nS({...x,element:x.motionValue.owner.current}):new Fd(x);h.finished.then(()=>this.notifyFinished()).catch(va),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(),K2()),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 xS=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function hS(t){const s=xS.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Tf(t,s,a=1){const[r,n]=hS(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const l=i.trim();return Kg(l)?parseFloat(l):l}return Sd(n)?Tf(n,s,a+1):n}function Ed(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const kf=new Set(["width","height","top","left","right","bottom",...In]),pS={test:t=>t==="auto",parse:t=>t},Df=t=>s=>s.test(t),Rf=[Rn,mt,za,ur,i2,n2,pS],Tx=t=>Rf.find(Df(t));function gS(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Xg(t):!0}const fS=new Set(["brightness","contrast","saturate","opacity"]);function bS(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(Ad)||[];if(!r)return t;const n=a.replace(r,"");let i=fS.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const jS=/\b([a-z-]*)\(.*?\)/gu,wc={...jr,getAnimatableNone:t=>{const s=t.match(jS);return s?s.map(bS).join(" "):t}},kx={...Rn,transform:Math.round},yS={rotate:ur,rotateX:ur,rotateY:ur,rotateZ:ur,scale:Oi,scaleX:Oi,scaleY:Oi,scaleZ:Oi,skew:ur,skewX:ur,skewY:ur,distance:mt,translateX:mt,translateY:mt,translateZ:mt,x:mt,y:mt,z:mt,perspective:mt,transformPerspective:mt,opacity:di,originX:px,originY:px,originZ:mt},_d={borderWidth:mt,borderTopWidth:mt,borderRightWidth:mt,borderBottomWidth:mt,borderLeftWidth:mt,borderRadius:mt,radius:mt,borderTopLeftRadius:mt,borderTopRightRadius:mt,borderBottomRightRadius:mt,borderBottomLeftRadius:mt,width:mt,maxWidth:mt,height:mt,maxHeight:mt,top:mt,right:mt,bottom:mt,left:mt,padding:mt,paddingTop:mt,paddingRight:mt,paddingBottom:mt,paddingLeft:mt,margin:mt,marginTop:mt,marginRight:mt,marginBottom:mt,marginLeft:mt,backgroundPositionX:mt,backgroundPositionY:mt,...yS,zIndex:kx,fillOpacity:di,strokeOpacity:di,numOctaves:kx},vS={..._d,color:bs,backgroundColor:bs,outlineColor:bs,fill:bs,stroke:bs,borderColor:bs,borderTopColor:bs,borderRightColor:bs,borderBottomColor:bs,borderLeftColor:bs,filter:wc,WebkitFilter:wc},If=t=>vS[t];function Ff(t,s){let a=If(t);return a!==wc&&(a=jr),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const NS=new Set(["auto","none","0"]);function wS(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!NS.has(i)&&mi(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=Ff(a,n)}class CS extends Pd{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(),Sd(d))){const m=Tf(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!kf.has(r)||s.length!==2)return;const[n,i]=s,l=Tx(n),o=Tx(i);if(l!==o)if(wx(l)&&wx(o))for(let c=0;c<s.length;c++){const d=s[c];typeof d=="string"&&(s[c]=parseFloat(d))}else Wr[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||gS(s[n]))&&r.push(n);r.length&&wS(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=Wr[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]=Wr[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 SS(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 Pf=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function Ef(t){return Qg(t)&&"offsetHeight"in t}const Dx=30,AS=t=>!isNaN(parseFloat(t));class TS{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=aa.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=aa.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=AS(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 vd);const r=this.events[s].add(a);return s==="change"?()=>{r(),ts.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=aa.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>Dx)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,Dx);return Jg(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 TS(t,s)}const{schedule:Md}=cf(queueMicrotask,!1),Ia={x:!1,y:!1};function _f(){return Ia.x||Ia.y}function kS(t){return t==="x"||t==="y"?Ia[t]?null:(Ia[t]=!0,()=>{Ia[t]=!1}):Ia.x||Ia.y?null:(Ia.x=Ia.y=!0,()=>{Ia.x=Ia.y=!1})}function Mf(t,s){const a=SS(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function Rx(t){return!(t.pointerType==="touch"||_f())}function DS(t,s,a={}){const[r,n,i]=Mf(t,a),l=o=>{if(!Rx(o))return;const{target:c}=o,d=s(c,o);if(typeof d!="function"||!c)return;const m=p=>{Rx(p)&&(d(p),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(o=>{o.addEventListener("pointerenter",l,n)}),i}const Lf=(t,s)=>s?t===s?!0:Lf(t,s.parentElement):!1,Ld=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,RS=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function IS(t){return RS.has(t.tagName)||t.tabIndex!==-1}const sl=new WeakSet;function Ix(t){return s=>{s.key==="Enter"&&t(s)}}function wo(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const FS=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=Ix(()=>{if(sl.has(a))return;wo(a,"down");const n=Ix(()=>{wo(a,"up")}),i=()=>wo(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 Fx(t){return Ld(t)&&!_f()}function PS(t,s,a={}){const[r,n,i]=Mf(t,a),l=o=>{const c=o.currentTarget;if(!Fx(o))return;sl.add(c);const d=s(c,o),m=(h,g)=>{window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",x),sl.has(c)&&sl.delete(c),Fx(h)&&typeof d=="function"&&d(h,{success:g})},p=h=>{m(h,c===window||c===document||a.useGlobalTarget||Lf(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),Ef(o)&&(o.addEventListener("focus",d=>FS(d,n)),!IS(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function Of(t){return Qg(t)&&"ownerSVGElement"in t}function ES(t){return Of(t)&&t.tagName==="svg"}const zs=t=>!!(t&&t.getVelocity),_S=[...Rf,bs,jr],MS=t=>_S.find(Df(t)),Od=u.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function Px(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function LS(...t){return s=>{let a=!1;const r=t.map(n=>{const i=Px(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():Px(t[n],null)}}}}function OS(...t){return u.useCallback(LS(...t),t)}class $S extends u.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=Ef(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 US({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(Od),c=OS(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($S,{isPresent:s,childRef:i,sizeRef:l,children:u.cloneElement(t,{ref:c})})}const BS=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=pd(zS),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(US,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(Yl.Provider,{value:x,children:t})};function zS(){return new Map}function $f(t=!0){const s=u.useContext(Yl);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 $i=t=>t.key||"";function Ex(t){const s=[];return u.Children.forEach(t,a=>{u.isValidElement(a)&&s.push(a)}),s}const Kl=({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]=$f(l),p=u.useMemo(()=>Ex(t),[t]),x=l&&!d?[]:p.map($i),h=u.useRef(!0),g=u.useRef(p),f=pd(()=>new Map),[b,y]=u.useState(p),[j,v]=u.useState(p);Yg(()=>{h.current=!1,g.current=p;for(let D=0;D<j.length;D++){const k=$i(j[D]);x.includes(k)?f.delete(k):f.get(k)!==!0&&f.set(k,!1)}},[j,x.length,x.join("-")]);const w=[];if(p!==b){let D=[...p];for(let k=0;k<j.length;k++){const C=j[k],F=$i(C);x.includes(F)||(D.splice(k,0,C),w.push(C))}return i==="wait"&&w.length&&(D=w),v(Ex(D)),y(p),null}const{forceRender:S}=u.useContext(hd);return e.jsx(e.Fragment,{children:j.map(D=>{const k=$i(D),C=l&&!d?!1:p===j||x.includes(k),F=()=>{if(f.has(k))f.set(k,!0);else return;let N=!0;f.forEach(E=>{E||(N=!1)}),N&&(S==null||S(),v(g.current),l&&(m==null||m()),r&&r())};return e.jsx(BS,{isPresent:C,initial:!h.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:C?void 0:F,anchorX:o,children:D},k)})})},Uf=u.createContext({strict:!1}),_x={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 _x)Cn[t]={isEnabled:s=>_x[t].some(a=>!!s[a])};function VS(t){for(const s in t)Cn[s]={...Cn[s],...t[s]}}const WS=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 jl(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||WS.has(t)}let Bf=t=>!jl(t);function HS(t){typeof t=="function"&&(Bf=s=>s.startsWith("on")?!jl(s):t(s))}try{HS(require("@emotion/is-prop-valid").default)}catch{}function GS(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(Bf(n)||a===!0&&jl(n)||!s&&!jl(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Ql=u.createContext({});function Xl(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function ui(t){return typeof t=="string"||Array.isArray(t)}const $d=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Ud=["initial",...$d];function Jl(t){return Xl(t.animate)||Ud.some(s=>ui(t[s]))}function zf(t){return!!(Jl(t)||t.variants)}function YS(t,s){if(Jl(t)){const{initial:a,animate:r}=t;return{initial:a===!1||ui(a)?a:void 0,animate:ui(r)?r:void 0}}return t.inherit!==!1?s:{}}function KS(t){const{initial:s,animate:a}=YS(t,u.useContext(Ql));return u.useMemo(()=>({initial:s,animate:a}),[Mx(s),Mx(a)])}function Mx(t){return Array.isArray(t)?t.join(" "):t}const xi={};function QS(t){for(const s in t)xi[s]=t[s],Cd(s)&&(xi[s].isCSSVariable=!0)}function Vf(t,{layout:s,layoutId:a}){return Fn.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!xi[t]||t==="opacity")}const XS={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},JS=In.length;function ZS(t,s,a){let r="",n=!0;for(let i=0;i<JS;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=Pf(o,_d[l]);if(!c){n=!1;const m=XS[l]||l;r+=`${m}(${d}) `}a&&(s[l]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function Bd(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(Cd(c)){n[c]=d;continue}else{const m=Pf(d,_d[c]);c.startsWith("origin")?(o=!0,i[c]=m):r[c]=m}}if(s.transform||(l||a?r.transform=ZS(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 zd=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Wf(t,s,a){for(const r in s)!zs(s[r])&&!Vf(r,a)&&(t[r]=s[r])}function qS({transformTemplate:t},s){return u.useMemo(()=>{const a=zd();return Bd(a,s,t),Object.assign({},a.vars,a.style)},[s])}function eA(t,s){const a=t.style||{},r={};return Wf(r,a,t),Object.assign(r,qS(t,s)),r}function tA(t,s){const a={},r=eA(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 sA={offset:"stroke-dashoffset",array:"stroke-dasharray"},aA={offset:"strokeDashoffset",array:"strokeDasharray"};function rA(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?sA:aA;t[i.offset]=mt.transform(-r);const l=mt.transform(s),o=mt.transform(a);t[i.array]=`${l} ${o}`}function Hf(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(Bd(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&&rA(p,n,i,l,!1)}const Gf=()=>({...zd(),attrs:{}}),Yf=t=>typeof t=="string"&&t.toLowerCase()==="svg";function nA(t,s,a,r){const n=u.useMemo(()=>{const i=Gf();return Hf(i,s,Yf(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};Wf(i,t.style,t),n.style={...i,...n.style}}return n}const iA=["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 Vd(t){return typeof t!="string"||t.includes("-")?!1:!!(iA.indexOf(t)>-1||/[A-Z]/u.test(t))}function lA(t,s,a,{latestValues:r},n,i=!1){const o=(Vd(t)?nA:tA)(s,r,n,t),c=GS(s,typeof t=="string",i),d=t!==u.Fragment?{...c,...o,ref:a}:{},{children:m}=s,p=u.useMemo(()=>zs(m)?m.get():m,[m]);return u.createElement(t,{...d,children:p})}function Lx(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function Wd(t,s,a,r){if(typeof s=="function"){const[n,i]=Lx(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]=Lx(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function al(t){return zs(t)?t.get():t}function oA({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:cA(a,r,n,t),renderState:s()}}function cA(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=al(i[x]);let{initial:l,animate:o}=t;const c=Jl(t),d=zf(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"&&!Xl(p)){const x=Array.isArray(p)?p:[p];for(let h=0;h<x.length;h++){const g=Wd(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 w=m?v.length-1:0;v=v[w]}v!==null&&(n[j]=v)}for(const j in f)n[j]=f[j]}}}return n}const Kf=t=>(s,a)=>{const r=u.useContext(Ql),n=u.useContext(Yl),i=()=>oA(t,s,r,n);return a?i():pd(i)};function Hd(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(zs(r[l])||s.style&&zs(s.style[l])||Vf(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const dA=Kf({scrapeMotionValuesFromProps:Hd,createRenderState:zd});function Qf(t,s,a){const r=Hd(t,s,a);for(const n in t)if(zs(t[n])||zs(s[n])){const i=In.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const mA=Kf({scrapeMotionValuesFromProps:Qf,createRenderState:Gf}),uA=Symbol.for("motionComponentSymbol");function un(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function xA(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):un(a)&&(a.current=r))},[s])}const Gd=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),hA="framerAppearId",Xf="data-"+Gd(hA),Jf=u.createContext({});function pA(t,s,a,r,n){var f,b;const{visualElement:i}=u.useContext(Ql),l=u.useContext(Uf),o=u.useContext(Yl),c=u.useContext(Od).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(Jf);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&gA(d.current,a,n,p);const x=u.useRef(!1);u.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const h=a[Xf],g=u.useRef(!!h&&!((f=window.MotionHandoffIsComplete)!=null&&f.call(window,h))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,h)));return Yg(()=>{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 gA(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:Zf(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&un(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function Zf(t){if(t)return t.options.allowProjection!==!1?t.projection:Zf(t.parent)}function Co(t,{forwardMotionProps:s=!1}={},a,r){a&&VS(a);const n=Vd(t)?mA:dA;function i(o,c){let d;const m={...u.useContext(Od),...o,layoutId:fA(o)},{isStatic:p}=m,x=KS(o),h=n(o,p);if(!p&&gd){bA();const g=jA(m);d=g.MeasureLayout,x.visualElement=pA(t,h,m,r,g.ProjectionNode)}return e.jsxs(Ql.Provider,{value:x,children:[d&&x.visualElement?e.jsx(d,{visualElement:x.visualElement,...m}):null,lA(t,o,xA(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[uA]=t,l}function fA({layoutId:t}){const s=u.useContext(hd).id;return s&&t!==void 0?s+"-"+t:t}function bA(t,s){u.useContext(Uf).strict}function jA(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 yA(t,s){if(typeof Proxy>"u")return Co;const a=new Map,r=(i,l)=>Co(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,Co(l,void 0,t,s)),a.get(l))})}function qf({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function vA({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function NA(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 So(t){return t===void 0||t===1}function Cc({scale:t,scaleX:s,scaleY:a}){return!So(t)||!So(s)||!So(a)}function Lr(t){return Cc(t)||e0(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function e0(t){return Ox(t.x)||Ox(t.y)}function Ox(t){return t&&t!=="0%"}function yl(t,s,a){const r=t-a,n=s*r;return a+n}function $x(t,s,a,r,n){return n!==void 0&&(t=yl(t,n,r)),yl(t,a,r)+s}function Sc(t,s=0,a=1,r,n){t.min=$x(t.min,s,a,r,n),t.max=$x(t.max,s,a,r,n)}function t0(t,{x:s,y:a}){Sc(t.x,s.translate,s.scale,s.originPoint),Sc(t.y,a.translate,a.scale,a.originPoint)}const Ux=.999999999999,Bx=1.0000000000001;function wA(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&&hn(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),l&&(s.x*=l.x.scale,s.y*=l.y.scale,t0(t,l)),r&&Lr(i.latestValues)&&hn(t,i.latestValues))}s.x<Bx&&s.x>Ux&&(s.x=1),s.y<Bx&&s.y>Ux&&(s.y=1)}function xn(t,s){t.min=t.min+s,t.max=t.max+s}function zx(t,s,a,r,n=.5){const i=ls(t.min,t.max,n);Sc(t,s,a,i,r)}function hn(t,s){zx(t.x,s.x,s.scaleX,s.scale,s.originX),zx(t.y,s.y,s.scaleY,s.scale,s.originY)}function s0(t,s){return qf(NA(t.getBoundingClientRect(),s))}function CA(t,s,a){const r=s0(t,a),{scroll:n}=s;return n&&(xn(r.x,n.offset.x),xn(r.y,n.offset.y)),r}const Vx=()=>({translate:0,scale:1,origin:0,originPoint:0}),pn=()=>({x:Vx(),y:Vx()}),Wx=()=>({min:0,max:0}),ps=()=>({x:Wx(),y:Wx()}),Ac={current:null},a0={current:!1};function SA(){if(a0.current=!0,!!gd)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>Ac.current=t.matches;t.addEventListener("change",s),s()}else Ac.current=!1}const AA=new WeakMap;function TA(t,s,a){for(const r in s){const n=s[r],i=a[r];if(zs(n))t.addValue(r,n);else if(zs(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 Hx=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class kA{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=Pd,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=aa.now();this.renderScheduledAt<x&&(this.renderScheduledAt=x,ts.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=Jl(a),this.isVariantNode=zf(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&&zs(h)&&h.set(c[x])}}mount(s){var a;this.current=s,AA.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)),a0.current||SA(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Ac.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),br(this.notifyUpdate),br(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&&ts.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):ps()}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<Hx.length;r++){const n=Hx[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=TA(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"&&(Kg(r)||Xg(r))?r=parseFloat(r):!MS(r)&&jr.test(a)&&(r=Ff(s,a)),this.setBaseTarget(s,zs(r)?r.get():r)),zs(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=Wd(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&&!zs(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 vd),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){Md.render(this.render)}}class r0 extends kA{constructor(){super(...arguments),this.KeyframeResolver=CS}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;zs(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function n0(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 DA(t){return window.getComputedStyle(t)}class RA extends r0{constructor(){super(...arguments),this.type="html",this.renderInstance=n0}readValueFromInstance(s,a){var r;if(Fn.has(a))return(r=this.projection)!=null&&r.isProjecting?fc(a):V2(s,a);{const n=DA(s),i=(Cd(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return s0(s,a)}build(s,a,r){Bd(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return Hd(s,a,r)}}const i0=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 IA(t,s,a,r){n0(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(i0.has(n)?n:Gd(n),s.attrs[n])}class FA extends r0{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ps}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Fn.has(a)){const r=If(a);return r&&r.default||0}return a=i0.has(a)?a:Gd(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return Qf(s,a,r)}build(s,a,r){Hf(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){IA(s,a,r,n)}mount(s){this.isSVGTag=Yf(s.tagName),super.mount(s)}}const PA=(t,s)=>Vd(t)?new FA(s):new RA(s,{allowProjection:t!==u.Fragment});function vn(t,s,a){const r=t.getProps();return Wd(r,s,a!==void 0?a:r.custom,t)}const Tc=t=>Array.isArray(t);function EA(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,wn(a))}function _A(t){return Tc(t)?t[t.length-1]||0:t}function MA(t,s){const a=vn(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=_A(i[l]);EA(t,l,o)}}function LA(t){return!!(zs(t)&&t.add)}function kc(t,s){const a=t.getValue("willChange");if(LA(a))return a.add(s);if(!a&&er.WillChange){const r=new er.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function l0(t){return t.props[Xf]}const OA=t=>t!==null;function $A(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(OA),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const UA={type:"spring",stiffness:500,damping:25,restSpeed:10},BA=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),zA={type:"keyframes",duration:.8},VA={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},WA=(t,{keyframes:s})=>s.length>2?zA:Fn.has(t)?t.startsWith("scale")?BA(s[1]):UA:VA;function HA({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 Yd=(t,s,a,r={},n,i)=>l=>{const o=Ed(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};HA(o)||Object.assign(m,WA(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)&&(Nc(m),m.delay===0&&(p=!0)),(er.instantAnimations||er.skipAnimations)&&(p=!0,Nc(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,p&&!i&&s.get()!==void 0){const x=$A(m.keyframes,o);if(x!==void 0){ts.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Fd(m):new uS(m)};function GA({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function o0(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&&GA(d,m))continue;const h={delay:a,...Ed(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=l0(t);if(y){const j=window.MotionHandoffAnimation(y,m,ts);j!==null&&(h.startTime=j,f=!0)}}kc(t,m),p.start(Yd(m,p,x,t.shouldReduceMotion&&kf.has(m)?{type:!1}:h,t,f));const b=p.animation;b&&c.push(b)}return l&&Promise.all(c).then(()=>{ts.update(()=>{l&&MA(t,l)})}),c}function c0(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 Dc(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(o0(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:p,staggerDirection:x}=n;return YA(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 YA(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(Dc(c,s,{...l,delay:a+(typeof r=="function"?0:r)+c0(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function KA(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>Dc(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=Dc(t,s,a);else{const n=typeof s=="function"?vn(t,s,a.custom):s;r=Promise.all(o0(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function d0(t,s){if(!Array.isArray(s))return!1;const a=s.length;if(a!==t.length)return!1;for(let r=0;r<a;r++)if(s[r]!==t[r])return!1;return!0}const QA=Ud.length;function m0(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?m0(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<QA;a++){const r=Ud[a],n=t.props[r];(ui(n)||n===!1)&&(s[r]=n)}return s}const XA=[...$d].reverse(),JA=$d.length;function ZA(t){return s=>Promise.all(s.map(({animation:a,options:r})=>KA(t,a,r)))}function qA(t){let s=ZA(t),a=Gx(),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=m0(t.parent)||{},p=[],x=new Set;let h={},g=1/0;for(let b=0;b<JA;b++){const y=XA[b],j=a[y],v=d[y]!==void 0?d[y]:m[y],w=ui(v),S=y===c?j.isActive:null;S===!1&&(g=b);let D=v===m[y]&&v!==d[y]&&w;if(D&&r&&t.manuallyAnimateOnMount&&(D=!1),j.protectedKeys={...h},!j.isActive&&S===null||!v&&!j.prevProp||Xl(v)||typeof v=="boolean")continue;const k=e5(j.prevProp,v);let C=k||y===c&&j.isActive&&!D&&w||b>g&&w,F=!1;const N=Array.isArray(v)?v:[v];let E=N.reduce(n(y),{});S===!1&&(E={});const{prevResolvedValues:_={}}=j,z={..._,...E},R=I=>{C=!0,x.has(I)&&(F=!0,x.delete(I)),j.needsAnimating[I]=!0;const A=t.getValue(I);A&&(A.liveStyle=!1)};for(const I in z){const A=E[I],G=_[I];if(h.hasOwnProperty(I))continue;let $=!1;Tc(A)&&Tc(G)?$=!d0(A,G):$=A!==G,$?A!=null?R(I):x.add(I):A!==void 0&&x.has(I)?R(I):j.protectedKeys[I]=!0}j.prevProp=v,j.prevResolvedValues=E,j.isActive&&(h={...h,...E}),r&&t.blockInitialAnimation&&(C=!1);const L=D&&k;C&&(!L||F)&&p.push(...N.map(I=>{const A={type:y};if(typeof I=="string"&&r&&!L&&t.manuallyAnimateOnMount&&t.parent){const{parent:G}=t,$=vn(G,I);if(G.enteringChildren&&$){const{delayChildren:M}=$.transition||{};A.delay=c0(G.enteringChildren,t,M)}}return{animation:I,options:A}}))}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=Gx()}}}function e5(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!d0(s,t):!1}function Pr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Gx(){return{animate:Pr(!0),whileInView:Pr(),whileHover:Pr(),whileTap:Pr(),whileDrag:Pr(),whileFocus:Pr(),exit:Pr()}}class wr{constructor(s){this.isMounted=!1,this.node=s}update(){}}class t5 extends wr{constructor(s){super(s),s.animationState||(s.animationState=qA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Xl(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 s5=0;class a5 extends wr{constructor(){super(...arguments),this.id=s5++}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 r5={animation:{Feature:t5},exit:{Feature:a5}};function hi(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function Di(t){return{point:{x:t.pageX,y:t.pageY}}}const n5=t=>s=>Ld(s)&&t(s,Di(s));function ei(t,s,a,r){return hi(t,s,n5(a),r)}const u0=1e-4,i5=1-u0,l5=1+u0,x0=.01,o5=0-x0,c5=0+x0;function Ys(t){return t.max-t.min}function d5(t,s,a){return Math.abs(t-s)<=a}function Yx(t,s,a,r=.5){t.origin=r,t.originPoint=ls(s.min,s.max,t.origin),t.scale=Ys(a)/Ys(s),t.translate=ls(a.min,a.max,t.origin)-t.originPoint,(t.scale>=i5&&t.scale<=l5||isNaN(t.scale))&&(t.scale=1),(t.translate>=o5&&t.translate<=c5||isNaN(t.translate))&&(t.translate=0)}function ti(t,s,a,r){Yx(t.x,s.x,a.x,r?r.originX:void 0),Yx(t.y,s.y,a.y,r?r.originY:void 0)}function Kx(t,s,a){t.min=a.min+s.min,t.max=t.min+Ys(s)}function m5(t,s,a){Kx(t.x,s.x,a.x),Kx(t.y,s.y,a.y)}function Qx(t,s,a){t.min=s.min-a.min,t.max=t.min+Ys(s)}function si(t,s,a){Qx(t.x,s.x,a.x),Qx(t.y,s.y,a.y)}function ba(t){return[t("x"),t("y")]}const h0=({current:t})=>t?t.ownerDocument.defaultView:null,Xx=(t,s)=>Math.abs(t-s);function u5(t,s){const a=Xx(t.x,s.x),r=Xx(t.y,s.y);return Math.sqrt(a**2+r**2)}class p0{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=To(this.lastMoveEventInfo,this.history),h=this.startEvent!==null,g=u5(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!h&&!g)return;const{point:f}=x,{timestamp:b}=Ms;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=Ao(h,this.transformPagePoint),ts.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=To(x.type==="pointercancel"?this.lastMoveEventInfo:Ao(h,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,y),f&&f(x,y)},!Ld(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=Di(s),c=Ao(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=Ms;this.history=[{...d,timestamp:m}];const{onSessionStart:p}=a;p&&p(s,To(c,this.history)),this.removeListeners=Ai(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(),br(this.updatePoint)}}function Ao(t,s){return s?{point:s(t.point)}:t}function Jx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function To({point:t},s){return{point:t,delta:Jx(t,g0(s)),offset:Jx(t,x5(s)),velocity:h5(s,.1)}}function x5(t){return t[0]}function g0(t){return t[t.length-1]}function h5(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=g0(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>Ba(s)));)a--;if(!r)return{x:0,y:0};const i=ja(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 p5(t,{min:s,max:a},r){return s!==void 0&&t<s?t=r?ls(s,t,r.min):Math.max(t,s):a!==void 0&&t>a&&(t=r?ls(a,t,r.max):Math.min(t,a)),t}function Zx(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 g5(t,{top:s,left:a,bottom:r,right:n}){return{x:Zx(t.x,a,n),y:Zx(t.y,s,r)}}function qx(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 f5(t,s){return{x:qx(t.x,s.x),y:qx(t.y,s.y)}}function b5(t,s){let a=.5;const r=Ys(t),n=Ys(s);return n>r?a=ci(s.min,s.max-r,t.min):r>n&&(a=ci(t.min,t.max-n,s.min)),qa(0,1,a)}function j5(t,s){const a={};return s.min!==void 0&&(a.min=s.min-t.min),s.max!==void 0&&(a.max=s.max-t.min),a}const Rc=.35;function y5(t=Rc){return t===!1?t=0:t===!0&&(t=Rc),{x:eh(t,"left","right"),y:eh(t,"top","bottom")}}function eh(t,s,a){return{min:th(t,s),max:th(t,a)}}function th(t,s){return typeof t=="number"?t:t[s]||0}const v5=new WeakMap;class N5{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=ps(),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(Di(p).point)},l=(p,x)=>{const{drag:h,dragPropagation:g,onDragStart:f}=this.getProps();if(h&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=kS(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),ba(y=>{let j=this.getAxisMotionValue(y).get()||0;if(za.test(j)){const{projection:v}=this.visualElement;if(v&&v.layout){const w=v.layout.layoutBox[y];w&&(j=Ys(w)*(parseFloat(j)/100))}}this.originPoint[y]=j}),f&&ts.postRender(()=>f(p,x)),kc(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=w5(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=()=>ba(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 p0(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:h0(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&&ts.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||!Ui(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=p5(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&&un(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=g5(r.layoutBox,s):this.constraints=!1,this.elastic=y5(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&ba(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=j5(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!un(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=CA(r,n.root,this.visualElement.getTransformPagePoint());let l=f5(n.layout.layoutBox,i);if(a){const o=a(vA(l));this.hasMutatedConstraints=!!o,o&&(l=qf(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=ba(m=>{if(!Ui(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 kc(this.visualElement,s),r.start(Yd(s,r,0,a,this.visualElement,!1))}stopAnimation(){ba(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){ba(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){ba(a=>{const{drag:r}=this.getProps();if(!Ui(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]-ls(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!un(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};ba(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=b5({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(),ba(l=>{if(!Ui(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(ls(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;v5.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();un(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()),ts.read(r);const l=hi(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(ba(m=>{const p=this.getAxisMotionValue(m);p&&(this.originPoint[m]+=c[m].translate,p.set(p.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=Rc,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Ui(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function w5(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class C5 extends wr{constructor(s){super(s),this.removeGroupControls=va,this.removeListeners=va,this.controls=new N5(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||va}unmount(){this.removeGroupControls(),this.removeListeners()}}const sh=t=>(s,a)=>{t&&ts.postRender(()=>t(s,a))};class S5 extends wr{constructor(){super(...arguments),this.removePointerDownListener=va}onPointerDown(s){this.session=new p0(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:h0(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:sh(s),onStart:sh(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&ts.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 rl={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function ah(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(mt.test(t))t=parseFloat(t);else return t;const a=ah(t,s.target.x),r=ah(t,s.target.y);return`${a}% ${r}%`}},A5={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=jr.parse(t);if(n.length>5)return r;const i=jr.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=ls(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 ko=!1;class T5 extends u.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;QS(k5),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),ko&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),rl.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,ko=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||ts.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Md.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;ko=!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 f0(t){const[s,a]=$f(),r=u.useContext(hd);return e.jsx(T5,{...t,layoutGroup:r,switchLayoutGroup:u.useContext(Jf),isPresent:s,safeToRemove:a})}const k5={borderRadius:{...Bn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Bn,borderTopRightRadius:Bn,borderBottomLeftRadius:Bn,borderBottomRightRadius:Bn,boxShadow:A5};function D5(t,s,a){const r=zs(t)?t:wn(t);return r.start(Yd("",r,s,a)),r.animation}const R5=(t,s)=>t.depth-s.depth;class I5{constructor(){this.children=[],this.isDirty=!1}add(s){fd(this.children,s),this.isDirty=!0}remove(s){bd(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(R5),this.isDirty=!1,this.children.forEach(s)}}function F5(t,s){const a=aa.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(br(r),t(i-s))};return ts.setup(r,!0),()=>br(r)}const b0=["TopLeft","TopRight","BottomLeft","BottomRight"],P5=b0.length,rh=t=>typeof t=="string"?parseFloat(t):t,nh=t=>typeof t=="number"||mt.test(t);function E5(t,s,a,r,n,i){n?(t.opacity=ls(0,a.opacity??1,_5(r)),t.opacityExit=ls(s.opacity??1,0,M5(r))):i&&(t.opacity=ls(s.opacity??1,a.opacity??1,r));for(let l=0;l<P5;l++){const o=`border${b0[l]}Radius`;let c=ih(s,o),d=ih(a,o);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||nh(c)===nh(d)?(t[o]=Math.max(ls(rh(c),rh(d),r),0),(za.test(d)||za.test(c))&&(t[o]+="%")):t[o]=d}(s.rotate||a.rotate)&&(t.rotate=ls(s.rotate||0,a.rotate||0,r))}function ih(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const _5=j0(0,.5,rf),M5=j0(.5,.95,va);function j0(t,s,a){return r=>r<t?0:r>s?1:a(ci(t,s,r))}function lh(t,s){t.min=s.min,t.max=s.max}function fa(t,s){lh(t.x,s.x),lh(t.y,s.y)}function oh(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function ch(t,s,a,r,n){return t-=s,t=yl(t,1/a,r),n!==void 0&&(t=yl(t,1/n,r)),t}function L5(t,s=0,a=1,r=.5,n,i=t,l=t){if(za.test(s)&&(s=parseFloat(s),s=ls(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=ls(i.min,i.max,r);t===i&&(o-=s),t.min=ch(t.min,s,a,o,n),t.max=ch(t.max,s,a,o,n)}function dh(t,s,[a,r,n],i,l){L5(t,s[a],s[r],s[n],s.scale,i,l)}const O5=["x","scaleX","originX"],$5=["y","scaleY","originY"];function mh(t,s,a,r){dh(t.x,s,O5,a?a.x:void 0,r?r.x:void 0),dh(t.y,s,$5,a?a.y:void 0,r?r.y:void 0)}function uh(t){return t.translate===0&&t.scale===1}function y0(t){return uh(t.x)&&uh(t.y)}function xh(t,s){return t.min===s.min&&t.max===s.max}function U5(t,s){return xh(t.x,s.x)&&xh(t.y,s.y)}function hh(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function v0(t,s){return hh(t.x,s.x)&&hh(t.y,s.y)}function ph(t){return Ys(t.x)/Ys(t.y)}function gh(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class B5{constructor(){this.members=[]}add(s){fd(this.members,s),s.scheduleRender()}remove(s){if(bd(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 z5(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 Do=["","X","Y","Z"],V5=1e3;let W5=0;function Ro(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function N0(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=l0(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",ts,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&N0(r)}function w0({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=W5++,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(Y5),this.nodes.forEach(J5),this.nodes.forEach(Z5),this.nodes.forEach(K5)},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 I5)}addEventListener(l,o){return this.eventHandlers.has(l)||this.eventHandlers.set(l,new vd),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=Of(l)&&!ES(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;ts.read(()=>{p=window.innerWidth}),t(l,()=>{const h=window.innerWidth;h!==p&&(p=h,this.root.updateBlockedByResize=!0,m&&m(),m=F5(x,250),rl.hasAnimatedSinceResize&&(rl.hasAnimatedSinceResize=!1,this.nodes.forEach(jh)))})}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()||aT,{onLayoutAnimationStart:f,onLayoutAnimationComplete:b}=d.getProps(),y=!this.targetLayout||!v0(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={...Ed(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||jh(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(),br(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(q5),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&&N0(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(fh);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(bh);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(X5),this.nodes.forEach(H5),this.nodes.forEach(G5)):this.nodes.forEach(bh),this.clearAllSnapshots();const o=aa.now();Ms.delta=qa(0,1e3/60,o-Ms.timestamp),Ms.timestamp=o,Ms.isProcessing=!0,bo.update.process(Ms),bo.preRender.process(Ms),bo.render.process(Ms),Ms.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Md.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Q5),this.sharedNodes.forEach(eT)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ts.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ts.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=ps(),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&&!y0(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,m=d!==this.prevTransformTemplateValue;l&&this.instance&&(o||Lr(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)),rT(c),{animationId:this.root.animationId,measuredBox:o,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var d;const{visualElement:l}=this.options;if(!l)return ps();const o=l.measureViewportBox();if(!(((d=this.scroll)==null?void 0:d.wasRoot)||this.path.some(nT))){const{scroll:m}=this.root;m&&(xn(o.x,m.offset.x),xn(o.y,m.offset.y))}return o}removeElementScroll(l){var c;const o=ps();if(fa(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&&fa(o,l),xn(o.x,p.offset.x),xn(o.y,p.offset.y))}return o}applyTransform(l,o=!1){const c=ps();fa(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&&hn(c,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),Lr(m.latestValues)&&hn(c,m.latestValues)}return Lr(this.latestValues)&&hn(c,this.latestValues),c}removeTransform(l){const o=ps();fa(o,l);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!Lr(d.latestValues))continue;Cc(d.latestValues)&&d.updateSnapshot();const m=ps(),p=d.measurePageBox();fa(m,p),mh(o,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return Lr(this.latestValues)&&mh(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!==Ms.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=Ms.timestamp,!this.targetDelta&&!this.relativeTarget){const h=this.getClosestProjectingParent();h&&h.layout&&this.animationProgress!==1?(this.relativeParent=h,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ps(),this.relativeTargetOrigin=ps(),si(this.relativeTargetOrigin,this.layout.layoutBox,h.layout.layoutBox),fa(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ps(),this.targetWithTransforms=ps()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),m5(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):fa(this.target,this.layout.layoutBox),t0(this.target,this.targetDelta)):fa(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=ps(),this.relativeTargetOrigin=ps(),si(this.relativeTargetOrigin,this.target,h.target),fa(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Cc(this.parent.latestValues)||e0(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===Ms.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;fa(this.layoutCorrected,this.layout.layoutBox);const p=this.treeScale.x,x=this.treeScale.y;wA(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=ps());const{target:h}=l;if(!h){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(oh(this.prevProjectionDelta.x,this.projectionDelta.x),oh(this.prevProjectionDelta.y,this.projectionDelta.y)),ti(this.projectionDelta,this.layoutCorrected,h,this.latestValues),(this.treeScale.x!==p||this.treeScale.y!==x||!gh(this.projectionDelta.x,this.prevProjectionDelta.x)||!gh(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=pn(),this.projectionDelta=pn(),this.projectionDeltaWithTransform=pn()}setAnimationOrigin(l,o=!1){const c=this.snapshot,d=c?c.latestValues:{},m={...this.latestValues},p=pn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!o;const x=ps(),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(sT));this.animationProgress=0;let v;this.mixTargetDelta=w=>{const S=w/1e3;yh(p.x,l.x,S),yh(p.y,l.y,S),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(si(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),tT(this.relativeTarget,this.relativeTargetOrigin,x,S),v&&U5(this.relativeTarget,v)&&(this.isProjectionDirty=!1),v||(v=ps()),fa(v,this.relativeTarget)),f&&(this.animationValues=m,E5(m,d,this.latestValues,S,j,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(br(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ts.update(()=>{rl.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=wn(0)),this.currentAnimation=D5(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(V5),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&&C0(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||ps();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}fa(o,c),hn(o,m),ti(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new B5),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&&Ro("z",l,d,this.animationValues);for(let m=0;m<Do.length;m++)Ro(`rotate${Do[m]}`,l,d,this.animationValues),Ro(`skew${Do[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=al(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=al(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!Lr(this.latestValues)&&(l.transform=c?c({},""):"none",this.hasProjected=!1);return}l.visibility="";const m=d.animationValues||d.latestValues;this.applyTransformsToTarget();let p=z5(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 xi){if(m[g]===void 0)continue;const{correct:f,applyTo:b,isCSSVariable:y}=xi[g],j=p==="none"?m[g]:f(m[g],d);if(b){const v=b.length;for(let w=0;w<v;w++)l[b[w]]=j}else y?this.options.visualElement.renderState.vars[g]=j:l[g]=j}this.options.layoutId&&(l.pointerEvents=d===this?al(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(fh),this.root.sharedNodes.clear()}}}function H5(t){t.updateLayout()}function G5(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"?ba(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],h=Ys(x);x.min=r[p].min,x.max=x.min+h}):C0(i,s.layoutBox,r)&&ba(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=pn();ti(o,r,s.layoutBox);const c=pn();l?ti(c,t.applyTransform(n,!0),s.measuredBox):ti(c,r,s.layoutBox);const d=!y0(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=ps();si(g,s.layoutBox,x.layoutBox);const f=ps();si(f,r,h.layoutBox),v0(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 Y5(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 K5(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Q5(t){t.clearSnapshot()}function fh(t){t.clearMeasurements()}function bh(t){t.isLayoutDirty=!1}function X5(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function jh(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function J5(t){t.resolveTargetDelta()}function Z5(t){t.calcProjection()}function q5(t){t.resetSkewAndRotation()}function eT(t){t.removeLeadSnapshot()}function yh(t,s,a){t.translate=ls(s.translate,0,a),t.scale=ls(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function vh(t,s,a,r){t.min=ls(s.min,a.min,r),t.max=ls(s.max,a.max,r)}function tT(t,s,a,r){vh(t.x,s.x,a.x,r),vh(t.y,s.y,a.y,r)}function sT(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const aT={duration:.45,ease:[.4,0,.1,1]},Nh=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),wh=Nh("applewebkit/")&&!Nh("chrome/")?Math.round:va;function Ch(t){t.min=wh(t.min),t.max=wh(t.max)}function rT(t){Ch(t.x),Ch(t.y)}function C0(t,s,a){return t==="position"||t==="preserve-aspect"&&!d5(ph(s),ph(a),.2)}function nT(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const iT=w0({attachResizeListener:(t,s)=>hi(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Io={current:void 0},S0=w0({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Io.current){const t=new iT({});t.mount(window),t.setOptions({layoutScroll:!0}),Io.current=t}return Io.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),lT={pan:{Feature:S5},drag:{Feature:C5,ProjectionNode:S0,MeasureLayout:f0}};function Sh(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&&ts.postRender(()=>i(s,Di(s)))}class oT extends wr{mount(){const{current:s}=this.node;s&&(this.unmount=DS(s,(a,r)=>(Sh(this.node,r,"Start"),n=>Sh(this.node,n,"End"))))}unmount(){}}class cT extends wr{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=Ai(hi(this.node.current,"focus",()=>this.onFocus()),hi(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ah(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&&ts.postRender(()=>i(s,Di(s)))}class dT extends wr{mount(){const{current:s}=this.node;s&&(this.unmount=PS(s,(a,r)=>(Ah(this.node,r,"Start"),(n,{success:i})=>Ah(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Ic=new WeakMap,Fo=new WeakMap,mT=t=>{const s=Ic.get(t.target);s&&s(t)},uT=t=>{t.forEach(mT)};function xT({root:t,...s}){const a=t||document;Fo.has(a)||Fo.set(a,{});const r=Fo.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(uT,{root:t,...s})),r[n]}function hT(t,s,a){const r=xT(s);return Ic.set(t,a),r.observe(t),()=>{Ic.delete(t),r.unobserve(t)}}const pT={some:0,all:1};class gT extends wr{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:a,margin:r,amount:n="some",once:i}=s,l={root:a?a.current:void 0,rootMargin:r,threshold:typeof n=="number"?n:pT[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:p}=this.node.getProps(),x=d?m:p;x&&x(c)};return hT(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(fT(s,a))&&this.startObserver()}unmount(){}}function fT({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const bT={inView:{Feature:gT},tap:{Feature:dT},focus:{Feature:cT},hover:{Feature:oT}},jT={layout:{ProjectionNode:S0,MeasureLayout:f0}},yT={...r5,...bT,...lT,...jT},Yt=yA(yT,PA),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:Fp,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 vT({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=lt.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(gt,{open:t,onOpenChange:s,children:e.jsxs(ht,{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(pt,{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(Ss,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsxs("div",{className:"min-h-full flex flex-col items-center justify-center px-6 py-12",children:[e.jsxs(Yt.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(Fl,{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(Yt.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(q,{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(me,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${x.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),f&&e.jsx(Yt.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(Se,{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(tt,{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(tt,{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(se,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(le,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(qt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ot,{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(ss,{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(He,{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(Yt.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(vs,{className:"w-4 h-4"})]})]}),e.jsx(Kl,{children:r&&e.jsx(Yt.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 en({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"),w=s.toLowerCase().includes("pdf"),S=v||w;u.useEffect(()=>{if(!l||!S||!a){g(null);return}return(async()=>{b(!0),j(null);try{let z=a;a.startsWith("/")&&!a.startsWith("//")&&(z=`${c}${a}`);const L=await fetch(z,{headers:{Accept:w?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!L.ok){const A=await L.text().catch(()=>"");throw new Error(`Failed to load file: ${L.status} ${L.statusText}. ${A}`)}const V=await L.blob();if(V.size===0)throw new Error("File is empty or could not be loaded");w&&!V.type.includes("pdf")&&V.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${V.type}`);const I=window.URL.createObjectURL(V);g(I)}catch(E){console.error("Failed to load file for preview:",E),j(E instanceof Error?E.message:"Failed to load file for preview")}finally{b(!1)}})(),()=>{h&&(window.URL.revokeObjectURL(h),g(null))}},[l,a,S,w]);const D=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},k=()=>m(N=>Math.min(N+25,200)),C=()=>m(N=>Math.max(N-25,50)),F=()=>x(N=>(N+90)%360);return e.jsx(gt,{open:l,onOpenChange:o,children:e.jsx(ht,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ft,{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(pt,{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:C,disabled:d<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(cy,{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(dy,{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(Pp,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(O,{variant:"outline",size:"sm",onClick:D,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(We,{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(Nt,{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:D,className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",t]})]}):S&&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"})}),w&&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:D,className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function Ri({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(gt,{open:t,onOpenChange:s,children:e.jsxs(ht,{className:"sm:max-w-lg",children:[e.jsxs(ft,{children:[e.jsxs(pt,{className:"flex items-center gap-2",children:[e.jsx(tt,{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(Rt,{children:e.jsx(O,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const ha=async t=>{const s=t?{category:t}:{};return(await we.get("/users/configurations",{params:s})).data.data},Zl=async t=>{const s=t?{category:t}:{};return(await we.get("/admin/configurations",{params:s})).data.data},Gs=async(t,s)=>{await we.put(`/admin/configurations/${t}`,{configValue:s})},NT=async t=>{await we.post(`/admin/configurations/${t}/reset`)},wT=async()=>{const t=await we.get("/admin/form16-config");return t.data.data??t.data},CT=async t=>{await we.put("/admin/form16-config",t)},ST=async()=>{const t=await we.get("/admin/cpc-csd-config");return t.data.data??t.data},AT=async t=>{await we.put("/admin/cpc-csd-config",t)},TT=async t=>{const s=t?{year:t}:{};return(await we.get("/admin/holidays",{params:s})).data.data},kT=async t=>(await we.post("/admin/holidays",t)).data.data,DT=async(t,s)=>(await we.put(`/admin/holidays/${t}`,s)).data.data,RT=async t=>{await we.delete(`/admin/holidays/${t}`)},IT=async()=>(await we.get("/config/activity-types")).data.data,FT=async t=>{const s={activeOnly:t.toString()};return(await we.get("/admin/activity-types",{params:s})).data.data},PT=async t=>(await we.post("/admin/activity-types",t)).data.data,ET=async(t,s)=>(await we.put(`/admin/activity-types/${t}`,s)).data.data,_T=async t=>{await we.delete(`/admin/activity-types/${t}`)},MT={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 LT(t,s,a){const[r,n]=u.useState(MT),[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 ha("DOCUMENT_POLICY"),v={};j.forEach(E=>{v[E.configKey]=E.configValue});const w=parseInt(v.MAX_FILE_SIZE_MB||"10"),D=(v.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(E=>E.trim().toLowerCase());x({maxFileSizeMB:w,allowedFileTypes:D});const k=await ha("SYSTEM_SETTINGS"),C=await ha("WORKFLOW_SHARING"),F=[...k,...C],N={};F.forEach(E=>{N[E.configKey]=E.configValue}),m({maxApprovalLevels:parseInt(N.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(N.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((y=N.ALLOW_ADD_SPECTATOR)==null?void 0:y.toLowerCase())==="true",maxSpectators:parseInt(N.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 Ls(s);if(!b||!y)return;const j=y.workflow||{},v=Array.isArray(y.approvals)?y.approvals:[],w=Array.isArray(y.participants)?y.participants:[],S=Array.isArray(y.documents)?y.documents.filter(_=>!_.isDeleted):[];g(S);const D=(j.priority||"").toString().toLowerCase(),k={standard:"standard",express:"express"},C=j.templateType==="TEMPLATE"?"existing-template":"custom",F=a.find(_=>_.id===C)||a[0]||null;l(F);const N=v.sort((_,z)=>(_.levelNumber||0)-(z.levelNumber||0)).map(_=>{const z=Number(_.tatHours||24),R=Math.floor(z/24),L=z%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:R>0?R:L,tatType:R>0?"days":"hours",userId:_.approverId}}),E=w.filter(_=>(_.participantType||_.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(_.userEmail||_.user_email||_.email):!1).map((_,z)=>{const R=_.userId||_.user_id||_.id,L=_.userName||_.user_name||_.name||"",V=_.userEmail||_.user_email||_.email||"",A=(L||V||"XX").split(" ").map(G=>G[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:R||`spectator-${s}-${z}-${Date.now()}`,userId:R,name:L||V||"Spectator",email:V,role:"Spectator",department:_.department||"",avatar:A,level:1,canClose:!1}});n(_=>({..._,template:C,title:j.title||"",description:j.description||"",priority:k[D]||"standard",approvers:N,approverCount:N.length||1,spectators:E,maxLevel:Math.max(...N.map(z=>z.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 Th=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function OT(t,s,a){const[r,n]=u.useState(t?2:1),i=Th.length,l=p=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p),o=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(p=>{if(!p||!p.email||!l(p.email))return!1;if(!p.userId)return!0;const 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:Th,isStepValid:o,nextStep:()=>{o()&&(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),r<i&&n(r+1))},prevStep:()=>{r>1&&(n(r-1),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}))},goToStep:p=>{p>=1&&p<=i&&n(p)},validateEmail:l}}function $T(){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 UT(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function BT(t,s,a){var n;const r=UT(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 zT(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return BT(a,n,n===s)})}function kh(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 Dh(t,s,a,r=!1){const n=zT(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 VT(t,s){const a=t.slice(0,s);if(a.some(l=>!(l!=null&&l.email)||!l.email.trim()))return{valid:!1,message:"Please provide email addresses for all approvers."};const n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return a.some(l=>!n.test((l==null?void 0:l.email)||""))?{valid:!1,message:"Please provide valid email addresses for all approvers."}:{valid:!0}}async function Rh(t,s){return{id:(await ud(t,s||[],"SUPPORTING")).id}}async function Ih(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await CC(t,s,a||[],r):await wC(t,s)}function WT({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=VT(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const y=Dh(t,n,r,!1);await Ih(l,y,a,r),Y.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=kh(t,s,n,!1),j=await Rh(y,a);Y.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),Y.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=Dh(t,n,r,!0);await Ih(l,b,a,r),Y.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=kh(t,s,n,!0),y=await Rh(b,a);Y.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),Y.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 Ca(t,s=10,a="default"){return await we.get("/users/search",{params:{q:t,limit:s,source:a}})}async function Na(t){var a;const s=await we.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function HT(t,s){return await we.post("/admin/users/assign-role",{email:t,role:s})}async function GT(t,s){return await we.put(`/admin/users/${t}/role`,{role:s})}async function YT(t,s=1,a=10){return await we.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function KT(){return await we.get("/admin/users/role-statistics")}async function QT(t){var a;const s=await we.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function XT(){var s,a;return((a=(s=(await we.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const ma={searchUsers:Ca,getUserById:QT,ensureUserExists:Na,assignRole:HT,updateUserRole:GT,getUsersByRole:YT,getRoleStatistics:KT,getAllUsers:XT};async function JT(t,s){var a;if(t.email.toLowerCase()===s.toLowerCase())return{success:!1,error:{type:"self-assign",email:t.email,message:""}};try{const n=((a=(await Ca(t.email,1)).data)==null?void 0:a.data)||[];if(n.length===0)return{success:!1,error:{type:"not-found",email:t.email,message:""}};const i=n[0];return i?(await Na({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 ZT(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 JT(l,s);if(!o.success)return{success:!1,error:o.error};try{const m=(((n=(await Ca(l.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const p=await Na({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 qT({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=fs(),[g,f]=u.useState(!1),[b,y]=u.useState(null);return{showTemplateModal:g,setShowTemplateModal:f,previewDocument:b,selectTemplate:C=>{s(C),a("template",C.id),a("category",C.category),a("priority",C.priority);const F=new Date;F.setDate(F.getDate()+C.suggestedSLA),a("slaEndDate",F),C.id!=="custom"&&C.id!=="existing-template"&&h(`/create-admin-request/${C.id}`)},handleTemplateSelection:C=>{C==="claim-management"?h("/claim-management"):C==="vendor-payment"?h("/vendor-payment"):x&&x({templateType:C})},nextStep:async()=>{var C;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 E=r.approverCount||1;if(E>m.maxApprovalLevels){p([{type:"Maximum Approval Levels Exceeded",message:`The request has ${E} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:E,maxValue:m.maxApprovalLevels}]);return}}const F=((C=c==null?void 0:c.email)==null?void 0:C.toLowerCase())||"",N=await ZT(r.approvers,F);if(!N.success&&N.error){d(N.error.type,N.error.email,N.error.message);return}N.validatedApprovers&&a("approvers",N.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(C,F)=>{if(F){const N=C.documentId||C.document_id||"";y({fileName:C.originalFileName||C.fileName||"Document",fileType:C.fileType||C.file_type||"application/octet-stream",fileUrl:Dn(N),fileSize:Number(C.fileSize||C.file_size||0),documentId:N})}else{const N=URL.createObjectURL(C);y({fileName:C.name,fileType:C.type||"application/octet-stream",fileUrl:N,fileSize:C.size,file:C})}},closePreview:()=>{b!=null&&b.fileUrl&&(b!=null&&b.file)&&URL.revokeObjectURL(b.fileUrl),y(null)}}}const Fh=[{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:Pl,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:Pe,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let Gr=null;const Ph=()=>Gr,ek=async t=>{const a=(await we.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 Gr&&Gr.push(r),r},ql=async()=>{var r;const a=(((r=(await we.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 Gr=a,a},tk=async(t,s)=>{const r=(await we.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 Gr&&(Gr=Gr.map(i=>i.id===t?n:i)),n};function A0({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 sk({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(Ss,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Previous"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 order-1 sm:order-2","data-testid":"wizard-footer-actions",children:[e.jsx(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(We,{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(We,{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(Ep,{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(vs,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const Eh=t=>{switch(t){case"high":return e.jsx(Ma,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(ss,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Qs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ss,{className:"w-4 h-4 text-gray-600"})}};function ak({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=u.useState("main"),l=fs(),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(Yt.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(Ss,{className:"w-4 h-4"}),"Back to All Types"]})}),e.jsx("div",{className:"w-full max-w-6xl grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8","data-testid":"template-selection-grid",children:c.length===0&&n==="admin"?e.jsxs("div",{className:"col-span-full text-center py-12 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200",children:[e.jsx(my,{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(Yt.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(q,{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(me,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl flex items-center justify-center ${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(Yt.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(le,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),Eh(m.priority)]})]})]}),e.jsxs(se,{className:"pt-0 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed line-clamp-2","data-testid":`template-card-${m.id}-description`,children:m.description}),!x&&e.jsxs(e.Fragment,{children:[e.jsx(qt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-estimated-time`,children:[e.jsx(ot,{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(es,{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(Kl,{children:s&&e.jsx(Yt.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(q,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Zr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-sla",children:[e.jsx(ne,{className:"text-blue-900 font-semibold",children:"Suggested SLA"}),e.jsxs("p",{className:"text-blue-700 mt-1",children:[s.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-priority",children:[e.jsx(ne,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[Eh(s.priority),e.jsx("span",{className:"text-blue-700 capitalize",children:s.priority})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-duration",children:[e.jsx(ne,{className:"text-blue-900 font-semibold",children:"Estimated Duration"}),e.jsx("p",{className:"text-blue-700 mt-1",children:s.estimatedTime})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-approvers",children:[e.jsx(ne,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,p)=>e.jsx(le,{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 Ee({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:Oe("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 rk({className:t,...s}){return e.jsx(yj,{"data-slot":"radio-group",className:Oe("grid gap-3",t),...s})}function _h({className:t,...s}){return e.jsx(vj,{"data-slot":"radio-group-item",className:Oe("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(Nj,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Vc,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function nk({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(Yt.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(Pe,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(ne,{htmlFor:"title",className:"text-base font-semibold",children:"Request Title *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Be specific and descriptive. This will be visible to all participants."}),e.jsx(Ee,{id:"title",placeholder:"e.g., Approval on new office location",value:t.title,onChange:r=>a("title",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-title-input"})]}),e.jsxs("div",{"data-testid":"basic-information-description-field",children:[e.jsx(ne,{htmlFor:"description",className:"text-base font-semibold",children:"Detailed Description *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Si,{value:t.description||"",onChange:r=>a("description",r),placeholder:"Provide comprehensive details about your request including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px","data-testid":"basic-information-description-textarea"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6","data-testid":"basic-information-priority-section",children:e.jsxs("div",{"data-testid":"basic-information-priority-field",children:[e.jsx(ne,{className:"text-base font-semibold",children:"Priority Level *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"select priority for your request"}),e.jsxs(rk,{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(_h,{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(Il,{className:"w-4 h-4 text-red-600"}),e.jsx(ne,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(le,{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(_h,{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(ot,{className:"w-4 h-4 text-blue-600"}),e.jsx(ne,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(le,{variant:"secondary",className:"text-xs",children:"DEFAULT"})]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Includes working days in TAT - regular processing timeline"})]})]})]})]})}),((s==null?void 0:s.fields.amount)||(s==null?void 0:s.fields.vendor)||(s==null?void 0:s.fields.timeline)||(s==null?void 0:s.fields.impact))&&e.jsxs("div",{className:"border-t pt-6","data-testid":"basic-information-additional-details",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Additional Details"}),e.jsxs("div",{className:"space-y-6",children:[(s==null?void 0:s.fields.amount)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-testid":"basic-information-amount-field",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Ee,{id:"amount",placeholder:"Enter amount",value:t.amount,onChange:r=>a("amount",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-amount-input"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(Ke,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Xe,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(J,{value:"USD",children:"USD ($)"}),e.jsx(J,{value:"EUR",children:"EUR (€)"}),e.jsx(J,{value:"GBP",children:"GBP (£)"}),e.jsx(J,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(ne,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Ee,{id:"vendor",placeholder:"Enter vendor or supplier name",value:t.vendor,onChange:r=>a("vendor",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-vendor-input"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{"data-testid":"basic-information-cost-center-field",children:[e.jsx(ne,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Ee,{id:"costCenter",placeholder:"e.g., Marketing, IT, Operations",value:t.costCenter,onChange:r=>a("costCenter",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-cost-center-input"})]}),e.jsxs("div",{"data-testid":"basic-information-project-field",children:[e.jsx(ne,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Ee,{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 T0(){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 Ca(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 Na({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 k0(){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 Ca(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 ik({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var p;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=k0();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,w,S;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||(w=g[x])==null?void 0:w.department,avatar:b||(S=g[x])==null?void 0:S.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((w,S)=>{var D,k;return S!==x&&(w.userId===h.userId||((D=w.email)==null?void 0:D.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(w=>{var S,D;return w.userId===h.userId||((S=w.email)==null?void 0:S.toLowerCase())===((D=h.email)==null?void 0:D.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 Na({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(Yt.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(es,{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(q,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(pr,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(Se,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(se,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(ne,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(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(Wc,{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(os,{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(q,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(js,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(Se,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx("div",{className:"p-4 rounded-lg border-2 border-blue-200 bg-blue-50","data-testid":"approval-workflow-initiator-card",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:e.jsx(Ht,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-blue-900",children:"Request Initiator"}),e.jsx(le,{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(le,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(ne,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),b.email&&b.userId&&e.jsxs(le,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(He,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ee,{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(ne,{htmlFor:`tat-${g}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ee,{id:`tat-${g}`,type:"number",placeholder:b.tatType==="days"?"7":"24",min:"1",max:b.tatType==="days"?"30":"720",value:b.tat||"",onChange:v=>{const w=[...t.approvers];w[h]={...w[h],tat:parseInt(v.target.value)||"",level:g,tatType:b.tatType||"hours"},s("approvers",w)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(Ke,{value:b.tatType||"hours",onValueChange:v=>{const w=[...t.approvers];w[h]={...w[h],tatType:v,level:g,tat:""},s("approvers",w)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(Xe,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Zr,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," → ",Array.from({length:t.approverCount||1},(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(ot,{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 lk({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=u.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=T0(),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 w,S;return v.userId===g.userId||((w=v.email)==null?void 0:w.toLowerCase())===((S=g.email)==null?void 0:S.toLowerCase())}),j=(f=t.approvers)==null?void 0:f.some(v=>{var w,S;return v.userId===g.userId||((w=v.email)==null?void 0:w.toLowerCase())===((S=g.email)==null?void 0:S.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),w={id:v.userId,userId:v.userId,name:v.displayName||g.email.split("@")[0],email:v.email,avatar:(v.displayName||v.email).substring(0,2).toUpperCase(),role:"Spectator",department:v.department||"",level:1,canClose:!1},S=[...t.spectators,w];s("spectators",S),i(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(v=>{var w;return((w=v.email)==null?void 0:w.toLowerCase())===n.toLowerCase()}),j=(b=t.approvers)==null?void 0:b.some(v=>{var w;return((w=v.email)==null?void 0:w.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(Yt.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(q,{"data-testid":"participants-spectators-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center justify-between text-base","data-testid":"participants-spectators-title",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(le,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(Se,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(se,{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(Ee,{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(Zr,{className:"w-3 h-3 flex-shrink-0"}),e.jsxs("span",{children:["Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users, or type email directly (will be validated against organization directory)"]})]})]}),e.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto","data-testid":"participants-spectators-list",children:t.spectators.map(g=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-teal-50 rounded-lg","data-testid":`participants-spectator-${g.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ms,{className:"h-6 w-6",children:e.jsx(us,{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(Nt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function ok({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(w=>{if(w.size>y){j.push({fileName:w.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(w.size/1048576).toFixed(2)}MB`});return}const S=w.name.toLowerCase(),D=S.substring(S.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(D)){j.push({fileName:w.name,reason:`File type "${D}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}v.push(w)}),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(Yt.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(Ns,{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(q,{"data-testid":"documents-upload-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Pe,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(Se,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(se,{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(Ns,{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(os,{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(q,{"data-testid":"documents-existing-card",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(le,{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(se,{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(Pe,{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(Nt,{className:"h-4 w-4 text-red-600"})})]})]},b)})})})]}),a.length>0&&e.jsxs(q,{"data-testid":"documents-new-card",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(le,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(se,{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(Pe,{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(Nt,{className:"h-4 w-4"})})]})]},b))})})]})]})]})}const ck=t=>{switch(t){case"high":return e.jsx(Ma,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(ss,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Qs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ss,{className:"w-4 h-4 text-gray-600"})}};function dk({formData:t,selectedTemplate:s}){return e.jsxs(Yt.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(He,{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(q,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(Ep,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6","data-testid":"review-submit-overview-grid",children:[e.jsxs("div",{"data-testid":"review-submit-overview-type",children:[e.jsx(ne,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(le,{variant:"outline",className:"mt-2 text-xs border-green-300 text-green-700",children:s==null?void 0:s.category})]}),e.jsxs("div",{"data-testid":"review-submit-overview-priority",children:[e.jsx(ne,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[ck(t.priority),e.jsx("span",{className:"text-green-800 capitalize",children:t.priority})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-workflow",children:[e.jsx(ne,{className:"text-green-900 font-semibold",children:"Workflow Type"}),e.jsx("p",{className:"text-green-800 mt-1 capitalize",children:t.workflowType}),e.jsxs("p",{className:"text-sm text-green-700",children:[t.approverCount||1," Level",(t.approverCount||1)>1?"s":""]})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-title",children:[e.jsx(ne,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(q,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Pe,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(ne,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(Os,{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(Fa,{className:"w-4 h-4 text-blue-600"}),e.jsx(ne,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(q,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(es,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(Se,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(se,{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(le,{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(q,{"data-testid":"review-submit-participants-card",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(wt,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(se,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(ne,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(le,{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(q,{"data-testid":"review-submit-documents-card",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(Ns,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(Se,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(se,{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(Pe,{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(q,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(se,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(He,{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 mk({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(Ss,{className:"h-4 w-4 sm:h-5 sm:w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-base sm:text-xl md:text-2xl font-bold text-gray-900 truncate","data-testid":"create-request-title",children:t?"Edit Draft":"New Request"}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600 hidden sm:block","data-testid":"create-request-step-info",children:["Step ",s," of ",a,": ",r[s-1]]})]})]}),e.jsx("div",{className:"hidden md:flex items-center gap-4","data-testid":"create-request-progress-info",children:e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-900",children:[Math.round(s/a*100),"% Complete"]}),e.jsxs("p",{className:"text-xs text-gray-600",children:[a-s," steps remaining"]})]})})]})})}function uk({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(Kl,{mode:"wait",children:t})})})}function xk({modal:t,onClose:s}){return e.jsx(gt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(ht,{className:"sm:max-w-md",children:[e.jsxs(ft,{children:[e.jsxs(pt,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(tt,{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(Pl,{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(Rt,{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 hk({modal:t,documentPolicy:s,onClose:a}){return e.jsx(gt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(ht,{className:"sm:max-w-lg",children:[e.jsxs(ft,{children:[e.jsxs(pt,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(tt,{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(Rt,{children:e.jsx(O,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function Mh({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Sa(),i=fs(),l=n.requestId||a||"",o=r&&!!l,{user:c}=xs(),[d,m]=u.useState([]);u.useEffect(()=>{(async()=>{try{const ye=(await ql()).map(oe=>({id:oe.id,name:oe.name,description:oe.description,category:oe.category,icon:Pe,estimatedTime:oe.estimatedTime,commonApprovers:oe.approvers.map(ke=>ke.name),workflowApprovers:oe.approvers,suggestedSLA:oe.suggestedSLA,priority:oe.priority,fields:oe.fields||{}}));m(ye)}catch($e){console.error("Failed to fetch admin templates:",$e)}})()},[]);const p=u.useMemo(()=>[...Fh,...d],[d]),{formData:x,updateFormData:h,selectedTemplate:g,setSelectedTemplate:f,loadingDraft:b,systemPolicy:y,documentPolicy:j,existingDocuments:v,setExistingDocuments:w}=LT(o,l,p),{currentStep:S,totalSteps:D,stepNames:k,isStepValid:C,nextStep:F,prevStep:N}=OT(o,g,x),[E,_]=u.useState([]),[z,R]=u.useState([]),L=u.useRef(null),{validationModal:V,policyViolationModal:I,documentErrorModal:A,openValidationModal:G,closeValidationModal:$,openPolicyViolationModal:M,closePolicyViolationModal:T,openDocumentErrorModal:U,closeDocumentErrorModal:H}=$T(),{submitting:W,savingDraft:P,handleSubmit:B,handleSaveDraft:K}=WT({formData:x,selectedTemplate:g,documents:E,documentsToDelete:z,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:Z,setShowTemplateModal:te,previewDocument:ae,selectTemplate:xe,handleTemplateSelection:be,nextStep:Ge,prevStep:Be,handlePreviewDocument:_e,closePreview:Re}=qT({selectedTemplate:g,setSelectedTemplate:f,updateFormData:h,formData:x,currentStep:S,isStepValid:C,wizardNextStep:F,wizardPrevStep:N,user:c,openValidationModal:G,systemPolicy:y,onPolicyViolation:M,onSubmit:s}),ce=u.useCallback(()=>{if(S===1){i("/dashboard",{replace:!0});return}S===3||S===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Be()},[S,t,i,Be]),je=u.useRef(!0),re=u.useRef(!1);u.useEffect(()=>{je.current&&x.documents&&x.documents.length>0&&!re.current&&(_(x.documents),re.current=!0),je.current=!1},[x.documents]);const pe=u.useRef(!1),ie=u.useRef(E);u.useEffect(()=>{if(pe.current){pe.current=!1,ie.current=E;return}ie.current!==E&&(h("documents",E),ie.current=E)},[E]);const fe=()=>{switch(S){case 1:return e.jsx(ak,{templates:Fh,selectedTemplate:g,onSelectTemplate:xe,adminTemplates:d});case 2:return e.jsx(nk,{formData:x,selectedTemplate:g,updateFormData:h});case 3:return e.jsx(ik,{formData:x,updateFormData:h,systemPolicy:y,onValidationError:Ie=>G(Ie.type,Ie.email,Ie.message),onPolicyViolation:M});case 4:return e.jsx(lk,{formData:x,updateFormData:h,onValidationError:Ie=>G(Ie.type,Ie.email,Ie.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(ok,{documentPolicy:j,isEditing:o,documents:E,existingDocuments:v,documentsToDelete:z,onDocumentsChange:_,onExistingDocumentsChange:w,onDocumentsToDeleteChange:R,onPreviewDocument:_e,onDocumentErrors:Ie=>U(Ie),fileInputRef:L});case 6:return e.jsx(dk,{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(mk,{isEditing:o,currentStep:S,totalSteps:D,stepNames:k,onBack:ce}),e.jsx(A0,{currentStep:S,totalSteps:D,stepNames:k}),e.jsx(uk,{children:fe()}),e.jsx(sk,{currentStep:S,totalSteps:D,isStepValid:C(),onPrev:Be,onNext:Ge,onSubmit:B,onSaveDraft:K,submitting:W,savingDraft:P,loadingDraft:b,isEditing:o}),e.jsx(vT,{open:Z,onClose:()=>te(!1),onSelectTemplate:be}),ae&&e.jsx(en,{fileName:ae.fileName,fileType:ae.fileType,fileUrl:ae.fileUrl,fileSize:ae.fileSize,open:!!ae,onClose:Re,onDownload:async()=>{if(ae.file){const Ie=document.createElement("a");Ie.href=ae.fileUrl,Ie.download=ae.fileName,document.body.appendChild(Ie),Ie.click(),document.body.removeChild(Ie)}else ae.documentId&&await Us(ae.documentId)},attachmentId:ae.documentId}),e.jsx(xk,{modal:V,onClose:$}),e.jsx(hk,{modal:A,documentPolicy:j,onClose:H}),e.jsx(Ri,{open:I.open,onClose:T,violations:I.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}function Ii({className:t,...s}){return e.jsx(wj,{"data-slot":"tabs",className:Oe("flex flex-col gap-2",t),...s})}function Fi({className:t,...s}){return e.jsx(Cj,{"data-slot":"tabs-list",className:Oe("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function Bt({className:t,...s}){return e.jsx(Sj,{"data-slot":"tabs-trigger",className:Oe("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 zt({className:t,...s}){return e.jsx(Aj,{"data-slot":"tabs-content",className:Oe("flex-1 outline-none",t),...s})}function pi(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 Kd(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=(D,k)=>(D||k||"NA").toString().split(" ").map(F=>F[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),b=D=>{const k=(D||"").toUpperCase();return k==="IN_PROGRESS"?"in-review":k==="PENDING"?"pending":k==="APPROVED"?"approved":k==="REJECTED"?"rejected":k==="CLOSED"?"closed":k==="SKIPPED"?"skipped":(D||"").toLowerCase()},y=D=>{const k=String(D||"").trim();if(!k)return"Document";const C=k.lastIndexOf("."),F=C>0&&C<k.length-1,N=F?k.slice(0,C):k,E=F?k.slice(C):"";return`${N.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[redacted-email]").replace(/(?:\+?\d[\d\s().-]{8,}\d)/g,"[redacted-phone]").replace(/\s{2,}/g," ").trim()||"Document"}${E}`},j=u.useCallback(async()=>{var D,k,C,F,N,E,_,z,R,L,V,I,A,G,$;l(!0);try{const M=await Xs.getWorkflowDetails(t);if(!M){console.warn("[useRequestDetails] No details returned from API");return}const T=M.workflow||{},U=Array.isArray(M.approvals)?M.approvals:[],H=Array.isArray(M.participants)?M.participants:[],W=Array.isArray(M.documents)?M.documents:[],P=M.summary||{},B=Array.isArray(M.tatAlerts)?M.tatAlerts:[];B.length>0;const K=(P==null?void 0:P.currentLevel)||T.currentLevel||1,Z=U.map(ye=>{const oe=ye.levelNumber||0,ke=(ye.status||"").toString().toUpperCase(),st=ye.levelId||ye.level_id;let at=b(ye.status);oe>K&&ke!=="APPROVED"&&ke!=="REJECTED"?at="waiting":oe===K&&ke==="PENDING"&&(at="pending");const ct=B.filter(Dt=>Dt.levelId===st);return{step:oe,levelId:st,role:ye.levelName||ye.approverName||"Approver",status:at,approver:ye.approverName||ye.approverEmail,approverId:ye.approverId||ye.approver_id,approverEmail:ye.approverEmail,tatHours:Number(ye.tatHours||0),elapsedHours:Number(ye.elapsedHours||0),remainingHours:Number(ye.remainingHours||0),tatPercentageUsed:Number(ye.tatPercentageUsed||0),actualHours:ye.levelEndTime&&ye.levelStartTime?Math.max(0,(new Date(ye.levelEndTime).getTime()-new Date(ye.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:ye.comments||void 0,timestamp:ye.actionDate||void 0,levelStartTime:ye.levelStartTime||ye.tatStartTime,tatAlerts:ct,skipReason:ye.skipReason||void 0,isSkipped:ke==="SKIPPED"||ye.isSkipped||!1}}),te=H.filter(ye=>(ye.participantType||ye.participant_type||"").toUpperCase()==="SPECTATOR").map(ye=>({name:ye.userName||ye.user_name||ye.userEmail||ye.user_email,role:"Spectator",email:ye.userEmail||ye.user_email,avatar:f(ye.userName||ye.user_name,ye.userEmail||ye.user_email)})),ae=ye=>{var ke,st;if(!ye)return;const oe=H.find(at=>at.userId===ye||at.user_id===ye);return oe!=null&&oe.userName||oe!=null&&oe.user_name?oe.userName||oe.user_name:T.initiatorId===ye?((ke=T.initiator)==null?void 0:ke.displayName)||((st=T.initiator)==null?void 0:st.email):ye},xe=W.map(ye=>{const oe=Number(ye.fileSize||ye.file_size||0),ke=(oe/(1024*1024)).toFixed(2)+" MB";return{documentId:ye.documentId||ye.document_id,name:y(ye.originalFileName||ye.fileName||ye.file_name),fileType:ye.fileType||ye.file_type||"",size:ke,sizeBytes:oe,uploadedBy:ae(ye.uploadedBy||ye.uploaded_by),uploadedAt:ye.uploadedAt||ye.uploaded_at}}),be=Array.isArray(M.activities)?M.activities.filter(ye=>(ye.type||"").toLowerCase()!=="sla_warning"):[];let Ge=null;if(T.isPaused||!1)try{Ge=await cx(T.requestId)}catch{}let _e=null,Re=null,ce=null,je=null,re=[],pe=null;if(pi(T)){try{const ye=await we.get(`/dealer-claims/${T.requestId}/credit-note-wfm`),oe=ye.data??ye;pe=Array.isArray(oe==null?void 0:oe.data)?oe.data:Array.isArray(oe)?oe:[]}catch(ye){console.warn("[useRequestDetails] Error fetching credit note WFM data:",ye)}try{const ye=await we.get(`/dealer-claims/${T.requestId}`),oe=((D=ye.data)==null?void 0:D.data)||ye.data;if(oe){_e=oe.claimDetails||oe.claim_details,Re=oe.proposalDetails||oe.proposal_details,ce=oe.completionDetails||oe.completion_details,je=oe.internalOrder||oe.internal_order||null,re=oe.internalOrders||oe.internal_orders||[];const ke=oe.budgetTracking||oe.budget_tracking||null,st=oe.invoice||null,at=oe.creditNote||oe.credit_note||null,ct=oe.completionExpenses||oe.completion_expenses||null;_e&&(_e.budgetTracking=ke,_e.invoice=st,_e.creditNote=at,_e.completionExpenses=ct,_e.creditNoteWfmData=pe)}else console.warn("[useRequestDetails] No claimData found in response")}catch(ye){console.error("[useRequestDetails] Error fetching claim details:",{error:(ye==null?void 0:ye.message)||ye,status:(k=ye==null?void 0:ye.response)==null?void 0:k.status,statusText:(C=ye==null?void 0:ye.response)==null?void 0:C.statusText,responseData:(F=ye==null?void 0:ye.response)==null?void 0:F.data,requestId:T.requestId})}}const ie={...T,id:T.requestNumber||T.requestId,requestId:T.requestId,requestNumber:T.requestNumber,initiatorId:T.initiatorId||T.initiator_id,title:T.title,description:T.description,status:b(T.status),priority:(T.priority||"").toString().toLowerCase(),workflowType:T.workflowType||(T.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:Z,approvals:U,participants:H,documents:xe,spectators:te,summary:P,sla:(P==null?void 0:P.sla)||T.sla||null,initiator:{userId:((N=T.initiator)==null?void 0:N.userId)||((E=T.initiator)==null?void 0:E.user_id)||T.initiatorId||T.initiator_id,name:((_=T.initiator)==null?void 0:_.displayName)||((z=T.initiator)==null?void 0:z.email),role:((R=T.initiator)==null?void 0:R.designation)||void 0,department:((L=T.initiator)==null?void 0:L.department)||void 0,email:((V=T.initiator)==null?void 0:V.email)||void 0,phone:((I=T.initiator)==null?void 0:I.phone)||void 0,avatar:f((A=T.initiator)==null?void 0:A.displayName,(G=T.initiator)==null?void 0:G.email)},createdAt:T.createdAt,updatedAt:T.updatedAt,totalSteps:T.totalLevels||1,currentStepRaw:(P==null?void 0:P.currentLevel)||T.currentLevel||1,currentStep:Math.min(Math.max(1,(P==null?void 0:P.currentLevel)||T.currentLevel||1),T.totalLevels||1),auditTrail:be,conclusionRemark:T.conclusionRemark||null,closureDate:T.closureDate||null,pauseInfo:Ge||null,claimDetails:_e||null,proposalDetails:Re||null,completionDetails:ce||null,internalOrder:je||null,internalOrders:re||[],budgetTracking:(_e==null?void 0:_e.budgetTracking)||null,invoice:(_e==null?void 0:_e.invoice)||(_e==null?void 0:_e.invoice)||null,creditNote:(_e==null?void 0:_e.creditNote)||null,creditNoteWfmData:pe||(_e==null?void 0:_e.creditNoteWfmData)||null,completionExpenses:(_e==null?void 0:_e.completionExpenses)||null,templateType:T.templateType||T.template_type,form16Submission:M.form16Submission||null};n(ie);const fe=($=a==null?void 0:a.email)==null?void 0:$.toLowerCase(),Ie=U.find(ye=>{const oe=(ye.status||"").toString().toUpperCase(),ke=(ye.approverEmail||"").toLowerCase(),st=ye.levelNumber||0;return(oe==="PENDING"||oe==="IN_PROGRESS"||oe==="PAUSED")&&ke===fe&&st===K});x(Ie||null);const $e=a==null?void 0:a.userId;if($e){const ye=H.some(oe=>(oe.participantType||oe.participant_type||"").toUpperCase()==="SPECTATOR"&&(oe.userId||oe.user_id)===$e);g(ye)}else g(!1)}catch(M){console.error("[useRequestDetails] Error refreshing details:",M),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);u.useEffect(()=>{if(!t){c(!1);return}let D=!0;return c(!0),m(null),(async()=>{var k,C,F,N,E,_,z,R,L,V,I,A,G,$;try{const M=await Xs.getWorkflowDetails(t);if(!D||!M){D&&c(!1);return}const T=M.workflow||{},U=Array.isArray(M.approvals)?M.approvals:[],H=Array.isArray(M.participants)?M.participants:[],W=Array.isArray(M.documents)?M.documents:[],P=M.summary||{},B=Array.isArray(M.tatAlerts)?M.tatAlerts:[],K=(T.priority||"").toString().toLowerCase(),Z=(P==null?void 0:P.currentLevel)||T.currentLevel||1,te=U.map(oe=>{const ke=oe.levelNumber||0,st=(oe.status||"").toString().toUpperCase(),at=oe.levelId||oe.level_id;let ct=b(oe.status);st==="PAUSED"?ct="paused":ke>Z&&st!=="APPROVED"&&st!=="REJECTED"?ct="waiting":ke===Z&&(st==="PENDING"||st==="IN_PROGRESS")&&(ct=st==="IN_PROGRESS"?"in-review":"pending");const Dt=B.filter(Q=>Q.levelId===at);return{step:ke,levelId:at,role:oe.levelName||oe.approverName||"Approver",status:ct,approver:oe.approverName||oe.approverEmail,approverId:oe.approverId||oe.approver_id,approverEmail:oe.approverEmail,tatHours:Number(oe.tatHours||0),elapsedHours:Number(oe.elapsedHours||0),remainingHours:Number(oe.remainingHours||0),tatPercentageUsed:Number(oe.tatPercentageUsed||0),actualHours:oe.elapsedHours!==void 0&&oe.elapsedHours!==null?Number(oe.elapsedHours):void 0,comment:oe.comments||void 0,timestamp:oe.actionDate||void 0,levelStartTime:oe.levelStartTime||oe.tatStartTime,tatAlerts:Dt}}),ae=H.filter(oe=>(oe.participantType||"").toUpperCase()==="SPECTATOR").map(oe=>({name:oe.userName||oe.userEmail,role:"Spectator",avatar:f(oe.userName,oe.userEmail)})),xe=oe=>{var st,at;if(!oe)return;const ke=H.find(ct=>ct.userId===oe);return ke!=null&&ke.userName?ke.userName:T.initiatorId===oe?((st=T.initiator)==null?void 0:st.displayName)||((at=T.initiator)==null?void 0:at.email):oe},be=W.map(oe=>{const ke=Number(oe.fileSize||0),st=(ke/(1024*1024)).toFixed(2)+" MB";return{documentId:oe.documentId||oe.document_id,name:y(oe.originalFileName||oe.fileName),fileType:oe.fileType||oe.file_type||"",size:st,sizeBytes:ke,uploadedBy:xe(oe.uploadedBy),uploadedAt:oe.uploadedAt}}),Ge=Array.isArray(M.activities)?M.activities.filter(oe=>(oe.type||"").toLowerCase()!=="sla_warning"):[];let Be=null;if(T.isPaused||!1)try{Be=await cx(T.requestId)}catch{}let Re=null,ce=null,je=null,re=null,pe=[],ie=null;if(pi(T)){try{const oe=await we.get(`/dealer-claims/${T.requestId}/credit-note-wfm`),ke=oe.data??oe;ie=Array.isArray(ke==null?void 0:ke.data)?ke.data:Array.isArray(ke)?ke:[]}catch(oe){console.warn("[useRequestDetails] Error fetching credit note WFM data:",oe)}try{const oe=await we.get(`/dealer-claims/${T.requestId}`),ke=((k=oe.data)==null?void 0:k.data)||oe.data;if(ke){Re=ke.claimDetails||ke.claim_details,ce=ke.proposalDetails||ke.proposal_details,je=ke.completionDetails||ke.completion_details,re=ke.internalOrder||ke.internal_order||null,pe=ke.internalOrders||ke.internal_orders||[];const st=ke.budgetTracking||ke.budget_tracking||null,at=ke.invoice||null,ct=ke.creditNote||ke.credit_note||null,Dt=ke.completionExpenses||ke.completion_expenses||null;Re&&(Re.budgetTracking=st,Re.invoice=at,Re.creditNote=ct,Re.completionExpenses=Dt,Re.creditNoteWfmData=ie)}}catch(oe){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(oe==null?void 0:oe.message)||oe,status:(C=oe==null?void 0:oe.response)==null?void 0:C.status,requestId:T.requestId})}}const fe={id:T.requestNumber||T.requestId,requestId:T.requestId,title:T.title,description:T.description,priority:K,status:b(T.status),workflowType:T.workflowType||(T.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:P,initiator:{name:((F=T.initiator)==null?void 0:F.displayName)||((N=T.initiator)==null?void 0:N.email),role:((E=T.initiator)==null?void 0:E.designation)||void 0,department:((_=T.initiator)==null?void 0:_.department)||void 0,email:((z=T.initiator)==null?void 0:z.email)||void 0,phone:((R=T.initiator)==null?void 0:R.phone)||void 0,avatar:f((L=T.initiator)==null?void 0:L.displayName,(V=T.initiator)==null?void 0:V.email)},createdAt:T.createdAt,updatedAt:T.updatedAt,totalSteps:T.totalLevels||1,currentStepRaw:(P==null?void 0:P.currentLevel)||T.currentLevel||1,currentStep:Math.min(Math.max(1,(P==null?void 0:P.currentLevel)||T.currentLevel||1),T.totalLevels||1),approvalFlow:te,approvals:U,documents:be,spectators:ae,auditTrail:Ge,conclusionRemark:T.conclusionRemark||null,closureDate:T.closureDate||null,pauseInfo:Be||null,claimDetails:Re||null,proposalDetails:ce||null,completionDetails:je||null,internalOrder:re||null,internalOrders:pe||[],budgetTracking:(Re==null?void 0:Re.budgetTracking)||null,invoice:(Re==null?void 0:Re.invoice)||null,creditNote:(Re==null?void 0:Re.creditNote)||null,creditNoteWfmData:ie||(Re==null?void 0:Re.creditNoteWfmData)||null,completionExpenses:(Re==null?void 0:Re.completionExpenses)||null,templateType:T.templateType||T.template_type,form16Submission:M.form16Submission||null};n(fe);const Ie=(I=a==null?void 0:a.email)==null?void 0:I.toLowerCase(),$e=U.find(oe=>{const ke=(oe.status||"").toString().toUpperCase(),st=(oe.approverEmail||"").toLowerCase(),at=oe.levelNumber||0;return(ke==="PENDING"||ke==="IN_PROGRESS"||ke==="PAUSED")&&st===Ie&&at===Z});x($e||null);const ye=a==null?void 0:a.userId;if(ye){const oe=H.some(ke=>(ke.participantType||"").toUpperCase()==="SPECTATOR"&&ke.userId===ye);g(oe)}else g(!1)}catch(M){if(console.error("[useRequestDetails] Error loading request details:",M),D){if(((A=M==null?void 0:M.response)==null?void 0:A.status)===403){const T=(($=(G=M==null?void 0:M.response)==null?void 0:G.data)==null?void 0:$.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:T})}n(null)}}finally{D&&c(!1)}})(),()=>{D=!1}},[t,a]);const v=u.useMemo(()=>{if(r)return r;const D=s.find(k=>k.id===t||k.requestNumber===t||k.request_number===t);return D||null},[t,s,r]),w=u.useMemo(()=>{var C,F,N;if(!v||!a)return!1;const D=(C=a==null?void 0:a.email)==null?void 0:C.toLowerCase(),k=(N=(F=v.initiator)==null?void 0:F.email)==null?void 0:N.toLowerCase();return D===k},[v,a]),S=u.useMemo(()=>{var k;if(!v)return[];const D=[];return(k=v.initiator)!=null&&k.email&&D.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(C=>{C.approverEmail&&D.push({email:C.approverEmail.toLowerCase(),participantType:"APPROVER",name:C.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(C=>{C.email&&D.push({email:C.email.toLowerCase(),participantType:"SPECTATOR",name:C.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(C=>{const F=(C.userEmail||C.email||"").toLowerCase(),N=(C.participantType||C.participant_type||"").toUpperCase(),E=C.userName||C.user_name||C.name;F&&N&&!D.find(_=>_.email===F)&&D.push({email:F,participantType:N,name:E})}),D},[v]);return u.useEffect(()=>{if(!t||!r)return;const D=Xr();if(!D)return;const k=C=>{((C==null?void 0:C.requestId)===r.requestId||(C==null?void 0:C.requestNumber)===t)&&j()};return D.on("request:updated",k),()=>{D.off("request:updated",k)}},[t,r,j]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:j,currentApprovalLevel:p,isSpectator:h,isInitiator:w,existingParticipants:S,accessDenied:d}}function D0(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=Xr();if(!x){console.error("[useRequestSocket] Socket not available");return}const h=r==null?void 0:r.userId,g=()=>{cc(x,p,h)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Zp(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=Xr();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(),w=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime();return v-w});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 we.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 pk=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],gk={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 Qd(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(!pk.includes(a))return!1;const r=gk[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(", "))),Y.error(r,{description:i||n,duration:8e3,style:{background:"#fef2f2",border:"1px solid #fca5a5",color:"#991b1b"}}),!0}function R0(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 ha("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(w=>{const S=m(w);S.valid?y.push(w):b.push({fileName:w.name,reason:S.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 w=y[0],S=t==null?void 0:t.requestId;if(!S){Y.error("Request ID not found");return}w&&await Xn(w,S,"SUPPORTING"),await s(),y.length<f.length?Y.warning(`${y.length} of ${f.length} file(s) were uploaded. ${b.length} file(s) were rejected.`):Y.success("Document uploaded successfully")}catch(w){console.error("[useDocumentUpload] Upload error:",w),Qd(w)||Y.error(((v=(j=w==null?void 0:w.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 fk="modulepreload",bk=function(t){return"/"+t},Lh={},Po=function(s,a,r){let n=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));n=Promise.allSettled(a.map(c=>{if(c=bk(c),c in Lh)return;Lh[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":fk,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 I0(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,w]=u.useState(!1),[S,D]=u.useState(0),k=async()=>{var _;const N=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),E=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(N||E){c(N||E),g(!!E);return}try{const{getConclusion:z}=await Po(async()=>{const{getConclusion:L}=await import("./conclusionApi-Dwb-WsdL.js");return{getConclusion:L}},__vite__mapDeps([0,1,2,3,4,5,6,7])),R=await z(t.requestId||s);R&&(R.aiGeneratedRemark||R.finalRemark)&&(c(R.finalRemark||R.aiGeneratedRemark||""),g(!!R.aiGeneratedRemark))}catch(z){((_=z==null?void 0:z.response)==null?void 0:_.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",z)}},C=async()=>{if(!v)try{m(!0),j(!1);const{generateConclusion:N}=await Po(async()=>{const{generateConclusion:R}=await import("./conclusionApi-Dwb-WsdL.js");return{generateConclusion:R}},__vite__mapDeps([0,1,2,3,4,5,6,7])),E=await N(t.requestId||s),_=f+1;if(b(_),!(E!=null&&E.aiGeneratedRemark)||E.aiGeneratedRemark.toLowerCase().includes("unable to generate")||E.aiGeneratedRemark.toLowerCase().includes("sorry")){const R=S+1;D(R),R>=2?(w(!0),i==null||i({success:!1,title:"AI Generation Limit Reached",message:"We're unable to process a conclusion remark at this time after 2 attempts. Please proceed with a manual approach using the editor below."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process a conclusion remark at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0),c((E==null?void 0:E.aiGeneratedRemark)||""),g(!1);return}c(E.aiGeneratedRemark),g(!0),D(0),_>=2&&(w(!0),i==null||i({success:!0,title:"Maximum Attempts Reached",message:"You've reached the maximum of 2 regeneration attempts. Feel free to manually edit the current suggestion to fit your specific needs."}),l==null||l(!0))}catch(N){console.error("[useConclusionRemark] AI generation failed:",N);const E=S+1;D(E),g(!1),E>=2?(w(!0),i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. Since the maximum of 2 attempts is reached, please proceed with a manual approach."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0)}finally{m(!1)}},F=async()=>{var E,_;const N=o.replace(/<[^>]*>/g,"").trim();if(!N){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(N.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),l==null||l(!0);return}try{x(!0);const{finalizeConclusion:z}=await Po(async()=>{const{finalizeConclusion:R}=await import("./conclusionApi-Dwb-WsdL.js");return{finalizeConclusion:R}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await z(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(z){i==null||i({success:!1,title:"Error",message:((_=(E=z.response)==null?void 0:E.data)==null?void 0:_.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{x(!1)}};return u.useEffect(()=>{var R;const N=(R=t==null?void 0:t.status)==null?void 0:R.toLowerCase();if(!((N==="approved"||N==="rejected"||N==="closed")&&a&&!o))return;const _=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),z=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);_||z?(c(_||z),g(!!z)):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:C,handleFinalizeConclusion:F,generationAttempts:f,generationFailed:y,maxAttemptsReached:v}}function F0(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 C=>{var N,E;const F=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!F){alert("Approval level not found");return}await Kn(t,F,C||""),await new Promise(_=>setTimeout(_,500)),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(E=window==null?void 0:window.toast)==null||E.call(window,"Approved successfully")},handleRejectConfirm:async C=>{var N,E;if(!(C!=null&&C.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 Mr(t,F,C.trim(),C.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(E=window==null?void 0:window.toast)==null||E.call(window,"Rejected successfully")},handleAddApprover:async(C,F,N)=>{var E,_;try{await Og(t,C,F,N),await a(),c(!1),j==null||j({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${F}h TAT`}),g==null||g(!0)}catch(z){throw j==null||j({success:!1,title:"Failed to Add Approver",message:((_=(E=z==null?void 0:z.response)==null?void 0:E.data)==null?void 0:_.error)||"Failed to add approver. Please try again."}),g==null||g(!0),z}},handleSkipApprover:async C=>{var F,N;if(f)try{await bC(t,f.levelId,C),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(E){throw j==null||j({success:!1,title:"Failed to Skip Approver",message:((N=(F=E==null?void 0:E.response)==null?void 0:F.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),E}},handleAddSpectator:async C=>{var F,N;try{await $g(t,C),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(E){throw j==null||j({success:!1,title:"Failed to Add Spectator",message:((N=(F=E==null?void 0:E.response)==null?void 0:F.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),E}}}}function jk({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 vg(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 pN(t),Y.success("Submission cancelled"),a==null||a()}catch(g){Y.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 gN(t),Y.success("Marked as resubmission needed"),a==null||a()}catch(g){Y.error(g instanceof Error?g.message:"Failed to update")}finally{c(null)}}};return i||!m||p?null:e.jsxs(q,{className:"border-blue-200 bg-blue-50/30","data-testid":"form16-quick-actions-card",children:[e.jsxs(me,{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(Se,{className:"text-xs text-gray-600",children:"View the document in the Documents tab. Cancel submission or mark resubmission needed."})]}),e.jsxs(se,{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(We,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(Nt,{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(We,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(_p,{className:"w-3 h-3 mr-1"}),"Resubmission needed"]})]})]})}const yk=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 Yr({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(Pe,{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 "]}),ys(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&yk(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 vk({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(q,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base text-amber-800",children:[e.jsx(Pe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-amber-600"}),"Previous submission(s) same quarter"]}),e.jsxs(Se,{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(se,{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,w=d(y.originalFileName??y.original_file_name??y.fileName??y.file_name??"Document"),S=Number(y.fileSize??y.file_size??0),D=S>0?(S/(1024*1024)).toFixed(2)+" MB":"—";return e.jsx(Yr,{document:{documentId:v,name:w,fileType:y.fileType??y.file_type??"",size:D,sizeBytes:S,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(q,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Pe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),c?"Current submission":"Request Documents"]}),e.jsx(Se,{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(Ns,{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(se,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((g,f)=>e.jsx(Yr,{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(q,{children:[e.jsxs(me,{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-purple-600"}),"Work Note Attachments"]}),e.jsx(Se,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(se,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((g,f)=>e.jsx(Yr,{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 Nk=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"}}},Oh=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending",icon:ot,iconColor:"text-yellow-600"};case"paused":return{color:"bg-gray-400 text-gray-100 border-gray-500",label:"paused",icon:as,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:He,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:He,iconColor:"text-gray-600"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped",icon:Vt,iconColor:"text-orange-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:as,iconColor:"text-gray-600"}}},wk=t=>{switch(t){case"approval":case"approved":return e.jsx(He,{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(Ks,{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(El,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Pe,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(ot,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(Rl,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(as,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(Vt,{className:"w-5 h-5 text-gray-600"})}};function Ck(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 Sk({request:t}){const s=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",a=s?Ck(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(q,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Vt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(Se,{className:"text-xs sm:text-sm",children:s?"Form 16 submission steps and audit trail":"Complete audit trail of all request activities"})]}),e.jsx(se,{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:wk(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:ys(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(Vt,{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 P0({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(gt,{open:t,onOpenChange:s,children:e.jsxs(ht,{className:"sm:max-w-md",children:[e.jsx(ft,{children:e.jsxs(pt,{className:"flex items-center gap-2",children:[a?e.jsx(He,{className:"w-5 h-5 text-green-600"}):e.jsx(tt,{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(He,{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(Rt,{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 E0({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:[]}),[w,S]=u.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});u.useEffect(()=>{t&&(async()=>{var E;try{const _=await ha("WORKFLOW_SHARING"),z=await ha("TAT_SETTINGS"),R=[..._,...z],L={};R.forEach(V=>{L[V.configKey]=V.configValue}),S({maxApprovalLevels:parseInt(L.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(L.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((E=L.ALLOW_ADD_SPECTATOR)==null?void 0:E.toLowerCase())==="true",maxSpectators:parseInt(L.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(_){console.error("Failed to load system policy:",_)}})()},[t]);const D=async()=>{var I,A;const N=n.trim().toLowerCase();if(!N){y({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){y({open:!0,type:"error",email:N,message:"Please enter a valid email address"});return}const _=r.find(G=>(G.email||"").toLowerCase()===N);if(_){const G=((I=_.participantType)==null?void 0:I.toUpperCase())||"PARTICIPANT",$=_.name||N;if(G==="INITIATOR"){y({open:!0,type:"error",email:N,message:`${$} is the request initiator and cannot be added as a spectator.`});return}else if(G==="APPROVER"){y({open:!0,type:"error",email:N,message:`${$} is already an approver on this request and cannot be added as a spectator.`});return}else if(G==="SPECTATOR"){y({open:!0,type:"error",email:N,message:`${$} is already a spectator on this request.`});return}else{y({open:!0,type:"error",email:N,message:`${$} is already a participant on this request.`});return}}const z=[];w.allowSpectators||z.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const L=r.filter(G=>(G.participantType||"").toUpperCase()==="SPECTATOR").length;L>=w.maxSpectators&&z.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:L,maxValue:w.maxSpectators});const V=r.length+1;if(V>w.maxParticipants&&z.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:V,maxValue:w.maxParticipants}),z.length>0){v({open:!0,violations:z});return}if(!x||x.email.toLowerCase()!==N)try{const $=((A=(await Ca(N,1)).data)==null?void 0:A.data)||[];if($.length===0){y({open:!0,type:"not-found",email:N,message:""});return}const M=$[0];await Na({userId:M.userId,email:M.email,displayName:M.displayName,firstName:M.firstName,lastName:M.lastName,department:M.department,phone:M.phone,mobilePhone:M.mobilePhone,designation:M.designation,jobTitle:M.jobTitle,manager:M.manager,employeeId:M.employeeId,employeeNumber:M.employeeNumber,secondEmail:M.secondEmail,location:M.location})}catch(G){console.error("Failed to validate spectator:",G),y({open:!0,type:"error",email:N,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(N),i(""),h(null),s()}catch(G){console.error("Failed to add spectator:",G)}finally{o(!1)}},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 C=N=>{if(i(N),x&&x.email.toLowerCase()!==N.toLowerCase()&&h(null),g.current&&clearTimeout(g.current),!N||!N.startsWith("@")||N.length<2){d([]),p(!1);return}p(!0),g.current=setTimeout(async()=>{var E;try{const _=N.slice(1),R=((E=(await Ca(_,10)).data)==null?void 0:E.data)||[];d(R)}catch(_){console.error("Search failed:",_),d([])}finally{p(!1)}},300)},F=async N=>{try{await Na({userId:N.userId,email:N.email,displayName:N.displayName,firstName:N.firstName,lastName:N.lastName,department:N.department,phone:N.phone,mobilePhone:N.mobilePhone,designation:N.designation,jobTitle:N.jobTitle,manager:N.manager,employeeId:N.employeeId,employeeNumber:N.employeeNumber,secondEmail:N.secondEmail,location:N.location}),i(N.email),h(N),d([]),p(!1)}catch(E){console.error("Failed to ensure user exists:",E),y({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(gt,{open:t,onOpenChange:k,children:[e.jsxs(ht,{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(Nt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ft,{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(pt,{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(_l,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ee,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:N=>C(N.target.value),className:"pl-10 h-11 border-gray-300",disabled:l,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>F(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ms,{className:"h-8 w-8",children:e.jsx(us,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(N.displayName||N.email).split(" ").map(E=>E[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:N.displayName||[N.firstName,N.lastName].filter(Boolean).join(" ")||N.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:N.email}),N.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:N.designation})]})]})},N.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(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:D,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(gt,{open:b.open,onOpenChange:N=>y(E=>({...E,open:N})),children:e.jsxs(ht,{className:"sm:max-w-md",children:[e.jsxs(ft,{children:[e.jsx(pt,{className:"flex items-center gap-2",children:b.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{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(Pl,{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(Rt,{children:e.jsx(O,{onClick:()=>y(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Ri,{open:j.open,onClose:()=>v({open:!1,violations:[]}),violations:j.violations,policyDetails:{maxApprovalLevels:w.maxApprovalLevels,maxParticipants:w.maxParticipants,allowSpectators:w.allowSpectators,maxSpectators:w.maxSpectators}})]})}function _0({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,w]=u.useState(null),S=u.useRef(null),D=u.useRef(null),[k,C]=u.useState({open:!1,type:"error",email:"",message:""}),F=n.filter(A=>A&&(A.status==="approved"||A.status==="rejected"||A.status==="skipped")),N=Math.max(1,F.length+1),E=Math.max(1,n.length+1),_=E>=N?Array.from({length:E-N+1},(A,G)=>N+G):[N];u.useEffect(()=>{_.length>0&&p===null&&x(_[0]||null)},[_.length,p]);const z=async()=>{var U,H;const A=o.trim().toLowerCase();if(!A){C({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A)){C({open:!0,type:"error",email:A,message:"Please enter a valid email address"});return}if(!d||d<=0){C({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(d>720){C({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!p){C({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(p<N){C({open:!0,type:"error",email:"",message:`Cannot add approver at level ${p}. Minimum allowed level is ${N} (after completed levels)`});return}const $=n.length>0?Math.max(...n.map(W=>W.levelNumber),0):0,M=p>$?p:$+1;if(i&&M>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${p} would result in ${M} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:M,maxValue:i}]):C({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${$} level(s).`});return}const T=r.find(W=>(W.email||"").toLowerCase()===A);if(T){const W=((U=T.participantType)==null?void 0:U.toUpperCase())||"PARTICIPANT",P=T.name||A;if(W==="INITIATOR"){C({open:!0,type:"error",email:A,message:`${P} is the request initiator and cannot be added as an approver.`});return}else if(W==="APPROVER"){C({open:!0,type:"error",email:A,message:`${P} is already an approver on this request.`});return}else if(W==="SPECTATOR"){C({open:!0,type:"error",email:A,message:`${P} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{C({open:!0,type:"error",email:A,message:`${P} is already a participant on this request.`});return}}if(!v||v.email.toLowerCase()!==A)try{const P=((H=(await Ca(A,1)).data)==null?void 0:H.data)||[];if(P.length===0){C({open:!0,type:"not-found",email:A,message:""});return}const B=P[0];await Na({userId:B.userId,email:B.email,displayName:B.displayName,firstName:B.firstName,lastName:B.lastName,department:B.department,phone:B.phone,mobilePhone:B.mobilePhone,designation:B.designation,jobTitle:B.jobTitle,manager:B.manager,employeeId:B.employeeId,employeeNumber:B.employeeNumber,secondEmail:B.secondEmail,location:B.location})}catch(W){console.error("Failed to validate approver:",W),C({open:!0,type:"error",email:A,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(A,d,p),c(""),m(24),x(null),w(null),s()}catch(W){console.error("Failed to add approver:",W)}finally{g(!1)}},R=()=>{h||(c(""),m(24),x(null),w(null),b([]),j(!1),s())},L=A=>{const G=A.toLowerCase();return G==="approved"?e.jsx(He,{className:"w-4 h-4 text-green-600"}):G==="rejected"?e.jsx(At,{className:"w-4 h-4 text-red-600"}):G==="skipped"?e.jsx(tt,{className:"w-4 h-4 text-orange-600"}):G==="in-review"||G==="pending"?e.jsx(ot,{className:"w-4 h-4 text-blue-600"}):e.jsx(ot,{className:"w-4 h-4 text-gray-400"})};u.useEffect(()=>{f.length>0&&D.current&&D.current.scrollTo({top:D.current.scrollHeight,behavior:"smooth"})},[f.length]),u.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const V=A=>{if(c(A),v&&v.email.toLowerCase()!==A.toLowerCase()&&w(null),S.current&&clearTimeout(S.current),!A||!A.startsWith("@")||A.length<2){b([]),j(!1);return}j(!0),S.current=setTimeout(async()=>{var G;try{const $=A.slice(1),T=((G=(await Ca($,10)).data)==null?void 0:G.data)||[];b(T)}catch($){console.error("Search failed:",$),b([])}finally{j(!1)}},300)},I=async A=>{try{await Na({userId:A.userId,email:A.email,displayName:A.displayName,firstName:A.firstName,lastName:A.lastName,department:A.department,phone:A.phone,mobilePhone:A.mobilePhone,designation:A.designation,jobTitle:A.jobTitle,manager:A.manager,employeeId:A.employeeId,employeeNumber:A.employeeNumber,secondEmail:A.secondEmail,location:A.location}),c(A.email),w(A),b([]),j(!1)}catch(G){console.error("Failed to ensure user exists:",G),C({open:!0,type:"error",email:A.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(gt,{open:t,onOpenChange:R,children:[e.jsxs(ht,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:R,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(Nt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ft,{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(es,{className:"w-5 h-5 text-blue-600"})}),e.jsx(pt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:D,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(A=>A.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(A=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${A.status==="approved"?"bg-green-100 border border-green-200":A.status==="rejected"?"bg-red-100 border border-red-200":A.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:A.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:A.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[A.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[L(A.status),e.jsx(le,{variant:"outline",className:`text-xs ${A.status==="approved"?"bg-green-50 text-green-700 border-green-300":A.status==="rejected"?"bg-red-50 text-red-700 border-red-300":A.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:A.status})]})]},A.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:[" New approver can only be added at level ",N," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(Ke,{value:(p==null?void 0:p.toString())||"",onValueChange:A=>x(Number(A)),disabled:h,children:[e.jsx(Xe,{className:"h-11 border-gray-300",children:e.jsx(Qe,{placeholder:"Select level"})}),e.jsx(Je,{children:_.map(A=>e.jsx(J,{value:A.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",A]}),A<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",A,")"]})]})},A))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Choose where to insert the new approver. Existing levels will be automatically shifted."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ee,{type:"number",min:"1",max:"720",value:d,onChange:A=>m(Number(A.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(ot,{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(_l,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ee,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:A=>V(A.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(A=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>I(A),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ms,{className:"h-8 w-8",children:e.jsx(us,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(A.displayName||A.email).split(" ").map(G=>G[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:A.displayName||[A.firstName,A.lastName].filter(Boolean).join(" ")||A.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:A.email}),A.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:A.designation})]})]})},A.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:R,className:"flex-1 h-11 border-gray-300",disabled:h,children:"Cancel"}),e.jsxs(O,{type:"button",onClick:z,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:h||!o.trim()||!p||!d,children:[e.jsx(es,{className:"w-4 h-4 mr-2"}),h?"Adding...":`Add at Level ${p||"?"}`]})]})]}),e.jsx(gt,{open:k.open,onOpenChange:A=>C(G=>({...G,open:A})),children:e.jsxs(ht,{className:"sm:max-w-md",children:[e.jsxs(ft,{children:[e.jsx(pt,{className:"flex items-center gap-2",children:k.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{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(Pl,{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(Rt,{children:e.jsx(O,{onClick:()=>C(A=>({...A,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Ak=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"}},Tk=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},kk=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)},Dk=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",$h=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Pe,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(Lp,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Pe,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Pe,{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(Rl,{className:`${s} text-gray-600`})};function M0({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=Sa(),h=t||x.requestId||"",[g,f]=u.useState(""),[b,y]=u.useState(""),[j,v]=u.useState(!1),[w,S]=u.useState([]),[D,k]=u.useState(!1),[C,F]=u.useState([]),[N,E]=u.useState(null),[_,z]=u.useState(null),[R,L]=u.useState(!1),[V,I]=u.useState(!1),[A,G]=u.useState(!1),[$,M]=u.useState({success:!0,title:"",message:""}),T=u.useRef(null),U=u.useRef(null),H=u.useRef(null),W=u.useRef(!1),[P,B]=u.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[K,Z]=u.useState({open:!1,errors:[]}),te=u.useMemo(()=>({id:h,title:n||"Request Details"}),[h,n]),[ae,xe]=u.useState([]),be=ae.filter(Q=>Q.status==="online"),Ge=w.filter(Q=>Q.content.toLowerCase().includes(b.toLowerCase())||Q.user.name.toLowerCase().includes(b.toLowerCase())),Be=u.useMemo(()=>o!==void 0?o:!N||ae.length===0?!1:ae.some(Q=>{const de=Q.userId||Q.user_id,ee=(Q.role||"").toString().toUpperCase(),Ae=(Q.participantType||Q.participant_type||"").toString().toUpperCase();return de===N&&(ee==="SPECTATOR"||Ae==="SPECTATOR")}),[o,N,ae]);u.useEffect(()=>{},[ae]),u.useEffect(()=>{!h||!N||s||(async()=>{try{const Q=await yn(h),de=Array.isArray(Q)?Q.map(ee=>{const Ae=ee.userId||ee.user_id;return{id:ee.noteId||ee.id||String(Math.random()),user:{name:ee.userName||"User",avatar:(ee.userName||"U").slice(0,2).toUpperCase(),role:ee.userRole||"Participant"},content:ee.message||"",timestamp:ee.createdAt||new Date().toISOString(),isCurrentUser:Ae===N,attachments:Array.isArray(ee.attachments)?ee.attachments.map(Ue=>({attachmentId:Ue.attachmentId||Ue.attachment_id,name:Ue.fileName||Ue.file_name||Ue.name,fileName:Ue.fileName||Ue.file_name||Ue.name,url:Ue.storageUrl||Ue.storage_url||Ue.url||"#",type:Ue.fileType||Ue.file_type||Ue.type||"file",fileType:Ue.fileType||Ue.file_type||Ue.type||"file",fileSize:Ue.fileSize||Ue.file_size})):void 0}}):[];S(de)}catch(Q){console.error("[WorkNoteChat] Failed to load messages:",Q)}})()},[h,N,s]);const _e=u.useMemo(()=>{const Q=[];return w.forEach(de=>{de.attachments&&de.attachments.length>0&&de.attachments.forEach(ee=>{Q.push({attachmentId:ee.attachmentId||ee.attachment_id,name:ee.fileName||ee.file_name||ee.name||"Untitled",fileName:ee.fileName||ee.file_name||ee.name||"Untitled",size:ee.fileSize||ee.file_size,type:ee.fileType||ee.file_type||ee.type||"file",uploadedBy:de.user.name,uploadedAt:de.timestamp,url:ee.storageUrl||ee.storage_url||ee.url||"#"})})}),Q},[w]);u.useEffect(()=>{i&&_e.length>=0&&i(_e)},[_e,i]);const Re=u.useMemo(()=>ae.map(Q=>({email:(Q.email||"").toLowerCase(),participantType:Q.role==="Initiator"?"INITIATOR":Q.role==="Approver"?"APPROVER":Q.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:Q.name})),[ae]),ce=Q=>{if(!Q)return"Participant";switch(Q.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return Q.charAt(0).toUpperCase()+Q.slice(1).toLowerCase()}},je=()=>{var Q;(Q=T.current)==null||Q.scrollIntoView({behavior:"smooth"})};u.useEffect(()=>{je()},[w]);const re=Q=>{switch(Q.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return Q.charAt(0).toUpperCase()+Q.slice(1).toLowerCase()}};u.useEffect(()=>{W.current||h&&(async()=>{try{const Q=await Ls(h),de=Array.isArray(Q==null?void 0:Q.participants)?Q.participants:[];if(de.length===0)return;const ee=de.map(ze=>{const qe=ze.participantType||ze.participant_type||"participant",Ze=ze.userId||ze.user_id||"";return{name:ze.userName||ze.user_name||ze.user_email||ze.userEmail||"User",avatar:(ze.userName||ze.user_name||ze.user_email||"U").toString().split(" ").map(nt=>nt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:re(qe.toString()),status:"offline",email:ze.userEmail||ze.user_email||"",permissions:["read","write","mention"],userId:Ze}});W.current=!0,xe(ee);let Ae=0;const Ue=3,et=()=>{H.current&&H.current.connected?(H.current.emit("request:online-users",{requestId:h}),Ae++,Ae<Ue&&setTimeout(et,500)):(Ae++,Ae<Ue&&setTimeout(et,200))};setTimeout(et,100)}catch(Q){console.error("[WorkNoteChat] ❌ Failed to load participants:",Q)}})()},[h]),u.useEffect(()=>()=>{h&&(W.current=!1)},[h]),u.useEffect(()=>{const Q=localStorage.getItem("userData");if(Q)try{const de=JSON.parse(Q),ee=(de==null?void 0:de.id)||(de==null?void 0:de.userId)||(de==null?void 0:de.user_id)||null;E(ee)}catch(de){console.error("[WorkNoteChat] Failed to parse userData:",de)}},[]),u.useEffect(()=>{(async()=>{try{const de=await ha("DOCUMENT_POLICY"),ee={};de.forEach(ze=>{ee[ze.configKey]=ze.configValue});const Ae=parseInt(ee.MAX_FILE_SIZE_MB||"10"),et=(ee.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(ze=>ze.trim().toLowerCase());B({maxFileSizeMB:Ae,allowedFileTypes:et})}catch(de){console.error("Failed to load document policy:",de)}})()},[]),u.useEffect(()=>{if(!N)return;let Q=h;return(async()=>{var de;try{const ee=await Ls(h);(de=ee==null?void 0:ee.workflow)!=null&&de.requestId&&(Q=ee.workflow.requestId)}catch{}try{const ee=Xr();r?xe(xt=>xt.map(Pt=>Pt.userId===N?{...Pt,status:"online"}:Pt)):(cc(ee,Q,N),xe(xt=>xt.map(Pt=>Pt.userId===N?{...Pt,status:"online"}:Pt)));const Ae=xt=>{const bt=(xt==null?void 0:xt.note)||xt;if(!bt)return;const Pt=bt.noteId||bt.id;S(As=>{if(As.some($t=>$t.id===Pt))return As;const ns=bt.userName||bt.user_name||"User",Ya=bt.userRole||bt.user_role,Ka=ce(Ya),Cr=bt.userId||bt.user_id,Aa={id:Pt||String(Date.now()),user:{name:ns,avatar:ns.split(" ").map($t=>$t[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ka},content:bt.message||"",timestamp:bt.createdAt||new Date().toISOString(),isCurrentUser:Cr===N,attachments:Array.isArray(bt.attachments)?bt.attachments.map($t=>({attachmentId:$t.attachmentId||$t.attachment_id,name:$t.fileName||$t.file_name||$t.name,fileName:$t.fileName||$t.file_name||$t.name,url:$t.storageUrl||$t.storage_url||$t.url||"#",type:$t.fileType||$t.file_type||$t.type||"file",fileType:$t.fileType||$t.file_type||$t.type||"file",fileSize:$t.fileSize||$t.file_size})):void 0};return[...As,Aa]})},Ue=xt=>{xe(bt=>bt.length===0||!bt.find(ns=>ns.userId===xt.userId)?bt:bt.map(ns=>ns.userId===xt.userId?{...ns,status:"online"}:ns))},et=xt=>{xt.userId!==N&&xe(bt=>bt.length===0||!bt.find(ns=>ns.userId===xt.userId)?bt:bt.map(ns=>ns.userId===xt.userId?{...ns,status:"offline"}:ns))},ze=xt=>{xe(bt=>bt.length===0?bt:bt.map(As=>{const ns=As.userId||"";if(ns===N)return{...As,status:"online"};const Ka=xt.userIds.includes(ns);return{...As,status:Ka?"online":"offline"}}))},qe=()=>{xe(xt=>xt.map(Pt=>Pt.userId===N?{...Pt,status:"online"}:Pt)),r||cc(ee,Q,N),W.current&&(ee.emit("request:online-users",{requestId:Q}),setTimeout(()=>ee.emit("request:online-users",{requestId:Q}),300),setTimeout(()=>ee.emit("request:online-users",{requestId:Q}),800))},Ze=xt=>{console.error("[WorkNoteChat] ❌ Socket error:",xt)},nt=xt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",xt),xe(bt=>bt.map(Pt=>Pt.userId===N?Pt:{...Pt,status:"offline"}))},rs=xt=>{xt.includes("presence")||xt.includes("worknote")||xt.includes("request")};ee.on("connect",qe),ee.on("disconnect",nt),ee.on("error",Ze),ee.on("worknote:new",Ae),ee.on("presence:join",Ue),ee.on("presence:leave",et),ee.on("presence:online",ze),ee.onAny(rs),H.current=ee,ee.connected&&W.current&&(ee.emit("request:online-users",{requestId:Q}),setTimeout(()=>{ee.emit("request:online-users",{requestId:Q})},300),setTimeout(()=>{ee.emit("request:online-users",{requestId:Q})},800),setTimeout(()=>{ee.emit("request:online-users",{requestId:Q})},1500));const Ot=()=>{ee.off("connect",qe),ee.off("disconnect",nt),ee.off("error",Ze),ee.off("worknote:new",Ae),ee.off("presence:join",Ue),ee.off("presence:leave",et),ee.off("presence:online",ze),ee.offAny(rs),r||Zp(ee,Q),H.current=null};window.__wn_cleanup=Ot}catch{}})(),()=>{var de;try{(de=window.__wn_cleanup)==null||de.call(window)}catch{}}},[h,N,r]);const pe=async()=>{if(g.trim()||C.length>0){const Q=at(g),de=Q.map(Ue=>{const et=ae.find(ze=>ze.name.toLowerCase().includes(Ue.toLowerCase()));return et==null?void 0:et.userId}).filter(Boolean),ee=C.map(Ue=>({name:Ue.name,url:URL.createObjectURL(Ue),type:Ue.type.split("/")[1]||"file"})),Ae={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:Q,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:ee.length>0?ee:void 0,isCurrentUser:!0};if(a)try{await a(g,C)}catch{}else try{await Lg(h,{message:g,mentions:de},C);const Ue=await yn(h),et=Array.isArray(Ue)?Ue.map(ze=>{const qe=ze.userId||ze.user_id;return{id:ze.noteId||ze.id||String(Math.random()),user:{name:ze.userName||"User",avatar:(ze.userName||"U").slice(0,2).toUpperCase(),role:ze.userRole||"Participant"},content:ze.message||"",timestamp:ze.createdAt||new Date().toISOString(),isCurrentUser:qe===N,attachments:Array.isArray(ze.attachments)?ze.attachments.map(Ze=>({attachmentId:Ze.attachmentId||Ze.attachment_id,name:Ze.fileName||Ze.file_name||Ze.name,fileName:Ze.fileName||Ze.file_name||Ze.name,url:Ze.storageUrl||Ze.storage_url||Ze.url||"#",type:Ze.fileType||Ze.file_type||Ze.type||"file",fileType:Ze.fileType||Ze.file_type||Ze.type||"file",fileSize:Ze.fileSize||Ze.file_size})):void 0}}):[];S(et)}catch{S(Ue=>[...Ue,Ae])}f(""),F([])}};u.useEffect(()=>{if(s&&Array.isArray(s))try{const de=s.filter(ee=>(ee.type||"").toLowerCase()!=="sla_warning").map(ee=>{var Ue;if(ee.type||ee.activityType||ee.isSystem)return{id:ee.id||`activity-${ee.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:ee.details||ee.action||ee.content||"",timestamp:ee.timestamp||ee.createdAt||ee.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const et=ee.userName||ee.user_name||((Ue=ee.user)==null?void 0:Ue.name)||"User",ze=ee.userRole||ee.user_role,qe=ce(ze),Ze=ee.userId||ee.user_id;return{id:ee.noteId||ee.note_id||ee.id||String(Math.random()),user:{name:et,avatar:et.split(" ").map(nt=>nt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:qe},content:ee.message||ee.content||"",timestamp:ee.createdAt||ee.created_at||ee.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(ee.attachments)?ee.attachments.map(nt=>({attachmentId:nt.attachmentId||nt.attachment_id,name:nt.fileName||nt.file_name||nt.name,fileName:nt.fileName||nt.file_name||nt.name,url:nt.storageUrl||nt.storage_url||nt.url||"#",type:nt.fileType||nt.file_type||nt.type||"file",fileType:nt.fileType||nt.file_type||nt.type||"file",fileSize:nt.fileSize||nt.file_size})):void 0,isCurrentUser:Ze===N}}}).sort((ee,Ae)=>new Date(ee.timestamp).getTime()-new Date(Ae.timestamp).getTime());S(de)}catch(Q){console.error("[WorkNoteChat] Error mapping messages:",Q)}else(async()=>{try{const Q=await yn(h),de=Array.isArray(Q)?Q.map(ee=>{const Ae=ee.userName||ee.user_name||"User",Ue=ee.userRole||ee.user_role,et=ce(Ue),ze=ee.userId||ee.user_id;return{id:ee.noteId||ee.note_id||ee.id||String(Math.random()),user:{name:Ae,avatar:Ae.split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:et},content:ee.message||"",timestamp:ee.createdAt||ee.created_at||new Date().toISOString(),attachments:Array.isArray(ee.attachments)?ee.attachments.map(qe=>({attachmentId:qe.attachmentId||qe.attachment_id,name:qe.fileName||qe.file_name||qe.name,fileName:qe.fileName||qe.file_name||qe.name,url:qe.storageUrl||qe.storage_url||qe.url||"#",type:qe.fileType||qe.file_type||qe.type||"file",fileType:qe.fileType||qe.file_type||qe.type||"file",fileSize:qe.fileSize||qe.file_size})):void 0,isCurrentUser:ze===N}}):[];S(de)}catch(Q){console.error("[WorkNoteChat] Error loading work notes:",Q)}})()},[s,h,ae]);const ie=Q=>{const de=P.maxFileSizeMB*1024*1024;if(Q.size>de)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${P.maxFileSizeMB}MB. Current size: ${(Q.size/(1024*1024)).toFixed(2)}MB`};const ee=Q.name.toLowerCase(),Ae=ee.substring(ee.lastIndexOf(".")+1);return P.allowedFileTypes.includes(Ae)?{valid:!0}:{valid:!1,reason:`File type "${Ae}" is not allowed. Allowed types: ${P.allowedFileTypes.join(", ")}`}},fe=Q=>{if(!Q.target.files||Q.target.files.length===0)return;const de=Array.from(Q.target.files),ee=[],Ae=[];de.forEach(Ue=>{const et=ie(Ue);et.valid?Ae.push(Ue):ee.push({fileName:Ue.name,reason:et.reason||"Unknown validation error"})}),ee.length>0&&Z({open:!0,errors:ee}),Ae.length>0&&(F(Ue=>[...Ue,...Ae]),Ae.length<de.length?Y.warning(`${Ae.length} of ${de.length} file(s) were added. ${ee.length} file(s) were rejected.`):Y.success(`${Ae.length} file(s) added successfully`)),Q.target&&(Q.target.value="")},Ie=Q=>{F(de=>de.filter((ee,Ae)=>Ae!==Q)),U.current&&(U.current.value="")},$e=Q=>{f(de=>de+Q),v(!1)},ye=()=>{var Q;(Q=U.current)==null||Q.click()},oe=async Q=>{var de,ee;try{await $g(h,Q);const Ae=await Ls(h),Ue=Array.isArray(Ae==null?void 0:Ae.participants)?Ae.participants:[];if(Ue.length){const et=Ue.map(ze=>{const qe=ze.participantType||ze.participant_type||"participant",Ze=ze.userId||ze.user_id||"",nt=ze.userName||ze.user_name||ze.userEmail||ze.user_email||"User",rs=ze.userEmail||ze.user_email||"",Ot=nt.split(" ").map(xt=>xt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:nt,avatar:Ot,role:re(qe),status:"offline",email:rs,lastSeen:void 0,permissions:["read"],userId:Ze}});xe(et),H.current&&H.current.connected&&H.current.emit("request:online-users",{requestId:h})}L(!1),M({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),G(!0)}catch(Ae){throw console.error("Failed to add spectator:",Ae),M({success:!1,title:"Failed to Add Spectator",message:((ee=(de=Ae==null?void 0:Ae.response)==null?void 0:de.data)==null?void 0:ee.error)||"Failed to add spectator. Please try again."}),G(!0),Ae}},ke=async(Q,de,ee)=>{var Ae,Ue;if(d)await d(Q,de,ee),I(!1);else try{await Og(h,Q,de,ee);const et=await Ls(h),ze=Array.isArray(et==null?void 0:et.participants)?et.participants:[];if(ze.length){const qe=ze.map(Ze=>{const nt=Ze.participantType||Ze.participant_type||"participant",rs=Ze.userId||Ze.user_id||"",Ot=Ze.userName||Ze.user_name||Ze.userEmail||Ze.user_email||"User",xt=Ze.userEmail||Ze.user_email||"",bt=Ot.split(" ").map(Pt=>Pt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Ot,avatar:bt,role:re(nt),status:"offline",email:xt,lastSeen:void 0,permissions:["read"],userId:rs}});xe(qe),H.current&&H.current.connected&&H.current.emit("request:online-users",{requestId:h})}I(!1),M({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${ee} with ${de}h TAT`}),G(!0)}catch(et){throw console.error("Failed to add approver:",et),M({success:!1,title:"Failed to Add Approver",message:((Ue=(Ae=et==null?void 0:et.response)==null?void 0:Ae.data)==null?void 0:Ue.error)||"Failed to add approver. Please try again."}),G(!0),et}},st=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","","","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],at=Q=>{const de=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,ee=[];let Ae;for(;(Ae=de.exec(Q))!==null;)if(Ae[1]){const Ue=Ae.index+Ae[0].length,et=Q.slice(Ue),ze=Q[Ue];(et.startsWith("@")||!ze||/\s|[.,!?;:]|@/.test(ze))&&ee.push(Ae[1].trim())}return ee},ct=Q=>{Q.key==="Enter"&&!Q.shiftKey&&(Q.preventDefault(),pe())},Dt=(Q,de)=>{S(ee=>ee.map(Ae=>{if(Ae.id===Q){const Ue=Ae.reactions||[],et=Ue.find(ze=>ze.emoji===de);if(et)if(et.users.includes("You")){if(et.users=et.users.filter(ze=>ze!=="You"),et.users.length===0)return{...Ae,reactions:Ue.filter(ze=>ze.emoji!==de)}}else et.users.push("You");else Ue.push({emoji:de,users:["You"]});return{...Ae,reactions:Ue}}return Ae}))};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(Ks,{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:te.title}),e.jsx(le,{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:[be.slice(0,3).map((Q,de)=>e.jsx(ms,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(us,{className:"bg-blue-500 text-white text-xs font-semibold",children:Q.avatar})},de)),be.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:["+",be.length-3]})]})}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>k(!D),className:"lg:hidden",children:e.jsx(es,{className:"h-4 w-4"})})]})]})}),e.jsxs("div",{className:"flex-1 flex overflow-hidden relative",children:[e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx("div",{className:"bg-white border-b border-gray-200 px-2 sm:px-3 lg:px-6 py-2 sm:py-3 flex-shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ee,{placeholder:"Search messages...",value:b,onChange:Q=>y(Q.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(Q=>{const de=Q.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${Q.isSystem?"justify-center":de?"justify-end":""}`,children:[!Q.isSystem&&!de&&e.jsx(ms,{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(us,{className:`text-white font-semibold text-xs sm:text-sm ${Q.user.role==="Initiator"?"bg-green-600":Q.user.role==="Current User"?"bg-blue-500":Q.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:Q.user.avatar})}),e.jsx("div",{className:`${de?"max-w-[70%]":"flex-1"} min-w-0 ${Q.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:Q.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(Vt,{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:Q.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:ys(Q.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${de?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[Q.user.name," ",de&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(le,{variant:"outline",className:"text-xs flex-shrink-0",children:Q.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(ot,{className:"w-3 h-3"}),ys(Q.timestamp)]}),Q.isHighPriority&&e.jsxs(le,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(uy,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${de?"bg-blue-50 border-blue-200":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:"text-gray-800 leading-relaxed text-sm sm:text-base",dangerouslySetInnerHTML:{__html:kk(Q.content)}}),Q.attachments&&Q.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:Q.attachments.map((ee,Ae)=>{const Ue=ee.fileSize||ee.file_size,et=ee.fileName||ee.file_name||ee.name,ze=ee.fileType||ee.file_type||ee.type||"",qe=ee.attachmentId||ee.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($h,{type:ze})}),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:et}),Ue&&e.jsx("p",{className:"text-xs text-gray-500",children:Dk(Ue)})]}),qe&&(()=>{const Ze=(ze||"").toLowerCase();return Ze.includes("image")||Ze.includes("pdf")||Ze.includes("jpg")||Ze.includes("jpeg")||Ze.includes("png")||Ze.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:Ze=>{Ze.preventDefault(),Ze.stopPropagation();const nt=NC(qe);z({fileName:et,fileType:ze,fileUrl:nt,fileSize:Ue,attachmentId:qe})},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 Ze=>{if(Ze.preventDefault(),Ze.stopPropagation(),!qe){Y.error("Cannot download: Attachment ID missing");return}try{await dx(qe)}catch{Y.error("Failed to download file")}},title:"Download file",children:e.jsx(kt,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Ae)})})}),Q.reactions&&Q.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:[Q.reactions.map((ee,Ae)=>e.jsxs("button",{onClick:()=>Dt(Q.id,ee.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${ee.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:ee.emoji}),e.jsx("span",{className:"text-xs font-medium",children:ee.users.length})]},Ae)),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(os,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!Q.isSystem&&de&&e.jsx(ms,{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(us,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:Q.user.avatar})})]},Q.id)}),e.jsx("div",{ref:T})]})}),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:fe,className:"hidden",multiple:!0,accept:P.allowedFileTypes.map(Q=>`.${Q}`).join(",")}),C.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:C.map((Q,de)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx($h,{type:Q.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:Q.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(Q.size/1024).toFixed(1)," KB"]}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>Ie(de),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(Nt,{className:"h-3 w-3 text-red-600"})})]},de))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const Q=g.lastIndexOf("@"),de=Q>=0;if(!de)return null;const ee=g.slice(Q+1),Ae=ee.trim(),Ue=ee.endsWith(" "),et=Ae.length>0,ze=Ae.includes(" ")&&!Ue,qe=Ue&&et;if(!(de&&ee.length<=20&&!ze&&!qe))return null;const nt=Ae.toLowerCase(),rs=ae.filter(Ot=>Ot.userId===N?!1:nt?Ot.name.toLowerCase().includes(nt):!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:rs.length>0?rs.map((Ot,xt)=>e.jsxs("button",{type:"button",onClick:bt=>{bt.preventDefault(),bt.stopPropagation();const Pt=g.lastIndexOf("@"),As=g.slice(0,Pt);f(As+"@"+Ot.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(ms,{className:"h-10 w-10",children:e.jsx(us,{className:`text-white text-sm font-semibold ${Ot.role==="Initiator"?"bg-green-600":Ot.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:Ot.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:Ot.name}),e.jsx("p",{className:"text-xs text-gray-600",children:Ot.role})]})]},xt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:nt?`No participants found matching "${nt}"`:"No other participants available"})})]})})(),e.jsx(Ws,{placeholder:Be?"Spectators cannot send messages":"Type your message... Use @username to mention someone",value:g,onChange:Q=>f(Q.target.value),onKeyPress:ct,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:Be}),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(Nt,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:st.map((Q,de)=>e.jsx("button",{onClick:()=>$e(Q),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:Q,children:Q},de))})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-shrink-0",children:[e.jsx(O,{variant:"ghost",size:"sm",onClick:ye,disabled:Be,title:Be?"Spectators cannot attach files":"Attach file",children:e.jsx(Rl,{className:"h-4 w-4"})}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>v(!j),disabled:Be,title:Be?"Spectators cannot add emojis":"Add emoji",children:e.jsx(xy,{className:"h-4 w-4"})}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>f(Q=>Q+"@"),disabled:Be,title:Be?"Spectators cannot mention users":"Mention someone",children:e.jsx(_l,{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:pe,disabled:!g.trim()&&C.length===0||Be,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:Be?"Spectators cannot send messages":"Send",children:[e.jsx(Mp,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),D&&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
${D?"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(Nt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:ae.map((Q,de)=>{const ee=Q.userId===N;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ms,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(us,{className:`text-white font-semibold text-sm ${Q.role==="Initiator"?"bg-green-600":ee?"bg-blue-500":"bg-slate-600"}`,children:Q.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${Ak(Q.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:[Q.name," ",ee&&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:Q.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:Tk(Q.status)})]}),Q.lastSeen&&Q.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:Q.lastSeen})]})]},de)})})]}),!Be&&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:()=>I(!0),children:[e.jsx(El,{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:()=>L(!0),children:[e.jsx(wt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),_&&e.jsx(en,{fileName:_.fileName,fileType:_.fileType,fileUrl:_.fileUrl,fileSize:_.fileSize,attachmentId:_.attachmentId,onDownload:dx,open:!!_,onClose:()=>z(null)}),!Be&&e.jsx(E0,{open:R,onClose:()=>L(!1),onConfirm:oe,requestIdDisplay:h,requestTitle:te.title,existingParticipants:Re}),!Be&&l&&e.jsx(_0,{open:V,onClose:()=>I(!1),onConfirm:ke,requestIdDisplay:h,requestTitle:te.title,existingParticipants:Re,currentLevels:c,maxApprovalLevels:m,onPolicyViolation:p}),e.jsx(gt,{open:K.open,onOpenChange:Q=>Z(de=>({...de,open:Q})),children:e.jsxs(ht,{className:"sm:max-w-lg",children:[e.jsxs(ft,{children:[e.jsxs(pt,{className:"flex items-center gap-2",children:[e.jsx(tt,{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:K.errors.map((Q,de)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:Q.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:Q.reason})]},de))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",P.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",P.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Rt,{children:e.jsx(O,{onClick:()=>Z({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(P0,{open:A,onClose:()=>G(!1),success:$.success,title:$.title,message:$.message})]})}function Rk({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(M0,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d})})}function Ik({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const c=o.toLowerCase();return c==="approved"?e.jsx(He,{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(ot,{className:"h-4 w-4 text-orange-600"}):e.jsx(Pe,{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(We,{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(le,{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(Os,{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:it(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:it(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(Os,{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(le,{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(Os,{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(Pe,{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 Fk({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(xr,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(He,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(At,{className:"h-4 w-4 text-red-600"}):e.jsx(ot,{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(xr,{className:`h-4 w-4 ${c.icon}`}):e.jsx(ot,{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(le,{className:`text-xs ${c.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(la,{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:[Jt(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${d==="breached"||d==="critical"?c.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[Jt(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(as,{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(ul,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function Pk({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var g,f;const c=Nk((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:Oh((t==null?void 0:t.status)||"pending").icon,label:m}:Oh((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(Ss,{className:"h-4 w-4 sm:h-5 sm:h-5"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Pe,{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(le,{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(le,{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",w=b==="CLAIM_MANAGEMENT"||y==="claim-management",S=b==="DEALER_CLAIM"||j==="DEALER CLAIM"||j==="DEALER_CLAIM";let D="Non-Templatized",k="bg-purple-100 !text-purple-600 border-purple-200";return v?(D="Form 16",k="bg-emerald-100 !text-emerald-700 border-emerald-200"):S?(D="Dealer Claim",k="bg-blue-100 !text-blue-700 border-blue-200"):w?(D="Claim Management",k="bg-blue-100 !text-blue-700 border-blue-200"):j==="TEMPLATE"&&(D="Template"),e.jsx(le,{className:`${k} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:D})})()]})]})]})]}),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(Fk,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function Xd(t){return(await we.get(`/summaries/${t}`)).data.data}async function Ek(t,s){return(await we.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function _k(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await we.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 L0(t){await we.patch(`/summaries/shared/${t}/view`)}async function O0(t){var s;try{return(await we.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 Mk(t){return(await we.get(`/summaries/${t}/recipients`)).data.data||[]}function Lk({activityInfo:t,className:s,createdAt:a,updatedAt:r}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(q,{className:s,children:e.jsx(se,{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 it(new Date(l),"MMM d, yyyy")}catch{return l}};return e.jsxs(q,{className:s,children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(jt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(se,{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(Hc,{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(Fa,{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(Os,{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:ys(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:ys(r)})]})]})]})]})}function Ok({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(q,{className:s,children:e.jsx(se,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(q,{className:s,children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ml,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(se,{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(wa,{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(ji,{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(Hc,{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(q,{className:s,children:e.jsx(se,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function $k({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 it(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(q,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${l}`,children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"text-base flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(Se,{children:"Workflow reference numbers"})]}),e.jsxs(se,{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(Vt,{className:"w-4 h-4 text-purple-600"}),e.jsx(ne,{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(ne,{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(Fa,{className:"w-4 h-4 text-green-600"}),e.jsx(ne,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),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(ii,{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(ne,{className:"text-xs font-semibold text-amber-900 uppercase tracking-wide",children:"Estimated Budget Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[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(ne,{className:"text-xs font-semibold text-indigo-900 uppercase tracking-wide",children:"Closed Expenses Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[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 Uk({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 it(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return it(new Date(o),"MMM d, yyyy")}catch{return o||"-"}};return e.jsxs(q,{className:s,children:[e.jsxs(me,{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(Se,{children:["Submitted on ",i(t.submittedOn)]})]}),e.jsxs(se,{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(jt,{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 Bk({initiatorInfo:t,className:s}){const a=r=>r.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2);return e.jsxs(q,{className:s,children:[e.jsx(me,{children:e.jsx(ue,{className:"text-base",children:"Request Initiator"})}),e.jsx(se,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(ms,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(us,{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(wa,{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(ji,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function $0(t,s){var a,r,n,i,l;try{if(!pi(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||"",w=p.proposalEstimatedBudget??p.proposal_estimated_budget??p.initialEstimatedBudget??p.initial_estimated_budget??o.estimatedBudget??o.estimated_budget,S=(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),D=S!=null?Number(S):void 0,k=Array.isArray(g)&&g.length>0?g.map(A=>({description:A.description||A.itemDescription||A.item_description||"",amount:Number(A.amount)||0,gstRate:A.gstRate??A.gst_rate,gstAmt:A.gstAmt??A.gst_amt,cgstAmt:A.cgstAmt??A.cgst_amt,sgstAmt:A.sgstAmt??A.sgst_amt,igstAmt:A.igstAmt??A.igst_amt,totalAmt:A.totalAmt??A.total_amt,hsnCode:A.hsnCode||A.hsn_code||A.hsnCd||A.hsn_cd||""})):(d==null?void 0:d.closedExpenses)||(d==null?void 0:d.closed_expenses)||(d==null?void 0:d.closedExpensesBreakdown)||[],C={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:w,closedExpenses:D,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 N=(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(A=>({description:A.description||A.itemDescription||A.item_description||"",amount:Number(A.amount)||0,gstRate:Number(A.gstRate??A.gst_rate??0),gstAmt:Number(A.gstAmt??A.gst_amt??0),cgstAmt:Number(A.cgstAmt??A.cgst_amt??0),sgstAmt:Number(A.sgstAmt??A.sgst_amt??0),igstAmt:Number(A.igstAmt??A.igst_amt??0),totalAmt:Number(A.totalAmt??A.total_amt??0),hsnCode:A.hsnCode||A.hsn_code||""})):Array.isArray(c.costBreakup||c.cost_breakup)?(c.costBreakup||c.cost_breakup).map(A=>({description:A.description||A.itemDescription||A.item_description||"",amount:Number(A.amount)||0,gstRate:A.gstRate??A.gst_rate,gstAmt:A.gstAmt??A.gst_amt,cgstAmt:A.cgstAmt??A.cgst_amt,sgstAmt:A.sgstAmt??A.sgst_amt,igstAmt:A.igstAmt??A.igst_amt,totalAmt:A.totalAmt??A.total_amt,hsnCode:A.hsnCode||A.hsn_code||""})):[],totalEstimatedBudget:c.totalEstimatedBudget||c.total_estimated_budget||0,timelineMode:c.timelineMode||c.timeline_mode,expectedCompletionDate:N,timelineForClosure:N,expectedCompletionDays:c.expectedCompletionDays||c.expected_completion_days,dealerComments:c.dealerComments||c.dealer_comments,submittedAt:c.submittedAt||c.submitted_at||c.submittedOn,submittedOn:c.submittedAt||c.submitted_at||c.submittedOn}:void 0,z={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||""},R=t.invoice||t.claimInvoice||t.claim_invoice||((n=t.claimRequest)==null?void 0:n.invoice)||((i=t.request)==null?void 0:i.invoice)||x||{},L=o||{},V={eInvoiceNumber:R.invoiceNumber||R.invoice_number||L.eInvoiceNumber||L.e_invoice_number||R.dmsNumber||R.dms_number,eInvoiceDate:R.invoiceDate||R.invoice_date||L.eInvoiceDate||L.e_invoice_date,dmsNumber:R.dmsNumber||R.dms_number||L.dmsNumber||L.dms_number,creditNoteNumber:h.creditNoteNumber||h.credit_note_number||L.creditNoteNumber||L.credit_note_number,creditNoteDate:h.creditNoteDate||h.credit_note_date||L.creditNoteDate||L.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):L.creditNoteAmount!==void 0&&L.creditNoteAmount!==null?Number(L.creditNoteAmount):L.credit_note_amount!==void 0&&L.credit_note_amount!==null?Number(L.credit_note_amount):void 0,irn:R.irn||L.irn,ackNo:R.ackNo||R.ack_no||L.ackNo||L.ack_no,ackDate:R.ackDate||R.ack_date||L.ackDate||L.ack_date,signedInvoiceUrl:R.signedInvoiceUrl||R.signed_invoice_url||L.signedInvoiceUrl||L.signed_invoice_url,taxBreakdown:R.taxBreakdown||L.taxBreakdown,creditNoteWfmData:(((l=t.creditNote)==null?void 0:l.items)||t.creditNoteWfmData||o.creditNoteWfmData||[]).map(A=>{var G;return{...A,DOC_NO:A.creditNoteNumber||((G=t.creditNote)==null?void 0:G.creditNoteNumber)||A.DOC_NO,TRNS_UNIQ_NO:A.transactionNo||A.TRNS_UNIQ_NO,MESSAGE:A.description||A.MESSAGE,TDS_AMT:A.tdsAmount||A.TDS_AMT,CREDITED_TOTAL_AMT:A.creditAmount||A.amount||A.CREDITED_TOTAL_AMT}})},I={estimated:C.estimatedBudget||0,closed:C.closedExpenses||0};return{activityInfo:C,dealerInfo:F,proposalDetails:_,ioDetails:Object.keys(z).some(A=>z[A])?z:void 0,dmsDetails:Object.keys(V).some(A=>V[A])?V:void 0,claimAmount:I}}catch(o){return console.error("[claimDataMapper] Error mapping claim data:",o),null}}function U0(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 w;return v.userId===s||v.user_id===s||((w=v.user)==null?void 0:w.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 w,S;return(v.userId===s||v.user_id===s||((w=v.user)==null?void 0:w.userId)===s||((S=v.user)==null?void 0:S.user_id)===s)&&(v.participantType||v.participant_type||v.type||"").toString().toUpperCase()==="DEALER"}))return"DEALER";const b=t.approvalLevels||[];return b.find(v=>{var w;return v.levelNumber===3&&(v.approverId===s||((w=v.approver)==null?void 0:w.userId)===s)})?"DEPARTMENT_LEAD":b.find(v=>{var w;return(v.approverId===s||((w=v.approver)==null?void 0:w.userId)===s)&&v.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(m){return console.error("[claimDataMapper] Error determining user role:",m),"SPECTATOR"}}function B0(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 zk({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 I,A,G,$,M;const{user:j}=xs(),[v,w]=u.useState([]),[S,D]=u.useState(!1),[k,C]=u.useState(!1),F=(t==null?void 0:t.status)==="closed",N=((I=t==null?void 0:t.pauseInfo)==null?void 0:I.isPaused)||!1,E=h||((G=(A=t==null?void 0:t.pauseInfo)==null?void 0:A.pausedBy)==null?void 0:G.userId),_=g||(j==null?void 0:j.userId)||"",z=!N&&!F&&(r||s),R=N&&d&&(r||s),L=N&&s&&E&&E!==_&&m;u.useEffect(()=>{if(!N||!r||!(t!=null&&t.requestId)){C(!1);return}(async()=>{var U;try{const P=(((U=(await hr.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:U.notifications)||[]).some(B=>B.requestId===t.requestId&&B.notificationType==="pause_retrigger_request");C(P)}catch(H){console.error("Failed to check retrigger notifications:",H),C(!1)}})()},[N,r,t==null?void 0:t.requestId,x]),u.useEffect(()=>{(async()=>{if(!F||!p||!s){w([]);return}try{D(!0);const U=await Mk(p);w(U)}catch(U){console.error("Failed to fetch shared recipients:",U),w([])}finally{D(!1)}})()},[F,p,s,x]);const V=u.useMemo(()=>{if(!f||!pi(f))return null;const T=$0(f);if(!T)return null;const U=U0(f,_),H=B0(U);return{claimRequest:T,visibility:H}},[f,_]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(q,{"data-testid":"quick-actions-card",children:[e.jsx(me,{className:"pb-2",children:e.jsx(ue,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(se,{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(El,{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"]}),z&&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(gr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),R&&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(ml,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),L&&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(tt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Request Resume"]}),e.jsxs("div",{className:"pt-3 sm:pt-4 space-y-2",children:[r&&!N&&!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(He,{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"]})]}),N&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:E===_?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[k&&e.jsx(tt,{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&&E!==_&&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(tt,{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&&E!==_?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&&E&&E!==_?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:L?'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(q,{"data-testid":"spectators-card",children:[e.jsx(me,{className:"pb-2",children:e.jsx(ue,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(se,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((T,U)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${U}`,children:[e.jsx(ms,{className:"h-8 w-8",children:e.jsx(us,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:T.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:T.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:T.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(q,{"data-testid":"shared-recipients-card",children:[e.jsx(me,{className:"pb-2",children:e.jsxs(ue,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Sn,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(se,{className:"space-y-3",children:S?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):v.length>0?v.map((T,U)=>{const H=(T.displayName||"NA").split(" ").map(W=>W[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${U}`,children:[e.jsx(ms,{className:"h-8 w-8",children:e.jsx(us,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:H})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:T.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:T.email}),T.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},T.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"})})})]}),V&&e.jsx($k,{ioDetails:V.claimRequest.ioDetails,dmsDetails:V.claimRequest.dmsDetails,claimAmount:{amount:V.claimRequest.claimAmount.closed||V.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:($=V.claimRequest.proposalDetails)==null?void 0:$.costBreakup,closedExpensesBreakdown:(M=V.claimRequest.activityInfo)==null?void 0:M.closedExpensesBreakdown,visibility:V.visibility,onEditClaimAmount:b})]})}function Vk({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(gt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(ht,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ft,{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(He,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(pt,{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(le,{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(Ws,{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(He,{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(Rt,{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(He,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function Wk({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(gt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(ht,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ft,{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(pt,{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(le,{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(Ws,{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(tt,{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(Rt,{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 Hk({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(gt,{open:t,onOpenChange:x,children:e.jsxs(ht,{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(Nt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ft,{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(tt,{className:"w-5 h-5 text-orange-600"})}),e.jsx(pt,{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(tt,{className:"w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-orange-900 mb-1",children:"Important Notice"}),e.jsx("p",{className:"text-sm text-orange-800",children:"You are about to skip the current approver. The request will be moved to the next approval level."})]})]})}),(i||l)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-semibold text-gray-700",children:"Request Details"}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3 space-y-1",children:[i&&e.jsxs("p",{className:"text-sm text-gray-900",children:[e.jsx("span",{className:"font-medium",children:"Request ID:"})," ",i]}),l&&e.jsxs("p",{className:"text-sm text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Title:"})," ",l]})]})]}),(r||n)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-semibold text-gray-700",children:"Approver Being Skipped"}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-1",children:[n&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Level:"})," ",n]}),r&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Approver:"})," ",r]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(Ws,{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(tt,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function Gk({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:w,setPreviewDocument:S,setDocumentError:D,setSkipApproverData:k,setActionStatus:C,handleApproveConfirm:F,handleRejectConfirm:N,handleAddApprover:E,handleAddSpectator:_,handleSkipApprover:z,downloadDocument:R,documentPolicy:L}){return e.jsxs(e.Fragment,{children:[e.jsx(Vk,{open:t,onClose:()=>f(!1),onConfirm:F,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(Wk,{open:s,onClose:()=>b(!1),onConfirm:N,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(_0,{open:a,onClose:()=>y(!1),onConfirm:E,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p,currentLevels:x,maxApprovalLevels:h,onPolicyViolation:g}),e.jsx(E0,{open:r,onClose:()=>j(!1),onConfirm:_,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p}),e.jsx(Hk,{open:n,onClose:()=>{v(!1),k(null)},onConfirm:z,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),l&&e.jsx(en,{fileName:l.fileName,fileType:l.fileType,fileUrl:Dn(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:R,open:!!l,onClose:()=>S(null)}),m&&e.jsx(P0,{open:i,onClose:()=>{w(!1),C(null)},success:m.success,title:m.title,message:m.message}),e.jsx(gt,{open:o.show,onOpenChange:V=>D(I=>({...I,show:V})),children:e.jsxs(ht,{className:"sm:max-w-lg",children:[e.jsxs(ft,{children:[e.jsxs(pt,{className:"flex items-center gap-2",children:[e.jsx(tt,{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((V,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:V.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:V.reason})]},I))}),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: ",L.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",L.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Rt,{children:e.jsx(O,{onClick:()=>D({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const z0={DocumentsTab:vk,ActivityTab:Sk,WorkNotesTab:Rk,SummaryTab:Ik,RequestDetailHeader:Pk,QuickActionsSidebar:zk,RequestDetailModals:Gk};function Jd({className:t,...s}){return e.jsx(Tj,{"data-slot":"checkbox",className:Oe("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(kj,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Ha,{className:"size-3.5"})})})}function V0({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 w=i.slice(1),S=await Ca(w,10),D=((v=S==null?void 0:S.data)==null?void 0:v.data)||(S==null?void 0:S.data)||[];c(Array.isArray(D)?D:[])}catch(w){console.error("Failed to search users:",w),Y.error("Failed to search users")}finally{x(!1)}},300);return()=>clearTimeout(j)},[i,t]);const f=j=>{m(v=>{const w=new Set(v);return w.has(j)?w.delete(j):w.add(j),w})},b=async()=>{var j,v;if(d.size===0){Y.error("Please select at least one user to share with");return}try{g(!0),await Ek(a,Array.from(d)),Y.success(`Summary shared with ${d.size} user(s)`),m(new Set),l(""),c([]),n==null||n(),s()}catch(w){console.error("Failed to share summary:",w),Y.error(((v=(j=w==null?void 0:w.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(gt,{open:t,onOpenChange:y,children:e.jsxs(ht,{className:"sm:max-w-[500px]",children:[e.jsx(ft,{children:e.jsx(pt,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Request"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:r})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ee,{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(We,{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:w=>w.stopPropagation(),onMouseDown:w=>w.stopPropagation(),className:"flex items-center",children:e.jsx(Jd,{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(Ht,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children: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(w=>w.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(Nt,{className:"h-3 w-3"})})]},j)})})]})]}),e.jsxs(Rt,{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(We,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function W0({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=()=>is().add(1,"month").format("YYYY-MM-DD"),x=()=>is().add(1,"month").format("YYYY-MM-DD"),h=()=>is().add(1,"day").format("YYYY-MM-DD");u.useEffect(()=>{t&&!o&&c(p())},[t]);const g=async()=>{var v,w,S,D;if(!i.trim()){Y.error("Please provide a reason for pausing");return}if(!o){Y.error("Please select a resume date");return}const b=is(o),y=is().add(1,"month"),j=is().add(1,"day");if(b.isAfter(y)){Y.error("Resume date cannot be more than 1 month from now");return}if(b.isBefore(j,"day")){Y.error("Resume date must be at least 1 day from now");return}try{m(!0),await jC(a,r,i.trim(),b.toDate()),Y.success("Workflow paused successfully"),n&&await n(),l(""),c(p()),s()}catch(k){console.error("Failed to pause workflow:",k),Y.error(((w=(v=k==null?void 0:k.response)==null?void 0:v.data)==null?void 0:w.error)||((D=(S=k==null?void 0:k.response)==null?void 0:S.data)==null?void 0:D.message)||"Failed to pause workflow")}finally{m(!1)}},f=()=>{d||(l(""),c(p()),s())};return e.jsx(gt,{open:t,onOpenChange:f,children:e.jsxs(ht,{className:"sm:max-w-[500px]",children:[e.jsx(ft,{children:e.jsxs(pt,{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"w-5 h-5 text-orange-600"}),"Pause Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-orange-800",children:[e.jsx("strong",{children:"Note:"})," Pausing will temporarily halt TAT calculations and notifications. The workflow will automatically resume on the selected date."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ws,{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(ne,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ee,{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(Rt,{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(We,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gr,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function H0({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 yC(a,n.trim()||void 0),Y.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),Y.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(gt,{open:t,onOpenChange:d,children:e.jsxs(ht,{className:"sm:max-w-[500px]",children:[e.jsx(ft,{children:e.jsxs(pt,{className:"flex items-center gap-2",children:[e.jsx(ml,{className:"w-5 h-5 text-green-600"}),"Resume Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-green-50 border border-green-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-green-800",children:[e.jsx("strong",{children:"Note:"})," Resuming will restart TAT calculations and notifications. The workflow will continue from where it was paused."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(Ws,{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(Rt,{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(We,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ml,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function G0({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 vC(a),Y.success("Retrigger request sent to approver"),n&&await n(),s()}catch(x){console.error("Failed to retrigger pause:",x),Y.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(gt,{open:t,onOpenChange:s,children:e.jsxs(ht,{className:"sm:max-w-[450px]",children:[e.jsx(ft,{children:e.jsxs(pt,{className:"flex items-center gap-2",children:[e.jsx(tt,{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(Rt,{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(We,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:Yk,ActivityTab:Kk,WorkNotesTab:Qk,SummaryTab:Xk,RequestDetailHeader:Jk,QuickActionsSidebar:Zk,RequestDetailModals:qk}=z0;let e4=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(as,{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 t4({requestId:t,onBack:s,dynamicRequests:a=[]}){var an,tr,Ar,sr,Tr,kr,ar,Oa,rr;const n=Sa().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,w]=u.useState(!1),[S,D]=u.useState(!1),[k,C]=u.useState(!1),[F,N]=u.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[E,_]=u.useState({open:!1,violations:[]}),{user:z}=xs(),{request:R,apiRequest:L,loading:V,refreshing:I,refreshDetails:A,currentApprovalLevel:G,isSpectator:$,isInitiator:M,existingParticipants:T,accessDenied:U}=Kd(n,a,z),{mergedMessages:H,unreadWorkNotes:W,workNoteAttachments:P,setWorkNoteAttachments:B}=D0(n,L,o,z),{uploadingDocument:K,triggerFileInput:Z,previewDocument:te,setPreviewDocument:ae,documentPolicy:xe,documentError:be,setDocumentError:Ge}=R0(L,A),{showApproveModal:Be,setShowApproveModal:_e,showRejectModal:Re,setShowRejectModal:ce,showAddApproverModal:je,setShowAddApproverModal:re,showAddSpectatorModal:pe,setShowAddSpectatorModal:ie,showSkipApproverModal:fe,setShowSkipApproverModal:Ie,showActionStatusModal:$e,setShowActionStatusModal:ye,skipApproverData:oe,setSkipApproverData:ke,actionStatus:st,setActionStatus:at,handleApproveConfirm:ct,handleRejectConfirm:Dt,handleAddApprover:Q,handleSkipApprover:de,handleAddSpectator:ee}=F0(n,G,A),{conclusionRemark:Ae,setConclusionRemark:Ue,conclusionLoading:et,conclusionSubmitting:ze,aiGenerated:qe,handleGenerateConclusion:Ze,handleFinalizeConclusion:nt,generationAttempts:rs,generationFailed:Ot,maxAttemptsReached:xt}=I0(R,n,M,A,s,at,ye);u.useEffect(()=>{(async()=>{var Ts;try{const oa=await ha("SYSTEM_SETTINGS"),Dr=await ha("WORKFLOW_SHARING"),Rr=[...oa,...Dr],ka={};Rr.forEach(nr=>{ka[nr.configKey]=nr.configValue}),N({maxApprovalLevels:parseInt(ka.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(ka.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((Ts=ka.ALLOW_ADD_SPECTATOR)==null?void 0:Ts.toLowerCase())==="true",maxSpectators:parseInt(ka.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(oa){console.error("Failed to load system policy:",oa)}})()},[]),u.useEffect(()=>{const Ts=new URLSearchParams(window.location.search).get("tab");Ts&&c(Ts)},[n]);const bt=()=>{A()},Pt=()=>{w(!0)},As=()=>{D(!0)},ns=async()=>{await A()},Ya=()=>{C(!0)},Ka=async()=>{await A()},Cr=async()=>{await A()},Aa=async()=>{if(!(L!=null&&L.requestId)){Y.error("Request ID not found");return}if(!p){Y.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},$t=((R==null?void 0:R.status)==="approved"||(R==null?void 0:R.status)==="rejected")&&M,Ta=(R==null?void 0:R.status)==="closed"||(R==null?void 0:R.status)==="approved"&&!M||(R==null?void 0:R.status)==="rejected"&&!M,Bs=((R==null?void 0:R.templateType)||(R==null?void 0:R.template_type)||"").toString().toUpperCase()==="FORM_16";u.useEffect(()=>{Bs&&o==="worknotes"&&c("overview")},[Bs,o]),u.useEffect(()=>{(async()=>{if(!Ta||!(L!=null&&L.requestId)){g(null),x(null);return}try{b(!0);const Ts=await O0(L.requestId);if(Ts!=null&&Ts.summaryId){x(Ts.summaryId);try{const oa=await Xd(Ts.summaryId);g(oa)}catch(oa){console.error("Failed to fetch summary details:",oa),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{b(!1)}})()},[Ta,L==null?void 0:L.requestId]);const tn=((R==null?void 0:R.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(V&&!R&&!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 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(Op,{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(Ss,{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(!R)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(Pe,{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(Ss,{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 sn=(z==null?void 0:z.role)==="MANAGEMENT"||(z==null?void 0:z.role)==="ADMIN",Sr=((an=lt.getUserData())==null?void 0:an.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:[Bs&&e.jsx("p",{className:"text-sm text-emerald-700 font-medium mb-2","data-testid":"form16-details-heading",children:"Form 16 Details"}),e.jsx(Jk,{request:R,refreshing:I,onBack:s||(()=>window.history.back()),onRefresh:bt,onShareSummary:Aa,isInitiator:M,slaData:((tr=R==null?void 0:R.summary)==null?void 0:tr.sla)||(R==null?void 0:R.sla)||null,isPaused:((Ar=R==null?void 0:R.pauseInfo)==null?void 0:Ar.isPaused)||!1}),e.jsxs(Ii,{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(Fi,{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(Bt,{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($p,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:Bs?"Form 16":"Overview"})]}),Ta&&h&&e.jsxs(Bt,{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(Gc,{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(Bt,{value:"workflow",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-workflow",children:[e.jsx(Qs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),e.jsxs(Bt,{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(Pe,{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(Bt,{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(Vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Activity"})]}),!Bs&&e.jsxs(Bt,{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(Ks,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),W>0&&e.jsx(le,{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:W>9?"9+":W})]})]})}),e.jsxs("div",{className:o==="worknotes"&&!Bs?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:o==="worknotes"&&!Bs?"":"lg:col-span-2",children:[e.jsx(zt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:Bs?e.jsx(OC,{request:R}):e.jsx(IC,{request:R,isInitiator:M,needsClosure:$t,conclusionRemark:Ae,setConclusionRemark:Ue,conclusionLoading:et,conclusionSubmitting:ze,aiGenerated:qe,handleGenerateConclusion:Ze,handleFinalizeConclusion:nt,onPause:Pt,onResume:As,onRetrigger:Ya,currentUserIsApprover:!!G,pausedByUserId:(Tr=(sr=R==null?void 0:R.pauseInfo)==null?void 0:sr.pausedBy)==null?void 0:Tr.userId,currentUserId:z==null?void 0:z.userId,generationAttempts:rs,generationFailed:Ot,maxAttemptsReached:xt})}),Ta&&e.jsx(zt,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(Xk,{summary:h,loading:f,onShare:Aa,isInitiator:M})}),e.jsx(zt,{value:"workflow",className:"mt-0",children:Bs?e.jsx(UC,{request:R,requestId:(L==null?void 0:L.requestId)||n,isReUser:sn,onRefresh:A}):e.jsx(_C,{request:R,user:z,isInitiator:M,onSkipApprover:Qt=>{if(!Qt.levelId){alert("Level ID not available");return}ke(Qt),Ie(!0)},onRefresh:A})}),e.jsx(zt,{value:"documents",className:"mt-0",children:e.jsx(Yk,{request:R,workNoteAttachments:P,uploadingDocument:K,documentPolicy:xe,triggerFileInput:Z,setPreviewDocument:ae,downloadDocument:Us,isSpectator:$})}),e.jsx(zt,{value:"activity",className:"mt-0",children:e.jsx(Kk,{request:R})}),!Bs&&e.jsx(zt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(Qk,{requestId:n,requestTitle:R.title,mergedMessages:H,setWorkNoteAttachments:B,isInitiator:M,isSpectator:$,currentLevels:tn,onAddApprover:Q,maxApprovalLevels:F.maxApprovalLevels,onPolicyViolation:Qt=>_({open:!0,violations:Qt})})})]}),!Sr&&o!=="worknotes"&&e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[Bs&&sn&&e.jsx(jk,{requestId:(L==null?void 0:L.requestId)||n,request:R,onRefresh:A}),e.jsx(Zk,{request:R,isInitiator:M,isSpectator:$,currentApprovalLevel:G,onAddApprover:()=>re(!0),onAddSpectator:()=>ie(!0),onApprove:()=>_e(!0),onReject:()=>ce(!0),onPause:Pt,onResume:As,onRetrigger:Ya,summaryId:p,refreshTrigger:y,pausedByUserId:(ar=(kr=R==null?void 0:R.pauseInfo)==null?void 0:kr.pausedBy)==null?void 0:ar.userId,currentUserId:z==null?void 0:z.userId,apiRequest:L,hideApproveReject:Sr})]})]})]})]})}),d&&p&&e.jsx(V0,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(R==null?void 0:R.title)||"N/A",onSuccess:()=>{A(),j(Qt=>Qt+1)}}),v&&(L==null?void 0:L.requestId)&&e.jsx(W0,{isOpen:v,onClose:()=>w(!1),requestId:L.requestId,levelId:(G==null?void 0:G.levelId)||null,onSuccess:Ka}),S&&(L==null?void 0:L.requestId)&&e.jsx(H0,{isOpen:S,onClose:()=>D(!1),requestId:L.requestId,onSuccess:ns}),k&&(L==null?void 0:L.requestId)&&e.jsx(G0,{isOpen:k,onClose:()=>C(!1),requestId:L.requestId,approverName:(rr=(Oa=R==null?void 0:R.pauseInfo)==null?void 0:Oa.pausedBy)==null?void 0:rr.name,onSuccess:Cr}),e.jsx(qk,{showApproveModal:Be,showRejectModal:Re,showAddApproverModal:je,showAddSpectatorModal:pe,showSkipApproverModal:fe,showActionStatusModal:$e,previewDocument:te,documentError:be,request:R,skipApproverData:oe,actionStatus:st,existingParticipants:T,currentLevels:tn,maxApprovalLevels:F.maxApprovalLevels,onPolicyViolation:Qt=>_({open:!0,violations:Qt}),setShowApproveModal:_e,setShowRejectModal:ce,setShowAddApproverModal:re,setShowAddSpectatorModal:ie,setShowSkipApproverModal:Ie,setShowActionStatusModal:ye,setPreviewDocument:ae,setDocumentError:Ge,setSkipApproverData:ke,setActionStatus:at,handleApproveConfirm:ct,handleRejectConfirm:Dt,handleAddApprover:Q,handleAddSpectator:ee,handleSkipApprover:de,downloadDocument:Us,documentPolicy:xe}),e.jsx(Ri,{open:E.open,onClose:()=>_({open:!1,violations:[]}),violations:E.violations,policyDetails:{maxApprovalLevels:F.maxApprovalLevels,maxParticipants:F.maxParticipants,allowSpectators:F.allowSpectators,maxSpectators:F.maxSpectators}})]})}function s4(t){return e.jsx(e4,{children:e.jsx(t4,{...t})})}const a4=[{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 r4(){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 n4({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=r4(),v=r==="FORM_16";return e.jsxs(q,{className:"shadow-lg border-0",children:[e.jsx(me,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(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(Se,{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(Nt,{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(se,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(Ee,{placeholder:"Search requests, IDs...",value:t,onChange:w=>c(w.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors"})]}),e.jsxs(Ke,{value:a,onValueChange:m,children:[e.jsx(Xe,{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(Qe,{placeholder:"All Priorities"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Priorities"}),e.jsx(J,{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(J,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Ke,{value:s,onValueChange:d,children:[e.jsx(Xe,{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(Qe,{placeholder:"All Statuses"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Statuses"}),e.jsx(J,{value:"pending",children:"Pending (In Approval)"}),e.jsx(J,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs(Ke,{value:r,onValueChange:p,children:[e.jsx(Xe,{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(Qe,{placeholder:"Request type"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(J,{value:"FORM_16",children:"Form 16"})]})]}),v&&x&&e.jsxs(Ke,{value:n||void 0,onValueChange:x,children:[e.jsx(Xe,{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(Qe,{placeholder:"Financial Year"})}),e.jsx(Je,{children:j.map(w=>e.jsx(J,{value:w,children:w},w))})]}),v&&h&&e.jsxs(Ke,{value:i||void 0,onValueChange:h,children:[e.jsx(Xe,{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(Qe,{placeholder:"Quarter"})}),e.jsx(Je,{children:a4.map(w=>e.jsx(J,{value:w.value,children:w.label},w.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ke,{value:l,onValueChange:w=>g(w),children:[e.jsx(Xe,{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(Qe,{placeholder:"Sort by"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{value:"priority",children:"Priority"}),e.jsx(J,{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(Ll,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Ol,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}const i4=[{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 l4(){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 o4({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=l4(),v=r==="FORM_16";return e.jsxs(q,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(me,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(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(Se,{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(Nt,{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(se,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(Ee,{placeholder:"Search requests, IDs...",value:t,onChange:w=>d(w.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white transition-colors","data-testid":"closed-requests-search"})]}),e.jsxs(Ke,{value:s,onValueChange:m,children:[e.jsx(Xe,{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(Qe,{placeholder:"All Priorities"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Priorities"}),e.jsx(J,{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(J,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Ke,{value:a,onValueChange:p,children:[e.jsx(Xe,{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(Qe,{placeholder:"Closure Type"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Closures"}),e.jsx(J,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(J,{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(Ke,{value:r,onValueChange:x,children:[e.jsx(Xe,{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(Qe,{placeholder:"Request type"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(J,{value:"FORM_16",children:"Form 16"})]})]}),v&&h&&e.jsxs(Ke,{value:n||void 0,onValueChange:h,children:[e.jsx(Xe,{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(Qe,{placeholder:"Financial Year"})}),e.jsx(Je,{children:j.map(w=>e.jsx(J,{value:w,children:w},w))})]}),v&&g&&e.jsxs(Ke,{value:i||void 0,onValueChange:g,children:[e.jsx(Xe,{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(Qe,{placeholder:"Quarter"})}),e.jsx(Je,{children:i4.map(w=>e.jsx(J,{value:w.value,children:w.label},w.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ke,{value:l,onValueChange:w=>f(w),children:[e.jsx(Xe,{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(Qe,{placeholder:"Sort by"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{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(Ll,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Ol,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function c4({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:w,onForm16QuarterChange:S,onSearchChange:D,onStatusChange:k,onPriorityChange:C,onTemplateTypeChange:F,onDepartmentChange:N,onSlaComplianceChange:E,onInitiatorChange:_,onApproverChange:z,onApproverTypeChange:R,onDateRangeChange:L,onCustomStartDateChange:V,onCustomEndDateChange:I,onShowCustomDatePickerChange:A,onApplyCustomDate:G,onClearFilters:$,hasActiveFilters:M}){return e.jsx(q,{className:"border-gray-200 shadow-md","data-testid":"user-all-requests-filters",children:e.jsx(se,{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"}),M&&e.jsx(le,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),M&&e.jsxs(O,{variant:"ghost",size:"sm",onClick:$,className:"gap-2",children:[e.jsx(_t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(qt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ee,{placeholder:"Search requests...",value:t,onChange:T=>D(T.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ke,{value:s,onValueChange:k,children:[e.jsx(Xe,{className:"h-10","data-testid":"status-filter",children:e.jsx(Qe,{placeholder:"All Status"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"paused",children:"Paused"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ke,{value:a,onValueChange:C,children:[e.jsx(Xe,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Qe,{placeholder:"All Priority"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Priority"}),e.jsx(J,{value:"express",children:"Express"}),e.jsx(J,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ke,{value:r,onValueChange:F,children:[e.jsx(Xe,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Qe,{placeholder:"All Templates"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Custom"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),y&&e.jsx(J,{value:"FORM_16",children:"Form 16"})]})]}),y&&r==="FORM_16"&&e.jsxs(e.Fragment,{children:[e.jsxs(Ke,{value:j,onValueChange:w??(()=>{}),children:[e.jsx(Xe,{className:"h-10","data-testid":"form16-financial-year-filter",children:e.jsx(Qe,{placeholder:"Financial Year"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Years"}),e.jsx(J,{value:"2024-25",children:"2024-25"}),e.jsx(J,{value:"2023-24",children:"2023-24"}),e.jsx(J,{value:"2022-23",children:"2022-23"})]})]}),e.jsxs(Ke,{value:v,onValueChange:S??(()=>{}),children:[e.jsx(Xe,{className:"h-10","data-testid":"form16-quarter-filter",children:e.jsx(Qe,{placeholder:"Quarter"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Quarters"}),e.jsx(J,{value:"Q1",children:"Q1"}),e.jsx(J,{value:"Q2",children:"Q2"}),e.jsx(J,{value:"Q3",children:"Q3"}),e.jsx(J,{value:"Q4",children:"Q4"})]})]})]}),e.jsxs(Ke,{value:n,onValueChange:N,disabled:g||h.length===0,children:[e.jsx(Xe,{className:"h-10","data-testid":"department-filter",children:e.jsx(Qe,{placeholder:g?"Loading...":"All Departments"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Departments"}),h.map(T=>e.jsx(J,{value:T,children:T},T))]})]}),e.jsxs(Ke,{value:i,onValueChange:E,children:[e.jsx(Xe,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Qe,{placeholder:"All SLA Status"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All SLA Status"}),e.jsx(J,{value:"compliant",children:"Compliant"}),e.jsx(J,{value:"on-track",children:"On Track"}),e.jsx(J,{value:"approaching",children:"Approaching"}),e.jsx(J,{value:"critical",children:"Critical"}),e.jsx(J,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children: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(Nt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{placeholder:"Search initiator...",value:f.searchQuery,onChange:T=>f.handleSearch(T.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(T=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(T),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:T.displayName||T.email}),T.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:T.email})]})},T.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Approver"}),o!=="all"&&R&&e.jsxs(Ke,{value:c,onValueChange:T=>R(T),children:[e.jsx(Xe,{className:"h-7 w-32 text-xs",children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(J,{value:"current",children:"Current Only"}),e.jsx(J,{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(Nt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{placeholder:"Search approver...",value:b.searchQuery,onChange:T=>b.handleSearch(T.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(T=>e.jsx("button",{type:"button",onClick:()=>b.handleSelect(T),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:T.displayName||T.email}),T.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:T.email})]})},T.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(jt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:d,onValueChange:T=>L(T),children:[e.jsx(Xe,{className:"w-[160px] h-10",children:e.jsx(Qe,{placeholder:"Date Range"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),d==="custom"&&e.jsxs(ra,{open:x,onOpenChange:A,children:[e.jsx(na,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(jt,{className:"w-4 h-4"}),m&&p?`${it(m,"MMM d, yyyy")} - ${it(p,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date",children:"Start Date"}),e.jsx(sa,{value:m||null,onChange:T=>{const U=T?new Date(T):void 0;U?(V==null||V(U),p&&U>p&&(I==null||I(U))):V==null||V(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",children:"End Date"}),e.jsx(sa,{value:p||null,onChange:T=>{const U=T?new Date(T):void 0;U?(I==null||I(U),m&&U<m&&(V==null||V(U))):I==null||I(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:G,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:()=>{A==null||A(!1),V==null||V(void 0),I==null||I(void 0),L("month")},children:"Cancel"})]})]})})]})]})]})})})}function d4({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 S,D,k,C,F,N,E,_,z;if(!pi(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=$0(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=U0(s,a),v=B0(j),w={name:((S=s.initiator)==null?void 0:S.name)||((D=s.initiator)==null?void 0:D.displayName)||((k=s.initiator)==null?void 0:k.email)||"Unknown",role:((C=s.initiator)==null?void 0:C.role)||((F=s.initiator)==null?void 0:F.designation)||"Initiator",department:((N=s.initiator)==null?void 0:N.department)||s.department||"",email:((E=s.initiator)==null?void 0:E.email)||"N/A",phone:((_=s.initiator)==null?void 0:_.phone)||((z=s.initiator)==null?void 0:z.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(Lk,{activityInfo:y.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(Ok,{dealerInfo:y.dealerInfo}),v.showProposalDetails&&y.proposalDetails&&e.jsx(Uk,{proposalDetails:y.proposalDetails}),e.jsx(Bk,{initiatorInfo:w}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base",children:[e.jsx(He,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(Se,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(se,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Os,{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 ",ys(s.closureDate)]}),e.jsxs("span",{children:["By ",w.name]})]})]})]}),l&&e.jsxs(q,{"data-testid":"conclusion-remark-card",children:[e.jsx(me,{className:`bg-gradient-to-r border-b ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:`flex items-center gap-2 text-base sm:text-lg ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(He,{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(Se,{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(se,{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(We,{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(Si,{value:o,onChange:R=>c(R),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(We,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function m4({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()){Y.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),Y.error("Failed to approve request. Please try again.")}finally{x(!1),g(null)}},b=async()=>{if(!d.trim()){Y.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),Y.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(gt,{open:t,onOpenChange:j,children:e.jsxs(ht,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(ft,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(pt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(He,{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(Pe,{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(Ks,{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(Os,{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(Ws,{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(Rt,{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(He,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function u4({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?ys(n.creditNoteDate,{includeTime:!1,format:"short"}):"",v=(n==null?void 0:n.creditNoteAmount)||0,w=(n==null?void 0:n.transactionNo)||"",S=(n==null?void 0:n.tdsAmount)||0,D=(n==null?void 0:n.creditAmount)||0,k=(n==null?void 0:n.status)||"PENDING",C=(n==null?void 0:n.items)||[],F=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",N=(i==null?void 0:i.dealerCode)||"RE-JP-009",E=l||"Activity",_=o||"RE-REQ-2024-CM-101",z=d?ys(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",R=(()=>{var A,G;if(C.length>1){const $=(A=C[0])==null?void 0:A.transactionNo,M=(G=C[C.length-1])==null?void 0:G.transactionNo;return $&&M&&$!==M?`${$} - ${M}`:$||w||"N/A"}return w||"N/A"})(),L=async()=>{if(a)try{x(!0),await a(),Y.success("Credit note downloaded successfully")}catch(A){console.error("Failed to download credit note:",A),Y.error("Failed to download credit note. Please try again.")}finally{x(!1)}else Y.info("Credit note will be automatically saved to Documents tab")},V=async()=>{if(r)try{g(!0),await r(),Y.success("Credit note sent to dealer successfully"),s()}catch(A){console.error("Failed to send credit note to dealer:",A),Y.error("Failed to send credit note. Please try again.")}finally{g(!1)}else Y.info("Email notification will be sent to dealer with credit note attachment")},I=A=>`₹${A.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(gt,{open:t,onOpenChange:s,children:e.jsxs(ht,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ft,{children:[e.jsxs(pt,{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(le,{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(le,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(He,{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(ne,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(rc,{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(ne,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(jt,{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(ne,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Pe,{className:"w-3 h-3"}),"Transaction ID"]}),e.jsx("p",{className:"font-bold text-emerald-700 mt-1 break-all",children:R})]})]})]}),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(ne,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(Fa,{className:"w-3 h-3"}),"Gross Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-blue-700",children:I(v)})]}),e.jsxs("div",{className:"bg-orange-50 border-2 border-orange-200 rounded-lg p-4",children:[e.jsxs(ne,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(Fa,{className:"w-3 h-3"}),"TDS Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-orange-700",children:I(S)})]}),e.jsxs("div",{className:"bg-emerald-50 border-2 border-emerald-200 rounded-lg p-4",children:[e.jsxs(ne,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(Fa,{className:"w-3 h-3"}),"Net Credit Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-emerald-700",children:I(D)})]})]}),C&&C.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(Pe,{className:"w-4 h-4 text-slate-500"}),"Line Item Breakdown"]}),e.jsxs(le,{variant:"outline",className:"text-[10px] font-medium uppercase tracking-wider",children:[C.length," ",C.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:C.map((A,G)=>e.jsxs("tr",{className:"border-b border-slate-100 hover:bg-slate-50/50 transition-colors",children:[e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:A.slNo}),e.jsx("td",{className:"px-4 py-2.5 font-medium text-slate-900 font-mono text-[11px]",children:A.transactionNo||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:A.hsnCd||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-right font-medium text-slate-700",children:I(A.claimAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-orange-600 font-medium",children:I(A.tdsAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-emerald-700 font-bold",children:I(A.creditAmount||0)})]},G))})]})})]})]}):e.jsx("div",{className:"bg-gray-50 border-2 border-gray-300 rounded-lg p-8 text-center",children:e.jsxs("div",{className:"flex flex-col items-center justify-center space-y-4",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center",children:e.jsx(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(Ml,{className:"w-5 h-5"}),"Dealer Information"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ne,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ne,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:N})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ne,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Activity"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:E})]})]})]}),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(Pe,{className:"w-4 h-4"}),"Reference Details"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Request ID"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:_})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Due Date"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:z})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Pe,{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(Rt,{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:L,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:V,disabled:p||h,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(Mp,{className:"w-4 h-4 mr-2"}),h?"Sending...":"Send to Dealer"]})]})})]})]})})}var Uh=1,x4=.9,h4=.8,p4=.17,Eo=.1,_o=.999,g4=.9999,f4=.99,b4=/[\\\/_+.#"@\[\(\{&]/,j4=/[\\\/_+.#"@\[\(\{&]/g,y4=/[\s-]/,Y0=/[\s-]/g;function Fc(t,s,a,r,n,i,l){if(i===s.length)return n===t.length?Uh:f4;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=Fc(t,s,a,r,d+1,i+1,l),p>m&&(d===n?p*=Uh:b4.test(t.charAt(d-1))?(p*=h4,h=t.slice(n,d-1).match(j4),h&&n>0&&(p*=Math.pow(_o,h.length))):y4.test(t.charAt(d-1))?(p*=x4,g=t.slice(n,d-1).match(Y0),g&&n>0&&(p*=Math.pow(_o,g.length))):(p*=p4,n>0&&(p*=Math.pow(_o,d-n))),t.charAt(d)!==s.charAt(i)&&(p*=g4)),(p<Eo&&a.charAt(d-1)===r.charAt(i+1)||r.charAt(i+1)===r.charAt(i)&&a.charAt(d-1)!==r.charAt(i))&&(x=Fc(t,s,a,r,d+1,i+2,l),x*Eo>p&&(p=x*Eo)),p>m&&(m=p),d=a.indexOf(c,d+1);return l[o]=m,m}function Bh(t){return t.toLowerCase().replace(Y0," ")}function v4(t,s,a){return t=a&&a.length>0?`${t+" "+a.join(" ")}`:t,Fc(t,s,Bh(t),Bh(s),0,0,{})}var Vn='[cmdk-group=""]',Mo='[cmdk-group-items=""]',N4='[cmdk-group-heading=""]',K0='[cmdk-item=""]',zh=`${K0}:not([aria-disabled="true"])`,Pc="cmdk-item-select",on="data-value",w4=(t,s,a)=>v4(t,s,a),Q0=u.createContext(void 0),Pi=()=>u.useContext(Q0),X0=u.createContext(void 0),Zd=()=>u.useContext(X0),J0=u.createContext(void 0),Z0=u.forwardRef((t,s)=>{let a=cn(()=>{var T,U;return{search:"",value:(U=(T=t.value)!=null?T:t.defaultValue)!=null?U:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=cn(()=>new Set),n=cn(()=>new Map),i=cn(()=>new Map),l=cn(()=>new Set),o=q0(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(),w=gn(),S=u.useRef(null),D=E4();Jr(()=>{if(m!==void 0){let T=m.trim();a.current.value=T,k.emit()}},[m]),Jr(()=>{D(6,z)},[]);let k=u.useMemo(()=>({subscribe:T=>(l.current.add(T),()=>l.current.delete(T)),snapshot:()=>a.current,setState:(T,U,H)=>{var W,P,B,K;if(!Object.is(a.current[T],U)){if(a.current[T]=U,T==="search")_(),N(),D(1,E);else if(T==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Z=document.getElementById(w);Z?Z.focus():(W=document.getElementById(j))==null||W.focus()}if(D(7,()=>{var Z;a.current.selectedItemId=(Z=R())==null?void 0:Z.id,k.emit()}),H||D(5,z),((P=o.current)==null?void 0:P.value)!==void 0){let Z=U??"";(K=(B=o.current).onValueChange)==null||K.call(B,Z);return}}k.emit()}},emit:()=>{l.current.forEach(T=>T())}}),[]),C=u.useMemo(()=>({value:(T,U,H)=>{var W;U!==((W=i.current.get(T))==null?void 0:W.value)&&(i.current.set(T,{value:U,keywords:H}),a.current.filtered.items.set(T,F(U,H)),D(2,()=>{N(),k.emit()}))},item:(T,U)=>(r.current.add(T),U&&(n.current.has(U)?n.current.get(U).add(T):n.current.set(U,new Set([T]))),D(3,()=>{_(),N(),a.current.value||E(),k.emit()}),()=>{i.current.delete(T),r.current.delete(T),a.current.filtered.items.delete(T);let H=R();D(4,()=>{_(),(H==null?void 0:H.getAttribute("id"))===T&&E(),k.emit()})}),group:T=>(n.current.has(T)||n.current.set(T,new Set),()=>{i.current.delete(T),n.current.delete(T)}),filter:()=>o.current.shouldFilter,label:c||t["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:j,inputId:w,labelId:v,listInnerRef:S}),[]);function F(T,U){var H,W;let P=(W=(H=o.current)==null?void 0:H.filter)!=null?W:w4;return T?P(T,a.current.search,U):0}function N(){if(!a.current.search||o.current.shouldFilter===!1)return;let T=a.current.filtered.items,U=[];a.current.filtered.groups.forEach(W=>{let P=n.current.get(W),B=0;P.forEach(K=>{let Z=T.get(K);B=Math.max(Z,B)}),U.push([W,B])});let H=S.current;L().sort((W,P)=>{var B,K;let Z=W.getAttribute("id"),te=P.getAttribute("id");return((B=T.get(te))!=null?B:0)-((K=T.get(Z))!=null?K:0)}).forEach(W=>{let P=W.closest(Mo);P?P.appendChild(W.parentElement===P?W:W.closest(`${Mo} > *`)):H.appendChild(W.parentElement===H?W:W.closest(`${Mo} > *`))}),U.sort((W,P)=>P[1]-W[1]).forEach(W=>{var P;let B=(P=S.current)==null?void 0:P.querySelector(`${Vn}[${on}="${encodeURIComponent(W[0])}"]`);B==null||B.parentElement.appendChild(B)})}function E(){let T=L().find(H=>H.getAttribute("aria-disabled")!=="true"),U=T==null?void 0:T.getAttribute(on);k.setState("value",U||void 0)}function _(){var T,U,H,W;if(!a.current.search||o.current.shouldFilter===!1){a.current.filtered.count=r.current.size;return}a.current.filtered.groups=new Set;let P=0;for(let B of r.current){let K=(U=(T=i.current.get(B))==null?void 0:T.value)!=null?U:"",Z=(W=(H=i.current.get(B))==null?void 0:H.keywords)!=null?W:[],te=F(K,Z);a.current.filtered.items.set(B,te),te>0&&P++}for(let[B,K]of n.current)for(let Z of K)if(a.current.filtered.items.get(Z)>0){a.current.filtered.groups.add(B);break}a.current.filtered.count=P}function z(){var T,U,H;let W=R();W&&(((T=W.parentElement)==null?void 0:T.firstChild)===W&&((H=(U=W.closest(Vn))==null?void 0:U.querySelector(N4))==null||H.scrollIntoView({block:"nearest"})),W.scrollIntoView({block:"nearest"}))}function R(){var T;return(T=S.current)==null?void 0:T.querySelector(`${K0}[aria-selected="true"]`)}function L(){var T;return Array.from(((T=S.current)==null?void 0:T.querySelectorAll(zh))||[])}function V(T){let U=L()[T];U&&k.setState("value",U.getAttribute(on))}function I(T){var U;let H=R(),W=L(),P=W.findIndex(K=>K===H),B=W[P+T];(U=o.current)!=null&&U.loop&&(B=P+T<0?W[W.length-1]:P+T===W.length?W[0]:W[P+T]),B&&k.setState("value",B.getAttribute(on))}function A(T){let U=R(),H=U==null?void 0:U.closest(Vn),W;for(;H&&!W;)H=T>0?F4(H,Vn):P4(H,Vn),W=H==null?void 0:H.querySelector(zh);W?k.setState("value",W.getAttribute(on)):I(T)}let G=()=>V(L().length-1),$=T=>{T.preventDefault(),T.metaKey?G():T.altKey?A(1):I(1)},M=T=>{T.preventDefault(),T.metaKey?V(0):T.altKey?A(-1):I(-1)};return u.createElement(vr.div,{ref:s,tabIndex:-1,...y,"cmdk-root":"",onKeyDown:T=>{var U;(U=y.onKeyDown)==null||U.call(y,T);let H=T.nativeEvent.isComposing||T.keyCode===229;if(!(T.defaultPrevented||H))switch(T.key){case"n":case"j":{b&&T.ctrlKey&&$(T);break}case"ArrowDown":{$(T);break}case"p":case"k":{b&&T.ctrlKey&&M(T);break}case"ArrowUp":{M(T);break}case"Home":{T.preventDefault(),V(0);break}case"End":{T.preventDefault(),G();break}case"Enter":{T.preventDefault();let W=R();if(W){let P=new Event(Pc);W.dispatchEvent(P)}}}}},u.createElement("label",{"cmdk-label":"",htmlFor:C.inputId,id:C.labelId,style:M4},c),eo(t,T=>u.createElement(X0.Provider,{value:k},u.createElement(Q0.Provider,{value:C},T))))}),C4=u.forwardRef((t,s)=>{var a,r;let n=gn(),i=u.useRef(null),l=u.useContext(J0),o=Pi(),c=q0(t),d=(r=(a=c.current)==null?void 0:a.forceMount)!=null?r:l==null?void 0:l.forceMount;Jr(()=>{if(!d)return o.item(n,l==null?void 0:l.id)},[d]);let m=eb(n,i,[t.value,t.children,i],t.keywords),p=Zd(),x=yr(D=>D.value&&D.value===m.current),h=yr(D=>d||o.filter()===!1?!0:D.search?D.filtered.items.get(n)>0:!0);u.useEffect(()=>{let D=i.current;if(!(!D||t.disabled))return D.addEventListener(Pc,g),()=>D.removeEventListener(Pc,g)},[h,t.onSelect,t.disabled]);function g(){var D,k;f(),(k=(D=c.current).onSelect)==null||k.call(D,m.current)}function f(){p.setState("value",m.current,!0)}if(!h)return null;let{disabled:b,value:y,onSelect:j,forceMount:v,keywords:w,...S}=t;return u.createElement(vr.div,{ref:ri(i,s),...S,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)}),S4=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=Pi(),p=yr(h=>n||m.filter()===!1?!0:h.search?h.filtered.groups.has(l):!0);Jr(()=>m.group(l),[]),eb(l,o,[t.value,t.heading,c]);let x=u.useMemo(()=>({id:l,forceMount:n}),[n]);return u.createElement(vr.div,{ref:ri(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),eo(t,h=>u.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":a?d:void 0},u.createElement(J0.Provider,{value:x},h))))}),A4=u.forwardRef((t,s)=>{let{alwaysRender:a,...r}=t,n=u.useRef(null),i=yr(l=>!l.search);return!a&&!i?null:u.createElement(vr.div,{ref:ri(n,s),...r,"cmdk-separator":"",role:"separator"})}),T4=u.forwardRef((t,s)=>{let{onValueChange:a,...r}=t,n=t.value!=null,i=Zd(),l=yr(d=>d.search),o=yr(d=>d.selectedItemId),c=Pi();return u.useEffect(()=>{t.value!=null&&i.setState("search",t.value)},[t.value]),u.createElement(vr.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)}})}),k4=u.forwardRef((t,s)=>{let{children:a,label:r="Suggestions",...n}=t,i=u.useRef(null),l=u.useRef(null),o=yr(d=>d.selectedItemId),c=Pi();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(vr.div,{ref:ri(i,s),...n,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},eo(t,d=>u.createElement("div",{ref:ri(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),D4=u.forwardRef((t,s)=>{let{open:a,onOpenChange:r,overlayClassName:n,contentClassName:i,container:l,...o}=t;return u.createElement(jp,{open:a,onOpenChange:r},u.createElement(bp,{container:l},u.createElement(Mc,{"cmdk-overlay":"",className:n}),u.createElement(Lc,{"aria-label":t.label,"cmdk-dialog":"",className:i},u.createElement(Z0,{ref:s,...o}))))}),R4=u.forwardRef((t,s)=>yr(a=>a.filtered.count===0)?u.createElement(vr.div,{ref:s,...t,"cmdk-empty":"",role:"presentation"}):null),I4=u.forwardRef((t,s)=>{let{progress:a,children:r,label:n="Loading...",...i}=t;return u.createElement(vr.div,{ref:s,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":100,"aria-label":n},eo(t,l=>u.createElement("div",{"aria-hidden":!0},l)))}),Pn=Object.assign(Z0,{List:k4,Item:C4,Input:T4,Group:S4,Separator:A4,Dialog:D4,Empty:R4,Loading:I4});function F4(t,s){let a=t.nextElementSibling;for(;a;){if(a.matches(s))return a;a=a.nextElementSibling}}function P4(t,s){let a=t.previousElementSibling;for(;a;){if(a.matches(s))return a;a=a.previousElementSibling}}function q0(t){let s=u.useRef(t);return Jr(()=>{s.current=t}),s}var Jr=typeof window>"u"?u.useEffect:u.useLayoutEffect;function cn(t){let s=u.useRef();return s.current===void 0&&(s.current=t()),s}function yr(t){let s=Zd(),a=()=>t(s.snapshot());return u.useSyncExternalStore(s.subscribe,a,a)}function eb(t,s,a,r=[]){let n=u.useRef(),i=Pi();return Jr(()=>{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(on,o),n.current=o}),n}var E4=()=>{let[t,s]=u.useState(),a=cn(()=>new Map);return Jr(()=>{a.current.forEach(r=>r()),a.current=new Map},[t]),(r,n)=>{a.current.set(r,n),s({})}};function _4(t){let s=t.type;return typeof s=="function"?s(t.props):"render"in s?s.render(t.props):t}function eo({asChild:t,children:s},a){return t&&u.isValidElement(s)?u.cloneElement(_4(s),{ref:s.ref},a(s.props.children)):a(s)}var M4={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function L4({className:t,...s}){return e.jsx(Pn,{"data-slot":"command",className:Oe("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",t),...s})}function O4({className:t,wrapperClassName:s,...a}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:Oe("flex h-9 items-center gap-2 border-b px-3",s),children:[e.jsx(Zt,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Pn.Input,{"data-slot":"command-input",className:Oe("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 $4({className:t,...s}){return e.jsx(Pn.List,{"data-slot":"command-list",className:Oe("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",t),...s})}function U4({...t}){return e.jsx(Pn.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...t})}function B4({className:t,...s}){return e.jsx(Pn.Group,{"data-slot":"command-group",className:Oe("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 z4({className:t,...s}){return e.jsx(Pn.Item,{"data-slot":"command-item",className:Oe("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 tb(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 we.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 V4(t){var a;const s=await we.post("/hsn-sac",t);return((a=s.data)==null?void 0:a.data)||s.data}async function W4(t,s){var r;const a=await we.patch(`/hsn-sac/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function H4(t){await we.delete(`/hsn-sac/${t}`)}async function G4(t){var a;const s=await we.patch(`/hsn-sac/${t}/toggle-active`);return((a=s.data)==null?void 0:a.data)||s.data}function sb({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 tb(!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(ra,{open:l,onOpenChange:o,children:[e.jsx(na,{asChild:!0,children:e.jsxs(O,{variant:"outline",role:"combobox","aria-expanded":l,disabled:n,className:Oe("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(hy,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(ia,{className:"w-[320px] p-0 shadow-2xl border-slate-200",align:"start",children:e.jsxs(L4,{className:"rounded-lg border-0",children:[e.jsxs("div",{className:"bg-slate-50/80 p-2.5 flex items-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4 text-slate-400"}),e.jsx(O4,{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($4,{className:"max-h-[350px] scrollbar-thin scrollbar-thumb-slate-200",children:[e.jsx(U4,{className:"py-8 text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Zt,{className:"h-8 w-8 text-slate-200"}),e.jsxs("p",{className:"text-sm font-medium text-slate-500",children:["No ",a," code found"]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Try a different search term"})]})}),e.jsx(B4,{className:"p-1.5",children:m.map(x=>e.jsxs(z4,{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:Oe("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 ya=(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:""}},Y4={"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"},K4="33",Q4=new Set(["04","25","26","31","35","38"]),ab=t=>{if(!t||t.length<2)return null;const s=t.substring(0,2);return Y4[s]?s:null},X4=t=>t?Q4.has(t):!1,J4=t=>t?t!==K4:!1,rb=t=>{if(!t)return{isIGST:!1,isCGST:!0,isSGST:!0,isUTGST:!1};if(J4(t))return{isIGST:!0,isCGST:!1,isSGST:!1,isUTGST:!1};const a=X4(t);return{isIGST:!1,isCGST:!0,isSGST:!a,isUTGST:a}};function Z4({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 re,pe;const[m,p]=u.useState(""),[x,h]=u.useState(""),g=u.useMemo(()=>{const ie=ab(n);return rb(ie)},[n]),f=u.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),[b,y]=u.useState([]),[j,v]=u.useState([]),[w,S]=u.useState([]),[D,k]=u.useState([]),[C,F]=u.useState(null),[N,E]=u.useState(""),[_,z]=u.useState(!1),[R,L]=u.useState(null),V=u.useRef(null),I=u.useRef(null),A=u.useRef(null),G=u.useRef(null),$=ie=>{const fe=ie.type.toLowerCase(),Ie=ie.name.toLowerCase();return fe.includes("image")||fe.includes("pdf")||Ie.endsWith(".pdf")||Ie.endsWith(".jpg")||Ie.endsWith(".jpeg")||Ie.endsWith(".png")||Ie.endsWith(".gif")||Ie.endsWith(".webp")};u.useEffect(()=>()=>{R!=null&&R.url&&URL.revokeObjectURL(R.url)},[R]),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 M=ie=>{if(!$(ie)){Y.error("Preview is only available for images and PDF files");return}R!=null&&R.url&&URL.revokeObjectURL(R.url);const fe=URL.createObjectURL(ie);L({file:ie,url:fe})},T=ie=>{const fe=URL.createObjectURL(ie),Ie=document.createElement("a");Ie.href=fe,Ie.download=ie.name,document.body.appendChild(Ie),Ie.click(),document.body.removeChild(Ie),URL.revokeObjectURL(fe)},U=u.useMemo(()=>b.reduce((ie,fe)=>ie+(fe.totalAmt||fe.amount||0),0),[b]),H=(ie,fe,Ie=1)=>{const $e=ie*Ie,ye=$e*(fe.cgstRate||0)/100,oe=$e*(fe.sgstRate||0)/100,ke=$e*(fe.utgstRate||0)/100,st=$e*(fe.igstRate||0)/100,at=ye+oe+ke+st,ct=$e+at;return{cgstRate:fe.cgstRate,cgstAmt:ye,sgstRate:fe.sgstRate,sgstAmt:oe,utgstRate:fe.utgstRate,utgstAmt:ke,igstRate:fe.igstRate,igstAmt:st,gstAmt:at,gstRate:(fe.cgstRate||0)+(fe.sgstRate||0)+(fe.utgstRate||0)+(fe.igstRate||0),totalAmt:ct}},W=u.useMemo(()=>{const ie=m!=="",fe=j.length>0,Ie=w.length>0,$e=N.trim().length>0,ye=b.length>0&&b.every(ke=>ke.description.trim()!==""&&ke.amount>0),oe=f?!1:b.some(ke=>{const{isValid:st}=ya(ke.hsnCode,ke.isService);return!st});return ie&&fe&&Ie&&$e&&ye&&!oe},[m,j,w,N,f,b]),P=new Date().toISOString().split("T")[0],B=()=>{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}])},K=(ie,fe,Ie)=>{y(b.map($e=>{if($e.id===ie){let ye={...$e,[fe]:Ie};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate","quantity"].includes(fe)){const oe=parseFloat(Ie);if(!isNaN(oe)&&oe<0)return Y.error("Value cannot be negative"),$e;const ke=fe==="amount"?parseFloat(Ie)||0:$e.amount,st=fe==="quantity"?parseInt(Ie)||1:$e.quantity;let at=$e.cgstRate,ct=$e.sgstRate,Dt=$e.utgstRate,Q=$e.igstRate;if(fe==="cgstRate"){if(!g.isCGST)return $e;at=parseFloat(Ie)||0,g.isUTGST?(Dt=at,ct=0):(ct=at,Dt=0),Q=0}else if(fe==="sgstRate"){if(!g.isSGST)return $e;ct=parseFloat(Ie)||0,at=ct,Dt=0,Q=0}else if(fe==="utgstRate"){if(!g.isUTGST)return $e;Dt=parseFloat(Ie)||0,at=Dt,ct=0,Q=0}else if(fe==="igstRate"){if(!g.isIGST)return $e;Q=parseFloat(Ie)||0,at=0,ct=0,Dt=0}else if(fe==="gstRate"){const ee=parseFloat(Ie)||0;g.isIGST?(Q=ee,at=0,ct=0,Dt=0):(at=ee/2,g.isUTGST?(Dt=ee/2,ct=0):(ct=ee/2,Dt=0),Q=0)}const de=H(ke,{cgstRate:at,sgstRate:ct,igstRate:Q,utgstRate:Dt},st);return fe==="isService"&&(ye.hsnCode=""),{...ye,amount:ke,quantity:st,...de}}return fe==="isService"&&(ye.hsnCode=""),ye}return $e}))},Z=ie=>{y(b.filter(fe=>fe.id!==ie))},te=ie=>{const fe=Array.from(ie.target.files||[]);if(fe.length>0){const Ie=[],$e=c.maxFileSizeMB*1024*1024,ye=[".pdf",".doc",".docx",".zip",".rar"];fe.forEach(oe=>{var at,ct;const ke="."+((at=oe.name.split(".").pop())==null?void 0:at.toLowerCase()),st=((ct=oe.name.split(".").pop())==null?void 0:ct.toLowerCase())||"";if(oe.size>$e){Y.error(`"${oe.name}" exceeds ${c.maxFileSizeMB}MB limit and was not added.`);return}if(!ye.includes(ke)){Y.error(`"${oe.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!c.allowedFileTypes.includes(st)){Y.error(`"${oe.name}" has an unallowed file type according to system policy.`);return}Ie.push(oe)}),Ie.length>0&&v([...j,...Ie]),V.current&&(V.current.value="")}},ae=ie=>{v(j.filter((fe,Ie)=>Ie!==ie))},xe=ie=>{const fe=Array.from(ie.target.files||[]);if(fe.length>0){const Ie=[],$e=c.maxFileSizeMB*1024*1024;fe.forEach(ye=>{var ke;const oe=((ke=ye.name.split(".").pop())==null?void 0:ke.toLowerCase())||"";if(ye.size>$e){Y.error(`Photo "${ye.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!ye.type.startsWith("image/")){Y.error(`"${ye.name}" is not an image file.`);return}if(!c.allowedFileTypes.includes(oe)){Y.error(`"${ye.name}" has an unsupported image format.`);return}Ie.push(ye)}),Ie.length>0&&S([...w,...Ie]),I.current&&(I.current.value="")}},be=ie=>{S(w.filter((fe,Ie)=>Ie!==ie))},Ge=ie=>{const fe=Array.from(ie.target.files||[]);if(fe.length>0){const Ie=[],$e=c.maxFileSizeMB*1024*1024,ye=[".pdf",".jpg",".jpeg",".png"];fe.forEach(oe=>{var at,ct;const ke="."+((at=oe.name.split(".").pop())==null?void 0:at.toLowerCase()),st=((ct=oe.name.split(".").pop())==null?void 0:ct.toLowerCase())||"";if(oe.size>$e){Y.error(`Invoice "${oe.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!ye.includes(ke)){Y.error(`"${oe.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!c.allowedFileTypes.includes(st)){Y.error(`"${oe.name}" format is not allowed by system policy.`);return}Ie.push(oe)}),Ie.length>0&&k([...D,...Ie]),A.current&&(A.current.value="")}},Be=ie=>{k(D.filter((fe,Ie)=>Ie!==ie))},_e=ie=>{var Ie,$e,ye;const fe=(Ie=ie.target.files)==null?void 0:Ie[0];if(fe){const oe=c.maxFileSizeMB*1024*1024,ke=[".pdf",".xlsx",".xls",".csv"],st="."+(($e=fe.name.split(".").pop())==null?void 0:$e.toLowerCase()),at=((ye=fe.name.split(".").pop())==null?void 0:ye.toLowerCase())||"";if(fe.size>oe){Y.error(`Attendance file exceeds ${c.maxFileSizeMB}MB limit.`),G.current&&(G.current.value="");return}if(!ke.includes(st)){Y.error("Please upload PDF, Excel, or CSV files only"),G.current&&(G.current.value="");return}if(!c.allowedFileTypes.includes(at)){Y.error(`"${fe.name}" format is not allowed by system policy.`),G.current&&(G.current.value="");return}F(fe)}},Re=async()=>{if(!W){Y.error("Please fill all required fields");return}if(b.some($e=>$e.amount<0||$e.quantity<1)){Y.error("Please ensure all amounts are non-negative and quantity is at least 1");return}const fe=b.filter($e=>$e.description.trim()!==""&&$e.amount>0);if(!f&&fe.some($e=>$e.description.trim()!==""&&$e.amount>0&&($e.gstRate===0||!$e.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.`)){z(!1);return}try{z(!0),await a({activityCompletionDate:m,numberOfParticipants:x?parseInt(x):void 0,closedExpenses:fe,totalClosedExpenses:U,completionDocuments:j,activityPhotos:w,invoicesReceipts:D.length>0?D:void 0,attendanceSheet:C||void 0,completionDescription:N}),ce(),s()}catch($e){console.error("Failed to submit completion documents:",$e),Qd($e)||Y.error("Failed to submit completion documents. Please try again.")}finally{z(!1)}},ce=()=>{R!=null&&R.url&&URL.revokeObjectURL(R.url),L(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([]),S([]),k([]),F(null),E(""),V.current&&(V.current.value=""),I.current&&(I.current.value=""),A.current&&(A.current.value=""),G.current&&(G.current.value="")},je=()=>{_||(ce(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(gt,{open:t,onOpenChange:je,children:e.jsxs(ht,{className:"dealer-completion-documents-modal overflow-hidden flex flex-col",children:[e.jsxs(ft,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs(pt,{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(Ns,{className:"w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]"}),"Activity Completion Documents"]}),d&&e.jsx(le,{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(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(jt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Completion Date *"]}),e.jsx(sa,{value:m||null,onChange:ie=>p(ie||""),maxDate:P,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:B,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(os,{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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item description"}),e.jsx(Ee,{placeholder:"e.g., Venue rental, Refreshments",value:ie.description,onChange:fe=>K(ie.id,"description",fe.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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Ee,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:ie.amount||"",onChange:fe=>K(ie.id,"amount",fe.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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Ee,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:ie.amount||"",onChange:fe=>K(ie.id,"amount",fe.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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN/SAC Code"}),e.jsx(sb,{value:ie.hsnCode||"",onChange:fe=>K(ie.id,"hsnCode",fe),type:ie.isService?"SAC":"HSN",className:ya(ie.hsnCode,ie.isService).isValid?"":"border-red-500",placeholder:ie.isService?"SAC":"HSN"}),!ya(ie.hsnCode,ie.isService).isValid&&e.jsx("span",{className:"text-[10px] text-red-500 absolute left-0 bottom-0 block leading-tight",children:ya(ie.hsnCode,ie.isService).message})]}),e.jsxs("div",{className:"w-24 sm:w-28 flex-shrink-0",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item Type"}),e.jsxs("select",{value:ie.isService?"SAC":"HSN",onChange:fe=>K(ie.id,"isService",fe.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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"CGST %"}),e.jsx(Ee,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ie.cgstRate||"",onChange:fe=>K(ie.id,"cgstRate",fe.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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"SGST %"}),e.jsx(Ee,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ie.sgstRate||"",onChange:fe=>K(ie.id,"sgstRate",fe.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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"UTGST %"}),e.jsx(Ee,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ie.utgstRate||"",onChange:fe=>K(ie.id,"utgstRate",fe.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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"IGST %"}),e.jsx(Ee,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:ie.igstRate||"",onChange:fe=>K(ie.id,"igstRate",fe.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:()=>Z(ie.id),children:e.jsx(Nt,{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(le,{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(le,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Pe,{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:V,type:"file",multiple:!0,accept:[".pdf",".doc",".docx",".zip",".rar"].filter(ie=>c.allowedFileTypes.includes(ie.replace(".",""))).join(","),className:"hidden",id:"completionDocs",onChange:te}),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(gs,{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(Ns,{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,fe)=>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(Pe,{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:[$(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:()=>M(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:()=>T(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:()=>ae(fe),title:"Remove document",children:e.jsx(Nt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},fe))]})]}),e.jsxs("div",{children:[e.jsxs(ne,{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 ${w.length>0?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:I,type:"file",multiple:!0,accept:[".jpg",".jpeg",".png",".gif",".webp"].filter(ie=>c.allowedFileTypes.includes(ie.replace(".",""))).join(","),className:"hidden",id:"completionPhotos",onChange:xe}),e.jsx("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:w.length>0?e.jsxs(e.Fragment,{children:[e.jsx(gs,{className:"w-8 h-8 text-green-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-green-700",children:[w.length," photo",w.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-green-600",children:"Click to add more photos"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(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)"})]})})]}),w.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Photos (",w.length,"):"]}),w.map((ie,fe)=>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:[$(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:()=>M(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:()=>T(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:()=>be(fe),title:"Remove photo",children:e.jsx(Nt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},fe))]})]})]})]}),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(le,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(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 ${D.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:A,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:D.length>0?e.jsxs(e.Fragment,{children:[e.jsx(gs,{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:[D.length," document",D.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)"})]})})]}),D.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 (",D.length,"):"]}),D.map((ie,fe)=>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:[$(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:()=>M(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:()=>T(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:()=>Be(fe),title:"Remove document",children:e.jsx(Nt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},fe))]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm sm:text-base font-semibold",children:"Attendance Sheet / Participant List"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload attendance records or participant lists (if applicable)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${C?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:G,type:"file",accept:[".pdf",".xlsx",".xls",".csv"].filter(ie=>c.allowedFileTypes.includes(ie.replace(".",""))).join(","),className:"hidden",id:"attendanceDoc",onChange:_e}),e.jsx("label",{htmlFor:"attendanceDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:C?e.jsxs(e.Fragment,{children:[e.jsx(gs,{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:C.name}),e.jsx("span",{className:"text-xs text-blue-600",children:"Document selected"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ns,{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)"})]})})]}),C&&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(Pe,{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:C.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[$(C)&&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:()=>M(C),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:()=>T(C),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),G.current&&(G.current.value="")},title:"Remove document",children:e.jsx(Nt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5 sm:space-y-2 max-w-3xl",children:[e.jsx(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(Ws,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:N,onChange:ie=>E(ie.target.value),className:"min-h-[100px] sm:min-h-[120px] text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[N.length," characters"]})]}),!W&&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(tt,{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(Rt,{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:je,disabled:_,className:"border-2",children:"Cancel"}),e.jsx(O,{onClick:Re,disabled:_||!W,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:_?"Submitting...":"Submit Documents"})]})]})}),R&&e.jsx(gt,{open:!!R,onOpenChange:()=>{R!=null&&R.url&&URL.revokeObjectURL(R.url),L(null)},children:e.jsx(ht,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ft,{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(pt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:R.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[R.file.type||"Unknown type"," • ",(R.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:()=>T(R.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:(re=R.file.type)!=null&&re.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:R.url,alt:R.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(pe=R.file.type)!=null&&pe.includes("pdf")||R.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:R.url,className:"w-full h-full rounded-lg border-0",title:R.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:()=>T(R.file),className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",R.file.name]})]})})]})})})]})}function q4({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 ce=ab(n);return rb(ce)},[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=(ce,je,re=1)=>{const pe=ce*re,ie=pe*(je.cgstRate||0)/100,fe=pe*(je.sgstRate||0)/100,Ie=pe*(je.utgstRate||0)/100,$e=pe*(je.igstRate||0)/100,ye=ie+fe+Ie+$e,oe=pe+ye;return{cgstRate:je.cgstRate,cgstAmt:ie,sgstRate:je.sgstRate,sgstAmt:fe,utgstRate:je.utgstRate,utgstAmt:Ie,igstRate:je.igstRate,igstAmt:$e,gstAmt:ye,gstRate:(je.cgstRate||0)+(je.sgstRate||0)+(je.utgstRate||0)+(je.igstRate||0),totalAmt:oe}},[v,w]=u.useState("date"),[S,D]=u.useState(""),[k,C]=u.useState(""),[F,N]=u.useState([]),[E,_]=u.useState(""),[z,R]=u.useState(!1),[L,V]=u.useState(null),[I,A]=u.useState(!1),G=u.useRef(null),$=u.useRef(null),M=ce=>{if(!ce)return!1;const je=ce.toLowerCase();return je.endsWith(".pdf")||!!je.match(/\.(jpg|jpeg|png|gif|webp)$/i)},T=ce=>M(ce.name);u.useEffect(()=>()=>{L!=null&&L.fileUrl&&L.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(L.fileUrl)},[L]);const U=ce=>{if(!T(ce)){Y.error("Preview is only available for images and PDF files");return}L!=null&&L.fileUrl&&L.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(L.fileUrl);const je=URL.createObjectURL(ce);V({fileName:ce.name,fileType:ce.type,documentId:"",fileUrl:je,fileSize:ce.size})},H=ce=>{const je=ce.originalFileName||ce.fileName||ce.name||"Document",re=ce.documentId||ce.id||"",pe=je.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let ie="";if(re)ie=Dn(re);else if(ie=ce.storageUrl||ce.documentUrl||"",ie&&!ie.startsWith("http")){const fe="https://reflow-uat.royalenfield.com/",Ie=fe.endsWith("/")?fe.slice(0,-1):fe,$e=ie.startsWith("/")?ie:`/${ie}`;ie=`${Ie}${$e}`}V({fileName:je,fileType:pe,documentId:re,fileUrl:ie})},W=ce=>{const je=URL.createObjectURL(ce),re=document.createElement("a");re.href=je,re.download=ce.name,document.body.appendChild(re),re.click(),document.body.removeChild(re),URL.revokeObjectURL(je)};u.useEffect(()=>{if(t&&o){const ce=p>0;if(o.costItems&&o.costItems.length>0){const je=o.costItems.map((re,pe)=>({id:`original-${pe}`,description:re.itemDescription||re.description||"",amount:Number(re.amount)||0,quantity:Number(re.quantity)||1,hsnCode:re.hsnCode||"",isService:!!re.isService,gstRate:Number(re.gstRate)||c,cgstRate:Number(re.cgstRate)||0,sgstRate:Number(re.sgstRate)||0,utgstRate:Number(re.utgstRate)||0,igstRate:Number(re.igstRate)||0,gstAmt:Number(re.gstAmt)||0,cgstAmt:Number(re.cgstAmt)||0,sgstAmt:Number(re.sgstAmt)||0,utgstAmt:Number(re.utgstAmt)||0,igstAmt:Number(re.igstAmt)||0,cessRate:Number(re.cessRate)||0,cessAmt:Number(re.cessAmt)||0,totalAmt:Number(re.totalAmt)||0,isOriginal:ce}));y(je)}o.expectedCompletionDate&&(D(o.expectedCompletionDate.split("T")[0]),w("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}]),D(""),_(""))},[t,o,c,p]);const P=u.useMemo(()=>b.reduce((ce,je)=>ce+(je.totalAmt||je.amount||0),0),[b]),B=u.useMemo(()=>{const ce=x!==null,je=b.length>0&&b.every(fe=>fe.description.trim()!==""&&fe.amount>0),re=v==="date"?S!=="":k!==""&&parseInt(k)>0,pe=E.trim().length>0,ie=f?!1:b.some(fe=>{const{isValid:Ie}=ya(fe.hsnCode,fe.isService);return!Ie});return ce&&je&&re&&pe&&!ie},[x,b,v,S,k,E,f]),K=ce=>{var re,pe,ie;const je=(re=ce.target.files)==null?void 0:re[0];if(je){const fe=d.maxFileSizeMB*1024*1024;if(je.size>fe){Y.error(`File size exceeds the maximum allowed size of ${d.maxFileSizeMB}MB. Current size: ${(je.size/(1024*1024)).toFixed(2)}MB`),G.current&&(G.current.value="");return}const Ie=[".pdf",".doc",".docx"],$e="."+((pe=je.name.split(".").pop())==null?void 0:pe.toLowerCase()),ye=((ie=je.name.split(".").pop())==null?void 0:ie.toLowerCase())||"";if(!Ie.includes($e)||!d.allowedFileTypes.includes(ye)){Y.error("Please upload a valid PDF, DOC, or DOCX file as per system policy"),G.current&&(G.current.value="");return}h(je)}},Z=ce=>{const je=Array.from(ce.target.files||[]),re=[],pe=d.maxFileSizeMB*1024*1024;je.forEach(ie=>{var Ie;if(ie.size>pe){Y.error(`"${ie.name}" exceeds ${d.maxFileSizeMB}MB limit and was not added.`);return}const fe=((Ie=ie.name.split(".").pop())==null?void 0:Ie.toLowerCase())||"";if(!d.allowedFileTypes.includes(fe)){Y.error(`"${ie.name}" has an unsupported file type and was not added.`);return}re.push(ie)}),re.length>0&&N(ie=>[...ie,...re]),$.current&&($.current.value="")},te=()=>{y(ce=>[...ce,{id:Date.now().toString(),description:"",amount:0,gstRate:c||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},ae=ce=>{b.length>1&&y(je=>je.filter(re=>re.id!==ce))},xe=(ce,je,re)=>{y(pe=>pe.map(ie=>{if(ie.id===ce){let fe={...ie,[je]:re};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate"].includes(je)){const Ie=parseFloat(re);if(!isNaN(Ie)&&Ie<0)return Y.error("Value cannot be negative"),ie;const $e=je==="amount"?parseFloat(re)||0:ie.amount,ye=1;let oe=ie.cgstRate,ke=ie.sgstRate,st=ie.utgstRate,at=ie.igstRate;if(je==="cgstRate"){if(!g.isCGST)return ie;oe=parseFloat(re)||0,g.isUTGST?(st=oe,ke=0):(ke=oe,st=0),at=0}else if(je==="sgstRate"){if(!g.isSGST)return ie;ke=parseFloat(re)||0,oe=ke,st=0,at=0}else if(je==="utgstRate"){if(!g.isUTGST)return ie;st=parseFloat(re)||0,oe=st,ke=0,at=0}else if(je==="igstRate"){if(!g.isIGST)return ie;at=parseFloat(re)||0,oe=0,ke=0,st=0}else if(je==="gstRate"){const Dt=parseFloat(re)||0;g.isIGST?(at=Dt,oe=0,ke=0,st=0):(oe=Dt/2,g.isUTGST?(st=Dt/2,ke=0):(ke=Dt/2,st=0),at=0)}const ct=j($e,{cgstRate:oe,sgstRate:ke,igstRate:at,utgstRate:st},ye);return{...fe,amount:$e,quantity:ye,...ct}}return fe}return ie}))},be=ce=>{N(je=>je.filter((re,pe)=>pe!==ce))},Ge=async()=>{if(!B){Y.error("Please fill all required fields");return}if(b.some(re=>re.amount<0)){Y.error("Please ensure all amounts are non-negative");return}if(v==="days"&&(parseInt(k)<=0||isNaN(parseInt(k)))){Y.error("Please enter a valid number of days greater than 0");return}let je=S||"";if(v==="days"&&k){const re=parseInt(k),pe=new Date;pe.setDate(pe.getDate()+re),je=pe.toISOString().split("T")[0]}try{if(R(!0),!f&&b.some(fe=>fe.description.trim()!==""&&fe.amount>0&&(fe.gstRate===0||!fe.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.`)){R(!1);return}const pe=p>0,ie=b.filter(fe=>fe.description.trim()!==""&&fe.amount>0).map(fe=>({...fe,description:o&&pe&&!fe.isOriginal?`[ADDITIONAL] ${fe.description}`:fe.description}));await a({proposalDocument:x,costBreakup:ie,totalEstimatedBudget:P,expectedCompletionDate:je,timelineMode:v,expectedCompletionDays:v==="days"?parseInt(k):0,otherDocuments:F,dealerComments:E}),Be(),s()}catch(re){console.error("Failed to submit proposal:",re),Qd(re)||Y.error("Failed to submit proposal. Please try again.")}finally{R(!1)}},Be=()=>{L!=null&&L.fileUrl&&L.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(L.fileUrl),V(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}]),w("date"),D(""),C(""),N([]),_(""),G.current&&(G.current.value=""),$.current&&($.current.value="")},_e=()=>{z||(Be(),s())},Re=new Date().toISOString().split("T")[0];return e.jsxs(gt,{open:t,onOpenChange:_e,children:[e.jsxs(ht,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(ft,{className:"flex-shrink-0 pb-3 lg:pb-4",children:[e.jsxs(pt,{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(Ns,{className:"w-5 h-5 lg:w-6 lg:h-6 text-[--re-green]"}),"Dealer Proposal Submission"]}),m&&e.jsx(le,{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:()=>A(!I),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(Pe,{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(le,{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:I?e.jsx(Wc,{className:"w-4 h-4"}):e.jsx(os,{className:"w-4 h-4"})})]}),I&&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(jt,{className:"w-3.5 h-3.5 text-gray-500"}),e.jsx("span",{className:"font-medium",children:"Expected Completion:"}),e.jsx("span",{children:new Date(o.expectedCompletionDate).toLocaleDateString("en-IN")})]}),o.documentUrl&&e.jsx("div",{className:"flex items-center gap-1.5",children:M(o.documentUrl)?e.jsxs(e.Fragment,{children:[e.jsx(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(Pe,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:o.otherDocuments.map((ce,je)=>e.jsx(Yr,{document:{documentId:ce.documentId||ce.id||"",name:ce.originalFileName||ce.fileName||ce.name||"Supporting Document",fileType:(ce.originalFileName||ce.fileName||ce.name||"").split(".").pop()||"file",uploadedAt:ce.uploadedAt||new Date().toISOString()},onPreview:M(ce.originalFileName||ce.fileName||ce.name||"")?()=>H(ce):void 0,onDownload:async re=>{if(re)await Us(re);else{let pe=ce.storageUrl||ce.documentUrl;if(pe&&!pe.startsWith("http")){const ie="https://reflow-uat.royalenfield.com/",fe=ie.endsWith("/")?ie.slice(0,-1):ie,Ie=pe.startsWith("/")?pe:`/${pe}`;pe=`${fe}${Ie}`}pe&&window.open(pe,"_blank")}}},je))})]})]}),(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((ce,je)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:ce.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(ce.amount).toLocaleString("en-IN")]})]},je)),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(le,{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:G,type:"file",accept:[".pdf",".doc",".docx"].filter(ce=>d.allowedFileTypes.includes(ce.replace(".",""))).join(","),className:"hidden",id:"proposalDoc",onChange:K}),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(gs,{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:[T(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:()=>W(x),className:"h-7 text-[10px]",children:"Download"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ns,{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(le,{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:()=>w("date"),className:v==="date"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Date"}),e.jsx(O,{type:"button",onClick:()=>w("days"),className:v==="days"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Days"})]}),v==="date"?e.jsx(sa,{value:S||null,onChange:ce=>D(ce||""),minDate:Re,placeholderText:"dd/mm/yyyy",className:"w-full"}):e.jsx(Ee,{type:"number",placeholder:"Enter number of days",min:"1",value:k,onChange:ce=>C(ce.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(le,{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:te,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(os,{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(ce=>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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold",children:"Item Description"}),ce.isOriginal?e.jsx(le,{className:"text-[9px] h-4 bg-gray-200 text-gray-700 hover:bg-gray-200 border-none",children:"ORIGINAL"}):o&&p>0?e.jsx(le,{className:"text-[9px] h-4 bg-amber-100 text-amber-700 hover:bg-amber-100 border-none",children:"ADDITIONAL"}):null]}),e.jsx(Ee,{placeholder:"e.g., Venue branding, Logistics, etc.",value:ce.description,onChange:je=>xe(ce.id,"description",je.target.value),className:`w-full bg-white shadow-sm ${ce.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:ce.isOriginal})]}),f&&e.jsxs("div",{className:"flex-1 min-w-[140px]",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Ee,{type:"number",value:ce.amount||"",onChange:je=>xe(ce.id,"amount",je.target.value),className:`pl-8 bg-white shadow-sm ${ce.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:ce.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:()=>ae(ce.id),disabled:b.length===1||ce.isOriginal,children:e.jsx(Nt,{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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Ee,{type:"number",value:ce.amount||"",onChange:je=>xe(ce.id,"amount",je.target.value),className:`pl-8 bg-white shadow-sm ${ce.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:ce.isOriginal})]})]}),e.jsxs("div",{className:"w-28 sm:w-32 relative pb-5",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN/SAC Code"}),e.jsx(sb,{value:ce.hsnCode||"",onChange:je=>xe(ce.id,"hsnCode",je),type:ce.isService?"SAC":"HSN",disabled:ce.isOriginal,className:ya(ce.hsnCode,ce.isService).isValid?"":"border-red-500",placeholder:ce.isService?"Select SAC":"Select HSN"}),!ya(ce.hsnCode,ce.isService).isValid&&e.jsx("span",{className:"text-[10px] text-red-500 absolute left-0 bottom-0 block leading-tight",children:ya(ce.hsnCode,ce.isService).message})]}),e.jsxs("div",{className:"w-28 sm:w-32",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Type"}),e.jsxs("select",{value:ce.isService?"SAC":"HSN",onChange:je=>xe(ce.id,"isService",je.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] ${ce.isOriginal?"bg-gray-100 cursor-not-allowed":""}`,disabled:ce.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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"CGST %"}),e.jsx(Ee,{type:"number",value:ce.cgstRate||"",onChange:je=>xe(ce.id,"cgstRate",je.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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"SGST %"}),e.jsx(Ee,{type:"number",value:ce.sgstRate||"",onChange:je=>xe(ce.id,"sgstRate",je.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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"UTGST %"}),e.jsx(Ee,{type:"number",value:ce.utgstRate||"",onChange:je=>xe(ce.id,"utgstRate",je.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(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"IGST %"}),e.jsx(Ee,{type:"number",value:ce.igstRate||"",onChange:je=>xe(ce.id,"igstRate",je.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:["₹",ce.cgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),ce.sgstAmt>0&&e.jsxs("span",{children:["SGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",ce.sgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),ce.utgstAmt>0&&e.jsxs("span",{children:["UTGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",ce.utgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs("span",{children:["IGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",ce.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:["₹",ce.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: ₹",ce.totalAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]})]})},ce.id))}),e.jsxs("div",{className:"bg-[#2d4a3e] rounded-xl p-5 text-white flex items-center justify-between shadow-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-white/20 rounded-lg",children:e.jsx(Vs,{className:"w-6 h-6"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-white/70 uppercase font-bold tracking-wider",children:"Estimated Total Budget"}),!f&&e.jsx("p",{className:"text-sm text-white/90",children:"Inclusive of all applicable taxes"})]})]}),e.jsxs("div",{className:"text-3xl font-bold border-l border-white/20 pl-6",children:["₹",P.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(le,{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:$,type:"file",multiple:!0,accept:d.allowedFileTypes.map(ce=>`.${ce}`).join(","),className:"hidden",id:"otherDocs",onChange:Z}),e.jsxs("label",{htmlFor:"otherDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(Ns,{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((ce,je)=>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(Pe,{className:"w-3.5 h-3.5 text-blue-600 flex-shrink-0"}),e.jsx("span",{className:"text-gray-700 font-medium truncate",children:ce.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[T(ce)&&e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",onClick:()=>U(ce),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:()=>W(ce),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:()=>be(je),children:e.jsx(Nt,{className:"w-3 h-3"})})]})]},je))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"font-semibold text-base lg:text-lg",children:"Dealer Comments *"}),e.jsx(Ws,{placeholder:"Details about execution, special requirements, etc.",value:E,onChange:ce=>_(ce.target.value),className:"min-h-[100px] bg-white shadow-sm"})]})]}),!B&&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(tt,{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(Rt,{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:_e,disabled:z,className:"border-2",children:"Cancel"}),e.jsx(O,{onClick:Ge,disabled:!B||z,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:z?"Submitting...":"Submit Documents"})]})]}),L&&e.jsx(en,{fileName:L.fileName||"",fileType:L.fileType||"",fileUrl:L.fileUrl||"",fileSize:L.fileSize||0,attachmentId:L.documentId||"",onDownload:Us,open:!!L,onClose:()=>V(null)})]})}function e6({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,w=u.useMemo(()=>(m==="reject"||y.trim().length>0)&&x.trim().length>0,[m,y,x]),S=async()=>{if(!w){if(m==="approve"&&!y.trim()){Y.error("IO number is required. Please block amount from IO tab first.");return}if(!x.trim()){Y.error("Please provide comments");return}return}try{f(!0),m==="approve"?await a({ioNumber:y.trim(),comments:x.trim()}):await r(x.trim()),D(),s()}catch(C){console.error(`Failed to ${m} request:`,C),Y.error(`Failed to ${m} request. Please try again.`)}finally{f(!1)}},D=()=>{p("approve"),h("")},k=()=>{g||(D(),s())};return e.jsx(gt,{open:t,onOpenChange:k,children:e.jsxs(ht,{className:"dept-lead-io-modal overflow-hidden flex flex-col",children:[e.jsxs(ft,{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(He,{className:"w-5 h-5 lg:w-6 lg:h-6 text-green-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(pt,{className:"font-semibold text-lg lg:text-xl flex items-center gap-2 flex-wrap",children:["Review and Approve",d&&e.jsx(le,{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(le,{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(le,{className:"bg-green-100 text-green-800 border-green-200 text-xs",children:[e.jsx(He,{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(He,{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(ne,{htmlFor:"ioNumber",className:"text-xs lg:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["IO Number ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ee,{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(ne,{htmlFor:"comment",className:"text-xs lg:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Comments & Remarks ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ws,{id:"comment",placeholder:m==="approve"?"Enter your approval comments and any conditions or notes...":"Enter detailed reasons for rejection...",value:x,onChange:C=>{const F=C.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(as,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[j,"/",v]})]})]})]})]})}),e.jsxs(Rt,{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:S,disabled:!w||g,className:`text-sm lg:text-base ${m==="approve"?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700"} text-white`,children:g?`${m==="approve"?"Approving":"Rejecting"}...`:e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),m==="approve"?"Approve Request":"Reject Request"]})})]})]})})}function t6({isOpen:t,onClose:s,onPush:a,onReQuotation:r,completionDetails:n,ioDetails:i,completionDocuments:l,requestTitle:o,requestNumber:c,taxationType:d}){var R,L;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,w=500,S=u.useMemo(()=>n!=null&&n.totalClosedExpenses?n.totalClosedExpenses:n!=null&&n.closedExpenses&&Array.isArray(n.closedExpenses)?n.closedExpenses.reduce((V,I)=>{const A=typeof I=="object"&&I.amount||0,G=typeof I=="object"&&I.gstAmt||0,$=I.totalAmt||A+G;return V+(Number($)||0)},0):0,[n]),D=V=>{if(!V)return"—";try{return new Date(V).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return V}},k=V=>`₹${V.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,C=V=>{if(!V.name)return!1;const I=V.name.toLowerCase();return I.endsWith(".pdf")||I.endsWith(".jpg")||I.endsWith(".jpeg")||I.endsWith(".png")||I.endsWith(".gif")||I.endsWith(".webp")},F=async V=>{if(!V.id){Y.error("Document preview not available - document ID missing");return}j(!0);try{const I=Dn(V.id),A=V.name.toLowerCase(),G=A.endsWith(".pdf"),$=A.match(/\.(jpg|jpeg|png|gif|webp)$/i),M=!0,T=M?null:localStorage.getItem("accessToken"),H=await fetch(I,{headers:{Accept:G?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!H.ok)throw new Error(`Failed to load file: ${H.status} ${H.statusText}`);const W=await H.blob();if(W.size===0)throw new Error("File is empty or could not be loaded");const P=window.URL.createObjectURL(W);b({name:V.name,url:P,type:W.type||(G?"application/pdf":$?"image":void 0),size:W.size})}catch(I){console.error("Failed to load document preview:",I),Y.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 N=async()=>{if(!p.trim()){Y.error("Please provide comments before proceeding");return}try{g(!0),await a(p.trim()),E(),s()}catch(V){console.error("Failed to generate e-invoice:",V),Y.error("Failed to generate e-invoice. Please try again.")}finally{g(!1)}},E=()=>{x("")},_=async()=>{if(!p.trim()){Y.error("Please provide comments (reason) for re-quotation request");return}if(!r){Y.error("Re-quotation handler not provided");return}try{g(!0),await r(p.trim()),E(),s()}catch(V){console.error("Failed to request re-quotation:",V)}finally{g(!1)}},z=()=>{h||(E(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(gt,{open:t,onOpenChange:z,children:e.jsxs(ht,{className:"settlement-push-modal overflow-hidden flex flex-col w-full max-w-none",children:[e.jsxs(ft,{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(Vt,{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(pt,{className:"font-semibold text-lg sm:text-xl flex items-center gap-2 flex-wrap",children:["E-Invoice Generation & Sync",d&&e.jsx(le,{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(le,{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(le,{className:"bg-indigo-100 text-indigo-800 border-indigo-200 text-xs",children:[e.jsx(Vt,{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(q,{children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(gs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Details"]}),e.jsx(Se,{className:"text-xs sm:text-sm",children:"Review activity completion information"})]}),e.jsxs(se,{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:D(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(q,{children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Et,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"IO Details"]}),e.jsx(Se,{className:"text-xs sm:text-sm",children:"Internal Order information for budget reference"})]}),e.jsxs(se,{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(q,{className:"md:col-span-2 lg:col-span-3",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs(ue,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Fa,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Expense Breakdown"]}),e.jsx(Se,{className:"text-xs sm:text-sm",children:"Review closed expenses breakdown (Base + GST)"})]}),e.jsxs(se,{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((V,I)=>{const A=typeof V=="object"&&V.amount||0,G=typeof V=="object"&&V.gstRate||0,$=typeof V=="object"&&V.gstAmt||0,M=typeof V=="object"?V.totalAmt||A+$: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:V.description||`Expense ${I+1}`}),e.jsx("span",{className:"font-bold text-gray-900",children:k(M)})]}),e.jsxs("div",{className:"sm:hidden flex justify-between w-full text-xs text-gray-500",children:[e.jsxs("span",{children:["Base: ",k(A)]}),!m&&e.jsxs("span",{children:["GST: ",G,"% (",k($),")"]})]}),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:V.description,children:V.description||`Expense ${I+1}`})}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:k(A)}),!m&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:[G,"%"]}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:k($)})]}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right font-semibold text-gray-900",children:k(M)})]},I)})}),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(S)})]})]})]})]}),l&&e.jsxs("div",{className:"space-y-4",children:[l.completionDocuments&&l.completionDocuments.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"font-semibold text-sm sm:text-base flex items-center gap-2",children:[e.jsx(gs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Documents"]}),e.jsxs(le,{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((V,I)=>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(gs,{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:V.name,children:V.name})})]}),V.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[C(V)&&e.jsx("button",{type:"button",onClick:()=>F(V),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(We,{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{V.id&&await Us(V.id)}catch(A){console.error("Failed to download document:",A),Y.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"})})]})]},I))})]}),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(Vt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Activity Photos"]}),e.jsxs(le,{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((V,I)=>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(Vt,{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:V.name,children:V.name})})]}),V.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[C(V)&&e.jsx("button",{type:"button",onClick:()=>F(V),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(We,{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{V.id&&await Us(V.id)}catch(A){console.error("Failed to download document:",A),Y.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"})})]})]},I))})]}),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(le,{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((V,I)=>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:V.name,children:V.name})})]}),V.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[C(V)&&e.jsx("button",{type:"button",onClick:()=>F(V),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(We,{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{V.id&&await Us(V.id)}catch(A){console.error("Failed to download document:",A),Y.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"})})]})]},I))})]}),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(Vt,{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(Vt,{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:[C(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(We,{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 V;try{(V=l.attendanceSheet)!=null&&V.id&&await Us(l.attendanceSheet.id)}catch(I){console.error("Failed to download document:",I),Y.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(as,{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(ne,{htmlFor:"comment",className:"text-xs sm:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Comments & Remarks ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ws,{id:"comment",placeholder:"Enter your comments about e-invoice generation (e.g., verified expenses, ready for settlement)...",value:p,onChange:V=>{const I=V.target.value;I.length<=w&&x(I)},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(as,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[v,"/",w]})]})]})]})}),e.jsxs(Rt,{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:z,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(We,{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:N,disabled:!p.trim()||h,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:h?"Processing...":e.jsxs(e.Fragment,{children:[e.jsx(Vt,{className:"w-4 h-4 mr-2"}),"Generate & Sync"]})})]})]})}),f&&e.jsx(gt,{open:!!f,onOpenChange:()=>b(null),children:e.jsx(ht,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ft,{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(pt,{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 V=document.createElement("a");V.href=f.url,V.download=f.name,V.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(We,{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")||(R=f.type)!=null&&R.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)||(L=f.type)!=null&&L.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 V=document.createElement("a");V.href=f.url,V.download=f.name,V.click()},className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Download ",f.name]})]})})]})})})]})}function s6({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(gt,{open:t,onOpenChange:s,children:e.jsxs(ht,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(ft,{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(wa,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(pt,{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(Ht,{className:"w-4 h-4 text-gray-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-gray-600",children:"To:"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:i})]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(wa,{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(Ml,{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(jt,{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(le,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(le,{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(Nt,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function a6({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,w]=u.useState(!1),S=u.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const $=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray($)?$.reduce((M,T)=>{const U=typeof T=="object"&&T.amount||0,H=typeof T=="object"&&T.quantity||1,W=U*H,P=typeof T=="object"&&T.gstAmt||0,B=T.totalAmt||W+P;return M+(Number(B)||0)},0):0},[i]),D=u.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const $=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray($)?$.reduce((M,T)=>{const U=typeof T=="object"&&T.amount||0,H=typeof T=="object"&&T.quantity||1;return M+Number(U)*Number(H)},0):0},[i]),k=u.useMemo(()=>{const $=(d==null?void 0:d.internalOrders)||(d==null?void 0:d.internal_orders)||[];if(Array.isArray($)&&$.length>0)return $.reduce((T,U)=>{const H=Number(U.ioBlockedAmount||U.io_blocked_amount||0);return T+H},0);const M=(d==null?void 0:d.internalOrder)||(d==null?void 0:d.internal_order);return Number((M==null?void 0:M.ioBlockedAmount)||(M==null?void 0:M.io_blocked_amount)||0)},[d==null?void 0:d.internalOrders,d==null?void 0:d.internal_orders,d==null?void 0:d.internalOrder,d==null?void 0:d.internal_order]),C=k>=D-.01,F=Math.max(0,D-k),[N,E]=u.useState(null),_=$=>{if(!$)return"—";try{return new Date($).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return $}},z=$=>{if(!$.name)return!1;const M=$.name.toLowerCase();return M.endsWith(".pdf")||M.endsWith(".jpg")||M.endsWith(".jpeg")||M.endsWith(".png")||M.endsWith(".gif")||M.endsWith(".webp")},R=$=>{let M=$.url||$.storageUrl||"";const T=$.id||$.documentId||"";if(!T&&!M){Y.error("Document preview not available");return}if(M&&!M.startsWith("http")&&!M.startsWith("blob:")){const U="https://reflow-uat.royalenfield.com/",H=U.endsWith("/")?U.slice(0,-1):U,W=M.startsWith("/")?M:`/${M}`;M=`${H}${W}`}E({name:$.name||"Document",url:M||(T?Dn(T):""),type:($.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:T})};u.useEffect(()=>()=>{N!=null&&N.url&&N.url.startsWith("blob:")&&window.URL.revokeObjectURL(N.url)},[N]);const L=async()=>{if(!h.trim()){Y.error("Please provide approval comments");return}try{b(!0),j("approve"),await a(h),A(),s()}catch($){console.error("Failed to approve proposal:",$),Y.error("Failed to approve proposal. Please try again.")}finally{b(!1),j(null)}},V=async()=>{if(!h.trim()){Y.error("Please provide rejection reason");return}try{b(!0),j("reject"),await r(h),A(),s()}catch($){console.error("Failed to reject proposal:",$),Y.error("Failed to reject proposal. Please try again.")}finally{b(!1),j(null)}},I=async()=>{if(!h.trim()){Y.error("Please provide reasons for requesting a revision");return}if(!n){Y.error("Revision feature is not available");return}try{b(!0),j("revision"),await n(h),A(),s()}catch($){console.error("Failed to request revision:",$),Y.error("Failed to request revision. Please try again.")}finally{b(!1),j(null)}},A=()=>{g(""),j(null)},G=()=>{f||(A(),s())};return t?e.jsxs(gt,{open:t,onOpenChange:G,children:[e.jsxs(ht,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(ft,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(pt,{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(He,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),p&&e.jsx(le,{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:()=>w(!v),children:[e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pe,{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(le,{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(Wc,{className:"w-4 h-4"}):e.jsx(os,{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(jt,{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:z({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(Vs,{className:"w-3 h-3"}),"Previous Cost Breakdown"]}),e.jsx("div",{className:"border rounded-md overflow-hidden text-[10px]",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-600",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-2 font-medium",children:"Description"}),e.jsx("th",{className:"p-2 font-medium text-right",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y",children:[(m.costItems||m.costBreakup).map(($,M)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:$.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number($.amount).toLocaleString("en-IN")]})]},M)),e.jsxs("tr",{className:"bg-gray-50 font-bold border-t",children:[e.jsx("td",{className:"p-2 text-gray-900",children:"Total"}),e.jsxs("td",{className:"p-2 text-right text-gray-900",children:["₹",Number(m.totalEstimatedBudget||m.totalBudget||0).toLocaleString("en-IN")]})]})]})]})})]}),m.otherDocuments&&m.otherDocuments.length>0&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1.5 flex items-center gap-1",children:[e.jsx(Pe,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:m.otherDocuments.map(($,M)=>e.jsx(Yr,{document:{documentId:$.documentId||$.id||"",name:$.originalFileName||$.fileName||$.name||"Supporting Document",fileType:($.originalFileName||$.fileName||$.name||"").split(".").pop()||"file",uploadedAt:$.uploadedAt||new Date().toISOString()},onPreview:z({name:$.originalFileName||$.fileName||$.name||""})?()=>R($):void 0,onDownload:async T=>{if(T)await Us(T);else{let U=$.storageUrl||$.documentUrl;if(U&&!U.startsWith("http")){const H="https://reflow-uat.royalenfield.com/",W=H.endsWith("/")?H.slice(0,-1):H,P=U.startsWith("/")?U:`/${U}`;U=`${W}${P}`}U&&window.open(U,"_blank")}}},M))})]}),(m.comments||m.dealerComments)&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1 flex items-center gap-1",children:[e.jsx(Ks,{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(Pe,{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(Pe,{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:[z(i.proposalDocument)&&e.jsx("button",{type:"button",onClick:()=>R(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 $;try{($=i.proposalDocument)!=null&&$.id&&await Us(i.proposalDocument.id)}catch(M){console.error("Failed to download document:",M),Y.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(Pe,{className:"w-4 h-4 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(le,{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(($,M)=>e.jsxs("div",{className:"border rounded-lg p-2 lg:p-3 bg-gray-50 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 min-w-0 flex-1",children:[e.jsx(Pe,{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:$.name,children:$.name})]}),$.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[z($)&&e.jsx("button",{type:"button",onClick:()=>R($),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{$.id&&await Us($.id)}catch(T){console.error("Failed to download document:",T),Y.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(kt,{className:"w-5 h-5 text-gray-600"})})]})]},M))})]})]}),e.jsxs("div",{className:"space-y-4 lg:space-y-4 flex flex-col",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const $=i!=null&&i.costBreakup?Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[]:[];return $&&Array.isArray($)&&$.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:$.map((M,T)=>{var U,H;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=M==null?void 0:M.description)!=null&&U.startsWith("[ADDITIONAL]")?M.description.replace("[ADDITIONAL]","").trim():(M==null?void 0:M.description)||"N/A"}),$.some(W=>{var P;return(P=W==null?void 0:W.description)==null?void 0:P.startsWith("[ADDITIONAL]")})&&((H=M==null?void 0:M.description)!=null&&H.startsWith("[ADDITIONAL]")?e.jsx(le,{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(le,{className:"text-[9px] h-3.5 px-1 bg-gray-100 text-gray-600 hover:bg-gray-100 border-none leading-none",children:"ORIGINAL"}))]}),!x&&(M!=null&&M.gstRate)?e.jsxs("span",{className:"block text-[10px] text-gray-400",children:[M.gstRate,"% GST"]}):null]}),e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(M==null?void 0:M.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!x&&e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(M==null?void 0:M.gstAmt)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsxs("div",{className:"text-xs lg:text-sm font-semibold text-gray-900 text-right",children:["₹",(Number((M==null?void 0:M.totalAmt)||((M==null?void 0:M.amount)||0)*((M==null?void 0:M.quantity)||1)+((M==null?void 0:M.gstAmt)||0))||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(M==null?void 0:M.id)||(M==null?void 0:M.description)||T)})})]}),e.jsx("div",{className:"border-2 border-[--re-green] rounded-lg p-2.5 lg:p-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4 text-[--re-green]"}),e.jsx("span",{className:"font-semibold text-xs lg:text-sm text-gray-700",children:"Total Estimated Budget"})]}),e.jsxs("div",{className:"text-lg lg:text-xl font-bold text-[--re-green]",children:["₹",S.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}):e.jsx("p",{className:"text-xs text-gray-500 italic",children:"No cost breakdown available"})})()]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(jt,{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(Ks,{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(Ws,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:h,onChange:$=>g($.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(Rt,{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:G,disabled:f,className:"border-2 w-full sm:w-auto",children:"Cancel"}),e.jsxs("div",{className:"flex flex-col gap-2 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(O,{onClick:I,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(Ks,{className:"w-4 h-4 mr-2"}),"Request Revised Quotation"]})}),e.jsx(O,{onClick:V,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:L,disabled:!h.trim()||!C||f,className:"bg-green-600 hover:bg-green-700 text-white disabled:opacity-50 disabled:cursor-not-allowed w-full sm:w-auto",title:C?"":"Please block IO budget before approving",children:f&&y==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Approve (Continue to Dept Lead)"]})})]}),!C&&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."})]})]})]}),N&&e.jsx(en,{fileName:N.name,fileType:N.type||"",fileUrl:N.url,fileSize:N.size,attachmentId:N.id,onDownload:Us,open:!!N,onClose:()=>E(null)})]}):null}function r6({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,w=y.startsWith("/")?y:`/${y}`;y=`${v}${w}`}l({fileName:g,fileType:b,documentId:f,fileUrl:y,fileSize:h.sizeBytes})};return e.jsxs(e.Fragment,{children:[e.jsx(gt,{open:t,onOpenChange:s,children:e.jsxs(ht,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs(ft,{className:"px-6 py-4 border-b",children:[e.jsxs(pt,{className:"flex items-center gap-2",children:[o?e.jsx(Pe,{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(jt,{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(Yr,{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(le,{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(Yr,{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?Us: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(Dp,{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(en,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:Us,open:!!i,onClose:()=>l(null)})]})}async function n6(t){var s;try{const a=await we.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 i6(t){var s;try{const a=await we.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 l6(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 we.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 o6(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 we.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 c6(t,s){var a;try{const r=await we.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 nb(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 we.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 d6(t,s){var a;try{const r=await we.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 m6(t){var s;try{const a=await we.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 u6(t,s,a){var r;try{const n={};t&&(n.dateRange=t),s&&(n.startDate=s),a&&(n.endDate=a);const i=await we.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 x6(t){var s;try{const a=await we.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 ln=t=>{if(!t)return"";try{return ys(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}}},h6=t=>{switch(t){case"approved":return e.jsx(He,{className:"w-5 h-5 text-green-600"});case"skipped":return e.jsx(He,{className:"w-5 h-5 text-green-600"});case"pending":return e.jsx(ot,{className:"w-5 h-5 text-blue-600"});case"rejected":return e.jsx(He,{className:"w-5 h-5 text-red-600"});default:return e.jsx(ot,{className:"w-5 h-5 text-gray-400"})}},p6=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"}},g6=(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",f6=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 b6({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i,isSpectator:l=!1}){var Tr,kr,ar,Oa,rr,Qt,Ts,oa,Dr,Rr,ka,nr,It,hs,Js,pa,rn,Da,ir,En,_n,Mn,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,Km,Qm,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,Pu,Eu;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,w]=u.useState(!1),[S,D]=u.useState(null),[k,C]=u.useState(!1),[F,N]=u.useState(null),[E,_]=u.useState([]),[z,R]=u.useState(!1),[L,V]=u.useState(new Set),[I,A]=u.useState(null),[G,$]=u.useState(null),[M,T]=u.useState(!1),[U,H]=u.useState(!1),[W,P]=u.useState([]),[B,K]=u.useState(0);u.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Ve=t.id||t.requestId;try{const Te=await Ls(Ve),he=(Te==null?void 0:Te.approvalLevels)||(Te==null?void 0:Te.approvals)||[];if(he&&he.length>0){const Ce=he.map(ge=>{var Me;return{step:ge.levelNumber||ge.level_number||0,levelNumber:ge.levelNumber||ge.level_number||0,levelName:ge.levelName||ge.level_name,approver:ge.approverName||ge.approver_name||"",approverEmail:(ge.approverEmail||ge.approver_email||"").toLowerCase(),status:((Me=ge.status)==null?void 0:Me.toLowerCase())||"waiting",tatHours:ge.tatHours||ge.tat_hours||24,elapsedHours:ge.elapsedHours||ge.elapsed_hours,approvedAt:ge.actionDate||ge.action_date,comment:ge.comments||ge.comment,levelId:ge.levelId||ge.level_id}}).sort((ge,Me)=>(ge.levelNumber||0)-(Me.levelNumber||0));P(ge=>ge.length!==Ce.length||ge.some((Le,Fe)=>{const Ct=Ce[Fe];return!Ct||Le.levelNumber!==Ct.levelNumber||Le.levelName!==Ct.levelName||Le.approverEmail!==Ct.approverEmail||Le.status!==Ct.status})?Ce:ge)}else P([])}catch(Te){console.warn("Failed to load approval flows from API:",Te),t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&P(t.approvalFlow)}}else t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&P(t.approvalFlow)})()},[t==null?void 0:t.id,t==null?void 0:t.requestId,t==null?void 0:t.totalLevels,B]),u.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const X=t.id||t.requestId;(async()=>{try{const Te=await Ls(X),he=(Te==null?void 0:Te.approvalLevels)||(Te==null?void 0:Te.approvals)||[];if(he&&he.length>0){const Ce=he.map(ge=>{var Me;return{step:ge.levelNumber||ge.level_number||0,levelNumber:ge.levelNumber||ge.level_number||0,levelName:ge.levelName||ge.level_name,approver:ge.approverName||ge.approver_name||"",approverEmail:(ge.approverEmail||ge.approver_email||"").toLowerCase(),status:((Me=ge.status)==null?void 0:Me.toLowerCase())||"waiting",tatHours:ge.tatHours||ge.tat_hours||24,elapsedHours:ge.elapsedHours||ge.elapsed_hours,approvedAt:ge.actionDate||ge.action_date,comment:ge.comments||ge.comment,levelId:ge.levelId||ge.level_id}}).sort((ge,Me)=>(ge.levelNumber||0)-(Me.levelNumber||0));P(Ce)}}catch(Te){console.warn("Failed to load approval flows from API:",Te)}})()}},[t==null?void 0:t.currentStep,t==null?void 0:t.totalLevels]);const Z=async()=>{K(X=>X+1),await new Promise(X=>setTimeout(X,500)),n==null||n(),te()},te=async()=>{if(t!=null&&t.id||t!=null&&t.requestId)try{const Ve=[...await AC(t.id||t.requestId)||[]].sort((Te,he)=>new Date(he.createdAt).getTime()-new Date(Te.createdAt).getTime());_(Ve)}catch(X){console.warn("Failed to load version history:",X)}};u.useEffect(()=>{te()},[t==null?void 0:t.id,t==null?void 0:t.requestId,B]);const ae=(X,Ve,Te)=>{var ge;const he=((t==null?void 0:t.totalLevels)||0)>5||(((ge=t==null?void 0:t.approvalLevels)==null?void 0:ge.length)||0)>5;if(Ve&&Ve.trim()&&(Ve.toLowerCase().includes("additional approver")||!/^step\s+\d+$/i.test(Ve)))return Ve;const Ce=he?{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 Ce[X]?Ce[X]:Te&&Te!=="Unknown"&&Te!=="System"?`Additional Approver - ${Te}`:`Additional Approver - Step ${X}`},xe=(X,Ve,Te)=>{var Me;if(Ve&&Ve.toLowerCase().includes("additional approver"))return Te&&Te!=="Unknown"&&Te!=="System"?`${Te} will review and approve this request as an additional approver.`:"Additional approver will review and approve this request.";const Ce=((t==null?void 0:t.totalLevels)||0)>5||(((Me=t==null?void 0:t.approvalLevels)==null?void 0:Me.length)||0)>5;if(Ve&&Ve.trim()){const Le=Ve.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 ge=Ce?{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 ge[X]?ge[X]:Te&&Te!=="Unknown"&&Te!=="System"?`${Te} will review and approve this request.`:`Step ${X} approval required.`},be=X=>{if(!E||E.length===0||!X)return{current:null,previous:null};const he=[...E.filter(Me=>{var Le;return!!(Me.levelName&&Me.levelName.trim()===X.trim()||(Le=Me.snapshotData)!=null&&Le.levelName&&Me.snapshotData.levelName.trim()===X.trim())})].sort((Me,Le)=>{if(Le.version!==Me.version)return Le.version-Me.version;const Fe=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 Fe-Ct}).filter((Me,Le,Fe)=>Me.snapshotType==="WORKFLOW"?!Fe.some(St=>St.snapshotType==="APPROVE"&&St.levelName===Me.levelName&&St.version>=Me.version):!0),Ce=he.length>0?he[0]:null,ge=he.length>1?he[1]:null;return{current:Ce,previous:ge,all:he}},Ge=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),Be=Ge!=null?Number(Ge):null,_e=((t==null?void 0:t.status)||"").toUpperCase(),Re=_e==="REJECTED",ce=_e==="CLOSED",je=!Re&&!ce&&(_e==="PENDING"||_e==="IN_PROGRESS"||_e==="IN-PROGRESS"),re=W.find(X=>{var he,Ce;const Ve=X.levelId||X.level_id,Te=(he=t==null?void 0:t.approvals)==null?void 0:he.find(ge=>ge.levelId===Ve);return((Ce=Te==null?void 0:Te.status)==null?void 0:Ce.toLowerCase())==="rejected"}),pe=re?Number(re.levelNumber||re.level_number||re.step||0):null,ie=W.map((X,Ve)=>{var Ra,Es,ve,yt,Gt,ws,Tt;const Te=Number(X.levelNumber||X.level_number||X.step||Ve+1),he=X.levelName||X.level_name,Ce=(Ra=t==null?void 0:t.approvals)==null?void 0:Ra.find(Ye=>Ye.levelId===X.levelId);let ge;if(he&&he.toLowerCase().includes("department lead")||Te===3){const Ye=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);(Ye!=null&&Ye.ioNumber||Ye!=null&&Ye.io_number)&&(ge={ioNumber:Ye.ioNumber||Ye.io_number||"",blockedAmount:Ye.ioBlockedAmount||Ye.io_blocked_amount||0,availableBalance:Ye.ioAvailableBalance||Ye.io_available_balance||0,remainingBalance:Ye.ioRemainingBalance||Ye.io_remaining_balance||0,organizedBy:((Es=Ye.organizer)==null?void 0:Es.displayName)||((ve=Ye.organizer)==null?void 0:ve.name)||Ye.organizedBy||X.approver||"N/A",organizedAt:Ye.organizedAt||Ye.organized_at||X.approvedAt||(t==null?void 0:t.updatedAt)||""})}let Le;Te===6&&(Ce!=null&&Ce.dmsDetails?Le={dmsNumber:Ce.dmsDetails.dmsNumber||"",dmsRemarks:Ce.dmsDetails.dmsRemarks||"",pushedBy:Ce.dmsDetails.pushedBy||X.approver,pushedAt:Ce.dmsDetails.pushedAt||X.approvedAt||""}:t!=null&&t.dmsNumber&&(Le={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((yt=t.dmsDetails)==null?void 0:yt.dmsRemarks)||"",pushedBy:X.approver,pushedAt:X.approvedAt||t.updatedAt||""}));let Fe;if(Re||ce)((Gt=Ce==null?void 0:Ce.status)==null?void 0:Gt.toLowerCase())==="rejected"?Fe="rejected":pe!==null&&Te>pe?Fe="waiting":((ws=Ce==null?void 0:Ce.status)==null?void 0:ws.toLowerCase())==="approved"?Fe="approved":pe!==null&&Te<pe?((Tt=Ce==null?void 0:Ce.status)==null?void 0:Tt.toLowerCase())==="approved"?Fe="approved":Fe="waiting":(Be!==null&&Te>Be,Fe="waiting");else if(je&&Be!==null&&Be>0)if(Te>Be)Fe="waiting";else if(Te<Be)if(Ce!=null&&Ce.status){const Ye=Ce.status.toLowerCase();Ye==="approved"?Fe="approved":Ye==="skipped"?Fe="skipped":Ye==="rejected"?Fe="rejected":Fe="waiting"}else Fe="waiting";else if(Ce!=null&&Ce.status){const Ye=Ce.status.toLowerCase();Ye==="approved"?Fe="approved":Ye==="rejected"?Fe="rejected":Fe="in_progress"}else{const Ye=(X.status||"pending").toLowerCase();Ye==="in-review"||Ye==="in_review"||Ye==="in review"||Ye==="pending"?Fe="in_progress":Fe=Ye}else if(Ce!=null&&Ce.status){const Ye=Ce.status.toLowerCase();Ye==="approved"?Fe="approved":Ye==="rejected"?Fe="rejected":Ye==="pending"||Ye==="in_progress"||Ye==="in-progress"?Fe="in_progress":Fe=(X.status||"waiting").toLowerCase()}else{const Ye=(X.status||"waiting").toLowerCase();Ye==="in-review"||Ye==="in_review"||Ye==="in review"||Ye==="pending"?Fe="in_progress":Fe=Ye}const St=Fe==="waiting"?0:X.elapsedHours||0,ks=X.approver||X.approverName||"Unknown",Ft=he?be(he):{current:null,previous:null};return{step:Te,title:ae(Te,he,ks),approver:ks,description:xe(Te,he,ks)||X.description||"",tatHours:X.tatHours||24,status:Fe,comment:X.comment||(Ce==null?void 0:Ce.comment),approvedAt:X.approvedAt||(Ce==null?void 0:Ce.timestamp),elapsedHours:St,ioDetails:ge,dmsDetails:Le,einvoiceUrl:Te===7?Ce==null?void 0:Ce.einvoiceUrl:void 0,emailTemplateUrl:(Ce==null?void 0:Ce.emailTemplateUrl)||void 0,versionHistory:Ft}});let fe=null,Ie=1;if(Re||ce)pe!==null?Ie=pe:Be!==null?Ie=Be:Ie=(t==null?void 0:t.currentStep)||1;else if(je){const X=Be!==null?ie.find(Ve=>Ve.step===Be):null;fe=X&&(X.status==="pending"||X.status==="in_progress")?X:ie.find(Ve=>{var he;const Te=((he=Ve.status)==null?void 0:he.toLowerCase())||"";return Te==="pending"||Te==="in_progress"||Te==="in-review"||Te==="in_review"}),Ie=fe?fe.step:Be||(t==null?void 0:t.currentStep)||1}else Ie=Be||(t==null?void 0:t.currentStep)||1;const $e=((Tr=s==null?void 0:s.email)==null?void 0:Tr.toLowerCase())||"",ye=((kr=t==null?void 0:t.dealerEmail)==null?void 0:kr.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())||((oa=(Ts=t==null?void 0:t.claimDetails)==null?void 0:Ts.dealer_email)==null?void 0:oa.toLowerCase())||"",oe=ye&&$e===ye,ke=W.find(X=>(X.step||X.levelNumber||X.level_number)===Ie),st=((ke==null?void 0:ke.approverEmail)||"").toLowerCase(),at=st&&$e===st,ct=((Rr=(Dr=t==null?void 0:t.initiator)==null?void 0:Dr.email)==null?void 0:Rr.toLowerCase())||((ka=t==null?void 0:t.initiatorEmail)==null?void 0:ka.toLowerCase())||"",Dt=W.find(X=>{const Ve=(X.approverEmail||"").toLowerCase(),Te=(X.levelName||"").toLowerCase();return ct&&Ve===ct||Te.includes("requestor evaluation")||Te.includes("requestor")&&Te.includes("confirmation")}),Q=Dt&&(Dt.step||Dt.levelNumber||Dt.level_number)||2,de=Dt||W.find(X=>(X.step||X.levelNumber||X.level_number)===2),ee=((de==null?void 0:de.approverEmail)||"").toLowerCase(),Ae=ee&&$e===ee,Ue=W.find(X=>(X.step||X.levelNumber||X.level_number)===1),et=((Ue==null?void 0:Ue.approverEmail)||"").toLowerCase(),ze=et&&$e===et,qe=W.find(X=>(X.levelName||"").toLowerCase().includes("department lead")),Ze=((qe==null?void 0:qe.approverEmail)||"").toLowerCase(),nt=Ze&&$e===Ze,rs=async X=>{var Ve,Te;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const he=t.id||t.requestId;X.proposalDocument&&await Xn(X.proposalDocument,he,"APPROVAL");for(const ge of X.otherDocuments)await Xn(ge,he,"SUPPORTING");const Ce=X.costBreakup.reduce((ge,Me)=>ge+(Me.totalAmt||Me.amount||0),0);await l6(he,{proposalDocument:X.proposalDocument||void 0,costBreakup:X.costBreakup.map(ge=>({description:ge.description,amount:ge.amount,gstRate:ge.gstRate,gstAmt:ge.gstAmt,cgstRate:ge.cgstRate,cgstAmt:ge.cgstAmt,sgstRate:ge.sgstRate,sgstAmt:ge.sgstAmt,igstRate:ge.igstRate,igstAmt:ge.igstAmt,utgstRate:ge.utgstRate,utgstAmt:ge.utgstAmt,cessRate:ge.cessRate,cessAmt:ge.cessAmt,totalAmt:ge.totalAmt,quantity:ge.quantity,hsnCode:ge.hsnCode,isService:ge.isService})),totalEstimatedBudget:Ce,expectedCompletionDate:X.expectedCompletionDate,dealerComments:X.dealerComments}),Y.success("Proposal submitted successfully"),Z()}catch(he){console.error("Failed to submit proposal:",he);const Ce=((Te=(Ve=he==null?void 0:he.response)==null?void 0:Ve.data)==null?void 0:Te.message)||(he==null?void 0:he.message)||"Failed to submit proposal. Please try again.";throw Y.error(Ce),he}},Ot=async X=>{var Ve,Te,he,Ce,ge;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 Ls(Me),Fe=(Le==null?void 0:Le.approvalLevels)||(Le==null?void 0:Le.approvals)||[],Ct=((Te=(Ve=t==null?void 0:t.initiator)==null?void 0:Ve.email)==null?void 0:Te.toLowerCase())||((he=t==null?void 0:t.initiatorEmail)==null?void 0:he.toLowerCase())||"",St=Fe.find(Ft=>{const Ra=(Ft.approverEmail||Ft.approver_email||"").toLowerCase(),Es=(Ft.levelName||Ft.level_name||"").toLowerCase(),ve=Ft.levelNumber||Ft.level_number;return Ct&&Ra===Ct||Es.includes("requestor evaluation")||Es.includes("requestor")&&Es.includes("confirmation")||ve===Q})||Fe.find(Ft=>(Ft.levelNumber||Ft.level_number)===2);if(!(St!=null&&St.levelId)&&!(St!=null&&St.level_id))throw new Error("Initiator approval level not found");const ks=St.levelId||St.level_id;await Kn(Me,ks,X),Y.success("Proposal approved successfully"),Z()}catch(Me){console.error("Failed to approve proposal:",Me);const Le=((ge=(Ce=Me==null?void 0:Me.response)==null?void 0:Ce.data)==null?void 0:ge.message)||(Me==null?void 0:Me.message)||"Failed to approve proposal. Please try again.";throw Y.error(Le),Me}},xt=async X=>{var Ve,Te,he,Ce,ge;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 Ls(Me),Fe=(Le==null?void 0:Le.approvalLevels)||(Le==null?void 0:Le.approvals)||[],Ct=((Te=(Ve=t==null?void 0:t.initiator)==null?void 0:Ve.email)==null?void 0:Te.toLowerCase())||((he=t==null?void 0:t.initiatorEmail)==null?void 0:he.toLowerCase())||"",St=Fe.find(Ft=>{const Ra=(Ft.approverEmail||Ft.approver_email||"").toLowerCase(),Es=(Ft.levelName||Ft.level_name||"").toLowerCase(),ve=Ft.levelNumber||Ft.level_number;return Ct&&Ra===Ct||Es.includes("requestor evaluation")||Es.includes("requestor")&&Es.includes("confirmation")||ve===Q})||Fe.find(Ft=>(Ft.levelNumber||Ft.level_number)===2);if(!(St!=null&&St.levelId)&&!(St!=null&&St.level_id))throw new Error("Initiator approval level not found");const ks=St.levelId||St.level_id;await Mr(Me,ks,"Proposal rejected by requestor",X),Y.success("Proposal rejected. Request has been cancelled."),Z()}catch(Me){console.error("Failed to reject proposal:",Me);const Le=((ge=(Ce=Me==null?void 0:Me.response)==null?void 0:Ce.data)==null?void 0:ge.message)||(Me==null?void 0:Me.message)||"Failed to reject proposal. Please try again.";throw Y.error(Le),Me}},bt=async X=>{var Ve,Te,he,Ce,ge;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 Ls(Me),Fe=(Le==null?void 0:Le.approvalLevels)||(Le==null?void 0:Le.approvals)||[],Ct=((Te=(Ve=t==null?void 0:t.initiator)==null?void 0:Ve.email)==null?void 0:Te.toLowerCase())||((he=t==null?void 0:t.initiatorEmail)==null?void 0:he.toLowerCase())||"",St=Fe.find(Ft=>{const Ra=(Ft.approverEmail||Ft.approver_email||"").toLowerCase(),Es=(Ft.levelName||Ft.level_name||"").toLowerCase(),ve=Ft.levelNumber||Ft.level_number;return Ct&&Ra===Ct||Es.includes("requestor evaluation")||Es.includes("requestor")&&Es.includes("confirmation")||ve===Q})||Fe.find(Ft=>(Ft.levelNumber||Ft.level_number)===2);if(!(St!=null&&St.levelId)&&!(St!=null&&St.level_id))throw new Error("Initiator approval level not found");const ks=St.levelId||St.level_id;await Mr(Me,ks,"Revised Quotation Requested",X),Y.success("Revision requested. Request returned to dealer."),Z()}catch(Me){console.error("Failed to request revision:",Me);const Le=((ge=(Ce=Me==null?void 0:Me.response)==null?void 0:Ce.data)==null?void 0:ge.message)||(Me==null?void 0:Me.message)||"Failed to request revision. Please try again.";throw Y.error(Le),Me}},Pt=async X=>{var Ve,Te;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const he=t.id||t.requestId,Ce=await Ls(he),Me=((Ce==null?void 0:Ce.approvalLevels)||(Ce==null?void 0:Ce.approvals)||[]).find(Fe=>{const Ct=(Fe.levelName||Fe.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 Mr(he,Le,"Revised Quotation Requested",X),Y.success("Re-quotation requested. Request returned to dealer."),Z()}catch(he){console.error("Failed to request re-quotation:",he);const Ce=((Te=(Ve=he==null?void 0:he.response)==null?void 0:Ve.data)==null?void 0:Te.message)||(he==null?void 0:he.message)||"Failed to request re-quotation. Please try again.";throw Y.error(Ce),he}},As=async X=>{var Ve,Te;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const he=t.id||t.requestId,Ce=await Ls(he),ge=(Ce==null?void 0:Ce.approvalLevels)||(Ce==null?void 0:Ce.approvals)||[],Me=ge.find(Fe=>(Fe.levelName||Fe.level_name||"").toLowerCase().includes("department lead"))||ge.find(Fe=>(Fe.levelNumber||Fe.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 nb(he,{ioNumber:X.ioNumber}),await Kn(he,Le,X.comments),Y.success("Request approved and IO organized successfully"),Z()}catch(he){console.error("Failed to approve and organize IO:",he);const Ce=((Te=(Ve=he==null?void 0:he.response)==null?void 0:Ve.data)==null?void 0:Te.message)||(he==null?void 0:he.message)||"Failed to approve request. Please try again.";throw Y.error(Ce),he}},ns=async X=>{var Ve,Te;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const he=t.id||t.requestId,Ce=X.closedExpenses.map(ge=>({description:ge.description,amount:ge.amount,gstRate:ge.gstRate,gstAmt:ge.gstAmt,cgstRate:ge.cgstRate,cgstAmt:ge.cgstAmt,sgstRate:ge.sgstRate,sgstAmt:ge.sgstAmt,igstRate:ge.igstRate,igstAmt:ge.igstAmt,utgstRate:ge.utgstRate,utgstAmt:ge.utgstAmt,cessRate:ge.cessRate,cessAmt:ge.cessAmt,totalAmt:ge.totalAmt,quantity:ge.quantity,hsnCode:ge.hsnCode,isService:ge.isService}));if(await o6(he,{activityCompletionDate:X.activityCompletionDate,numberOfParticipants:X.numberOfParticipants,closedExpenses:Ce,totalClosedExpenses:X.totalClosedExpenses,completionDocuments:X.completionDocuments,activityPhotos:X.activityPhotos,completionDescription:X.completionDescription}),X.invoicesReceipts&&X.invoicesReceipts.length>0)for(const ge of X.invoicesReceipts)await Xn(ge,he,"SUPPORTING");X.attendanceSheet&&await Xn(X.attendanceSheet,he,"SUPPORTING"),Y.success("Completion documents submitted successfully"),Z()}catch(he){console.error("Failed to submit completion documents:",he);const Ce=((Te=(Ve=he==null?void 0:he.response)==null?void 0:Ve.data)==null?void 0:Te.message)||(he==null?void 0:he.message)||"Failed to submit completion documents. Please try again.";throw Y.error(Ce),he}},Ya=async X=>{var Ve,Te;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const he=t.id||t.requestId,Ce=new Date().toISOString().slice(0,10);await d6(he,{eInvoiceDate:Ce}),Y.success("E-Invoice generation initiated successfully."),Z()}catch(he){console.error("[DealerClaimWorkflowTab] Error generating e-invoice:",he);let ge=((Te=(Ve=he==null?void 0:he.response)==null?void 0:Ve.data)==null?void 0:Te.message)||(he==null?void 0:he.message)||"E-Invoice generation failed. Please try again.";throw ge.length>300&&(ge=ge.substring(0,300)+"..."),Y.error(ge),he}},Ka=async X=>{var Ve,Te;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const he=t.id||t.requestId,Ce=await Ls(he),ge=(Ce==null?void 0:Ce.approvalLevels)||(Ce==null?void 0:Ce.approvals)||[],Me=ge.find(Fe=>(Fe.levelName||Fe.level_name||"").toLowerCase().includes("department lead"))||ge.find(Fe=>(Fe.levelNumber||Fe.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 Mr(he,Le,"Dept Lead rejected - More clarification required",X),Y.success("Request rejected. Request has been cancelled."),Z()}catch(he){console.error("Failed to reject request:",he);const Ce=((Te=(Ve=he==null?void 0:he.response)==null?void 0:Ve.data)==null?void 0:Te.message)||(he==null?void 0:he.message)||"Failed to reject request. Please try again.";throw Y.error(Ce),he}},[Cr,Aa]=u.useState(null);u.useEffect(()=>{if(!t){Aa(null);return}(async()=>{try{const Ve=t.id||t.requestId;if(!Ve){Aa(null);return}const Te=await Ls(Ve),he=(Te==null?void 0:Te.documents)||[],Ce=t.proposalDetails||(Te==null?void 0:Te.proposalDetails)||{},ge=he.find(Fe=>Fe.category==="APPROVAL"||Fe.type==="proposal"||Fe.documentCategory==="APPROVAL"),Me=he.filter(Fe=>Fe.category==="SUPPORTING"||Fe.type==="supporting"||Fe.documentCategory==="SUPPORTING");let Le=Ce.costBreakup||[];if(typeof Le=="string")try{Le=JSON.parse(Le)}catch(Fe){console.warn("Failed to parse costBreakup JSON:",Fe),Le=[]}Array.isArray(Le)||(Le=[]),Aa({proposalDocument:ge?{name:ge.fileName||ge.file_name||ge.name,id:ge.documentId||ge.document_id||ge.id}:void 0,costBreakup:Le,expectedCompletionDate:Ce.expectedCompletionDate||"",otherDocuments:Me.map(Fe=>({name:Fe.fileName||Fe.file_name||Fe.name,id:Fe.documentId||Fe.document_id||Fe.id})),dealerComments:Ce.dealerComments||"",submittedAt:Ce.submittedAt})}catch(Ve){console.warn("Failed to load proposal data:",Ve);const Te=t.proposalDetails||{};let he=Te.costBreakup||[];if(typeof he=="string")try{he=JSON.parse(he)}catch(Ce){console.warn("Failed to parse costBreakup JSON:",Ce),he=[]}Array.isArray(he)||(he=[]),Aa({proposalDocument:void 0,costBreakup:he,expectedCompletionDate:Te.expectedCompletionDate||"",otherDocuments:[],dealerComments:Te.dealerComments||"",submittedAt:Te.submittedAt})}})()},[t]);const[$t,Ta]=u.useState(null);u.useEffect(()=>{if(!t){Ta(null);return}(async()=>{try{const Ve=t.id||t.requestId;if(!Ve){Ta(null);return}const Te=await Ls(Ve),he=(Te==null?void 0:Te.documents)||[],Ce=[],ge=[],Me=[];let Le=null;he.forEach(Fe=>{const Ct=(Fe.category||Fe.documentCategory||Fe.type||"").toUpperCase(),St=(Fe.fileName||Fe.file_name||Fe.name||"").toLowerCase(),ks={name:Fe.fileName||Fe.file_name||Fe.name,id:Fe.documentId||Fe.document_id||Fe.id,url:Fe.url||Fe.storageUrl||Fe.storage_url};Ct==="COMPLETION"||Ct==="COMPLETION_DOCUMENT"?Ce.push(ks):Ct==="ACTIVITY_PHOTO"||Ct==="PHOTO"||Ct==="IMAGE"?ge.push(ks):Ct==="ATTENDANCE"||Ct==="ATTENDANCE_SHEET"?Le=ks:(Ct==="SUPPORTING"||Ct==="INVOICE"||Ct==="RECEIPT")&&(!Le&&(St.includes("attendance")||St.includes("participant"))?Le=ks:Me.push(ks))}),Ce.length===0&&ge.length===0&&t.completionDetails,Ta({completionDocuments:Ce,activityPhotos:ge,invoicesReceipts:Me,attendanceSheet:Le})}catch(Ve){console.warn("Failed to load completion documents:",Ve),Ta(null)}})()},[t]);const Bs=async()=>{try{Y.loading("Retriggering WFM push...",{id:"wfm-retrigger"}),await x6(t.id),Y.success("WFM push re-triggered successfully",{id:"wfm-retrigger"}),n?n():window.location.reload()}catch(X){console.error("Error retriggering WFM push:",X),Y.error(X.message||"Failed to re-trigger WFM push",{id:"wfm-retrigger"})}},tn=async()=>{try{const X=t.id||t.requestId;if(!X){Y.error("Request ID not found");return}const Te=await fetch(`https://reflow-uat.royalenfield.com/api/v1/dealer-claims/${X}/e-invoice/csv`,{headers:{Authorization:`Bearer ${lt.getAccessToken()||""}`},credentials:"include"});if(!Te.ok)throw new Error("Failed to download CSV");const he=await Te.blob(),Ce=window.URL.createObjectURL(he),ge=document.createElement("a");ge.href=Ce,ge.download=`Invoice_${t.requestNumber||"Export"}.csv`,document.body.appendChild(ge),ge.click(),window.URL.revokeObjectURL(Ce),document.body.removeChild(ge),Y.success("CSV downloaded successfully")}catch(X){console.error("Error downloading CSV:",X),Y.error("Failed to download CSV")}},sn=async()=>{try{const X=t.id||t.requestId;if(!X){Y.error("Request ID not found");return}if(!t.invoice&&!t.irn){Y.error("Invoice not generated yet");return}H(!0),T(!0);const Te=await fetch(`https://reflow-uat.royalenfield.com/api/v1/dealer-claims/${X}/e-invoice/pdf`,{headers:{Authorization:`Bearer ${lt.getAccessToken()||""}`},credentials:"include"});if(!Te.ok)throw new Error("Failed to fetch invoice PDF");const he=await Te.blob(),Ce=window.URL.createObjectURL(he);G&&window.URL.revokeObjectURL(G),$(Ce)}catch(X){console.error("Failed to preview invoice:",X),Y.error("Failed to load invoice preview"),T(!1)}finally{H(!1)}},Sr=()=>{T(!1),G&&(window.URL.revokeObjectURL(G),$(null))},an=()=>{if(G){const X=document.createElement("a");X.href=G,X.download=`Invoice_${t.requestNumber||"Download"}.pdf`,document.body.appendChild(X),X.click(),document.body.removeChild(X),Y.success("Invoice PDF downloaded")}},tr=((nr=t==null?void 0:t.claimDetails)==null?void 0:nr.dealerName)||((It=t==null?void 0:t.dealerInfo)==null?void 0:It.name)||"Dealer",Ar=((hs=t==null?void 0:t.claimDetails)==null?void 0:hs.dealerGstin)||((Js=t==null?void 0:t.dealerInfo)==null?void 0:Js.gstin)||((pa=t==null?void 0:t.dealerInfo)==null?void 0:pa.dealerGSTIN),sr=((rn=t==null?void 0:t.claimDetails)==null?void 0:rn.activityName)||((Da=t==null?void 0:t.activityInfo)==null?void 0:Da.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(q,{children:[e.jsx(me,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(Se,{className:"mt-2",children:"Approval process for dealer claim management"})]})})}),e.jsxs(se,{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(as,{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((X,Ve)=>{var St,ks,Ft,Ra,Es;const he=(((St=X.status)==null?void 0:St.toLowerCase())||"")==="in_progress",Ce=X.step===Ie,ge=je&&he&&Ce,Me=X.status==="approved"||X.status==="skipped",Le=W.find(ve=>(ve.step||ve.levelNumber||ve.level_number)===X.step),Fe=Le!=null&&Le.levelId?(ks=t==null?void 0:t.approvals)==null?void 0:ks.find(ve=>ve.levelId===Le.levelId||ve.level_id===Le.levelId):null,Ct=(Fe==null?void 0:Fe.status)==="PAUSED"||((Ft=t==null?void 0:t.pauseInfo)==null?void 0:Ft.isPaused)&&(((Ra=t==null?void 0:t.pauseInfo)==null?void 0:Ra.levelId)===(Fe==null?void 0:Fe.levelId)||((Es=t==null?void 0:t.pauseInfo)==null?void 0:Es.level_id)===(Fe==null?void 0:Fe.levelId));return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${g6(X.status,ge)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${f6(X.status)}`,children:h6(X.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:X.title}),e.jsx(le,{className:p6(X.status),children:X.status.toLowerCase()}),X.emailTemplateUrl&&X.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:()=>{D({stepNumber:X.step,stepName:X.title}),w(!0)},children:e.jsx(wa,{className:"w-3.5 h-3.5 text-blue-600"})}),X.step===7&&X.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(X.einvoiceUrl,"_blank"),children:e.jsx(kt,{className:"w-3.5 h-3.5 text-green-600"})}),(()=>{const ve=(X.levelName||X.title||"").toLowerCase().includes("requestor claim")||(X.levelName||X.title||"").toLowerCase().includes("requestor - claim"),yt=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&X.status==="approved";return ve&&yt&&e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-amber-100",title:"Preview Invoice",onClick:sn,children:e.jsx(Et,{className:"w-3.5 h-3.5 text-amber-600"})})})(),(()=>{var Tt,Ye,Cs,Wt;const ve=(X.levelName||X.title||"").toLowerCase().includes("requestor claim")||(X.levelName||X.title||"").toLowerCase().includes("requestor - claim"),yt=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&X.status==="approved",Gt=((Tt=t==null?void 0:t.invoice)==null?void 0:Tt.wfmPushStatus)||((Ye=t==null?void 0:t.invoice)==null?void 0:Ye.wfmPushStatus),ws=((Cs=t==null?void 0:t.invoice)==null?void 0:Cs.wfmPushError)||((Wt=t==null?void 0:t.invoice)==null?void 0:Wt.wfmPushError);return ve&&yt&&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:tn,children:e.jsx(Lp,{className:"w-3.5 h-3.5 text-emerald-600"})}),Gt==="SUCCESS"?e.jsx("div",{title:"Pushed to WFM successfully",children:e.jsx(gs,{className:"w-3.5 h-3.5 text-green-500"})}):Gt==="FAILED"?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{title:`WFM Push Failed: ${ws||"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:Bs,children:"Retry Push"})]}):e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{title:"WFM Push Pending",children:e.jsx(ot,{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:Bs,children:"Push Now"})]})]})})()]}),e.jsx("p",{className:"text-sm text-gray-600",children:X.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:X.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",Jt(X.tatHours)]}),X.elapsedHours&&(ge||Me)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",Jt(X.elapsedHours)]})]})]}),X.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:X.comment})}),X.versionHistory&&X.versionHistory.all&&X.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 ve=new Set(L);ve.has(X.step)?ve.delete(X.step):ve.add(X.step),V(ve)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Up,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"font-medium",children:"Version History"}),X.versionHistory.all&&X.versionHistory.all.length>0&&e.jsxs(le,{className:"bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0",children:[X.versionHistory.all.length," Versions"]})]}),L.has(X.step)?e.jsx(Dl,{className:"w-4 h-4"}):e.jsx(Qr,{className:"w-4 h-4"})]}),L.has(X.step)&&X.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:X.versionHistory.all.map((ve,yt)=>{var Gt,ws,Tt,Ye;return e.jsxs("div",{className:`space-y-2 ${yt>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(le,{className:`${yt===0?"bg-amber-500":"bg-gray-400"} text-white text-[10px] px-2 py-0.5`,children:[yt===0?"Current":"Previous",": v",ve.version]}),e.jsx("span",{className:"text-[10px] text-gray-600 font-medium",children:ln(ve.createdAt)})]})}),e.jsx("p",{className:"text-xs text-gray-700 font-medium",children:ve.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${yt===0?"bg-blue-100":"bg-gray-100"} flex items-center justify-center`,children:e.jsx("span",{className:`text-[8px] font-bold ${yt===0?"text-blue-600":"text-gray-600"}`,children:((ws=(Gt=ve.changer)==null?void 0:Gt.displayName)==null?void 0:ws.charAt(0))||"U"})}),e.jsxs("span",{className:"text-[10px] text-gray-600",children:["By ",((Tt=ve.changer)==null?void 0:Tt.displayName)||((Ye=ve.changer)==null?void 0:Ye.email)||"Unknown User"]})]}),ve.snapshotType==="PROPOSAL"&&ve.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(ve.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:()=>A({data:ve.snapshotData,type:"PROPOSAL",title:`Proposal (v${ve.version})`}),children:[e.jsx(wt,{className:"w-3 h-3"}),"View Details"]})]}),ve.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",ve.snapshotData.comments]})]}),ve.snapshotType==="INTERNAL_ORDER"&&ve.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: ",ve.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Blocked Amount: ₹",Number(ve.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),ve.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-[10px] text-gray-600",children:["SAP Doc: ",ve.snapshotData.sapDocumentNumber]})]}),ve.snapshotType==="COMPLETION"&&ve.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(ve.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:()=>A({data:ve.snapshotData,type:"COMPLETION",title:`Completion (v${ve.version})`}),children:[e.jsx(wt,{className:"w-3 h-3"}),"View Details"]})]}),ve.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",ve.snapshotData.comments]})]}),ve.snapshotType==="APPROVE"&&ve.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:[ve.snapshotData.action==="APPROVE"?"Approval":"Rejection"," Snapshot:"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["By: ",ve.snapshotData.approverName||ve.snapshotData.approverEmail||"Unknown"]}),ve.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1",children:["Comments: ",ve.snapshotData.comments.substring(0,100),ve.snapshotData.comments.length>100?"...":""]}),ve.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-[10px] text-red-600 mt-1",children:["Rejection Reason: ",ve.snapshotData.rejectionReason.substring(0,100),ve.snapshotData.rejectionReason.length>100?"...":""]})]}),ve.snapshotType==="WORKFLOW"&&ve.snapshotData&&ve.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:[ve.snapshotData.comments.substring(0,100),ve.snapshotData.comments.length>100?"...":""]})]})]},yt)})})]}),ge&&(Fe==null?void 0:Fe.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:Fe.sla.deadline?_a(Fe.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${Ct?"bg-gray-100 border-gray-300":(Fe.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(Fe.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(Fe.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(ot,{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:Fe.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:[Fe.sla.elapsedText||"0 hours"," / ",Jt(X.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const ve=Fe.sla.percentageUsed||0,yt=()=>Ct?"bg-gray-500":ve>=100?"bg-red-600":ve>=75?"bg-orange-500":ve>=50?"bg-amber-500":"bg-green-600",Gt=()=>Ct?"text-gray-600":ve>=100?"text-red-600":ve>=75?"text-orange-600":ve>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(la,{value:ve,className:"h-3",indicatorClassName:yt()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${Gt()}`,children:["Progress: ",Math.min(100,ve),"% of TAT used"]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[Fe.sla.remainingText||"0 hours"," remaining"]})]})]})})(),Fe.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(ul,{className:"w-4 h-4"}),"Deadline Breached"]}),Fe.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(as,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),(()=>{const ve=X.levelName||X.level_name;return(ve&&ve.toLowerCase().includes("department lead")||X.title&&X.title.toLowerCase().includes("department lead"))&&!oe&&X.status==="approved"&&X.ioDetails&&X.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:X.ioDetails.ioNumber})]}),X.ioDetails.blockedAmount!==void 0&&X.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:["₹",X.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),X.ioDetails.remainingBalance!==void 0&&X.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:["₹",X.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 ",X.ioDetails.organizedBy||X.approver||"N/A"," on"," ",X.ioDetails.organizedAt?ln(X.ioDetails.organizedAt):X.approvedAt?ln(X.approvedAt):"N/A"]})]})]})})(),X.step===6&&X.dmsDetails&&X.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(Vt,{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:X.dmsDetails.dmsNumber})]}),X.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:X.dmsDetails.dmsRemarks})]}),X.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Initiated by ",X.dmsDetails.pushedBy," on"," ",ln(X.dmsDetails.pushedAt)]})]})]}),(()=>{const ve=W.find(Ye=>(Ye.step||Ye.levelNumber||Ye.level_number)===X.step),yt=((ve==null?void 0:ve.approverEmail)||"").toLowerCase(),Gt=yt&&$e===yt,ws=X.step===1||(ve==null?void 0:ve.levelName)&&ve.levelName.toLowerCase().includes("dealer");return ge&&(Gt||ws&&oe)&&!l})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[(()=>{const ve=((Le==null?void 0:Le.levelName)||X.title||"").toLowerCase();return(X.step===1||ve.includes("proposal")||ve.includes("submission"))&&(oe||ze)})()&&e.jsxs(O,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{c(!0)},children:[e.jsx(Ns,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),(()=>{const ve=((Le==null?void 0:Le.levelName)||X.title||"").toLowerCase();return(ve.includes("requestor evaluation")||ve.includes("confirmation")||X.step===Q)&&(a||Ae)})()&&e.jsxs(O,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{m(!0)},children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const ve=W.find(Ye=>(Ye.step||Ye.levelNumber||Ye.level_number)===X.step);if(!((ve==null?void 0:ve.levelName)||X.title||"").toLowerCase().includes("initiator action")||!(a||$e===ct))return null;const Tt=async Ye=>{var Cs,Wt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const _s=t.requestId||t.id;await zg(_s,Ye,{reason:""}),Y.success(`Action "${Ye==="REVISE"?"Revision Requested":"Request Reopened"}" performed successfully`),Z()}catch(_s){console.error("Failed to perform initiator action:",_s);const Ib=((Wt=(Cs=_s==null?void 0:_s.response)==null?void 0:Cs.data)==null?void 0:Wt.message)||(_s==null?void 0:_s.message)||"Failed to perform action";Y.error(Ib)}};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(Pp,{className:"w-4 h-4 mr-2"}),"Reopen"]})]})})(),(()=>{const ve=W.find(Wt=>(Wt.levelName||"").toLowerCase().includes("department lead"));if(!(ve&&X.step===(ve.step||ve.levelNumber||ve.level_number)))return null;const Gt=((ve==null?void 0:ve.approverEmail)||"").toLowerCase();if(!(Gt&&$e===Gt||nt||at))return null;const Tt=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),Ye=(Tt==null?void 0:Tt.ioNumber)||(Tt==null?void 0:Tt.io_number)||(t==null?void 0:t.ioNumber)||"",Cs=Ye&&Ye.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:!Cs,children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Review and Approve"]}),!Cs&&e.jsx("p",{className:"text-xs text-amber-600",children:"Please add an IO number in the IO tab before approving this step."})]})})(),(()=>{const ve=W.find(Ye=>(Ye.step||Ye.levelNumber||Ye.level_number)===X.step),yt=((ve==null?void 0:ve.approverEmail)||"").toLowerCase(),Gt=oe&&yt===ye,ws=((ve==null?void 0:ve.levelName)||X.title||"").toLowerCase(),Tt=ws.includes("dealer completion")||ws.includes("completion documents");return Gt&&Tt})()&&e.jsxs(O,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{g(!0)},children:[e.jsx(Ns,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const ve=W.find(Tt=>{const Ye=(Tt.levelName||"").toLowerCase();return Ye.includes("requestor claim")||Ye.includes("requestor - claim")});if(!(ve&&X.step===(ve.step||ve.levelNumber||ve.level_number)))return null;const Gt=((ve==null?void 0:ve.approverEmail)||"").toLowerCase();return a||Gt&&$e===Gt?e.jsxs(O,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{b(!0)},children:[e.jsx(Vt,{className:"w-4 h-4 mr-2"}),"Generate E-Invoice & Sync"]}):null})(),(()=>{var Cs;const ve=((Le==null?void 0:Le.levelName)||X.title||"").toLowerCase(),yt=ve.includes("credit note")||ve.includes("sap")||X.step===8&&!ve.includes("additional"),Gt=((Le==null?void 0:Le.approverEmail)||"").toLowerCase(),ws=Gt&&$e===Gt,Tt=((Cs=s==null?void 0:s.role)==null?void 0:Cs.toUpperCase())||"";return yt&&(ws||(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 ve=W.find(Tt=>(Tt.step||Tt.levelNumber||Tt.level_number)===X.step),yt=((ve==null?void 0:ve.levelName)||X.title||"").toLowerCase(),Gt=yt.includes("additional approver"),ws=X.step===1||yt.includes("proposal")||yt.includes("submission")||yt.includes("requestor evaluation")||yt.includes("confirmation")||yt.includes("department lead")||yt.includes("dealer completion")||yt.includes("completion documents")||yt.includes("requestor claim")||yt.includes("requestor - claim")||yt.includes("credit note")||yt.includes("sap");if(Gt||!ws){const Tt=(ve==null?void 0:ve.levelId)||(ve==null?void 0:ve.level_id);if(Tt){const Ye=(ve==null?void 0:ve.levelName)||(ve==null?void 0:ve.level_name)||X.title||"Approval Level",Cs=(ve==null?void 0:ve.approverName)||(ve==null?void 0:ve.approver_name)||X.approver||"Approver";return e.jsxs(O,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{N({levelId:Tt,levelName:Ye,approverName:Cs}),C(!0)},children:[e.jsx(He,{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 Ye,Cs;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Wt=t.id||t.requestId;if(!Tt){Y.error("Approval level not found");return}await Kn(Wt,Tt,""),Y.success("Request approved successfully"),Z()}catch(Wt){console.error("Failed to approve:",Wt);const _s=((Cs=(Ye=Wt==null?void 0:Wt.response)==null?void 0:Ye.data)==null?void 0:Cs.message)||(Wt==null?void 0:Wt.message)||"Failed to approve request. Please try again.";Y.error(_s)}},children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(O,{variant:"destructive",onClick:async()=>{var Ye,Cs;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Wt=t.id||t.requestId;if(!Tt){Y.error("Approval level not found");return}const _s=prompt("Please provide a reason for rejection:");if(_s===null)return;await Mr(Wt,Tt,"Request rejected",_s),Y.success("Request rejected successfully"),Z()}catch(Wt){console.error("Failed to reject:",Wt);const _s=((Cs=(Ye=Wt==null?void 0:Wt.response)==null?void 0:Ye.data)==null?void 0:Cs.message)||(Wt==null?void 0:Wt.message)||"Failed to reject request. Please try again.";Y.error(_s)}},children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),X.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",ln(X.approvedAt)]})]})]})},Ve)})})]})]}),e.jsx(q4,{isOpen:o,onClose:()=>c(!1),onSubmit:rs,dealerName:tr,dealerGSTIN:Ar,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=E==null?void 0:E.find(X=>X.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((X,Ve)=>X+Number(Ve.ioBlockedAmount||Ve.io_blocked_amount||Ve.blockedAmount||0),0)}),e.jsx(a6,{isOpen:d,onClose:()=>{m(!1)},onApprove:Ot,onReject:xt,onRequestRevision:bt,proposalData:Cr,dealerName:tr,activityName:sr,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const X=(E==null?void 0:E.filter(Ve=>Ve.snapshotType==="PROPOSAL"))||[];return X.length>1?X[1].snapshotData:null})(),taxationType:(Mn=t==null?void 0:t.claimDetails)==null?void 0:Mn.taxationType}),e.jsx(e6,{isOpen:p,onClose:()=>x(!1),onApprove:As,onReject:Ka,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((tm=t==null?void 0:t.internalOrder)==null?void 0:tm.ioNumber)||((sm=t==null?void 0:t.internalOrder)==null?void 0:sm.io_number)||((am=t==null?void 0:t.internal_order)==null?void 0:am.ioNumber)||((rm=t==null?void 0:t.internal_order)==null?void 0:rm.io_number)||void 0,preFilledBlockedAmount:((nm=t==null?void 0:t.internalOrder)==null?void 0:nm.ioBlockedAmount)||((im=t==null?void 0:t.internalOrder)==null?void 0:im.io_blocked_amount)||((lm=t==null?void 0:t.internal_order)==null?void 0:lm.ioBlockedAmount)||((om=t==null?void 0:t.internal_order)==null?void 0:om.io_blocked_amount)||void 0,preFilledRemainingBalance:((cm=t==null?void 0:t.internalOrder)==null?void 0:cm.ioRemainingBalance)||((dm=t==null?void 0:t.internalOrder)==null?void 0:dm.io_remaining_balance)||((mm=t==null?void 0:t.internal_order)==null?void 0:mm.ioRemainingBalance)||((um=t==null?void 0:t.internal_order)==null?void 0:um.io_remaining_balance)||void 0,taxationType:(xm=t==null?void 0:t.claimDetails)==null?void 0:xm.taxationType}),e.jsx(Z4,{isOpen:h,onClose:()=>g(!1),onSubmit:ns,dealerName:tr,dealerGSTIN:Ar,activityName:sr,defaultGstRate:(hm=t==null?void 0:t.claimDetails)==null?void 0:hm.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i,taxationType:(pm=t==null?void 0:t.claimDetails)==null?void 0:pm.taxationType}),e.jsx(t6,{isOpen:f,onClose:()=>b(!1),onPush:Ya,completionDetails:{activityCompletionDate:((gm=t==null?void 0:t.completionDetails)==null?void 0:gm.activityCompletionDate)||((fm=t==null?void 0:t.completionDetails)==null?void 0:fm.activity_completion_date),numberOfParticipants:((bm=t==null?void 0:t.completionDetails)==null?void 0:bm.numberOfParticipants)||((jm=t==null?void 0:t.completionDetails)==null?void 0:jm.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((ym=t==null?void 0:t.completionDetails)==null?void 0:ym.closedExpenses)||((vm=t==null?void 0:t.completionDetails)==null?void 0:vm.closed_expenses),totalClosedExpenses:((Nm=t==null?void 0:t.budgetTracking)==null?void 0:Nm.closedExpenses)||((wm=t==null?void 0:t.budgetTracking)==null?void 0:wm.closed_expenses)||((Cm=t==null?void 0:t.completionDetails)==null?void 0:Cm.totalClosedExpenses)||((Sm=t==null?void 0:t.completionDetails)==null?void 0:Sm.total_closed_expenses),completionDescription:((Am=t==null?void 0:t.completionDetails)==null?void 0:Am.completionDescription)||((Tm=t==null?void 0:t.completionDetails)==null?void 0:Tm.completion_description)},ioDetails:{ioNumber:((km=t==null?void 0:t.internalOrder)==null?void 0:km.ioNumber)||((Dm=t==null?void 0:t.internalOrder)==null?void 0:Dm.io_number)||((Rm=t==null?void 0:t.internal_order)==null?void 0:Rm.ioNumber)||((Im=t==null?void 0:t.internal_order)==null?void 0:Im.io_number),blockedAmount:((Fm=t==null?void 0:t.internalOrder)==null?void 0:Fm.ioBlockedAmount)||((Pm=t==null?void 0:t.internalOrder)==null?void 0:Pm.io_blocked_amount)||((Em=t==null?void 0:t.internal_order)==null?void 0:Em.ioBlockedAmount)||((_m=t==null?void 0:t.internal_order)==null?void 0:_m.io_blocked_amount),availableBalance:((Mm=t==null?void 0:t.internalOrder)==null?void 0:Mm.ioAvailableBalance)||((Lm=t==null?void 0:t.internalOrder)==null?void 0:Lm.io_available_balance)||((Om=t==null?void 0:t.internal_order)==null?void 0:Om.ioAvailableBalance)||(($m=t==null?void 0:t.internal_order)==null?void 0:$m.io_available_balance),remainingBalance:((Um=t==null?void 0:t.internalOrder)==null?void 0:Um.ioRemainingBalance)||((Bm=t==null?void 0:t.internalOrder)==null?void 0:Bm.io_remaining_balance)||((zm=t==null?void 0:t.internal_order)==null?void 0:zm.ioRemainingBalance)||((Vm=t==null?void 0:t.internal_order)==null?void 0:Vm.io_remaining_balance)},completionDocuments:$t,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:(Wm=t==null?void 0:t.claimDetails)==null?void 0:Wm.taxationType,onReQuotation:Pt}),e.jsx(u4,{isOpen:y,onClose:()=>j(!1),taxationType:(Hm=t==null?void 0:t.claimDetails)==null?void 0:Hm.taxationType,onDownload:async()=>{Y.info("Download functionality will be implemented")},onSendToDealer:async()=>{var X,Ve;try{const Te=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!Te){Y.error("Request ID not found");return}await m6(Te),Y.success("Credit note sent to dealer successfully. Step 8 has been approved."),n&&n()}catch(Te){console.error("Failed to send credit note to dealer:",Te);const he=((Ve=(X=Te==null?void 0:Te.response)==null?void 0:X.data)==null?void 0:Ve.message)||(Te==null?void 0:Te.message)||"Failed to send credit note to dealer";Y.error(he)}},creditNoteData:{creditNoteNumber:((Gm=t==null?void 0:t.creditNote)==null?void 0:Gm.creditNoteNumber)||((Ym=t==null?void 0:t.creditNote)==null?void 0:Ym.credit_note_number)||((Qm=(Km=t==null?void 0:t.claimDetails)==null?void 0:Km.creditNote)==null?void 0:Qm.creditNoteNumber)||((Xm=t==null?void 0:t.claimDetails)==null?void 0:Xm.creditNoteNumber)||((Jm=t==null?void 0:t.claimDetails)==null?void 0:Jm.credit_note_number),creditNoteDate:((Zm=t==null?void 0:t.creditNote)==null?void 0:Zm.creditNoteDate)||((qm=t==null?void 0:t.creditNote)==null?void 0:qm.credit_note_date)||((tu=(eu=t==null?void 0:t.claimDetails)==null?void 0:eu.creditNote)==null?void 0:tu.creditNoteDate)||((su=t==null?void 0:t.claimDetails)==null?void 0:su.creditNoteDate)||((au=t==null?void 0:t.claimDetails)==null?void 0:au.credit_note_date),creditNoteAmount:(ru=t==null?void 0:t.creditNote)!=null&&ru.creditNoteAmount?Number((nu=t==null?void 0:t.creditNote)==null?void 0:nu.creditNoteAmount):(iu=t==null?void 0:t.creditNote)!=null&&iu.credit_note_amount?Number((lu=t==null?void 0:t.creditNote)==null?void 0:lu.credit_note_amount):(cu=(ou=t==null?void 0:t.claimDetails)==null?void 0:ou.creditNote)!=null&&cu.creditNoteAmount?Number((mu=(du=t==null?void 0:t.claimDetails)==null?void 0:du.creditNote)==null?void 0:mu.creditNoteAmount):(uu=t==null?void 0:t.claimDetails)!=null&&uu.creditNoteAmount?Number((xu=t==null?void 0:t.claimDetails)==null?void 0:xu.creditNoteAmount):(hu=t==null?void 0:t.claimDetails)!=null&&hu.credit_note_amount?Number((pu=t==null?void 0:t.claimDetails)==null?void 0:pu.credit_note_amount):void 0,transactionNo:((gu=t==null?void 0:t.creditNote)==null?void 0:gu.transactionNo)||((fu=t==null?void 0:t.creditNote)==null?void 0:fu.transaction_no),tdsAmount:((bu=t==null?void 0:t.creditNote)==null?void 0:bu.tdsAmount)||((ju=t==null?void 0:t.creditNote)==null?void 0:ju.tds_amount),creditAmount:((yu=t==null?void 0:t.creditNote)==null?void 0:yu.creditAmount)||((vu=t==null?void 0:t.creditNote)==null?void 0:vu.credit_amount),items:((Nu=t==null?void 0:t.creditNote)==null?void 0:Nu.items)||[],status:((wu=t==null?void 0:t.creditNote)==null?void 0:wu.status)||((Su=(Cu=t==null?void 0:t.claimDetails)==null?void 0:Cu.creditNote)==null?void 0:Su.status)||((Au=t==null?void 0:t.creditNote)!=null&&Au.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((Tu=t==null?void 0:t.claimDetails)==null?void 0:Tu.dealerName)||((ku=t==null?void 0:t.claimDetails)==null?void 0:ku.dealer_name),dealerCode:((Du=t==null?void 0:t.claimDetails)==null?void 0:Du.dealerCode)||((Ru=t==null?void 0:t.claimDetails)==null?void 0:Ru.dealer_code),dealerEmail:((Iu=t==null?void 0:t.claimDetails)==null?void 0:Iu.dealerEmail)||((Fu=t==null?void 0:t.claimDetails)==null?void 0:Fu.dealer_email)},activityName:((Pu=t==null?void 0:t.claimDetails)==null?void 0:Pu.activityName)||((Eu=t==null?void 0:t.claimDetails)==null?void 0:Eu.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(s6,{isOpen:v,onClose:()=>{w(!1),D(null)},stepNumber:(S==null?void 0:S.stepNumber)||4,stepName:(S==null?void 0:S.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(m4,{isOpen:k,onClose:()=>{C(!1),N(null)},onApprove:async X=>{var Ve,Te;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const he=t.id||t.requestId,Ce=F.levelId;if(!Ce){Y.error("Approval level not found");return}await Kn(he,Ce,X),Y.success("Request approved successfully"),Z(),C(!1),N(null)}catch(he){console.error("Failed to approve:",he);const Ce=((Te=(Ve=he==null?void 0:he.response)==null?void 0:Ve.data)==null?void 0:Te.message)||(he==null?void 0:he.message)||"Failed to approve request. Please try again.";throw Y.error(Ce),he}},onReject:async X=>{var Ve,Te;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const he=t.id||t.requestId,Ce=F.levelId;if(!Ce){Y.error("Approval level not found");return}await Mr(he,Ce,"Request rejected",X),Y.success("Request rejected successfully"),Z(),C(!1),N(null)}catch(he){console.error("Failed to reject:",he);const Ce=((Te=(Ve=he==null?void 0:he.response)==null?void 0:Ve.data)==null?void 0:Te.message)||(he==null?void 0:he.message)||"Failed to reject request. Please try again.";throw Y.error(Ce),he}},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}),E&&E.length>0&&e.jsxs(q,{className:"mt-6 border-amber-100 bg-amber-50/30",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ue,{className:"text-sm font-bold flex items-center gap-2 text-amber-900",children:[e.jsx(Vt,{className:"w-4 h-4"}),"Revision History & Audit Trail"]}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>R(!z),className:"text-amber-700 hover:text-amber-800 hover:bg-amber-100",children:z?"Hide History":"View History"})]}),e.jsx(Se,{className:"text-xs text-amber-700",children:"Records of all revisions and actions taken on this request"})]}),z&&e.jsx(se,{children:e.jsx("div",{className:"space-y-4",children:E.map((X,Ve)=>{var Te,he,Ce,ge;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 ",X.version]}),X.snapshotType&&e.jsx(le,{className:"bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0",children:X.snapshotType}),X.levelNumber&&e.jsxs(le,{className:"bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0",children:["Step ",X.levelNumber]})]}),e.jsx("span",{className:"text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full",children:ln(X.createdAt)})]}),e.jsx("p",{className:"text-xs font-medium text-gray-800",children:X.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:((he=(Te=X.changer)==null?void 0:Te.displayName)==null?void 0:he.charAt(0))||"U"})}),e.jsxs("span",{className:"text-xs text-gray-500",children:["By ",((Ce=X.changer)==null?void 0:Ce.displayName)||((ge=X.changer)==null?void 0:ge.email)||"Unknown User"]})]}),X.snapshotType==="PROPOSAL"&&X.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:"}),X.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:()=>A({data:X.snapshotData,type:"PROPOSAL",title:`Historical Proposal (Version ${X.version})`}),children:["View Details",e.jsx(wt,{className:"w-2 h-2"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Budget: ₹",Number(X.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),X.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",X.snapshotData.comments.substring(0,80),X.snapshotData.comments.length>80?"...":""]})]}),X.snapshotType==="COMPLETION"&&X.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:"}),X.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:()=>A({data:X.snapshotData,type:"COMPLETION",title:`Historical Completion (Version ${X.version})`}),children:["View Details",e.jsx(wt,{className:"w-3 h-3"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Total Expenses: ₹",Number(X.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),X.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",X.snapshotData.comments.substring(0,80),X.snapshotData.comments.length>80?"...":""]})]}),X.snapshotType==="INTERNAL_ORDER"&&X.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: ",X.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-gray-600",children:["Blocked: ₹",Number(X.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),X.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-gray-600",children:["SAP Doc: ",X.snapshotData.sapDocumentNumber]})]}),X.snapshotType==="APPROVE"&&X.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:[X.snapshotData.action==="APPROVE"?"Approval":"Rejection",":"]}),e.jsxs("p",{className:"text-gray-600",children:["By: ",X.snapshotData.approverName||X.snapshotData.approverEmail||"Unknown"]}),X.snapshotData.levelName&&e.jsxs("p",{className:"text-gray-600",children:["Level: ",X.snapshotData.levelName]}),X.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",X.snapshotData.comments.substring(0,80),X.snapshotData.comments.length>80?"...":""]}),X.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-red-600 mt-1",children:["Rejection Reason: ",X.snapshotData.rejectionReason.substring(0,80),X.snapshotData.rejectionReason.length>80?"...":""]})]}),X.snapshotType==="WORKFLOW"&&X.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: ",X.snapshotData.status||"N/A"]}),X.snapshotData.currentLevel&&e.jsxs("p",{className:"text-gray-600",children:["Current Level: ",X.snapshotData.currentLevel]})]})]})]},X.historyId||Ve)})})})]}),e.jsx(r6,{isOpen:!!I,onClose:()=>A(null),snapshot:I==null?void 0:I.data,type:(I==null?void 0:I.type)||"PROPOSAL",title:I==null?void 0:I.title}),M&&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:Sr}),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(le,{className:"bg-amber-100 text-amber-800 text-xs",children:t.requestNumber})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[G&&e.jsxs(O,{variant:"outline",size:"sm",onClick:an,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:Sr,className:"h-8 w-8 hover:bg-gray-200",children:e.jsx(Nt,{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(We,{className:"w-8 h-8 text-amber-600 animate-spin"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading invoice..."})]}):G?e.jsx("iframe",{src:G,className:"w-full h-full border-0",title:"Invoice PDF Preview"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Failed to load invoice"})})})]})]})]})}function j6({request:t,apiRequest:s,onRefresh:a,isSpectator:r=!1}){const{user:n}=xs(),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 z=(l==null?void 0:l.costBreakup)||(o==null?void 0:o.costBreakup)||[],R=Array.isArray(z)?z:typeof z=="string"?JSON.parse(z):[];return!Array.isArray(R)||R.length===0?Number((o==null?void 0:o.totalProposedTaxableAmount)||(l==null?void 0:l.totalEstimatedBudget)||(l==null?void 0:l.total_estimated_budget)||0):R.reduce((L,V)=>{const I=typeof V=="object"&&V.amount||0,A=typeof V=="object"&&V.quantity||1;return L+Number(I)*Number(A)},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((z,R)=>z+Number(R.ioBlockedAmount||R.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,w]=u.useState(null),[S,D]=u.useState(""),[k,C]=u.useState([]),[F,N]=u.useState(!1);u.useEffect(()=>{if(x.length>0){const z=x.map(R=>{const L=R.organizer||null,V=(L==null?void 0:L.displayName)||(L==null?void 0:L.display_name)||(L==null?void 0:L.name)||(L!=null&&L.firstName&&(L!=null&&L.lastName)?`${L.firstName} ${L.lastName}`.trim():null)||(L==null?void 0:L.email)||"Unknown User";return{ioNumber:R.ioNumber||R.io_number,blockedAmount:Number(R.ioBlockedAmount||R.io_blocked_amount||0),availableBalance:Number(R.ioAvailableBalance||R.io_available_balance||0),remainingBalance:Number(R.ioRemainingBalance||R.io_remaining_balance||0),blockedDate:R.organizedAt||R.organized_at||new Date().toISOString(),blockedBy:V,sapDocumentNumber:R.sapDocumentNumber||R.sap_document_number||"",status:R.status==="BLOCKED"?"blocked":R.status==="RELEASED"?"released":R.status==="PENDING"?"pending":"blocked"}});C(z),!g&&z.length>0&&b(z[z.length-1].ioNumber)}},[s,t,g,x]);const E=async()=>{var z,R;if(!f.trim()){Y.error("Please enter an IO number");return}if(!i){Y.error("Request ID not found");return}j(!0);try{const L=await c6(i,f.trim());if(L.isValid&&L.availableBalance>0){w(L.availableBalance);const V=k.reduce((A,G)=>A+G.blockedAmount,0),I=Math.max(0,d-V);I>0?D(String(I.toFixed(2))):d>0&&V===0?D(String(d.toFixed(2))):D(String(L.availableBalance.toFixed(2))),Y.success(`IO fetched from SAP. Available balance: ₹${L.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)}else Y.error("Invalid IO number or no available balance found"),w(null),D("")}catch(L){console.error("Failed to fetch IO budget:",L);const V=((R=(z=L==null?void 0:L.response)==null?void 0:z.data)==null?void 0:R.message)||(L==null?void 0:L.message)||"Failed to validate IO number or fetch budget from SAP";Y.error(V),w(null)}finally{j(!1)}},_=async()=>{var I,A;if(!f.trim()||v===null){Y.error("Please fetch IO amount first");return}if(!i){Y.error("Request ID not found");return}const z=parseFloat(S);if(!S||isNaN(z)||z<=0){Y.error("Please enter a valid amount to block");return}const R=parseFloat(z.toFixed(2));if(R>v){Y.error("Amount to block exceeds available IO budget");return}const V=k.reduce((G,$)=>G+$.blockedAmount,0)+R;if(d>0){const G=parseFloat(d.toFixed(2)),$=parseFloat(V.toFixed(2));if(Math.abs($-G)>.01){Y.error(`Total blocked amount (₹${$.toLocaleString("en-IN")}) must be exactly equal to the estimated budget (₹${G.toLocaleString("en-IN")})`);return}}N(!0);try{const G=parseFloat(v.toFixed(2)),$=parseFloat((G-R).toFixed(2)),M={ioNumber:f.trim(),ioAvailableBalance:G,ioBlockedAmount:R,ioRemainingBalance:$};await nb(i,M);const T=await i6(i),U=(T==null?void 0:T.internalOrder)||(T==null?void 0:T.internal_order);if(U){const H=Number(U.ioBlockedAmount||U.io_blocked_amount||R),W=Number(U.ioRemainingBalance||U.io_remaining_balance||0),P=v-H;Math.abs(H-R)>.01&&console.warn("[IOTab] ⚠️ Amount mismatch! Sent:",R,"Saved:",H),Math.abs(W-P)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:v,blockedAmount:H,expectedRemaining:P,backendRemaining:W,difference:W-P});const B=n,K=(B==null?void 0:B.displayName)||(B==null?void 0:B.display_name)||(B==null?void 0:B.name)||(B!=null&&B.firstName&&(B!=null&&B.lastName)?`${B.firstName} ${B.lastName}`.trim():null)||(B==null?void 0:B.email)||"Current User",Z={ioNumber:U.ioNumber||U.io_number||f,blockedAmount:H,availableBalance:v,remainingBalance:W,blockedDate:U.organizedAt||U.organized_at||new Date().toISOString(),blockedBy:K,sapDocumentNumber:U.sapDocumentNumber||U.sap_document_number||"",status:"blocked"};C(te=>[...te,Z]),D(""),w(null),Y.success("IO budget blocked successfully in SAP"),a==null||a()}else Y.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(G){console.error("Failed to block IO budget:",G);const $=((A=(I=G==null?void 0:G.response)==null?void 0:I.data)==null?void 0:A.message)||(G==null?void 0:G.message)||"Failed to block IO budget in SAP";Y.error($)}finally{N(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(Se,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ee,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:f,onChange:z=>b(z.target.value),disabled:y||k.length>0&&!g||r,className:"flex-1"}),e.jsxs(O,{onClick:E,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(He,{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(ne,{htmlFor:"blockAmount",children:"Amount to Block *"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",children:"₹"}),e.jsx(Ee,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:S,onChange:z=>{const R=z.target.value;if(parseFloat(R)<0){Y.error("Amount cannot be negative");return}D(R)},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||!S||parseFloat(S)<=0||parseFloat(S)>v||d>0&&Math.abs(k.reduce((z,R)=>z+R.blockedAmount,0)+parseFloat(S)-d)>.01||r,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(ss,{className:"w-4 h-4 mr-2"}),F?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(He,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(Se,{children:"Details of IO blocked in SAP system"})]}),e.jsx(se,{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(tt,{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((z,R)=>z+R.blockedAmount,0)).toLocaleString("en-IN",{minimumFractionDigits:2}),"."]})]})]})}),k.slice().reverse().map((z,R)=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:`p-3 flex justify-between items-center ${R===0?"bg-green-50":"bg-gray-50"}`,children:[e.jsxs("span",{className:"font-semibold text-sm",children:["IO: ",z.ioNumber]}),e.jsx(le,{className:z.status==="blocked"?"bg-green-100 text-green-800":z.status==="pending"?"bg-amber-100 text-amber-800":"bg-blue-100 text-blue-800",children:z.status==="blocked"?"Blocked":z.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:["₹",z.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:z.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:z.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(z.blockedDate).toLocaleString()})]})]})]},R)),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((z,R)=>z+R.blockedAmount,0).toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Fa,{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 y6(t){var s,a,r;try{const n=await we.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 v6(t){var s;try{const a=await we.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 N6({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}=k0(),[h,g]=u.useState(!1),[f,b]=u.useState(""),[y,j]=u.useState(24),[v,w]=u.useState("hours"),[S,D]=u.useState(3),[k,C]=u.useState([]),[F,N]=u.useState(!1),[E,_]=u.useState(null),z=u.useRef(null),R=()=>{const P=t.approvers||[],B=[];return qs.forEach(K=>{if(K.isAuto||K.approverType==="dealer"||K.approverType==="initiator")return;const Z=P.find(te=>te.level===K.level);(!Z||!Z.email||!Z.userId||!Z.tat)&&B.push(`${K.name}`)}),{isValid:B.length===0,missingSteps:B}};u.useEffect(()=>{if(l){const P=R();l(P.isValid)}},[t.approvers]),u.useEffect(()=>{const P=t.approvers||[];if(P.length>0){const B=[],K=P.filter(te=>te.isAdditional);qs.forEach(te=>{const ae=P.find(xe=>xe.originalStepLevel===te.level||!xe.originalStepLevel&&!xe.isAdditional&&xe.level===te.level);if(ae)B.push(ae);else if(te.isAuto){const xe=te.level===8?"finance@royalenfield.com":"system@royalenfield.com",be=te.level===8?"System/Finance":"System";B.push({email:xe,name:be,level:te.level,tat:te.defaultTat,tatType:"hours",originalStepLevel:te.level})}else te.approverType==="dealer"?B.push({email:t.dealerEmail||"",name:t.dealerName||"",level:te.level,tat:te.defaultTat,tatType:"hours",originalStepLevel:te.level}):te.approverType==="initiator"?B.push({email:r||"",name:i||r||"User",userId:n,level:te.level,tat:te.defaultTat,tatType:"hours",originalStepLevel:te.level}):B.push({email:"",name:"",level:te.level,tat:te.defaultTat,tatType:"hours",originalStepLevel:te.level})}),K.forEach(te=>{B.push(te)}),B.sort((te,ae)=>te.level-ae.level),JSON.stringify(P.map(te=>({level:te.level,originalStepLevel:te.originalStepLevel})))!==JSON.stringify(B.map(te=>({level:te.level,originalStepLevel:te.originalStepLevel})))&&s("approvers",B)}else{const B=[];qs.forEach(K=>{K.isAuto||(K.approverType==="dealer"?B.push({email:t.dealerEmail||"",name:t.dealerName||"",level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level}):K.approverType==="initiator"?B.push({email:r||"",name:i||r||"User",userId:n,level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level}):B.push({email:"",name:"",level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level}))}),s("approvers",B)}},[t.dealerEmail,t.dealerName,r,n,i]);const L=(P,B)=>{const K=[...t.approvers||[]],Z=K.findIndex(te=>te.originalStepLevel===P||!te.originalStepLevel&&te.level===P&&!te.isAdditional);if(Z===-1){const te=qs.find(ae=>ae.level===P);K.push({email:B,name:"",level:P,tat:(te==null?void 0:te.defaultTat)||48,tatType:"hours",originalStepLevel:P})}else{const te=K[Z];if(te){const ae=te.email;K[Z]={...te,email:B,name:B!==ae?"":te.name,userId:B!==ae?void 0:te.userId}}}if(s("approvers",K),!B||!B.startsWith("@")||B.length<2){x(P-1);return}p(P-1,B,10)},V=async(P,B)=>{var K,Z;try{const te=qs.find(_e=>_e.level===P);if(te&&!te.isAuto&&te.approverType!=="initiator"&&((K=B.email)==null?void 0:K.toLowerCase())===(r==null?void 0:r.toLowerCase())){Y.error(`You cannot assign yourself as ${te.name} approver.`),a&&a({type:"self-assign",email:B.email,message:`You cannot assign yourself as ${te.name} approver.`});return}if((t.approvers||[]).some(_e=>{var Re,ce;return _e.level!==P&&(_e.userId===B.userId||((Re=_e.email)==null?void 0:Re.toLowerCase())===((ce=B.email)==null?void 0:ce.toLowerCase()))})){Y.error("This user is already assigned to another step."),a&&a({type:"error",email:B.email,message:"This user is already assigned to another step."});return}const be=await Na({userId:B.userId,email:B.email,displayName:B.displayName,firstName:B.firstName,lastName:B.lastName,department:B.department,phone:B.phone,mobilePhone:B.mobilePhone,designation:B.designation,jobTitle:B.jobTitle,manager:B.manager,employeeId:B.employeeId,employeeNumber:B.employeeNumber,secondEmail:B.secondEmail,location:B.location}),Ge=[...t.approvers||[]],Be=Ge.findIndex(_e=>_e.originalStepLevel===P||!_e.originalStepLevel&&_e.level===P&&!_e.isAdditional);if(Be===-1){const _e=qs.find(Re=>Re.level===P);Ge.push({email:B.email,name:B.displayName||[B.firstName,B.lastName].filter(Boolean).join(" "),userId:be.userId,level:P,tat:(_e==null?void 0:_e.defaultTat)||48,tatType:"hours",originalStepLevel:P})}else{const _e=Ge[Be];_e&&(Ge[Be]={..._e,email:B.email,name:B.displayName||[B.firstName,B.lastName].filter(Boolean).join(" "),userId:be.userId,originalStepLevel:_e.originalStepLevel||P})}s("approvers",Ge),x(P-1),Y.success(`Approver for ${(Z=qs.find(_e=>_e.level===P))==null?void 0:Z.name} selected successfully.`)}catch(te){console.error("Failed to ensure user exists:",te),Y.error("Failed to validate user. Please try again."),a&&a({type:"error",email:B.email,message:"Failed to validate user. Please try again."})}},I=(P,B)=>{const K=[...t.approvers||[]],Z=K.findIndex(te=>te.originalStepLevel===P||!te.originalStepLevel&&te.level===P&&!te.isAdditional);if(Z!==-1){const te=K[Z];te&&(K[Z]={...te,tat:B},s("approvers",K))}},A=(P,B)=>{const K=[...t.approvers||[]],Z=K.findIndex(te=>te.originalStepLevel===P||!te.originalStepLevel&&te.level===P&&!te.isAdditional);if(Z!==-1){const te=K[Z];te&&(K[Z]={...te,tatType:B,tat:""},s("approvers",K))}},G=P=>{if(b(P),E&&E.email.toLowerCase()!==P.toLowerCase()&&_(null),z.current&&clearTimeout(z.current),!P||!P.startsWith("@")||P.length<2){C([]),N(!1);return}N(!0),z.current=setTimeout(async()=>{var B;try{const K=P.slice(1),te=((B=(await Ca(K,10)).data)==null?void 0:B.data)||[];C(te)}catch(K){console.error("Search failed:",K),C([])}finally{N(!1)}},300)},$=async P=>{try{await Na({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}),b(P.email),_(P),C([]),N(!1)}catch(B){console.error("Failed to ensure user exists:",B),Y.error("Failed to verify user. Please try again.")}},M=async()=>{var Re,ce;const P=f.trim().toLowerCase();if(!P){Y.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(P)){Y.error("Please enter a valid email address");return}const K=typeof y=="string"?Number(y):y;if(!K||K<=0||isNaN(K)){Y.error("Please enter valid TAT (minimum 1)");return}const Z=v==="days"?30:720;if((v==="days"?K*24:K)>720){Y.error(`TAT cannot exceed ${Z} ${v==="days"?"days":"hours"}`);return}const ae=qs.find(je=>je.name==="Requestor Claim Approval");if(ae&&S>=ae.level){Y.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if(P===(r==null?void 0:r.toLowerCase())){Y.error("You cannot add yourself as an additional approver.");return}const xe=t.approvers||[];if(xe.some(je=>{var re;return je.userId&&(E==null?void 0:E.userId)&&je.userId===E.userId||((re=je.email)==null?void 0:re.toLowerCase())===P})){Y.error("This user is already assigned as an approver.");return}const Ge=xe.find(je=>je.originalStepLevel===S||!je.originalStepLevel&&!je.isAdditional&&je.level===S),_e=(Ge?Ge.level:S)+1;if(o){const re=new Set(xe.map(pe=>pe.level)).size+1;if(re>o){const pe=[{type:"max_approval_levels",message:`Adding this approver would create ${re} approval levels, which exceeds the maximum allowed (${o}). Please remove some approvers before adding a new one.`,currentValue:re,maxValue:o}];c?c(pe):Y.error(((Re=pe[0])==null?void 0:Re.message)||"Maximum approval levels exceeded");return}}if(!E||E.email.toLowerCase()!==P)try{const re=((ce=(await Ca(P,1)).data)==null?void 0:ce.data)||[];if(re.length===0){Y.error("User not found in organization directory. Please use @ to search for users.");return}const pe=re[0];await Na({userId:pe.userId,email:pe.email,displayName:pe.displayName,firstName:pe.firstName,lastName:pe.lastName,department:pe.department,phone:pe.phone,mobilePhone:pe.mobilePhone,designation:pe.designation,jobTitle:pe.jobTitle,manager:pe.manager,employeeId:pe.employeeId,employeeNumber:pe.employeeNumber,secondEmail:pe.secondEmail,location:pe.location});const ie={email:pe.email,name:pe.displayName||[pe.firstName,pe.lastName].filter(Boolean).join(" "),userId:pe.userId,level:_e,tat:typeof y=="string"?Number(y):y,tatType:v,isAdditional:!0,insertAfterLevel:S,stepName:`Additional Approver - ${pe.displayName||pe.email}`},fe=xe.map(Ie=>Ie.level>=_e?{...Ie,level:Ie.level+1}:Ie);fe.push(ie),fe.sort((Ie,$e)=>Ie.level-$e.level),s("approvers",fe),Y.success("Additional approver added and subsequent steps shifted")}catch(je){console.error("Failed to validate approver:",je),Y.error("Failed to validate user. Please try again.");return}else{const je={email:E.email,name:E.displayName||[E.firstName,E.lastName].filter(Boolean).join(" "),userId:E.userId,level:_e,tat:y,tatType:v,isAdditional:!0,insertAfterLevel:S,stepName:`Additional Approver - ${E.displayName||E.email}`},re=xe.map(pe=>pe.level>=_e?{...pe,level:pe.level+1}:pe);re.push(je),re.sort((pe,ie)=>pe.level-ie.level),s("approvers",re),Y.success("Additional approver added and subsequent steps shifted")}b(""),j(24),w("hours"),D(3),_(null),C([]),g(!1)},T=P=>{const B=[...t.approvers||[]];if(!B.find(ae=>ae.level===P))return;const te=B.filter(ae=>ae.level!==P).map(ae=>ae.level>P&&!ae.isAdditional?{...ae,level:ae.level-1}:ae);te.sort((ae,xe)=>ae.level-xe.level),s("approvers",te),Y.success("Additional approver removed and subsequent steps shifted back")},U=()=>[...t.approvers||[]].sort((B,K)=>B.level-K.level),H=t.approvers||[],W=U();return e.jsxs(Yt.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(es,{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(q,{className:"border-2 border-blue-200 bg-blue-50",children:e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(Zr,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsxs(Se,{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 P=t.approvers||[],K=new Set(P.map(Z=>Z.level)).size;return K>0?e.jsxs("span",{children:[" (",K,"/",o,")"]}):null})()]})]})]})}),e.jsxs(q,{className:"border-2",children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx(Se,{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(se,{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 P=t.approvers||[],K=new Set(P.map(Z=>Z.level)).size;return K>0?e.jsxs("span",{children:[" (",K,"/",o,")"]}):null})()]}),e.jsxs(O,{type:"button",variant:"outline",onClick:()=>g(!0),className:"flex items-center gap-2",children:[e.jsx(os,{className:"w-4 h-4"}),"Add Additional Approver"]})]}),e.jsx("div",{className:"p-3 rounded-lg border-2 border-blue-200 bg-blue-50",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center flex-shrink-0",children:e.jsx(Ht,{className:"w-4 h-4 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-blue-900 text-sm",children:"Request Initiator"}),e.jsx(le,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-xs text-blue-700",children:"Creates and submits the request"})]})]})}),(()=>{const P=W.filter(K=>K.isAdditional&&K.insertAfterLevel===0);let B=P.length;return qs.filter(K=>!K.isAuto).map((K,Z,te)=>{const ae=H.find(Re=>Re.originalStepLevel===K.level||!Re.originalStepLevel&&Re.level===K.level&&!Re.isAdditional)||{email:"",name:"",level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level},xe=Z===te.length-1,be=K.isAuto||K.approverType==="dealer"||K.approverType==="initiator",Ge=!K.isAuto,Be=W.filter(Re=>Re.isAdditional&&Re.insertAfterLevel===K.level).sort((Re,ce)=>Re.level-ce.level),_e=B+1;return B++,B+=Be.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"})}),Z===0&&P.map((Re,ce)=>{const je=ce+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:je})}),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(le,{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:()=>T(Re.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(Nt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:Re.name||Re.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",Re.email]}),e.jsxs("div",{children:["TAT: ",Re.tat," ",Re.tatType]})]})]})]})})]},`additional-${Re.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${ae.email&&ae.userId?"border-green-200 bg-green-50":be?"border-blue-200 bg-blue-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${ae.email&&ae.userId?"bg-green-600":be?"bg-blue-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold text-sm",children:_e})}),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:K.name}),xe&&e.jsx(le,{variant:"destructive",className:"text-xs",children:"FINAL"}),be&&e.jsx(le,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:K.description}),Ge&&(()=>{var je,re;const Re=!!(ae.email&&ae.userId),ce=!ae.email&&!be;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(ne,{htmlFor:`approver-${K.level}`,className:`text-xs font-bold ${ce?"text-blue-900":Re?"text-green-900":"text-gray-900"}`,children:["Approver Email ",!be&&"*",ce&&e.jsx("span",{className:"ml-2 text-[10px] font-semibold italic text-blue-600",children:"(Required)"})]}),Re&&e.jsxs(le,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(He,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ee,{id:`approver-${K.level}`,type:"text",placeholder:be?ae.email:"@username or email...",value:ae.email||"",onChange:pe=>{const ie=pe.target.value;be||L(K.level,ie)},disabled:be||K.isAuto,className:`h-9 border-2 transition-all mt-1 w-full text-sm ${be?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":Re?"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"}`}),!be&&!K.isAuto&&(m[K.level-1]||(((je=d[K.level-1])==null?void 0:je.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[K.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:(re=d[K.level-1])==null?void 0:re.map(pe=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>V(K.level,pe),children:[e.jsx("div",{className:"font-medium text-gray-900",children:pe.displayName||pe.email}),e.jsx("div",{className:"text-xs text-gray-600",children:pe.email}),pe.department&&e.jsx("div",{className:"text-xs text-gray-500",children:pe.department})]},pe.userId))})})]}),ae.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:ae.name})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:`tat-${K.level}`,className:`text-xs font-bold ${ce?"text-blue-900":Re?"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(Ee,{id:`tat-${K.level}`,type:"number",placeholder:ae.tatType==="days"?"7":"24",min:"1",max:ae.tatType==="days"?"30":"720",value:ae.tat||"",onChange:pe=>I(K.level,parseInt(pe.target.value)||""),disabled:K.isAuto,className:`h-9 border-2 transition-all flex-1 text-sm ${be?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":Re?"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(Ke,{value:ae.tatType||"hours",onValueChange:pe=>A(K.level,pe),disabled:K.isAuto,children:[e.jsx(Xe,{className:`w-20 h-9 border-2 transition-all text-sm ${be?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed":Re?"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(Qe,{})}),e.jsxs(Je,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{value:"days",children:"Days"})]})]})]})]})]})})()]})]})}),Be.map((Re,ce)=>{const je=_e+ce+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:je})}),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:Re.stepName||"Additional Approver"}),e.jsx(le,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),Re.email&&Re.userId&&e.jsxs(le,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(He,{className:"w-3 h-3 mr-1"}),"Verified"]}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",onClick:()=>T(Re.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(Nt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:Re.name||Re.email||"No approver assigned"}),Re.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",Re.email]}),Re.tat&&e.jsxs("div",{children:["TAT: ",Re.tat," ",Re.tatType]})]})]})]})})]},`additional-${Re.level}`)})]},K.level)})})()]})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3",children:W.map(P=>{const B=P.originalStepLevel?qs.find(ae=>ae.level===P.originalStepLevel):qs.find(ae=>ae.level===P.level&&!P.isAdditional);if(B!=null&&B.isAuto)return null;const K=Number(P.tat||0),te=(P.tatType||"hours")==="days"?K*24:K;if(!K)return null;if(P.isAdditional){const ae=qs.find(xe=>xe.level===P.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:P.stepName||`Additional Approver (after "${(ae==null?void 0:ae.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[te," hours"]})]},P.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:(B==null?void 0:B.name)||"Unknown"}),e.jsxs("span",{className:"text-sm text-gray-600",children:[te," hours"]})]},P.level)})})})]})]}),e.jsx(gt,{open:h,onOpenChange:g,children:e.jsxs(ht,{className:"sm:max-w-md",children:[e.jsxs(ft,{children:[e.jsxs(pt,{className:"flex items-center gap-2",children:[e.jsx(os,{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(ne,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(Ke,{value:S.toString(),onValueChange:P=>D(Number(P)),children:[e.jsx(Xe,{className:"h-11 border-gray-300",children:e.jsx(Qe,{placeholder:"Select step"})}),e.jsx(Je,{children:qs.filter(P=>{if(P.isAuto)return!1;const B=qs.find(K=>K.name==="Requestor Claim Approval");return!(B&&P.level>=B.level)}).map(P=>e.jsx(J,{value:P.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:P.name})]})},P.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 P=t.approvers||[],K=new Set(P.map(Z=>Z.level)).size;return K>0?e.jsxs("span",{children:[" (",K,"/",o,")"]}):null})()]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ee,{type:"number",min:"1",max:v==="days"?"30":"720",value:y,onChange:P=>{const B=P.target.value;if(B==="")j("");else{const K=Number(B);!isNaN(K)&&K>=0&&j(K)}},onBlur:P=>{const B=P.target.value;(!B||B===""||Number(B)<=0)&&j(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(Ke,{value:v,onValueChange:P=>w(P),children:[e.jsx(Xe,{className:"w-24 h-11 border-gray-300",children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{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(ne,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(_l,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ee,{type:"text",placeholder:"@username or user@example.com",value:f,onChange:P=>G(P.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(P=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>$(P),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:P.displayName||[P.firstName,P.lastName].filter(Boolean).join(" ")||P.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:P.email}),P.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:P.designation})]})})},P.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(Rt,{children:[e.jsx(O,{type:"button",variant:"outline",onClick:()=>{g(!1),b(""),j(24),w("hours"),D(3),_(null),C([])},className:"flex-1",children:"Cancel"}),e.jsxs(O,{type:"button",onClick:M,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!f.trim()||!y,children:[e.jsx(os,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const Lo=[{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"}],Oo=["Claim Details","Approver Selection","Review & Submit"];function w6({onBack:t,onSubmit:s}){const{user:a}=xs(),[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,w]=u.useState({open:!1,violations:[]}),[S,D]=u.useState([]),[k,C]=u.useState(!0);u.useEffect(()=>{(async()=>{try{C(!0);const T=await IT();D(T)}catch(T){console.error("Failed to load activity types:",T),Y.error("Failed to load activity types. Please refresh the page.")}finally{C(!1)}})()},[]),u.useEffect(()=>{(async()=>{var T;try{const U=await ha("SYSTEM_SETTINGS"),H=await ha("WORKFLOW_SHARING"),W=[...U,...H],P={};W.forEach(B=>{P[B.configKey]=B.configValue}),j({maxApprovalLevels:parseInt(P.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(P.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((T=P.ALLOW_ADD_SPECTATOR)==null?void 0:T.toLowerCase())==="true",maxSpectators:parseInt(P.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(U){console.error("Failed to load system policy:",U)}})()},[]),u.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const[F,N]=u.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",dealerItemGroup:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),E=Oo.length,_=M=>{if(x(M),h.current&&clearTimeout(h.current),!M||M.trim().length<2){c([]),m(!1);return}m(!0),h.current=setTimeout(async()=>{try{const T=await v6(M);if(T){const U={dealerId:T.dealer||T.dealer_code||M,dealerCode:T.dealer||T.dealer_code||M,dealerName:T["dealer name"]||T.dealer_name||"Unknown Dealer",displayName:T["dealer name"]||T.dealer_name||"Unknown Dealer",email:T["dealer email"]||"",phone:T["dealer phone"]||"",city:T["re city"]||T.city||"",state:T["re state code"]||T.state||"",isLoggedIn:!0,parentCode:T.parentcode||null,itemGroup:T["item group"]||null};c([U])}else c([])}catch(T){console.error("Error searching external dealer:",T),c([])}finally{m(!1)}},300)},z=(M,T)=>{N(U=>{const H={...U,[M]:T};if(M==="periodStartDate")T&&H.periodEndDate&&T>H.periodEndDate&&(H.periodEndDate=void 0,Y.error("End date must be on or after the start date. End date has been cleared."));else if(M==="periodEndDate"&&T&&H.periodStartDate&&T<H.periodStartDate)return Y.error("End date must be on or after the start date."),U;if(M==="activityType"&&H.dealerCode){const W=S.find(P=>P.title===T);if(W)if(W.creditPostingOn){const P=W.creditPostingOn.toLowerCase(),B=(H.dealerItemGroup||"").toLowerCase();if(B){let K=!1;if(((P==="vehicle"||P==="vehicles")&&(B==="vehicle"||B==="vehicles")||P==="spares"&&B==="spares"||P==="gma"&&B==="gma"||P==="apparel"&&B==="apparel"||P===B)&&(K=!0),!K)return Y.error("incorrect Delercode for selected service group",{description:`Activity requires ${W.creditPostingOn}, but already selected dealer is ${H.dealerItemGroup}`,duration:6e3}),U}}else console.warn(`[ClaimWizard] Activity type "${T}" is missing creditPostingOn configuration.`)}return H})},R=M=>{N(T=>({...T,...M}))},L=()=>{switch(r){case 1:return F.activityName&&F.activityType&&F.dealerCode&&F.dealerName&&F.activityDate&&F.location&&F.requestDescription;case 2:const T=(F.approvers||[]).find(U=>U.originalStepLevel===3||!U.originalStepLevel&&U.level===3&&!U.isAdditional);return(T==null?void 0:T.email)&&(T==null?void 0:T.userId)&&(T==null?void 0:T.tat);case 3:return!0;default:return!1}},V=()=>{if(r<E){if(!L()){if(r===2){const T=(F.approvers||[]).find(H=>H.originalStepLevel===3||!H.originalStepLevel&&H.level===3&&!H.isAdditional),U=[];(!(T!=null&&T.email)||!(T!=null&&T.userId)||!(T!=null&&T.tat))&&U.push("Department Lead Approval"),U.length>0?Y.error(`Please add missing approvers: ${U.join(", ")}`):Y.error("Please complete all required approver selections (email, user verification, and TAT) before proceeding.")}else Y.error("Please complete all required fields before proceeding.");return}n(r+1)}},I=()=>{r>1&&n(r-1)},A=async M=>{l(!0);try{const T=await y6(M.dealerCode);if(!T.isLoggedIn){Y.error(`Dealer "${T.dealerName||T.displayName}" (${T.dealerCode}) is not mapped to the system.`,{duration:5e3}),x(""),c([]),z("dealerCode",""),z("dealerName",""),z("dealerEmail",""),z("dealerPhone",""),z("dealerAddress",""),l(!1);return}if(F.activityType){const U=S.find(H=>H.title===F.activityType);if(U&&U.creditPostingOn){const H=U.creditPostingOn.toLowerCase(),W=(T.itemGroup||"").toLowerCase();let P=!1;if((H==="vehicle"&&W==="vehicle"||H==="spares"&&W==="spares"||H==="gma"&&W==="gma"||H==="apparel"&&W==="apparel"||H===W)&&(P=!0),!P){Y.error("incorrect Delercode for selected service group",{description:`Activity requires ${U.creditPostingOn}, but dealer is ${T.itemGroup||"N/A"}`,duration:6e3}),x(""),c([]),l(!1);return}}}R({dealerCode:T.dealerCode,dealerName:T.dealerName||T.displayName,dealerEmail:T.email||"",dealerPhone:T.phone||"",dealerAddress:"",dealerItemGroup:T.itemGroup||""}),x(T.dealerName||T.displayName),c([]),Y.success(`Dealer "${T.dealerName||T.displayName}" verified and mapped to the System`)}catch{Y.error("Dealer is not mapped to the system",{duration:5e3}),x(""),c([]),z("dealerCode",""),z("dealerName",""),z("dealerEmail",""),z("dealerPhone",""),z("dealerAddress","")}finally{l(!1)}},G=()=>{if(g)return;const T=[...F.approvers||[]].sort((B,K)=>B.level-K.level),U=new Map,H=[];if(T.forEach(B=>{U.has(B.level)?H.push(B.level):U.set(B.level,B)}),H.length>0){Y.error(`Duplicate approver levels detected: ${H.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",H,T);return}const W=T.map(B=>{const K={email:B.email,name:B.name,userId:B.userId,level:B.level,tat:B.tat,tatType:B.tatType};return B.isAdditional&&B.stepName&&(K.stepName=B.stepName,K.isAdditional=!0),B.originalStepLevel&&(K.originalStepLevel=B.originalStepLevel),K}),P={...F,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:W};if(f(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{f(!1),b.current=null},3e4),s)try{s(P)}catch(B){b.current&&(clearTimeout(b.current),b.current=null),f(!1),console.error("Error submitting claim:",B)}else b.current&&(clearTimeout(b.current),b.current=null),f(!1)},$=()=>{switch(r){case 1:return e.jsxs(Yt.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(ne,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(Ee,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:F.activityName,onChange:M=>z("activityName",M.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(Ke,{value:F.activityType,onValueChange:M=>z("activityType",M),disabled:k,children:[e.jsx(Xe,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(Qe,{placeholder:k?"Loading activity types...":"Select activity type"})}),e.jsx(Je,{className:"max-h-80",children:S.length>0?S.map(M=>e.jsx(J,{value:M.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:M.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:[M.creditPostingOn&&e.jsx("span",{children:M.creditPostingOn}),M.creditPostingOn&&M.taxationType&&e.jsx("span",{className:"opacity-40 select-none",children:"•"}),M.taxationType&&e.jsx("span",{children:M.taxationType})]})]})},M.activityTypeId)):e.jsx("div",{className:"px-2 py-1.5 text-sm text-gray-500 text-center",children:"No activity types available"})})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsx("div",{className:"mt-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ee,{placeholder:"Type dealer code, name, or email to search...",value:F.dealerCode?`${F.dealerName} (${F.dealerCode})`:p,onChange:M=>{F.dealerCode?(z("dealerCode",""),z("dealerName",""),z("dealerEmail",""),z("dealerPhone",""),z("dealerAddress",""),x(M.target.value)):_(M.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(le,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(He,{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(M=>e.jsx("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>A(M),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:M.dealerName||M.displayName}),e.jsxs("div",{className:"text-[10px] text-gray-600 mt-0.5 font-medium flex items-center gap-1.5",children:[e.jsx("span",{className:"font-mono",children:M.dealerCode}),M.email&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-40",children:"•"}),e.jsx("span",{children:M.email})]})]}),e.jsxs("div",{className:"text-[10px] text-gray-500 mt-0.5",children:[M.city,", ",M.state]}),M.itemGroup&&e.jsx("div",{className:"text-[9px] text-blue-600 font-bold uppercase tracking-wider mt-0.5",children:M.itemGroup})]}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:M.isLoggedIn?e.jsx(He,{className:"w-4 h-4 text-green-600"}):e.jsx(At,{className:"w-4 h-4 text-red-500"})})]})},M.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(ne,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(O,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(jt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:F.activityDate?it(F.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(Ji,{mode:"single",selected:F.activityDate,onSelect:M=>z("activityDate",M),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(Ee,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:F.location,onChange:M=>z("location",M.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Si,{value:F.requestDescription||"",onChange:M=>z("requestDescription",M),placeholder:"Provide comprehensive details about your claim requirement including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ne,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(le,{variant:"secondary",className:"text-xs",children:"Optional"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(O,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(jt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:F.periodStartDate?it(F.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(Ji,{mode:"single",selected:F.periodStartDate,onSelect:M=>z("periodStartDate",M),initialFocus:!0,toDate:F.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(ra,{children:[e.jsx(na,{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(jt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:F.periodEndDate?it(F.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(Ji,{mode:"single",selected:F.periodEndDate,onSelect:M=>z("periodEndDate",M),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: ",it(F.periodStartDate,"d MMM yyyy")," - ",it(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(N6,{formData:F,updateFormData:z,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:M=>w({open:!0,violations:M})});case 3:return e.jsxs(Yt.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(He,{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(q,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Et,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F.activityName})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(le,{variant:"secondary",className:"mt-1",children:F.activityType})]})]})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Ml,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1 font-mono",children:F.dealerCode})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F.dealerName})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:F.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:F.dealerPhone})]}),F.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:F.dealerAddress})]})]})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-5 h-5 text-purple-600"}),"Selected Approvers"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsx("div",{className:"space-y-3",children:[...F.approvers||[]].filter(T=>{var U,H;return!((U=T.email)!=null&&U.includes("system@"))&&!((H=T.email)!=null&&H.includes("finance@"))}).sort((T,U)=>T.level-U.level).map(T=>{const U=Number(T.tat||0),W=(T.tatType||"hours")==="days"?U*24:U;let P="Unknown",B="";if(T.isAdditional){P=T.stepName||"Additional Approver";const K=Lo.find(Z=>Z.level===T.insertAfterLevel);B=T.stepName||`Additional Approver (after "${(K==null?void 0:K.name)||"Unknown"}")`}else{const K=T.originalStepLevel?Lo.find(Z=>Z.level===T.originalStepLevel):Lo.find(Z=>Z.level===T.level&&!Z.isAuto);P=(K==null?void 0:K.name)||"Unknown",B=P}return e.jsx("div",{className:`p-3 rounded-lg border ${T.isAdditional?"bg-purple-50 border-purple-200":"bg-gray-50 border-gray-200"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:B}),T.isAdditional&&e.jsx(le,{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:T.name||T.email||"Not selected"}),T.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:T.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[W," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${T.level}-${T.email}`)})})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F.activityDate?it(F.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Location"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Hc,{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(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Estimated Budget"}),e.jsx("p",{className:"text-xl font-bold text-blue-900 mt-1",children:F.estimatedBudget})]})]})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Brief Requirement"}),e.jsx("div",{className:"mt-2 p-4 bg-gray-50 rounded-lg border",children:e.jsx(Os,{content:F.requestDescription||"",className:"text-sm"})})]})})]}),(F.periodStartDate||F.periodEndDate)&&e.jsxs(q,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F.periodStartDate?it(F.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:F.periodEndDate?it(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(Zr,{className:"w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-blue-900 mb-1",children:"Ready to Submit"}),e.jsx("p",{className:"text-sm text-blue-800",children:"Please review all the information above. Once submitted, your claim request will enter the approval workflow."})]})]})})]})]});default:return null}};return e.jsxs("div",{className:"w-full bg-gradient-to-br from-gray-50 to-gray-100 py-4 sm:py-6 lg:py-8 px-3 sm:px-4 lg:px-6 overflow-y-auto",children:[e.jsxs("div",{className:"max-w-6xl mx-auto pb-8",children:[e.jsxs("div",{className:"mb-6 sm:mb-8",children:[e.jsxs(O,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Ss,{className:"w-3 h-3 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Back to Templates"}),e.jsx("span",{className:"sm:hidden",children:"Back"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-0",children:e.jsxs("div",{children:[e.jsx(le,{variant:"secondary",className:"mb-2 text-xs",children:"Claim Management Template"}),e.jsx("h1",{className:"text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900",children:"New Claim Request"}),e.jsxs("p",{className:"text-sm sm:text-base text-gray-600 mt-1",children:["Step ",r," of ",E,": ",e.jsx("span",{className:"hidden sm:inline",children:Oo[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(la,{value:r/E*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:Oo.map((M,T)=>e.jsx("span",{className:`text-xs sm:text-sm ${T+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:T+1},T))})]})]}),e.jsx(q,{className:"mb-6 sm:mb-8",children:e.jsx(se,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(Kl,{mode:"wait",children:$()})})}),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:I,disabled:r===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Ss,{className:"w-4 h-4"}),"Previous"]}),r<E?e.jsxs(O,{onClick:V,className:`gap-2 w-full sm:w-auto order-1 sm:order-2 ${L()?"":"opacity-50 cursor-pointer hover:opacity-60"}`,children:["Next",e.jsx(vs,{className:"w-4 h-4"})]}):e.jsx(O,{onClick:G,disabled:!L()||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(We,{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(Ri,{open:v.open,onClose:()=>w({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}const{DocumentsTab:C6,ActivityTab:S6,WorkNotesTab:A6,SummaryTab:T6,RequestDetailHeader:k6,QuickActionsSidebar:D6,RequestDetailModals:R6}=z0;let I6=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(as,{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 F6({requestId:t,onBack:s,dynamicRequests:a=[]}){var Qt,Ts,oa,Dr,Rr,ka,nr;const n=Sa().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,w]=u.useState(!1),[S,D]=u.useState(!1),[k,C]=u.useState(!1),[F,N]=u.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[E,_]=u.useState({open:!1,violations:[]}),{user:z}=xs(),{request:R,apiRequest:L,loading:V,refreshing:I,refreshDetails:A,currentApprovalLevel:G,isSpectator:$,isInitiator:M,existingParticipants:T,accessDenied:U}=Kd(n,a,z),H=(z==null?void 0:z.userId)||"",W=(Qt=z==null?void 0:z.email)==null?void 0:Qt.toLowerCase(),P=((R==null?void 0:R.approvalFlow)||[]).some(It=>{var hs;return It.role==="Department Lead Approval"&&((hs=It.approverEmail)==null?void 0:hs.toLowerCase())===W}),B=(z==null?void 0:z.jobTitle)==="Dealer"||(z==null?void 0:z.designation)==="Dealer",Z=((R==null?void 0:R.workflowType)==="CLAIM_MANAGEMENT"||(L==null?void 0:L.workflowType)==="CLAIM_MANAGEMENT"||(R==null?void 0:R.templateType)==="claim-management")&&!B&&(M||P),{mergedMessages:te,unreadWorkNotes:ae,workNoteAttachments:xe,setWorkNoteAttachments:be}=D0(n,L,o,z),{uploadingDocument:Ge,triggerFileInput:Be,previewDocument:_e,setPreviewDocument:Re,documentPolicy:ce,documentError:je,setDocumentError:re}=R0(L,A),[pe,ie]=u.useState(null),fe=pe||G,{showApproveModal:Ie,setShowApproveModal:$e,showRejectModal:ye,setShowRejectModal:oe,showAddApproverModal:ke,setShowAddApproverModal:st,showAddSpectatorModal:at,setShowAddSpectatorModal:ct,showSkipApproverModal:Dt,setShowSkipApproverModal:Q,showActionStatusModal:de,setShowActionStatusModal:ee,skipApproverData:Ae,setSkipApproverData:Ue,actionStatus:et,setActionStatus:ze,handleApproveConfirm:qe,handleRejectConfirm:Ze,handleAddApprover:nt,handleSkipApprover:rs,handleAddSpectator:Ot}=F0(n,fe,A),xt=async It=>{await qe(It),ie(null)},bt=async It=>{await Ze(It),ie(null)},Pt=((R==null?void 0:R.status)||(L==null?void 0:L.status)||"").toLowerCase(),As=(Pt==="approved"||Pt==="rejected")&&M,{conclusionRemark:ns,setConclusionRemark:Ya,conclusionLoading:Ka,conclusionSubmitting:Cr,aiGenerated:Aa,handleGenerateConclusion:$t,handleFinalizeConclusion:Ta,generationAttempts:Bs,generationFailed:tn,maxAttemptsReached:sn}=I0(R,n,M,A,s,ze,ee);u.useEffect(()=>{(async()=>{var hs;try{const Js=await ha("SYSTEM_SETTINGS"),pa=await ha("WORKFLOW_SHARING"),rn=[...Js,...pa],Da={};rn.forEach(ir=>{Da[ir.configKey]=ir.configValue}),N({maxApprovalLevels:parseInt(Da.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Da.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((hs=Da.ALLOW_ADD_SPECTATOR)==null?void 0:hs.toLowerCase())==="true",maxSpectators:parseInt(Da.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Js){console.error("Failed to load system policy:",Js)}})()},[]),u.useEffect(()=>{const hs=new URLSearchParams(window.location.search).get("tab");hs&&c(hs)},[n]);const Sr=()=>{A()},an=()=>{w(!0)},tr=()=>{D(!0)},Ar=async()=>{await A()},sr=()=>{C(!0)},Tr=async()=>{await A()},kr=async()=>{await A()},ar=async()=>{if(!(L!=null&&L.requestId)){Y.error("Request ID not found");return}if(!p){Y.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Oa=(R==null?void 0:R.status)==="closed";u.useEffect(()=>{(async()=>{if(!Oa||!(L!=null&&L.requestId)){g(null),x(null);return}try{b(!0);const hs=await O0(L.requestId);if(hs!=null&&hs.summaryId){x(hs.summaryId);try{const Js=await Xd(hs.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,L==null?void 0:L.requestId]),u.useEffect(()=>{if(!H||!(L!=null&&L.requestId))return;const It=Xr();if(!It)return;qc(It,H);const hs=Js=>{var ir,En,_n,Mn;const pa=Js==null?void 0:Js.notification;if(!pa)return;const rn=pa.requestId||pa.request_id,Da=((ir=pa.metadata)==null?void 0:ir.requestNumber)||((En=pa.metadata)==null?void 0:En.request_number);rn!==L.requestId&&Da!==n&&Da!==L.requestNumber||((_n=pa.metadata)!=null&&_n.creditNoteNumber||(Mn=pa.metadata)!=null&&Mn.credit_note_number)&&A()};return It.on("notification:new",hs),()=>{It.off("notification:new",hs)}},[H,L==null?void 0:L.requestId,n,A]);const rr=((R==null?void 0:R.approvalFlow)||[]).filter(It=>It&&typeof It.step=="number").map(It=>({levelNumber:It.step||0,approverName:It.approver||"Unknown",status:It.status||"pending",tatHours:It.tatHours||24}));return V&&!R&&!L?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(Op,{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(Ss,{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"})]})]})}):R?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(k6,{request:R,refreshing:I,onBack:s||(()=>window.history.back()),onRefresh:Sr,onShareSummary:ar,isInitiator:M,slaData:((Ts=R==null?void 0:R.summary)==null?void 0:Ts.sla)||(R==null?void 0:R.sla)||null,isPaused:((oa=R==null?void 0:R.pauseInfo)==null?void 0:oa.isPaused)||!1}),e.jsxs(Ii,{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(Fi,{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(Bt,{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($p,{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(Bt,{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(Gc,{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(Bt,{value:"workflow",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-workflow",children:[e.jsx(Qs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),Z&&e.jsxs(Bt,{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(Fa,{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(Bt,{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(Pe,{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(Bt,{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(Vt,{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(Bt,{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(Ks,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),ae>0&&e.jsx(le,{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:ae>9?"9+":ae})]})]})}),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(zt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(d4,{request:R,apiRequest:L,currentUserId:H,isInitiator:M,needsClosure:As,conclusionRemark:ns,setConclusionRemark:Ya,conclusionLoading:Ka,conclusionSubmitting:Cr,aiGenerated:Aa,handleGenerateConclusion:$t,handleFinalizeConclusion:Ta,generationAttempts:Bs,generationFailed:tn,maxAttemptsReached:sn})}),Oa&&e.jsx(zt,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(T6,{summary:h,loading:f,onShare:ar,isInitiator:M})}),e.jsx(zt,{value:"workflow",className:"mt-0",children:e.jsx(b6,{request:R,user:z,isInitiator:M,isSpectator:$,onSkipApprover:It=>{if(!It.levelId){alert("Level ID not available");return}Ue(It),Q(!0)},onRefresh:A,documentPolicy:ce})}),Z&&e.jsx(zt,{value:"io",className:"mt-0",children:e.jsx(j6,{request:R,apiRequest:L,onRefresh:A,isSpectator:$})}),e.jsx(zt,{value:"documents",className:"mt-0",children:e.jsx(C6,{request:R,workNoteAttachments:xe,uploadingDocument:Ge,documentPolicy:ce,triggerFileInput:Be,setPreviewDocument:Re,downloadDocument:Us,isSpectator:$})}),e.jsx(zt,{value:"activity",className:"mt-0",children:e.jsx(S6,{request:R})}),e.jsx(zt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(A6,{requestId:n,requestTitle:R.title,mergedMessages:te,setWorkNoteAttachments:be,isInitiator:M,isSpectator:$,currentLevels:rr,onAddApprover:nt,maxApprovalLevels:F.maxApprovalLevels,onPolicyViolation:It=>_({open:!0,violations:It})})})]}),o!=="worknotes"&&e.jsx(D6,{request:R,isInitiator:M,isSpectator:$,currentApprovalLevel:G,onAddApprover:()=>st(!0),onAddSpectator:()=>ct(!0),onApprove:()=>$e(!0),onReject:()=>oe(!0),onPause:an,onResume:tr,onRetrigger:sr,summaryId:p,refreshTrigger:y,pausedByUserId:(Rr=(Dr=R==null?void 0:R.pauseInfo)==null?void 0:Dr.pausedBy)==null?void 0:Rr.userId,currentUserId:H,apiRequest:L,hideApproveReject:B})]})]})]})}),d&&p&&e.jsx(V0,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(R==null?void 0:R.title)||"N/A",onSuccess:()=>{A(),j(It=>It+1)}}),v&&(L==null?void 0:L.requestId)&&e.jsx(W0,{isOpen:v,onClose:()=>w(!1),requestId:L.requestId,levelId:(G==null?void 0:G.levelId)||null,onSuccess:Tr}),S&&(L==null?void 0:L.requestId)&&e.jsx(H0,{isOpen:S,onClose:()=>D(!1),requestId:L.requestId,onSuccess:Ar}),k&&(L==null?void 0:L.requestId)&&e.jsx(G0,{isOpen:k,onClose:()=>C(!1),requestId:L.requestId,approverName:(nr=(ka=R==null?void 0:R.pauseInfo)==null?void 0:ka.pausedBy)==null?void 0:nr.name,onSuccess:kr}),e.jsx(R6,{showApproveModal:Ie,showRejectModal:ye,showAddApproverModal:ke,showAddSpectatorModal:at,showSkipApproverModal:Dt,showActionStatusModal:de,previewDocument:_e,documentError:je,request:R,skipApproverData:Ae,actionStatus:et,existingParticipants:T,currentLevels:rr,maxApprovalLevels:F.maxApprovalLevels,onPolicyViolation:It=>_({open:!0,violations:It}),setShowApproveModal:$e,setShowRejectModal:oe,setShowAddApproverModal:st,setShowAddSpectatorModal:ct,setShowSkipApproverModal:Q,setShowActionStatusModal:ee,setPreviewDocument:Re,setDocumentError:re,setSkipApproverData:Ue,setActionStatus:ze,handleApproveConfirm:xt,handleRejectConfirm:bt,handleAddApprover:nt,handleAddSpectator:Ot,handleSkipApprover:rs,downloadDocument:Us,documentPolicy:ce}),e.jsx(Ri,{open:E.open,onClose:()=>_({open:!1,violations:[]}),violations:E.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(Pe,{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(Ss,{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 P6(t){return e.jsx(I6,{children:e.jsx(F6,{...t})})}function E6({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 z=await u6(m||"all",x,g);o(z.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(z.categoryData||[])}catch(z){console.error("[DealerDashboard] Error fetching data:",z),Y.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=(_,z=!1)=>{if(_==null||isNaN(_))return"₹0";const R=typeof _=="string"?parseFloat(_):Number(_);return R<=0?"₹0":z||R<1e4?`₹${Math.round(R).toLocaleString("en-IN")}`:R>=1e5?`₹${(R/1e5).toFixed(1)}L`:R>=1e3?`₹${(R/1e3).toFixed(1)}K`:`₹${Math.round(R).toLocaleString("en-IN")}`},j=_=>_.toLocaleString("en-IN"),v=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),w=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),S=u.useMemo(()=>{const _=c.reduce((z,R)=>z+R.raised,0);return _===0?[]:c.map(z=>({name:z.activityType.length>20?z.activityType.substring(0,20)+"...":z.activityType,value:z.raised,fullName:z.activityType,percentage:(z.raised/_*100).toFixed(0)}))},[c]),D=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]),C=["#166534","#15803d","#16a34a","#22c55e","#4ade80","#86efac","#bbf7d0"],F=u.useMemo(()=>c.length===0?null:c.reduce((_,z)=>z.approvalRate>((_==null?void 0:_.approvalRate)||0)?z:_),[c]),N=u.useMemo(()=>c.length===0?null:c.reduce((_,z)=>z.raisedValue>((_==null?void 0:_.raisedValue)||0)?z:_),[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(q,{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(se,{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(js,{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(q,{className:"shadow-lg",children:e.jsxs(se,{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(ac,{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(q,{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(se,{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(js,{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(ot,{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(Pe,{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(xl,{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(q,{className:"border-l-4 border-l-blue-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Raised Claims"}),e.jsx("div",{className:"p-2 rounded-lg bg-blue-50",children:e.jsx(Pe,{className:"h-4 w-4 text-blue-600"})})]})}),e.jsxs(se,{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(q,{className:"border-l-4 border-l-green-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Approved"}),e.jsx("div",{className:"p-2 rounded-lg bg-green-50",children:e.jsx(He,{className:"h-4 w-4 text-green-600"})})]})}),e.jsxs(se,{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(Qs,{className:"h-3 w-3 text-green-600"}),e.jsxs("p",{className:"text-xs text-green-600",children:[v(),"% approval rate"]})]})]})]}),e.jsxs(q,{className:"border-l-4 border-l-red-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Rejected"}),e.jsx("div",{className:"p-2 rounded-lg bg-red-50",children:e.jsx(At,{className:"h-4 w-4 text-red-600"})})]})}),e.jsxs(se,{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(py,{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(q,{className:"border-l-4 border-l-orange-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Pending"}),e.jsx("div",{className:"p-2 rounded-lg bg-orange-50",children:e.jsx(ot,{className:"h-4 w-4 text-orange-600"})})]})}),e.jsxs(se,{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(q,{className:"border-l-4 border-l-emerald-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Credited"}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-50",children:e.jsx(gy,{className:"h-4 w-4 text-emerald-600"})})]})}),e.jsxs(se,{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(Qs,{className:"h-3 w-3 text-emerald-600"}),e.jsxs("p",{className:"text-xs text-emerald-600",children:[w(),"% credit rate"]})]})]})]}),e.jsxs(q,{className:"border-l-4 border-l-amber-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(me,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Pending Credit"}),e.jsx("div",{className:"p-2 rounded-lg bg-amber-50",children:e.jsx(as,{className:"h-4 w-4 text-amber-600"})})]})}),e.jsxs(se,{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(q,{className:"shadow-lg",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(ac,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Claims Distribution by Activity Type"}),e.jsx(Se,{children:"Total claims raised across activity types"})]})]})}),e.jsxs(se,{children:[e.jsx(fn,{width:"100%",height:300,children:e.jsxs(vp,{children:[e.jsx(Np,{data:S,cx:"50%",cy:"50%",labelLine:!1,label:({name:_,percentage:z})=>`${_}: ${z}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:S.map((_,z)=>e.jsx(wp,{fill:C[z%C.length]},`cell-${z}`))}),e.jsx(bn,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:S.slice(0,3).map((_,z)=>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:C[z%C.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)})]})]},z))})]})]}),e.jsxs(q,{className:"shadow-lg",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(xl,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Claims Status by Activity Type"}),e.jsx(Se,{children:"Count comparison across workflow stages"})]})]})}),e.jsx(se,{children:e.jsx(fn,{width:"100%",height:300,children:e.jsxs(qo,{data:D,children:[e.jsx(ll,{strokeDasharray:"3 3"}),e.jsx(ol,{dataKey:"name"}),e.jsx(cl,{}),e.jsx(bn,{}),e.jsx(dl,{}),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(q,{className:"shadow-lg",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-emerald-100 rounded-lg",children:e.jsx(Vt,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Detailed Activity Type Breakdown"}),e.jsx(Se,{children:"In-depth analysis of claims by type and status"})]})]})}),e.jsx(se,{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(qo,{data:k,children:[e.jsx(ll,{strokeDasharray:"3 3"}),e.jsx(ol,{dataKey:"name"}),e.jsx(cl,{tickFormatter:_=>y(_)}),e.jsx(bn,{formatter:_=>y(_),labelFormatter:_=>_}),e.jsx(dl,{}),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((_,z)=>e.jsxs(q,{className:"shadow-md hover:shadow-lg transition-shadow",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-base",children:_.activityType}),e.jsxs(le,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[_.approvalRate.toFixed(1),"% approved"]})]})}),e.jsxs(se,{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(la,{value:_.creditRate,className:"h-2"})]})]})]},z))})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(q,{className:"border-t-4 border-t-green-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{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(ss,{className:"h-6 w-6 text-green-600"})}),e.jsx(Qs,{className:"h-5 w-5 text-green-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Best Performing"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:(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(q,{className:"border-t-4 border-t-blue-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{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(Fa,{className:"h-6 w-6 text-blue-600"})}),e.jsx(Vt,{className:"h-5 w-5 text-blue-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Top Activity Type"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:(N==null?void 0:N.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-blue-600",children:[N?y(N.raisedValue,!0):"₹0"," raised"]})]})}),e.jsx(q,{className:"border-t-4 border-t-emerald-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{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(Il,{className:"h-6 w-6 text-emerald-600"})}),e.jsx(He,{className:"h-5 w-5 text-emerald-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Overall Credit Rate"}),e.jsxs("p",{className:"text-xl text-gray-900 mb-1",children:[w(),"%"]}),e.jsxs("p",{className:"text-sm text-emerald-600",children:[j(l.credited)," claims credited"]})]})}),e.jsx(q,{className:"border-t-4 border-t-amber-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{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(Fp,{className:"h-6 w-6 text-amber-600"})}),e.jsx(as,{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 _6({searchTerm:t,sortBy:s,sortOrder:a,onSearchChange:r,onSortByChange:n,onSortOrderChange:i,onClearFilters:l,activeFiltersCount:o,...c}){return e.jsxs(q,{className:"shadow-lg border-0",children:[e.jsx(me,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(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(Se,{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(Nt,{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(se,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(Ee,{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(Ke,{value:s,onValueChange:d=>n(d),children:[e.jsx(Xe,{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(Qe,{placeholder:"Sort by"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{value:"priority",children:"Priority"}),e.jsx(J,{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(Ll,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Ol,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function M6({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(q,{className:"shadow-lg border-0","data-testid":"dealer-closed-requests-filters",children:[e.jsx(me,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(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(Se,{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(Nt,{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(se,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(Ee,{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(Ke,{value:s,onValueChange:i,children:[e.jsx(Xe,{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(Qe,{placeholder:"Closure Type"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Closures"}),e.jsx(J,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(J,{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(Ke,{value:a,onValueChange:p=>l(p),children:[e.jsx(Xe,{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(Qe,{placeholder:"Sort by"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{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(Ll,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Ol,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function L6({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:w,onClearFilters:S,hasActiveFilters:D,...k}){return e.jsx(q,{className:"border-gray-200 shadow-md","data-testid":"dealer-user-all-requests-filters",children:e.jsx(se,{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"}),D&&e.jsx(le,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),D&&e.jsxs(O,{variant:"ghost",size:"sm",onClick:S,className:"gap-2",children:[e.jsx(_t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(qt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ee,{placeholder:"Search requests...",value:t,onChange:C=>p(C.target.value),className:"pl-10 h-10","data-testid":"dealer-search-input"})]}),e.jsxs(Ke,{value:s,onValueChange:x,children:[e.jsx(Xe,{className:"h-10","data-testid":"dealer-status-filter",children:e.jsx(Qe,{placeholder:"All Status"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"paused",children:"Paused"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:d.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:d.selectedUser.displayName||d.selectedUser.email}),e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:d.handleClear,children:e.jsx(Nt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{placeholder:"Search initiator...",value:d.searchQuery,onChange:C=>d.handleSearch(C.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(C=>e.jsx("button",{type:"button",onClick:()=>d.handleSelect(C),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:C.displayName||C.email}),C.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:C.email})]})},C.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r!=="all"&&f&&e.jsxs(Ke,{value:n,onValueChange:C=>f(C),children:[e.jsx(Xe,{className:"h-7 w-32 text-xs",children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(J,{value:"current",children:"Current Only"}),e.jsx(J,{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(Nt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{placeholder:"Search approver...",value:m.searchQuery,onChange:C=>m.handleSearch(C.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(C=>e.jsx("button",{type:"button",onClick:()=>m.handleSelect(C),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:C.displayName||C.email}),C.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:C.email})]})},C.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(jt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:i,onValueChange:C=>b(C),children:[e.jsx(Xe,{className:"w-[160px] h-10",children:e.jsx(Qe,{placeholder:"Date Range"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),i==="custom"&&e.jsxs(ra,{open:c,onOpenChange:v,children:[e.jsx(na,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(jt,{className:"w-4 h-4"}),l&&o?`${it(l,"MMM d, yyyy")} - ${it(o,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date",children:"Start Date"}),e.jsx(sa,{value:l||null,onChange:C=>{const F=C?new Date(C):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(ne,{htmlFor:"end-date",children:"End Date"}),e.jsx(sa,{value:o||null,onChange:C=>{const F=C?new Date(C):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:w,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 O6(t){switch(t){case"DEALER_CLAIM":return P6;case"CUSTOM":default:return s4}}function $6(t){switch(t){case"DEALER":return _6;case"STANDARD":default:return n4}}function U6(t){switch(t){case"DEALER":return M6;case"STANDARD":default:return o4}}function B6(t){switch(t){case"DEALER":return L6;case"STANDARD":default:return c4}}const z6=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:ss,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ss,iconColor:"text-gray-600"}}},V6=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:ot,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:tt,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:He,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:tt,iconColor:"text-gray-600",label:t}}};function W6({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=dC(),g=u.useMemo(()=>{try{const F=lt.getUserData();return xd(F)}catch(F){return console.error("[OpenRequests] Error getting user filter type:",F),"STANDARD"}},[]),f=u.useMemo(()=>$6(g),[g]),b=g==="DEALER",y=F=>{const N={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 N.templateType==="FORM_16"&&(h.form16FinancialYear&&(N.financialYear=h.form16FinancialYear),h.form16Quarter&&(N.quarter=h.form16Quarter)),N},j=u.useCallback(async(F=1,N)=>{try{F===1&&(n(!0),a([]));const E=await Xs.listOpenForMe({page:F,limit:p,search:N==null?void 0:N.search,status:N==null?void 0:N.status,priority:N==null?void 0:N.priority,templateType:N==null?void 0:N.templateType,financialYear:N==null?void 0:N.financialYear,quarter:N==null?void 0:N.quarter,sortBy:N==null?void 0:N.sortBy,sortOrder:N==null?void 0:N.sortOrder}),_=Array.isArray(E==null?void 0:E.data)?E.data:[],z=E==null?void 0:E.pagination;z&&(h.setCurrentPage(z.page||1),c(z.totalPages||1),m(z.total||0));const R=_.map(L=>{var I,A,G,$;const V=L.submittedAt||L.submitted_at||L.createdAt||L.created_at;return{id:L.requestNumber||L.request_number||L.requestId,requestId:L.requestId,displayId:L.requestNumber||L.request_number||L.requestId,title:L.title,description:L.description,status:(L.status||"").toString().toLowerCase().replace("_","-"),priority:(L.priority||"").toString().toLowerCase(),initiator:{name:((I=L.initiator)==null?void 0:I.displayName)||((A=L.initiator)==null?void 0:A.email)||"—",avatar:(((G=L.initiator)==null?void 0:G.displayName)||(($=L.initiator)==null?void 0:$.email)||"NA").split(" ").map(M=>M[0]).join("").slice(0,2).toUpperCase()},currentApprover:L.currentApprover?{name:L.currentApprover.name||L.currentApprover.email||"—",avatar:(L.currentApprover.name||L.currentApprover.email||"CA").split(" ").map(M=>M[0]).join("").slice(0,2).toUpperCase(),sla:L.currentApprover.sla}:void 0,createdAt:V||"—",approvalStep:L.currentLevel?`Step ${L.currentLevel} of ${L.totalLevels||"?"}`:void 0,department:L.department,currentLevelSLA:L.currentLevelSLA,templateType:L.templateType||L.template_type,form16Submission:L.form16Submission??null}});a(R)}finally{n(!1),l(!1)}},[p,h]);x.current=j;const v=u.useCallback(()=>{l(!0),j(h.currentPage,y(!0))},[h.currentPage,j]),w=u.useCallback(F=>{F>=1&&F<=o&&(h.setCurrentPage(F),j(F,y(!0)))},[o,h,j]),S=()=>{const F=[];let E=Math.max(1,h.currentPage-Math.floor(2.5)),_=Math.min(o,E+5-1);_-E<4&&(E=Math.max(1,_-5+1));for(let z=E;z<=_;z++)F.push(z);return F},D=u.useRef(!1);u.useEffect(()=>{if(!D.current){D.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(!D.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 E=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(E)},[h.searchTerm,h.statusFilter,h.priorityFilter,h.templateTypeFilter,h.form16FinancialYear,h.form16Quarter,h.sortBy,h.sortOrder,b]);const C=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(Pe,{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(le,{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:C.map(F=>{const N=z6(F.priority),E=(F.templateType||F.template_type||"").toString().toUpperCase()==="FORM_16",_=F.form16Submission,z=_==null?void 0:_.displayStatus,R=z&&/balance mismatch|failed/i.test(String(z)),L=E&&z?{color:R?"bg-red-100 text-red-800 border-red-200":z==="Completed"?"bg-green-100 text-green-800 border-green-200":"bg-gray-100 text-gray-700 border-gray-200",icon:tt,label:z}:V6(F.status);return e.jsx(q,{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(se,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${N.color} border shadow-sm`,children:e.jsx(N.icon,{className:`w-5 h-5 ${N.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:F.displayId||F.id}),e.jsxs(le,{variant:"outline",className:`${L.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(L.icon,{className:"w-3.5 h-3.5 mr-1"}),L.label||F.status]}),F.department&&e.jsx(le,{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(le,{variant:"outline",className:`${N.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:F.priority}),(()=>{const V=(F==null?void 0:F.templateType)||(F==null?void 0:F.template_type)||"",I=(V==null?void 0:V.toUpperCase())||"";let A="Non-Templatized",G="bg-purple-100 !text-purple-600 border-purple-200";return I==="DEALER CLAIM"?(A="Dealer Claim",G="bg-blue-100 !text-blue-700 border-blue-200"):I==="FORM_16"?(A="Form 16",G="bg-emerald-100 !text-emerald-700 border-emerald-200"):I==="TEMPLATE"&&(A="Template"),e.jsx(le,{variant:"outline",className:`${G} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:A})})()]}),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 $;const V=!!(F.isPaused||($=F.pauseInfo)!=null&&$.isPaused||F.status==="paused"),I=F.currentLevelSLA.percentageUsed||0,G=V?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:I>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:I>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:I>=50?{bg:"bg-amber-50 border border-amber-200",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{bg:"bg-green-50 border border-green-200",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"};return e.jsxs("div",{className:`p-2 rounded-md ${G.bg}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[V?e.jsx(xr,{className:`w-3.5 h-3.5 ${G.icon}`}):e.jsx(ot,{className:`w-3.5 h-3.5 ${G.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",I,"% ",V&&"(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 ${G.text}`,children:[F.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(la,{value:I,className:"h-1.5",indicatorClassName:G.progress})]})})(),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ms,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(us,{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(ms,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(us,{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(tt,{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(jt,{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(vs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},F.id)})}),C.length===0&&e.jsx(q,{className:"shadow-lg border-0",children:e.jsxs(se,{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(Pe,{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(q,{className:"shadow-md",children:e.jsx(se,{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:()=>w(h.currentPage-1),disabled:h.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(vs,{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:()=>w(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),S().map(F=>e.jsx(O,{variant:F===h.currentPage?"default":"outline",size:"sm",onClick:()=>w(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:()=>w(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>w(h.currentPage+1),disabled:h.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(vs,{className:"h-4 w-4"})})]})]})})})]})}function H6({totalRecords:t,loading:s,refreshing:a,onRefresh:r}){return e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-3 sm:gap-4 md:gap-6","data-testid":"closed-requests-header",children:[e.jsx("div",{className:"space-y-1 sm:space-y-2",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-slate-800 to-slate-900 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(Pe,{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(le,{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 G6(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:ss,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ss,iconColor:"text-gray-600"}}}function Y6(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:He,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:tt,iconColor:"text-gray-600",label:t,description:""}}}function K6({request:t,onViewRequest:s}){var l;const a=G6(t.priority),r=Y6(t.status),n=a.icon,i=r.icon;return e.jsx(q,{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(se,{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(le,{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(le,{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(le,{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(le,{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(ms,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(us,{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(He,{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(jt,{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(He,{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(vs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function Q6({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(K6,{request:r,onViewRequest:a},r.id))})}function X6({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(q,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(se,{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(Pe,{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 J6(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 Z6({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=J6(a,r);return e.jsx(q,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(se,{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(vs,{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(vs,{className:"h-4 w-4"})})]})]})})})}function q6(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 eD(t){return t.map(q6)}function tD({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=eD(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 sD={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},ib=An({name:"closedRequests",initialState:sD,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:aD,setStatusFilter:rD,setPriorityFilter:nD,setTemplateTypeFilter:iD,setForm16FinancialYear:lD,setForm16Quarter:oD,setSortBy:cD,setSortOrder:dD,setCurrentPage:mD,clearFilters:uD}=ib.actions;function xD({onFiltersChange:t,debounceMs:s=500}={}){const a=vi(),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(N=>N.closedRequests),g=u.useCallback(N=>a(aD(N)),[a]),f=u.useCallback(N=>a(rD(N)),[a]),b=u.useCallback(N=>a(nD(N)),[a]),y=u.useCallback(N=>a(iD(N)),[a]),j=u.useCallback(N=>a(lD(N)),[a]),v=u.useCallback(N=>a(oD(N)),[a]),w=u.useCallback(N=>a(cD(N)),[a]),S=u.useCallback(N=>a(dD(N)),[a]),D=u.useCallback(N=>a(mD(N)),[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 N=setTimeout(()=>{t&&t(k())},i?s:0);return r.current=N,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,p,x,t,k,s]);const C=u.useCallback(()=>{a(uD())},[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:w,setSortOrder:S,setCurrentPage:D,clearFilters:C,activeFiltersCount:F,getFilters:k}}function hD({onViewRequest:t}){const s=tD({itemsPerPage:10}),a=u.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=xD(),n=u.useMemo(()=>{try{const x=lt.getUserData();return xd(x)}catch(x){return console.error("[ClosedRequests] Error getting user filter type:",x),"STANDARD"}},[]),i=u.useMemo(()=>U6(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(H6,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:p}),e.jsx(i,{searchTerm:r.searchTerm,priorityFilter:r.priorityFilter,statusFilter:r.statusFilter,templateTypeFilter:r.templateTypeFilter,form16FinancialYear:r.form16FinancialYear,form16Quarter:r.form16Quarter,sortBy:r.sortBy,sortOrder:r.sortOrder,activeFiltersCount:r.activeFiltersCount,onSearchChange:r.setSearchTerm,onPriorityChange:r.setPriorityFilter,onStatusChange:r.setStatusFilter,onTemplateTypeChange:r.setTemplateTypeFilter,onForm16FinancialYearChange:r.setForm16FinancialYear,onForm16QuarterChange:r.setForm16Quarter,onSortByChange:r.setSortBy,onSortOrderChange:()=>r.setSortOrder(r.sortOrder==="asc"?"desc":"asc"),onClearFilters:r.clearFilters}),e.jsx(Q6,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(X6,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(Z6,{pagination:s.pagination,onPageChange:m})]})}function pD(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 gD(t){return pD(t)?"DEALER_CLAIM":"CUSTOM"}function fD(t,s){return`/request/${t}`}class bD 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(as,{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 jD({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=Sa().requestId||t||"",{user:i}=xs(),{apiRequest:l,loading:o}=Kd(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=gD(l),d=O6(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function yD(t){return e.jsx(bD,{children:e.jsx(jD,{...t})})}function vD({onViewSummary:t}){const s=fs(),[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 w=await _k({page:v,limit:g});r(w.data||[]),p(w.pagination.totalPages||1),h(w.pagination.total||0),d(w.pagination.page||1)}catch(w){console.error("Failed to fetch shared summaries:",w),Y.error("Failed to load shared summaries")}finally{i(!1)}},[]);u.useEffect(()=>{f(1)},[f]);const b=async v=>{try{await L0(v),r(w=>w.map(S=>S.sharedSummaryId===v?{...S,isRead:!0,viewedAt:new Date().toISOString()}:S)),t?t(v):s(`/shared-summaries/${v}`)}catch(w){console.error("Failed to mark as viewed:",w),t?t(v):s(`/shared-summaries/${v}`)}},y=v=>{v>=1&&v<=m&&f(v)},j=a.filter(v=>{var S,D,k,C;if(!l)return!0;const w=l.toLowerCase();return((S=v.title)==null?void 0:S.toLowerCase().includes(w))||((D=v.requestNumber)==null?void 0:D.toLowerCase().includes(w))||((k=v.initiatorName)==null?void 0:k.toLowerCase().includes(w))||((C=v.sharedByName)==null?void 0:C.toLowerCase().includes(w))});return e.jsx("div",{className:"min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden",children:e.jsxs("div",{className:"max-w-7xl mx-auto w-full",children:[e.jsxs("div",{className:"mb-4 sm:mb-6",children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900 mb-1 sm:mb-2",children:"Shared Summaries"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600",children:"View summaries of closed requests shared with you"})]}),e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ee,{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(We,{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(Pe,{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(fy,{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(Ht,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Initiator: ",e.jsx("span",{className:"font-medium",children:v.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Ht,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared by: ",e.jsx("span",{className:"font-medium",children:v.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(jt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",it(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: ",it(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:w=>{w.stopPropagation(),b(v.sharedSummaryId)},children:"View"})]})})},v.sharedSummaryId))}),m>1&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 sm:gap-4 bg-white rounded-lg shadow-sm border border-gray-200 p-3 sm:p-4",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-gray-600 text-center sm:text-left",children:["Showing ",(c-1)*g+1," to ",Math.min(c*g,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 ND(){const{sharedSummaryId:t}=Sa(),s=fs(),[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 L0(t)}catch(h){console.warn("Failed to mark as viewed:",h)}const x=await Xd(t);r(x)}catch(x){console.error("Failed to fetch summary details:",x),Y.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(He,{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(ot,{className:"h-4 w-4 text-orange-600"}):e.jsx(Pe,{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(We,{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(Ss,{className:"h-4 w-4 mr-2"}),"Back to Shared Summaries"]}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-2",children:"Request Summary"})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 mb-6",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:a.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",a.requestNumber]})]}),e.jsxs(le,{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(Os,{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:it(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:it(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(le,{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(Os,{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(Pe,{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 wD(){const{requestId:t}=Sa(),s=fs(),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(M0,{requestId:t||""})})})}function lb({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(le,{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 da({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:l,testId:o="stats-card",onClick:c}){return e.jsx(q,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":o,onClick:c,children:e.jsx(se,{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 CD({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(da,{label:"Total",value:t.total,icon:Pe,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(da,{label:"Pending",value:t.pending,icon:ot,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(da,{label:"Paused",value:t.paused,icon:gr,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(da,{label:"Approved",value:t.approved,icon:He,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(da,{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(da,{label:"Draft",value:t.draft,icon:$l,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(da,{label:"Closed",value:t.closed,icon:Ul,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 SD({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,onSearchChange:n,onStatusChange:i,onPriorityChange:l,onTemplateTypeChange:o}){return e.jsx(q,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(se,{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-3 sm:gap-4 items-start md:items-center",children:[e.jsxs("div",{className:"flex-1 relative w-full",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(Ee,{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(Ke,{value:s,onValueChange:i,children:[e.jsx(Xe,{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(Qe,{placeholder:"Status"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"draft",children:"Draft"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"paused",children:"Paused"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ke,{value:a,onValueChange:l,children:[e.jsx(Xe,{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(Qe,{placeholder:"Priority"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Priority"}),e.jsx(J,{value:"express",children:"Express"}),e.jsx(J,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ke,{value:r,onValueChange:o,children:[e.jsx(Xe,{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(Qe,{placeholder:"Template Type"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]})]})]})})})}function AD(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:ss,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ss,iconColor:"text-gray-600"}}}function TD(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:He,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:ot,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:He,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:$l,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:tt,iconColor:"text-gray-600"}}}const kD=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 DD({request:t,index:s,onViewRequest:a}){var o;const r=TD(t.status),n=AD(t.priority),i=r.icon,l=n.icon;return e.jsx(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(q,{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(se,{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(le,{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(le,{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(gr,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(le,{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(le,{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:kD(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(vs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400 group-hover:text-blue-600 transition-colors flex-shrink-0 mt-1"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-4 pt-3 border-t border-gray-100",children:[e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16"?e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Qs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-emerald-600 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm font-medium text-emerald-700","data-testid":"form16-ocr-flow",children:"Form 16 OCR FLOW"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ht,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm truncate","data-testid":"current-approver",children:[e.jsx("span",{className:"text-gray-500",children:"Current Approver:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.currentApprover})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm","data-testid":"approval-level",children:[e.jsx("span",{className:"text-gray-500",children:"Approval Level:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.approverLevel})]})]})]})}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-500",children:[e.jsx(ot,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",_a(t.submittedDate)]})]})]})]})})})})}function RD({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(q,{"data-testid":"loading-state",children:e.jsx(se,{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(q,{"data-testid":"empty-state",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(Pe,{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(DD,{request:l,index:o,onViewRequest:i},l.id))})}function ID(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 ob(t){return Array.isArray(t)?t.map(ID):[]}function FD({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=ob(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 PD={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},cb=An({name:"myRequests",initialState:PD,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:ED,setStatusFilter:_D,setPriorityFilter:MD,setTemplateTypeFilter:LD,setCurrentPage:OD,clearFilters:$D}=cb.actions;function UD({onFiltersChange:t,debounceMs:s=500}={}){const a=vi(),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(ED(y)),[a]),p=u.useCallback(y=>a(_D(y)),[a]),x=u.useCallback(y=>a(MD(y)),[a]),h=u.useCallback(y=>a(LD(y)),[a]),g=u.useCallback(y=>a(OD(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($D())},[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 BD({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=xs(),r=FD({itemsPerPage:10}),n=u.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=UD(),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 Ut.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=ob(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(lb,{icon:Pe,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(CD,{stats:f,onStatusFilter:y=>{i.setStatusFilter(y)}}),e.jsx(SD,{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(RD,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(qr,{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 db({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(lb,{icon:Pe,title:i(),description:l(),testId:"requests-header"}),e.jsx(le,{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 mb({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(da,{label:"Total",value:t.total,icon:Pe,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(da,{label:"Pending",value:t.pending,icon:ot,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(da,{label:"Paused",value:t.paused,icon:gr,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(da,{label:"Approved",value:t.approved,icon:He,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(da,{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(da,{label:"Closed",value:t.closed,icon:Ul,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 zD=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:ss,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ss,iconColor:"text-gray-600"}}},Vh=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:He,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:ot,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"closed",icon:He,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"draft",icon:$l,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:tt,iconColor:"text-gray-600"}}},VD=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 WD(t){return t==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function HD({request:t,index:s,onViewRequest:a}){var p;const r=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",n=t==null?void 0:t.form16Submission,i=n==null?void 0:n.displayStatus,l=i&&/balance mismatch|failed/i.test(String(i)),o=r&&i?{color:l?"bg-red-100 !text-red-800 border-red-200":i==="Completed"?"bg-green-100 !text-green-800 border-green-200":"bg-gray-100 !text-gray-700 border-gray-200",icon:Vh(t.status).icon,label:i}:Vh(t.status),c=zD(t.priority),d=o.icon,m=c.icon;return e.jsx(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(q,{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(se,{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(le,{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(le,{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(gr,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(le,{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(le,{variant:"outline",className:`${f} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:g})})(),t.department&&e.jsx(le,{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:VD(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?WD(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(vs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400 group-hover:text-blue-600 transition-colors flex-shrink-0 mt-1"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-4 pt-3 border-t border-gray-100",children:[e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16"?e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Qs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-emerald-600 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm font-medium text-emerald-700","data-testid":"form16-ocr-flow",children:"Form 16 OCR FLOW"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ht,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm truncate","data-testid":"current-approver",children:[e.jsx("span",{className:"text-gray-500",children:"Current Approver:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.currentApprover})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm","data-testid":"approval-level",children:[e.jsx("span",{className:"text-gray-500",children:"Approval Level:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.approverLevel})]})]})]})}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-500",children:[e.jsx(ot,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",_a(t.submittedDate)]})]})]})]})})})})}function ub({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(q,{"data-testid":"loading-state",children:e.jsx(se,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(q,{"data-testid":"empty-state",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(Pe,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600",children:a?"Try adjusting your search or filters":"No requests match the current criteria"})]})}):e.jsx("div",{className:"space-y-4","data-testid":"requests-list",children:t.map((n,i)=>e.jsx(HD,{request:n,index:i,onViewRequest:r},n.id))})}const GD={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},xb=An({name:"requests",initialState:GD,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:YD,setStatusFilter:KD,setPriorityFilter:QD,setTemplateTypeFilter:XD,setRequestTypeFilter:JD,setForm16FinancialYear:ZD,setForm16Quarter:qD,setSlaComplianceFilter:eR,setDepartmentFilter:tR,setInitiatorFilter:sR,setApproverFilter:aR,setApproverFilterType:rR,setDateRange:Wh,setCustomStartDate:$o,setCustomEndDate:Uo,setShowCustomDatePicker:Bi,setCurrentPage:nR,clearFilters:iR}=xb.actions;function hb(){const t=vi(),{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(W=>W.requests),j=u.useCallback(W=>t(YD(W)),[t]),v=u.useCallback(W=>t(KD(W)),[t]),w=u.useCallback(W=>t(QD(W)),[t]),S=u.useCallback(W=>t(XD(W)),[t]),D=u.useCallback(W=>t(JD(W)),[t]),k=u.useCallback(W=>t(ZD(W)),[t]),C=u.useCallback(W=>t(qD(W)),[t]),F=u.useCallback(W=>t(eR(W)),[t]),N=u.useCallback(W=>t(tR(W)),[t]),E=u.useCallback(W=>t(sR(W)),[t]),_=u.useCallback(W=>t(aR(W)),[t]),z=u.useCallback(W=>t(rR(W)),[t]),R=u.useCallback(W=>t(Wh(W)),[t]),L=u.useCallback(W=>t($o(W)),[t]),V=u.useCallback(W=>t(Uo(W)),[t]),I=u.useCallback(W=>t(Bi(W)),[t]),A=u.useCallback(W=>t(nR(W)),[t]),G=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]),$=u.useCallback(()=>{t(iR())},[t]),M=u.useCallback(W=>{const P=W;t(Wh(P)),P!=="custom"?(t($o(void 0)),t(Uo(void 0)),t(Bi(!1))):t(Bi(!0))},[t]),T=u.useCallback(()=>{g&&f&&(g>f&&(t($o(f)),t(Uo(g))),t(Bi(!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:w,setTemplateTypeFilter:S,setRequestTypeFilter:D,setForm16FinancialYear:k,setForm16Quarter:C,setSlaComplianceFilter:F,setDepartmentFilter:N,setInitiatorFilter:E,setApproverFilter:_,setApproverFilterType:z,setDateRange:R,setCustomStartDate:L,setCustomEndDate:V,setShowCustomDatePicker:I,setCurrentPage:A,getFilters:G,clearFilters:$,handleDateRangeChange:M,handleApplyCustomDate:T}}function vl({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 ma.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 w=((j=(await ma.searchUsers(y.trim(),10,a)).data)==null?void 0:j.data)||[];l(w),c(w.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 lR(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,w)=>{const S=v.levelNumber||v.level_number||0;return(w.levelNumber||w.level_number||0)-S})[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 pb(t){return Array.isArray(t)?t.map(lR):[]}function oR(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 gb={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Tl,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(gb);var cR=gb.exports;const fb=kl(cR);var bb={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Tl,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(bb);var dR=bb.exports;const jb=kl(dR);is.extend(jb);is.extend(fb);function mR(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 w=(r.status||"").toString().toUpperCase();if(!(w==="APPROVED"||w==="REJECTED"||w==="CLOSED"))return!1;const D=((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 D?D!=="breached"&&D.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=is(s.startDate).startOf("day").toDate(),n=is(s.endDate).endOf("day").toDate();else{const i=is();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=is(m).startOf("day").toDate(),x=is(r).startOf("day").toDate(),h=is(n).endOf("day").toDate();return p>=x&&p<=h}const o=is(l).startOf("day").toDate(),c=is(r).startOf("day").toDate(),d=is(n).endOf("day").toDate();return o>=c&&o<=d}))}return a}is.extend(fb);is.extend(jb);function uR(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return it(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function yb(t,s){const a=mR(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var j,v,w,S,D;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||((w=c.initiator)==null?void 0:w.department)||"N/A",h=((S=c.currentApprover)==null?void 0:S.displayName)||((D=c.currentApprover)==null?void 0:D.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",f=uR(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 xR({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 hR(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 pR({onViewRequest:t}){const{user:s}=xs(),a=kn($=>$.dashboard.viewAsUser),r=u.useMemo(()=>Vl(s),[s]),n=u.useMemo(()=>r&&!a,[r,a]),i=hb(),[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),[w,S]=u.useState(0),[D]=u.useState(10),k=vl({filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter,source:"local"}),C=vl({filterValue:i.approverFilter,onFilterChange:i.setApproverFilter,source:"local"}),F=u.useCallback(async($,M,T,U)=>{try{const H=U==null?void 0:U.slaCompliance;if(H&&H!=="all"&&H!=="breached"&&H!=="compliant"){const P={};U!=null&&U.search&&(P.search=U.search),U!=null&&U.priority&&U.priority!=="all"&&(P.priority=U.priority),U!=null&&U.department&&U.department!=="all"&&(P.department=U.department),U!=null&&U.initiator&&U.initiator!=="all"&&(P.initiator=U.initiator),U!=null&&U.approver&&U.approver!=="all"&&(P.approver=U.approver,P.approverType=U.approverType||"current"),P.slaCompliance=H,$&&(P.dateRange=$),M&&(P.startDate=M.toISOString()),T&&(P.endDate=T.toISOString());const B=n?await Xs.listWorkflows({page:1,limit:1e3,...P}):await Xs.listParticipantRequests({page:1,limit:1e3,...P}),K=Array.isArray(B==null?void 0:B.data)?B.data:[],Z=K.length,te=K.filter(Ge=>{const Be=(Ge.status||"").toString().toUpperCase();return Be==="PENDING"||Be==="IN_PROGRESS"}).length,ae=K.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="APPROVED").length,xe=K.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="REJECTED").length,be=K.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="CLOSED").length;h({total:Z,pending:te,paused:0,approved:ae,rejected:xe,draft:0,closed:be})}else{const P=await Ut.getRequestStats($,M?M.toISOString():void 0,T?T.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:P.totalRequests||0,pending:P.openRequests||0,paused:P.pausedRequests||0,approved:P.approvedRequests||0,rejected:P.rejectedRequests||0,draft:P.draftRequests||0,closed:P.closedRequests||0})}}catch(H){console.error("Failed to fetch backend stats:",H)}finally{}},[n]),N=u.useCallback(async()=>{try{y(!0);const $=await Ut.getDepartments();f($)}catch{}finally{y(!1)}},[]),E=u.useRef(i),_=u.useRef(F);u.useEffect(()=>{E.current=i,_.current=F},[i,F]),u.useEffect(()=>{const $=new URLSearchParams(window.location.search),M=$.get("approver"),T=$.get("approverType"),U=$.get("slaCompliance"),H=$.get("dateRange"),W=$.get("startDate"),P=$.get("endDate");M&&i.setApproverFilter(M),(T==="current"||T==="any")&&i.setApproverFilterType(T),U&&i.setSlaComplianceFilter(U),H&&i.setDateRange(H),W&&i.setCustomStartDate(new Date(W)),P&&i.setCustomEndDate(new Date(P))},[]);const z=u.useCallback(async($=1)=>{try{$===1&&(d(!0),o([]));const M=E.current.getFilters(),T=await xR({page:$,itemsPerPage:D,filters:M,isOrgLevel:n});o(T.data),i.setCurrentPage(T.pagination.page),v(T.pagination.totalPages),S(T.pagination.total)}catch{o([])}finally{d(!1)}},[D,n]),R=u.useCallback(async()=>{try{p(!0);const $=await hR(n);await yb($,i.getFilters())}catch($){console.error("Failed to export requests:",$),alert("Failed to export requests. Please try again.")}finally{p(!1)}},[n,i]);u.useEffect(()=>{N()},[N]),u.useEffect(()=>{const $=setTimeout(()=>{const M={priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0,department:i.departmentFilter!=="all"?i.departmentFilter:void 0,initiator:i.initiatorFilter!=="all"?i.initiatorFilter:void 0,approver:i.approverFilter!=="all"?i.approverFilter:void 0,approverType:i.approverFilter!=="all"?i.approverFilterType:void 0,search:i.searchTerm||void 0,slaCompliance:i.slaComplianceFilter!=="all"?i.slaComplianceFilter:void 0},T=i.dateRange||"all";_.current(T,i.customStartDate,i.customEndDate,M)},i.searchTerm?500:0);return()=>clearTimeout($)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.templateTypeFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const L=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}),V=u.useRef(!1);u.useEffect(()=>{const $=i.currentPage||1;z($),V.current=!0},[]),u.useEffect(()=>{if(!V.current)return;const $=L.current;if(!($.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))return;const T=setTimeout(()=>{i.setCurrentPage(1),z(1),L.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!==$.searchTerm?500:0);return()=>clearTimeout(T)},[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 I=u.useCallback($=>{$>=1&&$<=j&&(i.setCurrentPage($),z($))},[j,z,i]),A=u.useMemo(()=>pb(l),[l]),G=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}:oR([],n,x,!1,w,A),[n,x,w,A]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(db,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:R}),e.jsx(mb,{stats:G,onStatusFilter:$=>{i.setStatusFilter($)}}),e.jsx(q,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(se,{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(le,{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(qt,{}),i.isForm16?e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"All Templates"}),e.jsxs(Ke,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(Xe,{className:"h-10 w-[180px]","data-testid":"template-type-filter",children:e.jsx(Qe,{placeholder:"All Templates"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Custom"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(J,{value:"FORM_16",children:"Form 16"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Financial Year"}),e.jsxs(Ke,{value:i.form16FinancialYear,onValueChange:i.setForm16FinancialYear,children:[e.jsx(Xe,{className:"h-10 w-[140px]","data-testid":"form16-financial-year-filter",children:e.jsx(Qe,{placeholder:"Financial Year"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Years"}),e.jsx(J,{value:"2024-25",children:"2024-25"}),e.jsx(J,{value:"2023-24",children:"2023-24"}),e.jsx(J,{value:"2022-23",children:"2022-23"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Quarter"}),e.jsxs(Ke,{value:i.form16Quarter,onValueChange:i.setForm16Quarter,children:[e.jsx(Xe,{className:"h-10 w-[130px]","data-testid":"form16-quarter-filter",children:e.jsx(Qe,{placeholder:"Quarter"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Quarters"}),e.jsx(J,{value:"Q1",children:"Q1"}),e.jsx(J,{value:"Q2",children:"Q2"}),e.jsx(J,{value:"Q3",children:"Q3"}),e.jsx(J,{value:"Q4",children:"Q4"})]})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ee,{placeholder:"Search requests...",value:i.searchTerm,onChange:$=>i.setSearchTerm($.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ke,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Xe,{className:"h-10","data-testid":"status-filter",children:e.jsx(Qe,{placeholder:"All Status"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"paused",children:"Paused"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ke,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(Xe,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Qe,{placeholder:"All Priority"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Priority"}),e.jsx(J,{value:"express",children:"Express"}),e.jsx(J,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ke,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(Xe,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Qe,{placeholder:"All Templates"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(J,{value:"FORM_16",children:"Form 16"})]})]}),e.jsxs(Ke,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:b||g.length===0,children:[e.jsx(Xe,{className:"h-10","data-testid":"department-filter",children:e.jsx(Qe,{placeholder:b?"Loading...":"All Departments"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Departments"}),g.map($=>e.jsx(J,{value:$,children:$},$))]})]}),e.jsxs(Ke,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Xe,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Qe,{placeholder:"All SLA Status"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All SLA Status"}),e.jsx(J,{value:"compliant",children:"Compliant"}),e.jsx(J,{value:"on-track",children:"On Track"}),e.jsx(J,{value:"approaching",children:"Approaching"}),e.jsx(J,{value:"critical",children:"Critical"}),e.jsx(J,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children: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(Nt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{placeholder:"Search initiator...",value:k.searchQuery,onChange:$=>k.handleSearch($.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($=>e.jsx("button",{type:"button",onClick:()=>k.handleSelect($),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:$.displayName||$.email}),$.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:$.email})]})},$.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(Ke,{value:i.approverFilterType,onValueChange:$=>i.setApproverFilterType($),children:[e.jsx(Xe,{className:"h-7 w-32 text-xs",children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(J,{value:"current",children:"Current Only"}),e.jsx(J,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:C.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:C.selectedUser.displayName||C.selectedUser.email}),e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:C.handleClear,children:e.jsx(Nt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{placeholder:"Search approver...",value:C.searchQuery,onChange:$=>C.handleSearch($.target.value),onFocus:()=>{C.searchResults.length>0&&C.setShowResults(!0)},onBlur:()=>setTimeout(()=>C.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),C.showResults&&C.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:C.searchResults.map($=>e.jsx("button",{type:"button",onClick:()=>C.handleSelect($),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:$.displayName||$.email}),$.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:$.email})]})},$.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(jt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Xe,{className:"w-[160px] h-10",children:e.jsx(Qe,{placeholder:"Date Range"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(ra,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(na,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(jt,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${it(i.customStartDate,"MMM d, yyyy")} - ${it(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date",children:"Start Date"}),e.jsx(sa,{value:i.customStartDate||null,onChange:$=>{const M=$?new Date($):void 0;M?(i.setCustomStartDate(M),i.customEndDate&&M>i.customEndDate&&i.setCustomEndDate(M)):i.setCustomStartDate(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",children:"End Date"}),e.jsx(sa,{value:i.customEndDate||null,onChange:$=>{const M=$?new Date($):void 0;M?(i.setCustomEndDate(M),i.customStartDate&&M<i.customStartDate&&i.setCustomStartDate(M)):i.setCustomEndDate(void 0)},minDate:i.customStartDate||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsx(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(ub,{requests:A,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(qr,{currentPage:i.currentPage||1,totalPages:j,totalRecords:w,itemsPerPage:D,onPageChange:I,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function gR({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 Hh=100;async function fR(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:Hh,...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===Hh}}return s}function bR({onViewRequest:t}){const s=hb(),a=u.useMemo(()=>{try{const H=lt.getUserData();return xd(H)}catch(H){return console.error("[UserAllRequests] Error getting user filter type:",H),"STANDARD"}},[]),r=u.useMemo(()=>B6(a),[a]),n=a==="DEALER",i=u.useCallback(()=>{const H=s.getFilters();if(!n)return H;const W=s.requestTypeFilter;if(W==="form_16")return{templateType:"FORM_16",financialYear:s.form16FinancialYear!=="all"?s.form16FinancialYear:void 0,quarter:s.form16Quarter!=="all"?s.form16Quarter:void 0};if(W==="claim_management")return{templateType:"DEALER CLAIM",search:H.search,status:H.status!=="all"?H.status:void 0,dateRange:H.dateRange,startDate:H.startDate,endDate:H.endDate,initiator:H.initiator,approver:H.approver,approverType:H.approverType};const{priority:P,templateType:B,department:K,slaCompliance:Z,...te}=H;return te},[s,n]),l=u.useCallback(()=>{if(n){const H=s.requestTypeFilter;return H==="form_16"?s.form16FinancialYear!=="all"||s.form16Quarter!=="all":H==="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,w]=u.useState(!1),[S,D]=u.useState(1),[k,C]=u.useState(0),[F]=u.useState(10),N=vl({filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter,source:"local"}),E=vl({filterValue:s.approverFilter,onFilterChange:s.setApproverFilter,source:"local"}),_=u.useCallback(async(H,W,P,B)=>{try{const K=await Ut.getRequestStats(H,W?W.toISOString():void 0,P?P.toISOString():void 0,void 0,B==null?void 0:B.priority,B==null?void 0:B.templateType,B==null?void 0:B.department,B==null?void 0:B.initiator,B==null?void 0:B.approver,B==null?void 0:B.approverType,B==null?void 0:B.search,B==null?void 0:B.slaCompliance,!0);g({total:K.totalRequests||0,pending:K.openRequests||0,paused:K.pausedRequests||0,approved:K.approvedRequests||0,rejected:K.rejectedRequests||0,draft:K.draftRequests||0,closed:K.closedRequests||0})}catch(K){console.error("Failed to fetch backend stats:",K)}},[]),z=u.useCallback(async()=>{try{j(!0);const H=await Ut.getDepartments();b(H)}catch{}finally{j(!1)}},[]);u.useEffect(()=>{a==="STANDARD"&&ad().then(H=>w(!!(H.canViewForm16Submission||H.canView26AS))).catch(()=>w(!1))},[a]);const R=u.useRef(s),L=u.useRef(_),V=u.useRef(i);u.useEffect(()=>{R.current=s,L.current=_,V.current=i},[s,_,i]);const I=u.useCallback(async(H=1)=>{try{H===1&&(m(!0),c([]));const W=V.current(),P=await gR({page:H,itemsPerPage:F,filters:W});c(P.data),s.setCurrentPage(P.pagination.page),D(P.pagination.totalPages),C(P.pagination.total)}catch{c([])}finally{m(!1)}},[F,s]),A=u.useCallback(async()=>{try{x(!0);const H=i(),W=await fR(H);await yb(W,H)}catch(H){console.error("Failed to export requests:",H),alert("Failed to export requests. Please try again.")}finally{x(!1)}},[i]);u.useEffect(()=>{z()},[z]),u.useEffect(()=>{const H=setTimeout(()=>{const W={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"&&(W.priority=s.priorityFilter),s.templateTypeFilter!=="all"&&(W.templateType=s.templateTypeFilter),s.departmentFilter!=="all"&&(W.department=s.departmentFilter),s.slaComplianceFilter!=="all"&&(W.slaCompliance=s.slaComplianceFilter));const P=s.dateRange==="all"?"all":s.dateRange||"month";L.current(P,s.customStartDate,s.customEndDate,W)},s.searchTerm?500:0);return()=>clearTimeout(H)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter,n]);const G=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}),$=u.useRef(!1);u.useEffect(()=>{const H=s.currentPage||1;I(H),$.current=!0},[]),u.useEffect(()=>{if(!$.current)return;const H=G.current;if(!(H.searchTerm!==s.searchTerm||H.statusFilter!==s.statusFilter||H.priorityFilter!==s.priorityFilter||H.templateTypeFilter!==s.templateTypeFilter||H.slaComplianceFilter!==s.slaComplianceFilter||H.departmentFilter!==s.departmentFilter||H.initiatorFilter!==s.initiatorFilter||H.approverFilter!==s.approverFilter||H.approverFilterType!==s.approverFilterType||H.dateRange!==s.dateRange||H.customStartDate!==s.customStartDate||H.customEndDate!==s.customEndDate))return;const P=setTimeout(()=>{s.setCurrentPage(1),I(1),G.current={searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}},s.searchTerm!==H.searchTerm?500:0);return()=>clearTimeout(P)},[s.searchTerm,s.statusFilter,s.priorityFilter,s.templateTypeFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const M=u.useCallback(H=>{H>=1&&H<=S&&(s.setCurrentPage(H),I(H))},[S,I,s]),T=u.useMemo(()=>pb(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 H=T.filter(Z=>{const te=(Z.status||"").toString().toLowerCase();return te==="pending"||te==="in-progress"}).length,W=T.filter(Z=>(Z.status||"").toString().toLowerCase()==="paused").length,P=T.filter(Z=>(Z.status||"").toString().toLowerCase()==="approved").length,B=T.filter(Z=>(Z.status||"").toString().toLowerCase()==="rejected").length,K=T.filter(Z=>(Z.status||"").toString().toLowerCase()==="closed").length;return{total:k>0?k:T.length,pending:H,paused:W,approved:P,rejected:B,draft:0,closed:K}},[h,k,T]);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(db,{isOrgLevel:!1,isAdmin:!1,loading:d,exporting:p,onExport:A}),e.jsx(mb,{stats:U,onStatusFilter:H=>{s.setStatusFilter(H)}}),e.jsx(r,{requestTypeFilter:s.requestTypeFilter,onRequestTypeChange:H=>s.setRequestTypeFilter(H),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:N,approverSearch:E,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(ub,{requests:T,loading:d,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(qr,{currentPage:s.currentPage||1,totalPages:S,totalRecords:k,itemsPerPage:F,onPageChange:M,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function jR(){const t=fs();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(q,{children:e.jsxs(se,{className:"p-8 text-center",children:[e.jsx(tt,{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(Ss,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function yR({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(es,{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 vR({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(q,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(se,{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(ss,{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(la,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(q,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(se,{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(He,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(q,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[t.avgResponseHours.toFixed(1),"h"]}),e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(Yc,{className:"w-5 h-5 text-purple-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:t.avgResponseHours<24?`${(t.avgResponseHours/8).toFixed(1)} working days`:`${(t.avgResponseHours/24).toFixed(1)} days`})]})]}),e.jsxs(q,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(se,{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(ot,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function NR({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(q,{"data-testid":"approver-actions-stats",children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Approver's Actions"}),e.jsxs(Se,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?W1(a,r,n,""):"(all time)"]})]}),e.jsxs(se,{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(es,{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(He,{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(ot,{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(Ul,{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(Pe,{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(ss,{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(by,{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(tt,{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(xl,{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 wR({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(q,{"data-testid":"approver-performance-filters",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Filters"}),e.jsx(O,{variant:"ghost",size:"sm",onClick:v,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(se,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ee,{placeholder:"Search requests...",value:t,onChange:w=>m(w.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(Ke,{value:s,onValueChange:p,children:[e.jsx(Xe,{"data-testid":"status-filter",children:e.jsx(Qe,{placeholder:"Status"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ke,{value:a,onValueChange:x,children:[e.jsx(Xe,{"data-testid":"priority-filter",children:e.jsx(Qe,{placeholder:"Priority"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Priority"}),e.jsx(J,{value:"express",children:"Express"}),e.jsx(J,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ke,{value:r,onValueChange:h,children:[e.jsx(Xe,{"data-testid":"sla-compliance-filter",children:e.jsx(Qe,{placeholder:"SLA Compliance"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All SLA"}),e.jsx(J,{value:"compliant",children:"Compliant"}),e.jsx(J,{value:"on-track",children:"On Track"}),e.jsx(J,{value:"approaching",children:"Approaching"}),e.jsx(J,{value:"critical",children:"Critical"}),e.jsx(J,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:n,onValueChange:g,children:[e.jsx(Xe,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Qe,{placeholder:"Date Range"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(ra,{open:o,onOpenChange:f,children:[e.jsx(na,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(jt,{className:"w-4 h-4"}),c&&d?`${it(c,"MMM d")} - ${it(d,"MMM d")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Ee,{id:"start-date",type:"date",value:c?it(c,"yyyy-MM-dd"):"",onChange:w=>{const S=w.target.value?new Date(w.target.value):void 0;S?(b(S),d&&S>d&&y(S)):b(void 0)},max:it(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Ee,{id:"end-date",type:"date",value:d?it(d,"yyyy-MM-dd"):"",onChange:w=>{const S=w.target.value?new Date(w.target.value):void 0;S?(y(S),c&&S<c&&b(S)):y(void 0)},min:c?it(c,"yyyy-MM-dd"):void 0,max:it(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 CR=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Qs,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:ss,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ss,iconColor:"text-gray-600"}}},SR=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:He,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:ot,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:ot,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:He,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"}}},AR=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 TR(t){if(!t)return"N/A";try{return it(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function kR(t){if(!t)return"N/A";try{return it(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function Nl(t){const{requestId:s,status:a,request:r,navigate:n}=t;if((a==null?void 0:a.toLowerCase())==="draft"||a==="DRAFT"){n(`/edit-request/${s}`);return}const l=fD(s);n(l)}function DR({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const c=fs();return e.jsxs(q,{"data-testid":"approver-performance-request-list",children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Request Details"}),e.jsxs(Se,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(se,{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(Pe,{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=CR(d.priority),p=SR(d.status),x=AR(d.slaStatus||""),h=m.icon,g=p.icon;return e.jsx(q,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{Nl({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(se,{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(le,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(h,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(le,{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(le,{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(He,{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(ot,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(le,{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(Ht,{className:"w-3 h-3"}),d.initiatorName,d.initiatorDepartment&&e.jsxs("span",{className:"ml-1",children:["(",d.initiatorDepartment,")"]})]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"submission-date",children:[e.jsx(ot,{className:"w-3 h-3"}),"Submitted: ",TR(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(He,{className:"w-3 h-3"}),"Action: ",kR(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(ss,{className:"w-3 h-3"}),"Level ",d.levelNumber," of ",d.totalLevels]}),d.levelElapsedHours&&d.levelElapsedHours>0&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"tat-info",children:[e.jsx(Yc,{className:"w-3 h-3"}),Jt(d.levelElapsedHours)," / ",Jt(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(O,{variant:"ghost",size:"sm",onClick:f=>{f.stopPropagation(),Nl({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(vs,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(qr,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function RR(){const[t]=Wp(),[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,w]=u.useState(void 0),S=u.useCallback(()=>{a(""),n("all"),l("all"),c("all"),m("all"),x(void 0),g(void 0),j(void 0),w(void 0),b(!1)},[]),D=u.useCallback(C=>{const F=C;m(F),F!=="custom"?(x(void 0),g(void 0),j(void 0),w(void 0),b(!1)):(j(p),w(h),b(!0))},[p,h]),k=u.useCallback(()=>{if(y&&v){if(y>v){const C=y;x(v),g(C),j(v),w(C)}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:w,clearFilters:S,handleDateRangeChange:D,handleApplyCustomDate:k}}function IR({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,w]=u.useState(1),[S,D]=u.useState(1),[k,C]=u.useState(0),F=u.useRef(!0),N=u.useCallback(async()=>{if(t)try{const R=s==="all"?void 0:s,L=await Ut.getSingleApproverStats(t,R,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);x(L)}catch(R){console.error("[ApproverPerformance] Failed to fetch approver stats:",R),x(null)}},[t,s,a,r,i,l]),E=u.useCallback(async(R=1)=>{if(!t){b(!1);return}try{b(!0);const L=await Ut.getRequestsByApprover(t,R,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(L.requests),C(L.pagination.totalRecords),D(L.pagination.totalPages),w(L.pagination.currentPage),g(L.requests)}catch(L){console.error("Failed to fetch requests:",L)}finally{b(!1),j(!1)}},[t,s,a,r,n,i,l,o,c]);u.useEffect(()=>{F.current&&(F.current=!1,N(),E(1))},[]),u.useEffect(()=>{F.current||N()},[s,a,r,i,l]),u.useEffect(()=>{F.current||E(1)},[s,a,r,n,i,l,o]);const _=u.useCallback(()=>{j(!0),N(),E(1)},[N,E]),z=u.useCallback(R=>{E(R)},[E]);return{requests:d,approverStats:p,allFilteredRequests:h,loading:f,refreshing:y,currentPage:v,totalPages:S,totalRecords:k,handleRefresh:_,handlePageChange:z}}const Gh=10;function FR(){const[t]=Wp(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=RR(),n=IR({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:Gh});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(yR,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(vR,{approverStats:n.approverStats}),n.approverStats&&e.jsx(NR,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(wR,{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(DR,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:Gh,onPageChange:n.handlePageChange})]}):e.jsx(jR,{})}function PR(){const{user:t}=xs(),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(q,{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(se,{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(ms,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Hl,{src:(t==null?void 0:t.picture)||""}),e.jsx(us,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),_r(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(js,{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:[_r(t)&&e.jsxs(le,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(js,{className:"w-3 h-3 mr-1"}),"Administrator"]}),On(t)&&e.jsxs(le,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(es,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(le,{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(q,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Ht,{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(Se,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(se,{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(wa,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Email"}),e.jsx("p",{className:"text-base text-gray-900 break-words",children:(t==null?void 0:t.email)||"Not provided"})]})]}),(t==null?void 0:t.firstName)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Ht,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"First Name"}),e.jsx("p",{className:"text-base text-gray-900",children:t.firstName})]})]}),(t==null?void 0:t.lastName)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Ht,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Last Name"}),e.jsx("p",{className:"text-base text-gray-900",children:t.lastName})]})]}),(t==null?void 0:t.displayName)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Ht,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Display Name"}),e.jsx("p",{className:"text-base text-gray-900",children:t.displayName})]})]}),(t==null?void 0:t.phone)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(ji,{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(q,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-emerald-100 rounded-lg",children:e.jsx(Uu,{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(Se,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(se,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[(t==null?void 0:t.employeeId)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Ht,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Employee ID"}),e.jsx("p",{className:"text-base text-gray-900 font-medium",children:t.employeeId})]})]}),(t==null?void 0:t.department)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(zc,{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(Uu,{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(js,{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(le,{variant:_r(t)||On(t)?"default":"secondary",className:_r(t)?"bg-yellow-400 text-slate-900":On(t)?"bg-blue-400 text-slate-900":"",children:_r(t)?"Administrator":On(t)?"Management":"User"}),(_r(t)||On(t))&&e.jsx(He,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(q,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(jt,{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(Se,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(se,{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(He,{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(le,{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 zi="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",ER="https://reflow-uat.royalenfield.com/";function Bo(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 _R(){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 MR(t){if(zi.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:Bo(zi)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Bo(zi)})}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:Bo(zi)})}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(`${ER}/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 LR(){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 _R()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await MR(s)}catch(a){throw a}}function Ec({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(Dj,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:Oe("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(Rj,{"data-slot":"slider-track",className:Oe("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(Ij,{"data-slot":"slider-range",className:Oe("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,c)=>e.jsx(Fj,{"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 OR({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 N,E;try{n(!0),c(null);const _=await Zl();a(_)}catch(_){c(((E=(N=_.response)==null?void 0:N.data)==null?void 0:E.error)||"Failed to load configurations")}finally{n(!1)}},g=async N=>{var E,_;try{l(N.configKey),c(null);const z=d[N.configKey]??N.configValue;if(N.validationRules){const R=parseFloat(z);if(N.valueType==="NUMBER"){if(N.validationRules.min!==void 0&&R<N.validationRules.min)throw new Error(`Value must be at least ${N.validationRules.min}`);if(N.validationRules.max!==void 0&&R>N.validationRules.max)throw new Error(`Value must be at most ${N.validationRules.max}`)}}await Gs(N.configKey,z),a(R=>R.map(L=>L.configKey===N.configKey?{...L,configValue:z}:L)),m(R=>{const L={...R};return delete L[N.configKey],L}),x(`${N.displayName} updated successfully`),setTimeout(()=>x(null),3e3),t&&t()}catch(z){c(z.message||((_=(E=z.response)==null?void 0:E.data)==null?void 0:_.error)||"Failed to save configuration")}finally{l(null)}},f=async N=>{var E,_;if(confirm(`Reset "${N.displayName}" to default value?`))try{l(N.configKey),c(null),await NT(N.configKey),a(z=>z.map(R=>R.configKey===N.configKey?{...R,configValue:R.defaultValue||""}:R)),m(z=>{const R={...z};return delete R[N.configKey],R}),x(`${N.displayName} reset to default`),setTimeout(()=>x(null),3e3)}catch(z){c(((_=(E=z.response)==null?void 0:E.data)==null?void 0:_.error)||"Failed to reset configuration")}finally{l(null)}},b=(N,E)=>{m(_=>({..._,[N]:E}))},y=N=>d[N.configKey]??N.configValue,j=N=>d[N.configKey]!==void 0&&d[N.configKey]!==N.configValue,v=N=>{var z,R,L,V;const E=y(N),_=i===N.configKey;if(!N.isEditable)return e.jsxs("div",{className:"p-3 bg-slate-100 border border-slate-200 rounded-md",children:[e.jsx("p",{className:"text-sm text-slate-700 font-mono",children:N.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(tt,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(N.uiComponent||N.valueType.toLowerCase()){case"toggle":return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${E==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${E==="true"?"text-green-700":"text-slate-600"}`,children:E==="true"?"Enabled":"Disabled"})]}),e.jsx(ds,{checked:E==="true",onCheckedChange:$=>b(N.configKey,$?"true":"false"),disabled:_})]});case"slider":const I=parseInt(E)||0,A=((z=N.validationRules)==null?void 0:z.min)||0,G=((R=N.validationRules)==null?void 0:R.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:[I,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",A,"-",G]})]}),e.jsx(Ec,{value:[I],min:A,max:G,step:1,onValueChange:([$])=>{$!==void 0&&b(N.configKey,$.toString())},disabled:_,className:"w-full"})]});case"number":return e.jsx(Ee,{type:"number",value:E,onChange:$=>b(N.configKey,$.target.value),disabled:_,min:(L=N.validationRules)==null?void 0:L.min,max:(V=N.validationRules)==null?void 0:V.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(Ee,{type:"text",value:E,onChange:$=>b(N.configKey,$.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"})}},w=N=>{switch(N){case"TAT_SETTINGS":return e.jsx(ot,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Pe,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx($s,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Fl,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(Sn,{className:"w-5 h-5"});default:return e.jsx(pr,{className:"w-5 h-5"})}},S=["DASHBOARD_LAYOUT"],D=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],k=s.filter(N=>!S.includes(N.configCategory)&&!D.includes(N.configKey)),C=k.reduce((N,E)=>(N[E.configCategory]||(N[E.configCategory]=[]),N[E.configCategory].push(E),N),{});if(Object.keys(C).forEach(N=>{const E=C[N];E&&E.sort((_,z)=>_.sortOrder-z.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(We,{className:"w-8 h-8 animate-spin text-gray-400"})});if(k.length===0)return e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{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(pr,{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(C);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(He,{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(tt,{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(Ii,{defaultValue:F[0],className:"w-full",children:[e.jsx(Fi,{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(N=>e.jsx(Bt,{value:N,className:"flex-1 min-w-[120px] text-[10px] xs:text-xs sm:text-sm font-medium py-2 sm:py-2.5 px-2 sm:px-3 rounded-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-slate-900 transition-all",children:e.jsx("span",{className:"truncate block",children:N.replace(/_/g," ")})},N))}),F.map(N=>{var E,_,z;return e.jsx(zt,{value:N,className:"space-y-4 mt-6",children:e.jsxs(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx("div",{className:"text-white",children:w(N)})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg font-semibold text-slate-900",children:N.replace(/_/g," ")}),e.jsxs(Se,{className:"text-sm",children:[((E=C[N])==null?void 0:E.length)||0," setting",(((_=C[N])==null?void 0:_.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(se,{className:"space-y-6",children:(z=C[N])==null?void 0:z.map(R=>e.jsxs("div",{className:"space-y-3 pb-6 border-b border-slate-100 last:border-b-0 last:pb-0 hover:bg-slate-50/50 -mx-6 px-6 py-4 rounded-md transition-colors",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[e.jsx(ne,{className:"text-sm font-semibold text-slate-900",children:R.displayName}),j(R)&&e.jsx(le,{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"}),R.requiresRestart&&e.jsx(le,{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"})]}),R.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:R.description}),R.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:R.defaultValue})]})]})}),v(R),R.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(O,{size:"sm",onClick:()=>g(R),disabled:!j(R)||i===R.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===R.configKey?e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(La,{className:"w-4 h-4"}),"Save Changes"]})}),R.defaultValue&&e.jsxs(O,{size:"sm",variant:"outline",onClick:()=>f(R),disabled:i===R.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(_p,{className:"w-4 h-4"}),"Reset to Default"]})]})]},R.configKey))})]})},N)})]})]})}function $R(){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 N,E;try{r(!0),p(null);const _=await TT(n);s(_)}catch(_){p(((E=(N=_.response)==null?void 0:N.data)==null?void 0:E.error)||"Failed to load holidays")}finally{r(!1)}},y=()=>{f({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),o(!0)},j=N=>{f({holidayDate:N.holidayDate,holidayName:N.holidayName,description:N.description||"",holidayType:N.holidayType,isRecurring:N.isRecurring}),d(N),o(!0)},v=()=>{if(c)return;const N=new Date;return N.setDate(N.getDate()+1),N.toISOString().split("T")[0]},w=async()=>{var N,E;try{if(p(null),!g.holidayDate||!g.holidayName){p("Holiday date and name are required");return}c?(await DT(c.holidayId,g),Y.success("Holiday updated successfully")):(await kT(g),Y.success("Holiday created successfully")),await b(),o(!1),setTimeout(()=>h(null),3e3)}catch(_){p(((E=(N=_.response)==null?void 0:N.data)==null?void 0:E.error)||"Failed to save holiday")}},S=async N=>{var E,_;if(confirm(`Delete "${N.holidayName}"?`))try{p(null),await RT(N.holidayId),Y.success("Holiday deleted successfully"),await b()}catch(z){const R=((_=(E=z.response)==null?void 0:E.data)==null?void 0:_.error)||"Failed to delete holiday";p(R),Y.error(R)}},D=N=>{switch(N){case"NATIONAL":return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300";case"REGIONAL":return"bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-800 border-blue-300";case"ORGANIZATIONAL":return"bg-gradient-to-r from-purple-50 to-violet-50 text-purple-800 border-purple-300";case"OPTIONAL":return"bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-300";default:return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300"}},k=Array.from({length:5},(N,E)=>new Date().getFullYear()-1+E),C=t.reduce((N,E)=>{const _=new Date(E.holidayDate).toLocaleString("default",{month:"long"});return N[_]||(N[_]=[]),N[_].push(E),N},{}),F=Object.keys(C).sort((N,E)=>{const _=new Date(Date.parse(N+" 1, 2000")).getMonth(),z=new Date(Date.parse(E+" 1, 2000")).getMonth();return _-z});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(He,{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(tt,{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(q,{className:"shadow-lg border-0 rounded-md",children:e.jsx(me,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(jt,{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(Se,{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(Ke,{value:n.toString(),onValueChange:N=>i(parseInt(N)),children:[e.jsx(Xe,{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(Qe,{})}),e.jsx(Je,{className:"rounded-md",children:k.map(N=>e.jsx(J,{value:N.toString(),children:N},N))})]}),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(os,{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(We,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{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(jt,{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(os,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:F.map(N=>{var E,_,z;return e.jsxs(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[N," ",n]}),e.jsxs(Se,{className:"text-xs sm:text-sm",children:[((E=C[N])==null?void 0:E.length)||0," holiday",(((_=C[N])==null?void 0:_.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(jt,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:(z=C[N])==null?void 0:z.map(R=>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:R.holidayName}),e.jsx(le,{variant:"outline",className:`${D(R.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:R.holidayType}),R.isRecurring&&e.jsx(le,{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:Vg(R.holidayDate)}),R.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:R.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(R),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(O,{size:"sm",variant:"ghost",onClick:()=>S(R),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(Nr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},R.holidayId))})]},N)})}),e.jsx(gt,{open:l,onOpenChange:o,children:e.jsxs(ht,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(ft,{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(jt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(pt,{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(ne,{htmlFor:"date",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ee,{id:"date",type:"date",value:g.holidayDate,onChange:N=>f({...g,holidayDate:N.target.value}),min:v(),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:c?"Select the holiday date":"Select the holiday date (minimum: tomorrow)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"name",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Holiday Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ee,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:N=>f({...g,holidayName:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"description",className:"text-sm font-semibold text-slate-900",children:["Description ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Ee,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:N=>f({...g,description:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(Ke,{value:g.holidayType,onValueChange:N=>f({...g,holidayType:N}),children:[e.jsx(Xe,{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(Qe,{})}),e.jsxs(Je,{className:"rounded-lg",children:[e.jsx(J,{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(J,{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(J,{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(J,{value:"OPTIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-500"}),e.jsx("span",{children:"Optional"})]})})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select the category of this holiday"})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gradient-to-br from-slate-50 to-slate-100/50 border-2 border-slate-200 rounded-lg hover:border-slate-300 hover:bg-slate-100 transition-all cursor-pointer group",onClick:()=>f({...g,isRecurring:!g.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:g.isRecurring,onChange:N=>f({...g,isRecurring:N.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ne,{htmlFor:"recurring",className:"font-semibold cursor-pointer text-sm text-slate-900 block mb-1",children:"Recurring Holiday"}),e.jsx("p",{className:"text-xs text-slate-600",children:"This holiday will automatically repeat every year on the same date"})]})]})]}),e.jsxs(Rt,{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:w,disabled:!g.holidayDate||!g.holidayName,className:"h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(jt,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function UR(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function BR(){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}),[w,S]=u.useState("ELEVATED"),[D,k]=u.useState(1),[C,F]=u.useState(1),[N,E]=u.useState(0),_=10,z=u.useRef(null),R=u.useRef(null),L=u.useCallback(UR(async P=>{var B,K,Z;if(!P||!P.startsWith("@")||P.length<2){r([]),i(!1);return}i(!0);try{const te=P.slice(1),xe=((B=(await ma.searchUsers(te,20)).data)==null?void 0:B.data)||[];r(xe)}catch(te){console.error("Search failed:",te),h({type:"error",text:((Z=(K=te.response)==null?void 0:K.data)==null?void 0:Z.message)||"Failed to search users"})}finally{i(!1)}},300),[]),V=P=>{const B=P.target.value;s(B),L(B)},I=async P=>{o(P),s(P.email),r([]);const B=g.find(K=>K.email.toLowerCase()===P.email.toLowerCase()||K.userId===P.userId);if(B&&B.role)d(B.role);else try{const Z=(await ma.getAllUsers()).find(te=>te.email&&te.email.toLowerCase()===P.email.toLowerCase()||te.userId&&te.userId===P.userId);Z&&Z.role?d(Z.role):d("USER")}catch(K){console.error("Failed to check user role:",K),d("USER")}},A=async()=>{var P,B;if(!l||!c){h({type:"error",text:"Please select a user and role"});return}p(!0),h(null);try{await ma.assignRole(l.email,c),h({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await G(),await $()}catch(K){console.error("Role assignment failed:",K),h({type:"error",text:((B=(P=K.response)==null?void 0:P.data)==null?void 0:B.error)||"Failed to assign role"})}finally{p(!1)}},G=async(P=D)=>{var B,K,Z,te,ae,xe;y(!0);try{const be=await ma.getUsersByRole(w,P,_),Ge=((K=(B=be.data)==null?void 0:B.data)==null?void 0:K.users)||[],Be=(te=(Z=be.data)==null?void 0:Z.data)==null?void 0:te.pagination,_e=(xe=(ae=be.data)==null?void 0:ae.data)==null?void 0:xe.summary;f(Ge),Be&&(k(Be.currentPage),F(Be.totalPages),E(Be.totalUsers)),_e&&v({admins:_e.ADMIN||0,management:_e.MANAGEMENT||0,users:_e.USER||0})}catch(be){console.error("Failed to fetch users:",be)}finally{y(!1)}},$=async()=>{var P,B,K,Z,te,ae;try{const xe=await ma.getRoleStatistics(),be=((B=(P=xe.data)==null?void 0:P.data)==null?void 0:B.statistics)||((K=xe.data)==null?void 0:K.statistics)||[];v({admins:parseInt(((Z=be.find(Ge=>Ge.role==="ADMIN"))==null?void 0:Z.count)||"0"),management:parseInt(((te=be.find(Ge=>Ge.role==="MANAGEMENT"))==null?void 0:te.count)||"0"),users:parseInt(((ae=be.find(Ge=>Ge.role==="USER"))==null?void 0:ae.count)||"0")})}catch(xe){console.error("Failed to fetch statistics:",xe)}};u.useEffect(()=>{G(1),$()},[w]);const M=P=>{S(P),k(1)},T=P=>{G(P)},U=P=>{S(P),k(1),requestAnimationFrame(()=>{const B=R.current;B&&B.scrollIntoView({behavior:"smooth",block:"start"})})};u.useEffect(()=>{const P=B=>{z.current&&!z.current.contains(B.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",P),()=>{document.removeEventListener("mousedown",P)}},[a]);const H=P=>{switch(P){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"}},W=P=>{switch(P){case"ADMIN":return e.jsx(dn,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(es,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(Ht,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(jy,{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(Se,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(se,{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(q,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${w==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>U("ADMIN"),children:e.jsx(se,{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:w==="ADMIN"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-xl shadow-md",children:e.jsx(dn,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(q,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${w==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>U("MANAGEMENT"),children:e.jsx(se,{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:w==="MANAGEMENT"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-blue-400 to-blue-500 rounded-xl shadow-md",children:e.jsx(es,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(q,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${w==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>U("USER"),children:e.jsx(se,{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:w==="USER"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-gray-400 to-gray-500 rounded-xl shadow-md",children:e.jsx(Ht,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(qt,{}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"Assign User Role"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Search for a user in Okta and assign them a role"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",ref:z,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(Ee,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:V,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(We,{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(P=>e.jsxs("button",{onClick:()=>I(P),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${P.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:P.displayName||P.email}),e.jsx("p",{className:"text-xs text-gray-600",children:P.email}),P.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[P.department,P.designation?` • ${P.designation}`:""]})]},P.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(Ke,{value:c,onValueChange:P=>d(P),children:[e.jsx(Xe,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Qe,{placeholder:"Select role"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(J,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(J,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(O,{onClick:A,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(We,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(js,{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(He,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(tt,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${x.type==="success"?"text-green-800":"text-red-800"}`,children:x.text})]})})]})]}),e.jsx(qt,{}),e.jsxs("div",{ref:R,children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"User Management"}),e.jsxs("p",{className:"text-sm text-gray-600",children:["View and manage user roles (",N," ",w!=="ALL"&&w!=="ELEVATED"?w.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Ke,{value:w,onValueChange:M,children:[e.jsx(Xe,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Qe,{placeholder:"Filter by role"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",j.admins+j.management,")"]})]})}),e.jsx(J,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",j.admins,")"]})]})}),e.jsx(J,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",j.management,")"]})]})}),e.jsx(J,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",j.users,")"]})]})}),e.jsx(J,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{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(We,{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(es,{className:"w-6 h-6 text-gray-400"})}),e.jsx("p",{className:"font-medium text-gray-700",children:"No users found"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:w==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2","data-testid":"users-list",children:g.map(P=>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-${P.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 ${H(P.role)} flex items-center justify-center shadow-sm`,children:W(P.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:P.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:P.email}),P.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[P.department,P.designation?` • ${P.designation}`:""]})]})]}),e.jsx(le,{className:`${H(P.role)} shrink-0`,"data-testid":`role-badge-${P.role}`,children:P.role})]})},P.userId))}),C>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 ",(D-1)*_+1," to ",Math.min(D*_,N)," of ",N," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{variant:"outline",size:"sm",onClick:()=>T(D-1),disabled:D===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,C)},(P,B)=>{let K;return C<=5||D<=3?K=B+1:D>=C-2?K=C-4+B:K=D-2+B,e.jsx(O,{variant:D===K?"default":"outline",size:"sm",onClick:()=>T(K),className:`w-9 h-9 p-0 ${D===K?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${K}-button`,children:K},K)})}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>T(D+1),disabled:D===C,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function zR(){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 S,D;try{r(!0),d(null);const k=await FT(!1);s(k)}catch(k){const C=((D=(S=k.response)==null?void 0:S.data)==null?void 0:D.error)||"Failed to load activity types";d(C),Y.error(C)}finally{r(!1)}},f=()=>{h({title:"",itemCode:"",taxationType:"",sapRefNo:"",creditPostingOn:""}),o(null),i(!0)},b=S=>{h({title:S.title,itemCode:S.itemCode||"",taxationType:S.taxationType||"",sapRefNo:S.sapRefNo||"",creditPostingOn:S.creditPostingOn||""}),o(S),i(!0)},y=async()=>{var S,D;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"),Y.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 ET(l.activityTypeId,k),Y.success("Activity type updated successfully")):(await PT(k),Y.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>p(null),3e3)}catch(k){const C=((D=(S=k.response)==null?void 0:S.data)==null?void 0:D.error)||"Failed to save activity type";d(C),Y.error(C)}},j=async S=>{var D,k;if(confirm(`Delete "${S.title}"? This will deactivate the activity type.`))try{d(null),await _T(S.activityTypeId),Y.success("Activity type deleted successfully"),await g()}catch(C){const F=((k=(D=C.response)==null?void 0:D.data)==null?void 0:k.error)||"Failed to delete activity type";d(F),Y.error(F)}},v=t.filter(S=>S.isActive!==!1&&S.isActive!==void 0),w=t.filter(S=>S.isActive===!1);return e.jsxs("div",{className:"space-y-6",children:[m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(He,{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(tt,{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(q,{className:"shadow-lg border-0 rounded-md",children:e.jsx(me,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Pe,{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(Se,{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(os,{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(We,{className:"w-8 h-8 animate-spin text-gray-400"})}):v.length===0?e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{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(Pe,{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(os,{className:"w-4 h-4"}),"Add First Activity Type"]})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Active Activity Types"}),e.jsxs(Se,{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(He,{className:"w-4 h-4 text-green-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:v.map(S=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 hover:border-slate-300 transition-all shadow-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-900 text-sm sm:text-base",children:S.title}),e.jsx(le,{variant:"outline",className:"bg-gradient-to-r from-green-50 to-emerald-50 text-green-800 border-green-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Active"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs sm:text-sm text-slate-600",children:[S.itemCode&&e.jsxs("span",{className:"font-medium",children:["Item Code: ",e.jsx("span",{className:"text-slate-900",children:S.itemCode})]}),S.taxationType&&e.jsxs("span",{className:"font-medium",children:["Taxation: ",e.jsx("span",{className:"text-slate-900",children:S.taxationType})]}),S.sapRefNo&&e.jsxs("span",{className:"font-medium",children:["SAP Ref: ",e.jsx("span",{className:"text-slate-900",children:S.sapRefNo})]}),S.creditPostingOn&&e.jsxs("span",{className:"font-medium",children:["Credit Posting On: ",e.jsx(le,{variant:"secondary",className:"ml-1 bg-slate-200 text-slate-800",children:S.creditPostingOn})]}),!S.itemCode&&!S.taxationType&&!S.sapRefNo&&!S.creditPostingOn&&e.jsx("span",{className:"text-slate-500 italic",children:"No additional details"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(O,{size:"sm",variant:"ghost",onClick:()=>b(S),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(O,{size:"sm",variant:"ghost",onClick:()=>j(S),className:"gap-1.5 text-red-600 hover:text-red-700 hover:bg-red-50 border border-transparent hover:border-red-200 text-xs sm:text-sm",children:[e.jsx(Nr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},S.activityTypeId))})]}),w.length>0&&e.jsxs(q,{className:"shadow-lg border-0 rounded-md border-amber-200",children:[e.jsx(me,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Inactive Activity Types"}),e.jsxs(Se,{className:"text-xs sm:text-sm",children:[w.length," inactive type",w.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-amber-50 rounded-md",children:e.jsx(tt,{className:"w-4 h-4 text-amber-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:w.map(S=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-amber-50/50 border border-amber-200 rounded-md hover:bg-amber-50 hover:border-amber-300 transition-all shadow-sm",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-700 text-sm sm:text-base line-through",children:S.title}),e.jsx(le,{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(S),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]})})]},S.activityTypeId))})]})]}),e.jsx(gt,{open:n,onOpenChange:i,children:e.jsxs(ht,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(ft,{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(Pe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(pt,{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(ne,{htmlFor:"title",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Title ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ee,{id:"title",placeholder:"e.g., Riders Mania Claims, Legal Claims Reimbursement",value:x.title,onChange:S=>h({...x,title:S.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the activity type title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"itemCode",className:"text-sm font-semibold text-slate-900",children:["Item Code ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Ee,{id:"itemCode",placeholder:"e.g., 1, 2, 3",value:x.itemCode,onChange:S=>h({...x,itemCode:S.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional item code for the activity type"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{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(Ke,{value:x.taxationType,onValueChange:S=>h({...x,taxationType:S}),children:[e.jsx(Xe,{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(Qe,{placeholder:"Select Taxation Type"})}),e.jsxs(Je,{className:"rounded-lg",children:[e.jsx(J,{value:"GST",className:"p-3",children:"GST"}),e.jsx(J,{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(ne,{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(Ee,{id:"sapRefNo",placeholder:"e.g., ZCNS, ZRE",value:x.sapRefNo,onChange:S=>h({...x,sapRefNo:S.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Required SAP reference number for CSV generation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{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(Ke,{value:x.creditPostingOn,onValueChange:S=>h({...x,creditPostingOn:S}),children:[e.jsx(Xe,{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(Qe,{placeholder:"Select Credit Posting Group"})}),e.jsxs(Je,{className:"rounded-lg",children:[e.jsx(J,{value:"Vehicles",className:"p-3",children:"Vehicles"}),e.jsx(J,{value:"Spares",className:"p-3",children:"Spares"}),e.jsx(J,{value:"GMA",className:"p-3",children:"GMA"}),e.jsx(J,{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(Rt,{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(Pe,{className:"w-4 h-4 mr-2"}),l?"Update Activity Type":"Add Activity Type"]})]})]})})]})}function Is({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:Oe("w-full caption-bottom text-sm",t),...s})})}function Fs({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:Oe("[&_tr]:border-b",t),...s})}function Ps({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:Oe("[&_tr:last-child]:border-0",t),...s})}function rt({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:Oe("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function De({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:Oe("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 Ne({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:Oe("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function VR(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function Yh({emails:t,onAdd:s,onRemove:a,placeholder:r}){const[n,i]=u.useState(""),l=()=>{const o=n.trim().toLowerCase();if(o){if(!VR(o)){Y.error("Please enter a valid email address");return}if(t.includes(o)){Y.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(Ee,{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(os,{className:"w-4 h-4"}),"Add"]})]}),t.length>0?e.jsx("div",{className:"rounded-md border",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{children:[e.jsx(De,{children:"Email"}),e.jsx(De,{className:"w-[80px] text-right",children:"Actions"})]})}),e.jsx(Ps,{children:t.map(o=>e.jsxs(rt,{children:[e.jsx(Ne,{className:"font-medium",children:o}),e.jsx(Ne,{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(Nr,{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 Kh(t,s){return{enabled:t,template:s}}const zo=()=>({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 WR(){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(zo()),[g,f]=u.useState(!0),[b,y]=u.useState(0),[j,v]=u.useState(Kh(!0,"Form 16 submitted successfully. Credit note: [CreditNoteRef].")),[w,S]=u.useState(Kh(!0,"Form 16 submission was unsuccessful. Issue: [Issue]. Please review.")),[D,k]=u.useState(!0),[C,F]=u.useState(0),[N,E]=u.useState(7),[_,z]=u.useState(0),[R,L]=u.useState(24),[V,I]=u.useState("09:00"),[A,G]=u.useState("Dear [Name], please submit Form 16A for the pending period. Due: [DueDate]."),[$,M]=u.useState(!0),[T,U]=u.useState(0),[H,W]=u.useState(12),[P,B]=u.useState("10:00"),[K,Z]=u.useState("Reminder: Dear [Name], your Form 16A submission is pending for request [Request ID]. Please complete it.");u.useEffect(()=>{let ae=!0;return wT().then(xe=>{if(ae){if(i(xe.submissionViewerEmails??[]),o(xe.twentySixAsViewerEmails??[]),d(xe.reminderEnabled??!0),p(typeof xe.reminderDays=="number"?xe.reminderDays:7),xe.notification26AsDataAdded){const be=xe.notification26AsDataAdded;h({enabled:be.enabled??!0,templateRe:be.templateRe??be.template??zo().templateRe,templateDealers:be.templateDealers??zo().templateDealers})}f(xe.reminder26AsUploadEnabled??!0),y(typeof xe.reminder26AsUploadAfterQuarterEndDays=="number"?xe.reminder26AsUploadAfterQuarterEndDays:0),xe.notificationForm16SuccessCreditNote&&v(xe.notificationForm16SuccessCreditNote),xe.notificationForm16Unsuccessful&&S(xe.notificationForm16Unsuccessful),k(xe.alertSubmitForm16Enabled??!0),F(typeof xe.alertSubmitForm16AfterQuarterEndDays=="number"?xe.alertSubmitForm16AfterQuarterEndDays:0),E(typeof xe.alertSubmitForm16EveryDays=="number"?xe.alertSubmitForm16EveryDays:7),z(xe.alertSubmitForm16FrequencyDays??0),L(xe.alertSubmitForm16FrequencyHours??24),I(xe.alertSubmitForm16RunAtTime!==void 0&&xe.alertSubmitForm16RunAtTime!==null?xe.alertSubmitForm16RunAtTime:"09:00"),G(xe.alertSubmitForm16Template??"Dear [Name], please submit Form 16A for the pending period. Due: [DueDate]."),M(xe.reminderNotificationEnabled??!0),U(xe.reminderFrequencyDays??0),W(xe.reminderFrequencyHours??12),B(xe.reminderRunAtTime!==void 0&&xe.reminderRunAtTime!==null?xe.reminderRunAtTime:"10:00"),Z(xe.reminderNotificationTemplate??"Reminder: Dear [Name], your Form 16A submission is pending for request [Request ID]. Please complete it.")}}).catch(()=>{ae&&Y.error("Failed to load Form 16 configuration")}).finally(()=>{ae&&s(!1)}),()=>{ae=!1}},[]);const te=async()=>{r(!0);try{await CT({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:w,alertSubmitForm16Enabled:D,alertSubmitForm16AfterQuarterEndDays:Math.max(0,Math.min(365,C)),alertSubmitForm16EveryDays:Math.max(1,Math.min(365,N)),alertSubmitForm16FrequencyDays:Math.max(0,Math.min(365,_)),alertSubmitForm16FrequencyHours:Math.max(0,Math.min(168,R)),alertSubmitForm16RunAtTime:V??"",alertSubmitForm16Template:A,reminderNotificationEnabled:$,reminderFrequencyDays:Math.max(0,Math.min(365,T)),reminderFrequencyHours:Math.max(0,Math.min(168,H)),reminderRunAtTime:P??"",reminderNotificationTemplate:K}),Y.success("Form 16 configuration saved")}catch{Y.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(We,{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,w==null?void 0:w.enabled,D,$].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(q,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Bu,{className:"w-5 h-5 text-re-green"}),"Quarter calendar (how reminders/alerts work)"]}),e.jsx(Se,{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(se,{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(q,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5"}),"Submission data who can see"]}),e.jsxs(Se,{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(se,{children:e.jsx(Yh,{emails:n,onAdd:ae=>i(xe=>[...xe,ae].sort()),onRemove:ae=>i(xe=>xe.filter(be=>be!==ae)),placeholder:"e.g., user@royalenfield.com"})})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Bu,{className:"w-5 h-5"}),"26AS page and button who can see"]}),e.jsxs(Se,{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(se,{children:e.jsx(Yh,{emails:l,onAdd:ae=>o(xe=>[...xe,ae].sort()),onRemove:ae=>o(xe=>xe.filter(be=>be!==ae)),placeholder:"e.g., user@royalenfield.com"})})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx($s,{className:"w-5 h-5"}),"Reminder schedule (for dealers)"]}),e.jsx(Se,{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(se,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{htmlFor:"reminder-enabled",children:"Enable reminders to dealers"}),e.jsx(ds,{id:"reminder-enabled",checked:c,onCheckedChange:d})]}),e.jsxs("div",{className:"space-y-2 max-w-xs",children:[e.jsx(ne,{htmlFor:"reminder-days",children:"Remind dealers every (days)"}),e.jsx(Ee,{id:"reminder-days",type:"number",min:1,max:365,value:m,onChange:ae=>p(parseInt(ae.target.value,10)||7)})]})]})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Email and in-app notifications"}),e.jsx(Se,{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(se,{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(ne,{htmlFor:"re-26as-after-days",className:"text-sm whitespace-nowrap",children:"Start after (days):"}),e.jsx(Ee,{id:"re-26as-after-days",type:"number",min:0,max:365,value:b,onChange:ae=>y(parseInt(ae.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(ds,{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(ds,{checked:x.enabled,onCheckedChange:ae=>h(xe=>({...xe,enabled:ae}))})]}),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(ne,{htmlFor:"dealer-submit-after-days",className:"text-sm whitespace-nowrap",children:"Start after (days):"}),e.jsx(Ee,{id:"dealer-submit-after-days",type:"number",min:0,max:365,value:C,onChange:ae=>F(parseInt(ae.target.value||"0",10)||0),className:"w-24"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{htmlFor:"dealer-submit-every-days",className:"text-sm whitespace-nowrap",children:"Repeat every (days):"}),e.jsx(Ee,{id:"dealer-submit-every-days",type:"number",min:1,max:365,value:N,onChange:ae=>E(parseInt(ae.target.value||"7",10)||7),className:"w-24"})]})]})]}),e.jsx(ds,{checked:D,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(ds,{checked:j.enabled,onCheckedChange:ae=>v(xe=>({...xe,enabled:ae}))})]}),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(ds,{checked:w.enabled,onCheckedChange:ae=>S(xe=>({...xe,enabled:ae}))})]}),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(ne,{htmlFor:"reminder-run-at",className:"text-sm whitespace-nowrap",children:"Run daily at (optional):"}),e.jsx(Ee,{id:"reminder-run-at",type:"time",value:P,onChange:ae=>B(ae.target.value),className:"w-28"}),P?e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>B(""),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(ne,{htmlFor:"reminder-freq-days",className:"text-sm whitespace-nowrap",children:"Frequency (days):"}),e.jsx(Ee,{id:"reminder-freq-days",type:"number",min:0,max:365,value:T,onChange:ae=>U(Math.max(0,parseInt(ae.target.value,10)||0)),className:"w-20"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{htmlFor:"reminder-freq-hours",className:"text-sm whitespace-nowrap",children:"Hours:"}),e.jsx(Ee,{id:"reminder-freq-hours",type:"number",min:0,max:168,value:H,onChange:ae=>W(Math.max(0,parseInt(ae.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(ds,{checked:$,onCheckedChange:M})]})]})})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(O,{onClick:te,disabled:a,className:"bg-re-green hover:bg-re-green/90 gap-2",children:[a?e.jsx(We,{className:"w-4 h-4 animate-spin"}):e.jsx(La,{className:"w-4 h-4"}),"Save Form 16 configuration"]})})]})}function HR(){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,w]=u.useState(""),[S,D]=u.useState({code:"",type:"HSN",gstRate:"",description:"",isActive:!0});u.useEffect(()=>{const z=setTimeout(()=>{w(y),p(1)},500);return()=>clearTimeout(z)},[y]),u.useEffect(()=>{k()},[m,v]);const k=async()=>{var z,R;try{r(!0),d(null);const L=await tb(!1,m,b,v);s(L.codes),h(L.pagination.totalPages),f(L.pagination.totalRecords)}catch(L){const V=((R=(z=L.response)==null?void 0:z.data)==null?void 0:R.error)||"Failed to load HSN/SAC codes";d(V),Y.error(V)}finally{r(!1)}},C=()=>{D({code:"",type:"HSN",gstRate:"",description:"",isActive:!0}),o(null),i(!0)},F=z=>{var R;D({code:z.code,type:z.type,gstRate:((R=z.gstRate)==null?void 0:R.toString())||"",description:z.description||"",isActive:z.isActive}),o(z),i(!0)},N=async()=>{var z,R;try{if(d(null),!S.code.trim()||!S.type){d("Code and Type are required"),Y.error("Please fill in required fields");return}const{isValid:L,message:V}=ya(S.code,S.type==="SAC");if(!L){d(V),Y.error(V);return}const I={code:S.code.trim(),type:S.type,gstRate:S.gstRate?parseFloat(S.gstRate):void 0,description:S.description.trim()||void 0,isActive:S.isActive};l?(await W4(l.id,I),Y.success(`${S.type} code updated successfully`)):(await V4(I),Y.success(`${S.type} code created successfully`)),await k(),i(!1)}catch(L){const V=((R=(z=L.response)==null?void 0:z.data)==null?void 0:R.error)||"Failed to save code";d(V),Y.error(V)}},E=async z=>{var R,L;if(confirm(`Delete ${z.type} code "${z.code}"?`))try{d(null),await H4(z.id),Y.success("Code deleted successfully"),await k()}catch(V){const I=((L=(R=V.response)==null?void 0:R.data)==null?void 0:L.error)||"Failed to delete code";d(I),Y.error(I)}},_=async z=>{try{await G4(z),await k(),Y.success("Status updated successfully")}catch{Y.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(tt,{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(q,{className:"shadow-lg border-0 rounded-md",children:e.jsx(me,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex flex-col 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(rc,{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(Se,{className:"text-xs sm:text-sm",children:["Manage HSN/SAC codes and associated GST rates (",g," total)"]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-3 w-full lg:w-auto",children:[e.jsxs("div",{className:"relative flex-1 sm:w-64",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(Ee,{placeholder:"Search code or description...",value:y,onChange:z=>j(z.target.value),className:"pl-9 bg-slate-50 border-slate-200 focus:bg-white transition-all text-sm"})]}),e.jsxs(O,{onClick:C,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm whitespace-nowrap",children:[e.jsx(os,{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(We,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{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(yy,{className:"w-10 h-10 text-slate-400"}):e.jsx(rc,{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:C,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50",children:[e.jsx(os,{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(z=>e.jsx(GR,{code:z,onEdit:()=>F(z),onDelete:()=>E(z),onToggle:()=>_(z.id)},z.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(z=>Math.max(1,z-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((z,R)=>{const L=R+1;return x<=7||L===1||L===x||L>=m-1&&L<=m+1?e.jsx(O,{variant:m===L?"default":"outline",size:"sm",onClick:()=>p(L),className:`w-9 h-9 p-0 ${m===L?"bg-slate-800":"text-slate-600"}`,children:L},L):L===m-2&&L>1||L===m+2&&L<x?e.jsx("span",{className:"px-1 text-slate-400",children:"..."},L):null})}),e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>p(z=>Math.min(x,z+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(gt,{open:n,onOpenChange:i,children:e.jsxs(ht,{className:"sm:max-w-[500px]",children:[e.jsxs(ft,{children:[e.jsx(pt,{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(ne,{htmlFor:"type",children:["Type ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs(Ke,{value:S.type,onValueChange:z=>D({...S,type:z}),children:[e.jsx(Xe,{children:e.jsx(Qe,{placeholder:"Select type"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"HSN",children:"HSN"}),e.jsx(J,{value:"SAC",children:"SAC"})]})]})]}),e.jsxs("div",{className:"space-y-2 relative pb-5",children:[e.jsxs(ne,{htmlFor:"code",children:["Code ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ee,{id:"code",placeholder:"e.g., 998311",value:S.code,onChange:z=>D({...S,code:z.target.value}),className:ya(S.code,S.type==="SAC").isValid?"":"border-red-500"}),!ya(S.code,S.type==="SAC").isValid&&S.code&&e.jsx("p",{className:"text-[10px] text-red-500 absolute left-0 bottom-0 leading-tight",children:ya(S.code,S.type==="SAC").message})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ee,{id:"description",placeholder:"Brief description of the code",value:S.description,onChange:z=>D({...S,description:z.target.value})})]})]}),e.jsxs(Rt,{children:[e.jsx(O,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(O,{onClick:N,className:"bg-re-green hover:bg-re-green/90 text-white",children:l?"Update Code":"Create Code"})]})]})})]})}function GR({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(vy,{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(ii,{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(Nr,{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 YR(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function KR(){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 ST().then(x=>{p&&i(x.viewerEmails??[])}).catch(()=>{p&&Y.error("Failed to load CPC-CSD configuration")}).finally(()=>{p&&s(!1)}),()=>{p=!1}},[]);const c=()=>{const p=l.trim().toLowerCase();if(p){if(!YR(p)){Y.error("Please enter a valid email address");return}if(n.includes(p)){Y.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 AT({viewerEmails:n}),Y.success("CPC-CSD configuration saved")}catch{Y.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(We,{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(q,{children:[e.jsxs(me,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5"}),"CPC-CSD module viewers"]}),e.jsx(Se,{children:"Users with these email addresses can access the CPC-CSD sidebar and pages. Use exact login email."})]}),e.jsxs(se,{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ee,{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(os,{className:"w-4 h-4"}),"Add"]})]}),n.length>0?e.jsx("div",{className:"rounded-md border",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{children:[e.jsx(De,{children:"Email"}),e.jsx(De,{className:"w-[80px] text-right",children:"Actions"})]})}),e.jsx(Ps,{children:n.map(p=>e.jsxs(rt,{children:[e.jsx(Ne,{className:"font-medium",children:p}),e.jsx(Ne,{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(Nr,{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(We,{className:"w-4 h-4 animate-spin"}):e.jsx(La,{className:"w-4 h-4"}),"Save CPC-CSD configuration"]})})})]})}function QR({open:t,onClose:s,success:a,message:r}){return e.jsx(gt,{open:t,onOpenChange:s,children:e.jsxs(ht,{className:"sm:max-w-md",children:[e.jsxs(ft,{children:[e.jsxs(pt,{className:"flex items-center gap-2",children:[e.jsx($s,{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(He,{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(Rt,{children:e.jsx(O,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const XR=async()=>(await we.get("/user/preferences/notifications")).data.data,JR=async t=>(await we.put("/user/preferences/notifications",t)).data.data;function ZR({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 XR();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 JR(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(gt,{open:t,onOpenChange:s,children:e.jsxs(ht,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(ft,{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(pr,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(pt,{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(qt,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(We,{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(He,{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(tt,{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(wa,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"email-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Receive important updates and alerts via email"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="emailNotificationsEnabled"&&e.jsx(We,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ds,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:g=>h("emailNotificationsEnabled",g),disabled:l==="emailNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx($s,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"push-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Push Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Get instant browser notifications for real-time updates"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="pushNotificationsEnabled"&&e.jsx(We,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ds,{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(Ks,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"inapp-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"View notifications in the notification center"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="inAppNotificationsEnabled"&&e.jsx(We,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ds,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>h("inAppNotificationsEnabled",g),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx(qt,{}),e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-lg",children:e.jsxs("p",{className:"text-sm text-gray-700 leading-relaxed",children:[e.jsx("span",{className:"font-semibold",children:"Note:"})," These settings control your notification preferences across all channels. Critical system alerts and urgent notifications may still be delivered regardless of these settings to ensure important information reaches you."]})})]})]})})}function qR(){const t=fs(),{user:s}=xs(),a=_r(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,w]=u.useState(!1),[S,D]=u.useState(!1),[k,C]=u.useState(!1);u.useEffect(()=>{F()},[]);const F=async()=>{try{b(!0);const E=await uN();g(E.length>0)}catch(E){console.error("Failed to check subscription status:",E),g(!1)}finally{b(!1)}},N=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 E=Notification.permission;if(E==="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(E==="default"&&(E=await Notification.requestPermission(),E==="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(E!=="granted"){l(!1),c("Notification permission is required to enable push notifications. Please grant permission and try again."),n(!0),m(!1);return}await LR(),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(E){console.error("[Settings] Error enabling notifications:",E),l(!1);const _=(E==null?void 0:E.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(q,{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(se,{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(pr,{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(Ii,{defaultValue:"user",className:"w-full",children:[e.jsxs(Fi,{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(Bt,{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(pr,{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(Bt,{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(js,{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(Bt,{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(Bp,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(Bt,{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(jt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Holidays"}),e.jsx("span",{className:"sm:hidden",children:"Holidays"})]}),e.jsxs(Bt,{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(Pe,{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(zt,{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(q,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx($s,{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(Se,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(se,{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:N,disabled:d||h,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx($s,{className:`w-4 h-4 mr-2 ${d?"animate-pulse":""}`}),d?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(q,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(xr,{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(Se,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(se,{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(xr,{className:"w-4 h-4 mr-2"}),"Manage Security"]})]})})})]}),e.jsxs(q,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(zu,{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(Se,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(se,{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(q,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(js,{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(Se,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(se,{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(js,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(zt,{value:"roles",className:"mt-0",children:e.jsx(BR,{})}),e.jsx(zt,{value:"system",className:"mt-0",children:e.jsx(OR,{})}),e.jsx(zt,{value:"holidays",className:"mt-0",children:e.jsx($R,{})}),e.jsx(zt,{value:"templates",className:"mt-0",children:v?e.jsxs("div",{className:"space-y-4",children:[e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsx(me,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(O,{variant:"ghost",size:"sm",onClick:()=>w(!1),className:"gap-2 hover:bg-slate-100",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]}),e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-emerald-600 to-emerald-700 rounded-md shadow-md",children:e.jsx(Pe,{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(Se,{className:"text-sm",children:"Configure Form 16 access, who can view submission data and 26AS, and notification settings"})]})]})})})}),e.jsx(WR,{})]}):k?e.jsxs("div",{className:"space-y-4",children:[e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsx(me,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(O,{variant:"ghost",size:"sm",onClick:()=>C(!1),className:"gap-2 hover:bg-slate-100",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]}),e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-teal-600 to-cyan-700 rounded-md shadow-md",children:e.jsx(Pe,{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(Se,{className:"text-sm",children:"Configure who can access CPC-CSD module and pages"})]})]})})})}),e.jsx(KR,{})]}):y?e.jsxs("div",{className:"space-y-4",children:[e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsx(me,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(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(Pe,{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(Se,{className:"text-sm",children:"Manage activity types for dealer claim workflows"})]})]})})})}),e.jsx(zR,{})]}):S?e.jsxs("div",{className:"space-y-4",children:[e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsx(me,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(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-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Pe,{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(Se,{className:"text-sm",children:"Manage HSN/SAC codes and associated GST rates"})]})]})})})}),e.jsx(HR,{})]}):e.jsxs(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Pe,{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(Se,{className:"text-sm",children:"Manage templates and activity types for workflows"})]})]})}),e.jsx(se,{className:"pt-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(q,{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(se,{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(Pe,{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(q,{className:"shadow-md hover:shadow-lg transition-all duration-300 border border-slate-200 rounded-lg cursor-pointer group",onClick:()=>C(!0),children:e.jsx(se,{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(Pe,{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(q,{className:"shadow-md hover:shadow-lg transition-all duration-300 border border-slate-200 rounded-lg cursor-pointer group",onClick:()=>w(!0),children:e.jsx(se,{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(Pe,{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(q,{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(se,{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(Pe,{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(q,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx($s,{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(Se,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(se,{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:N,disabled:d||h,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx($s,{className:`w-4 h-4 mr-2 ${d?"animate-pulse":""}`}),d?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(q,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(xr,{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(Se,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(se,{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(xr,{className:"w-4 h-4 mr-2"}),"Manage Security"]})]})})})]}),e.jsxs(q,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(zu,{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(Se,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(se,{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(q,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(js,{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(Se,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(se,{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(js,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(QR,{open:r,onClose:()=>n(!1),success:i,message:o}),e.jsx(ZR,{open:p,onClose:()=>x(!1)})]})}const eI=ed("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 tI({className:t,variant:s,...a}){return e.jsx("div",{"data-slot":"alert",role:"alert",className:Oe(eI({variant:s}),t),...a})}function sI({className:t,...s}){return e.jsx("div",{"data-slot":"alert-title",className:Oe("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",t),...s})}function aI({className:t,...s}){return e.jsx("div",{"data-slot":"alert-description",className:Oe("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",t),...s})}function rI(){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 C=await we.get("/api-tokens");s(C.data.data.tokens)}catch(C){console.error("Failed to fetch API tokens:",C),Y.error("Failed to load API tokens")}finally{r(!1)}},v=async()=>{if(l.trim())try{h(!0);const C={name:l};c&&(C.expiresInDays=Number(c));const F=await we.post("/api-tokens",C);p(F.data.data.token),Y.success("API Token created successfully"),j()}catch(C){console.error("Failed to create token:",C),Y.error("Failed to create API token")}finally{h(!1)}},w=C=>{y(C)},S=async()=>{if(b)try{await we.delete(`/api-tokens/${b.id}`),Y.success("Token revoked successfully"),s(t.filter(C=>C.id!==b.id)),y(null)}catch(C){console.error("Failed to revoke token:",C),Y.error("Failed to revoke token")}},D=()=>{m&&(navigator.clipboard.writeText(m),f(!0),setTimeout(()=>f(!1),2e3),Y.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(os,{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(zp,{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(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{children:[e.jsx(De,{children:"Name"}),e.jsx(De,{children:"Prefix"}),e.jsx(De,{children:"Last Used"}),e.jsx(De,{children:"Expires"}),e.jsx(De,{className:"text-right",children:"Actions"})]})}),e.jsx(Ps,{children:t.map(C=>e.jsxs(rt,{children:[e.jsx(Ne,{className:"font-medium",children:C.name}),e.jsxs(Ne,{className:"font-mono text-xs bg-slate-100 rounded px-2 py-1 w-fit",children:[C.prefix,"..."]}),e.jsx(Ne,{className:"text-gray-500 text-sm",children:C.lastUsedAt?it(new Date(C.lastUsedAt),"MMM d, yyyy"):"Never"}),e.jsx(Ne,{className:"text-gray-500 text-sm",children:C.expiresAt?it(new Date(C.expiresAt),"MMM d, yyyy"):"No Expiry"}),e.jsx(Ne,{className:"text-right",children:e.jsxs(O,{variant:"ghost",size:"sm",onClick:()=>w(C),className:"text-red-600 hover:text-red-700 hover:bg-red-50",children:[e.jsx(Nr,{className:"w-4 h-4"}),e.jsx("span",{className:"sr-only",children:"Revoke"})]})})]},C.id))})]})}),e.jsx(gt,{open:n,onOpenChange:C=>!C&&k(),children:e.jsxs(ht,{className:"sm:max-w-md",children:[e.jsxs(ft,{children:[e.jsx(pt,{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(tI,{className:"bg-green-50 border-green-200",children:[e.jsx(Ha,{className:"h-4 w-4 text-green-600"}),e.jsx(sI,{className:"text-green-800",children:"Token Generated Successfully"}),e.jsx(aI,{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:D,children:g?e.jsx(Ha,{className:"w-4 h-4 text-green-500"}):e.jsx(Ny,{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(ne,{htmlFor:"token-name",children:"Token Name"}),e.jsx(Ee,{id:"token-name",placeholder:"e.g., CI/CD Pipeline, Prometheus",value:l,onChange:C=>o(C.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"token-expiry",children:"Expiration (Days)"}),e.jsx(Ee,{id:"token-expiry",type:"number",min:"1",placeholder:"Leave empty for no expiry",value:c,onChange:C=>{const F=C.target.value;if(F==="")d("");else{const N=parseInt(F);!isNaN(N)&&N>=1&&d(N)}}})]})]}),e.jsx(Rt,{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(og,{open:!!b,onOpenChange:C=>!C&&y(null),children:e.jsxs(sd,{children:[e.jsxs(dg,{children:[e.jsx(ug,{children:"Revoke API Token"}),e.jsxs(xg,{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(mg,{children:[e.jsx(pg,{children:"Cancel"}),e.jsx(hg,{onClick:S,className:"bg-red-600 hover:bg-red-700 text-white",children:"Revoke Token"})]})]})})]})}function nI(){const t=fs();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(Ss,{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(q,{className:"shadow-md",children:[e.jsx(me,{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(xr,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Password"}),e.jsx(Se,{children:"Manage your sign-in password"})]})]})}),e.jsx(se,{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(q,{className:"shadow-md",children:[e.jsx(me,{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(zp,{className:"w-5 h-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ue,{children:"API Tokens"}),e.jsx(Se,{children:"Manage personal access tokens for external integrations"})]})]})}),e.jsx(se,{children:e.jsx(rI,{})})]})]})]})}function iI({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,N=p==="unread")=>{var E,_;try{n(F===1);const z=await hr.list({page:F,limit:f,unreadOnly:N}),R=((E=z.data)==null?void 0:E.notifications)||[],L=((_=z.data)==null?void 0:_.pagination)||{},V=L.total||0,I=L.totalPages||1;a(R),m(V),c(I),l(F)}catch(z){console.error("[Notifications] Failed to fetch:",z)}finally{n(!1),g(!1)}};u.useEffect(()=>{l(1),b(1,p==="unread")},[p]);const y=async F=>{var N;try{if(F.isRead||(await hr.markAsRead(F.notificationId),a(E=>E.map(_=>_.notificationId===F.notificationId?{..._,isRead:!0}:_))),F.actionUrl&&t){const E=(N=F.metadata)==null?void 0:N.requestNumber;if(E){let _=`request/${E}`;(F.notificationType==="mention"||F.notificationType==="comment"||F.notificationType==="worknote")&&(_+="?tab=worknotes"),F.notificationType==="document_added"&&(_+="?tab=documents"),t(_)}}}catch(E){console.error("[Notifications] Error handling notification click:",E)}},j=async()=>{try{g(!0),await hr.markAllAsRead(),await b(i,p==="unread")}catch(F){console.error("[Notifications] Error marking all as read:",F),g(!1)}},v=async F=>{try{await hr.delete(F),a(N=>N.filter(E=>E.notificationId!==F)),m(N=>N-1)}catch(N){console.error("[Notifications] Error deleting notification:",N)}},w=()=>{g(!0),b(i,p==="unread")},S=F=>{F<1||F>o||(l(F),b(F,p==="unread"))},D=F=>{const N="w-6 h-6";switch(F){case"mention":case"comment":return e.jsx(Ks,{className:`${N} text-blue-600`});case"worknote":return e.jsx(Pe,{className:`${N} text-purple-600`});case"document_added":return e.jsx(Pe,{className:`${N} text-teal-600`});case"assignment":return e.jsx(El,{className:`${N} text-indigo-600`});case"approval":return e.jsx(He,{className:`${N} text-green-600`});case"rejection":return e.jsx(At,{className:`${N} text-red-600`});case"tat_alert":return e.jsx(ot,{className:`${N} text-orange-600`});case"tat_breach":return e.jsx(tt,{className:`${N} text-red-600`});case"tat_breach_initiator":return e.jsx(as,{className:`${N} text-amber-600`});default:return e.jsx($s,{className:`${N} 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"}},C=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($s,{className:"w-8 h-8 text-blue-600"}),"Notifications"]}),e.jsxs("p",{className:"text-gray-600 mt-1",children:[d," total notification",d!==1?"s":"",C>0&&` • ${C} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(O,{variant:"outline",size:"sm",onClick:w,disabled:h,className:"gap-2",children:[e.jsx(_t,{className:`w-4 h-4 ${h?"animate-spin":""}`}),"Refresh"]}),C>0&&e.jsxs(O,{variant:"outline",size:"sm",onClick:j,disabled:h,className:"gap-2",children:[e.jsx(wy,{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",C>0&&e.jsx(le,{className:"ml-2 bg-red-500 text-white",children:C})]})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Recent Activity"}),e.jsx(Se,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(se,{children:r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"})}):s.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx($s,{className:"w-16 h-16 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-lg font-medium text-gray-900 mb-2",children:"No notifications"}),e.jsx("p",{className:"text-sm text-gray-500",children:p==="unread"?"You're all caught up! No unread notifications.":"You don't have any notifications yet."})]}):e.jsx("div",{className:"space-y-2",children:s.map(F=>{var N;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:D(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(le,{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:[Cp(new Date(F.createdAt),{addSuffix:!0}),((N=F.metadata)==null?void 0:N.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:E=>{E.stopPropagation(),v(F.notificationId)},children:e.jsx(Nr,{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:()=>S(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,N)=>{let E;return o<=5||i<=3?E=N+1:i>=o-2?E=o-4+N:E=i-2+N,e.jsx(O,{variant:i===E?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>S(E),children:E},E)})}),e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>S(i+1),disabled:i===o,children:["Next",e.jsx(Wa,{className:"w-4 h-4"})]})]})]})]})}function lI({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(Ss,{className:"w-4 h-4 mr-2"}),"Back to Dashboard"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(Pe,{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 qd({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?`${it(s,"d MMM yyyy")} - ${it(a,"d MMM yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${x}-container`,children:[e.jsx(jt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:t,onValueChange:l,"data-testid":`${x}-select`,children:[e.jsx(Xe,{className:"w-[160px]",children:e.jsx(Qe,{placeholder:"Date Range"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(ra,{open:r,onOpenChange:o,children:[e.jsx(na,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${x}-custom-trigger`,children:[e.jsx(jt,{className:"w-4 h-4"}),h]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:`${x}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(sa,{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(ne,{htmlFor:`${x}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(sa,{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 oI(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 vb(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 Nb(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 cI(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function dI({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:w}){return e.jsxs(q,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(me,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Vt,{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(Se,{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(qd,{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(se,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(We,{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(tt,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"lifecycle-empty",children:e.jsx("p",{className:"text-sm",children:"No lifecycle data available"})}):e.jsx("div",{className:"space-y-4",children:t.map(S=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${S.id}`,children:e.jsx("div",{className:"p-4 bg-gradient-to-r from-gray-50 to-white hover:bg-gray-100 cursor-pointer transition-all",onClick:()=>w(S.requestId||S.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("button",{onClick:D=>{D.stopPropagation(),w(S.requestId||S.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${S.id}`,children:S.id}),e.jsx(le,{className:vb(S.priority),"data-testid":`lifecycle-priority-${S.id}`,children:S.priority}),e.jsx(le,{className:Nb(S.status),"data-testid":`lifecycle-status-${S.id}`,children:S.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:S.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:S.initiator})," on ",S.initDate]}),S.currentStage&&!S.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",S.currentStage]})]})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Current Stage"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:S.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",S.currentLevel,"/",S.totalLevels,")"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Overall TAT"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:S.overallTAT}),S.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[S.breachCount," breach",S.breachCount>1?"es":""]})]}),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>w(S.requestId||S.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${S.id}`,children:e.jsx(Wa,{className:"w-4 h-4"})})]})]})})},S.id))}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"lifecycle-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(We,{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 mI({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:w,onSeverityChange:S,onClearFilters:D,onPageChange:k,onExport:C,onViewRequest:F}){const N=p!=="all"||x!=="all"||i!=="month"||l||o;return e.jsxs(q,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(me,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-indigo-100 rounded-lg",children:e.jsx(Up,{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(Se,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2",onClick:C,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(qd,{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(Ke,{value:p,onValueChange:w,"data-testid":"activity-category-filter",children:[e.jsx(Xe,{className:"w-40",children:e.jsx(Qe,{placeholder:"All Categories"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Categories"}),e.jsx(J,{value:"WORKFLOW",children:"Workflow"}),e.jsx(J,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(J,{value:"DOCUMENT",children:"Document"}),e.jsx(J,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(J,{value:"SYSTEM",children:"System"}),e.jsx(J,{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(Ke,{value:x,onValueChange:S,"data-testid":"activity-severity-filter",children:[e.jsx(Xe,{className:"w-40",children:e.jsx(Qe,{placeholder:"All Severities"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Severities"}),e.jsx(J,{value:"INFO",children:"Info"}),e.jsx(J,{value:"WARNING",children:"Warning"}),e.jsx(J,{value:"ERROR",children:"Error"}),e.jsx(J,{value:"CRITICAL",children:"Critical"})]})]})]}),N&&e.jsx(O,{variant:"ghost",size:"sm",onClick:D,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(se,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(We,{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(tt,{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(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{className:"bg-gray-50",children:[e.jsx(De,{className:"font-semibold",children:"Timestamp"}),e.jsx(De,{className:"font-semibold",children:"User"}),e.jsx(De,{className:"font-semibold",children:"Action"}),e.jsx(De,{className:"font-semibold",children:"Details"}),e.jsx(De,{className:"font-semibold",children:"IP Address"}),e.jsx(De,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(Ps,{children:t.map((E,_)=>e.jsxs(rt,{className:"hover:bg-gray-50","data-testid":`activity-row-${_}`,children:[e.jsx(Ne,{className:"text-xs font-medium",children:E.timestamp}),e.jsx(Ne,{className:"text-sm",children:E.user}),e.jsx(Ne,{children:e.jsx(le,{className:oI(E.action),"data-testid":`activity-action-${_}`,children:E.action})}),e.jsx(Ne,{className:"text-sm text-gray-600",children:E.details}),e.jsx(Ne,{className:"text-xs font-mono text-gray-500",children:E.ip&&E.ip!=="N/A"?e.jsx("span",{title:E.userAgent||"",children:E.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(Ne,{children:E.requestId!=="-"&&E.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const z=E.requestId;z&&F(z)},className:"hover:underline","data-testid":`activity-request-link-${_}`,children:e.jsx(le,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:E.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(We,{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 uI({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:w,onApplyCustomDate:S,onCancelCustomDate:D,onSearchChange:k,onPageChange:C,onExport:F,onViewRequest:N}){return e.jsxs(q,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(me,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-amber-100 rounded-lg",children:e.jsx(Yc,{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(Se,{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(Ee,{type:"number",min:"1",value:i,onChange:E=>f(E.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(le,{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(qd,{dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:p,tempCustomEndDate:x,onDateRangeChange:y,onShowCustomDatePickerChange:j,onStartDateChange:v,onEndDateChange:w,onApply:S,onCancel:D,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ee,{placeholder:"Search by Request ID, Title, or Initiator...",value:h,onChange:E=>k(E.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(se,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(We,{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(tt,{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(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{className:"bg-gray-50",children:[e.jsx(De,{className:"font-semibold",children:"Request ID"}),e.jsx(De,{className:"font-semibold",children:"Title"}),e.jsx(De,{className:"font-semibold",children:"Initiator"}),e.jsx(De,{className:"font-semibold",children:"Start Date"}),e.jsx(De,{className:"font-semibold",children:"Days Open"}),e.jsx(De,{className:"font-semibold",children:"Current Stage"}),e.jsx(De,{className:"font-semibold",children:"Assigned To"}),e.jsx(De,{className:"font-semibold",children:"Priority"}),e.jsx(De,{className:"font-semibold",children:"Status"})]})}),e.jsx(Ps,{children:t.map(E=>e.jsxs(rt,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${E.id}`,children:[e.jsx(Ne,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>N(E.requestId||E.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${E.id}`,children:E.id})}),e.jsx(Ne,{className:"text-sm",children:E.title}),e.jsx(Ne,{className:"text-sm",children:E.initiator}),e.jsx(Ne,{className:"text-sm text-gray-600",children:E.startDate}),e.jsx(Ne,{children:e.jsxs(le,{className:`${cI(E.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${E.id}`,children:[E.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(Ne,{className:"text-sm",children:E.currentStage}),e.jsx(Ne,{className:"text-sm",children:E.assignedTo&&E.assignedTo!=="N/A"?E.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(Ne,{children:e.jsx(le,{className:vb(E.priority),"data-testid":`aging-priority-${E.id}`,children:E.priority})}),e.jsx(Ne,{children:e.jsx(le,{className:Nb(E.status),"data-testid":`aging-status-${E.id}`,children:E.status})})]},E.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(We,{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:()=>C(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>C(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function Vo(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(w=>{const S=w;a(S),S!=="custom"?(n(void 0),l(void 0),m(void 0),x(void 0),c(!1)):(m(r),x(i),c(!0))},[r,i]),g=u.useCallback(()=>{if(d&&p){if(d>p){const w=d;n(p),l(w),m(p),x(w)}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(w=>{w?(m(w),p&&w>p&&x(w)):m(void 0)},[p]),y=u.useCallback(w=>{w?(x(w),d&&w<d&&m(w)):x(void 0)},[d]),j=u.useCallback(()=>r&&i?`${it(r,"MMM d, yyyy")} - ${it(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 xI(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return Jt(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${Jt(r)}`:`${a}d`}function wb(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 $r(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 Cb(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 hI=10;function pI({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 Ut.getLifecycleReport(f,hI,t,s,a),j=y.lifecycleData.map(v=>{const w=xI(v.overallTATHours);return{id:v.requestNumber,requestId:v.requestId,title:v.title,priority:v.priority||"medium",status:v.status,initiator:v.initiatorName||"Unknown",initDate:wb(v.submissionDate),currentStage:v.currentStageName||`Level ${v.currentLevel}`,overallTAT:w,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 gI=20;function fI({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 Ut.getActivityLogReport(y,gI,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),w=v.activities.map(S=>{const D=Cb(S.type||"",S.details),k=(S.type||"").toLowerCase()==="login"||S.requestId==="00000000-0000-0000-0000-000000000001"||S.requestId==="SYSTEM_LOGIN",C=k?S.details||"User login":S.requestTitle||S.requestNumber||S.details||"N/A";return{timestamp:S.timestamp?wb(S.timestamp):"N/A",user:S.userName||"Unknown",action:D,details:C,ip:S.ipAddress||"N/A",userAgent:S.userAgent||null,requestId:k?"System Login":S.requestNumber||S.requestId||"-",userId:S.userId}});l(w),g({page:v.pagination.currentPage,totalPages:v.pagination.totalPages,totalRecords:v.pagination.totalRecords})}catch(v){console.error("Failed to fetch activity data:",v),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 bI=20;function jI({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 w=parseInt(t,10);if(isNaN(w)||w<1){x("Please enter a valid threshold (minimum 1 day)");return}const S=await Ut.getWorkflowAgingReport(w,j,bI,s,a,r),D=S.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(D),g({page:S.pagination.currentPage,totalPages:S.pagination.totalPages,totalRecords:S.pagination.totalRecords})}catch(w){console.error("Failed to fetch aging data:",w),x((w==null?void 0:w.message)||"Failed to load aging data")}finally{v?c(!1):m(!1)}v&&(f.current=!1)},[t,s,a,r]),y=u.useMemo(()=>i.filter(j=>{var w,S,D;if(!n)return!0;const v=n.toLowerCase();return((w=j.id)==null?void 0:w.toLowerCase().includes(v))||((S=j.title)==null?void 0:S.toLowerCase().includes(v))||((D=j.initiator)==null?void 0:D.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 yI(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 vI(t,s,a){const r=await Ut.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 Ls(i.requestId||i.requestNumber),o=i.submissionDate?$r(i.submissionDate):"N/A",c=i.closureDate?$r(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?$r(g.levelStartTime):"N/A",b=g.levelEndTime||g.completedAt?$r(g.levelEndTime||g.completedAt):"N/A",y=g.tatHours||0,j=g.tatDays||(y>0?(y/8).toFixed(2):"0");let v="N/A",w="N/A",S="N/A",D="N/A";if(g.levelStartTime){const C=new Date(g.levelStartTime);if(w=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-C.getTime())/(1e3*60*60)).toFixed(2),y>0){const E=parseFloat(w);S=Math.max(0,y-E).toFixed(2),D=(E/y*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?v=E<=y?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?v=E<=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,w,S,D];n.push(k.join(","))})}catch(l){console.error(`Failed to fetch details for request ${i.requestNumber}:`,l);const o=i.submissionDate?$r(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(","))}em(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function NI(t,s,a,r,n){const i=await Ut.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=Cb(o.type||"",o.details),m=[o.timestamp?$r(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(","))}),em(l,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function wI(t,s,a,r){const n=await Ut.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?$r(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(","))}),em(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function em(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 CI(){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 vI(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 NI(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 wI(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 SI({onBack:t}){const s=fs(),[a,r]=u.useState(""),[n,i]=u.useState("all"),[l,o]=u.useState("all"),c=Vo("month"),d=Vo("month"),m=Vo("month"),p=yI("7"),x=pI({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),h=fI({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:l}),g=jI({threshold:p.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),f=CI(),b=u.useCallback(()=>{t?t():s("/dashboard")},[t,s]),y=u.useCallback(D=>{Nl({requestId:D,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]),w=u.useCallback(()=>{const D=parseInt(p.threshold,10);!isNaN(D)&&D>=1&&f.handleExportAging(D,m.dateRange,m.customStartDate,m.customEndDate)},[f,p.threshold,m]),S=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(lI,{onBack:b}),e.jsx(dI,{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(mI,{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:S,onPageChange:h.fetchData,onExport:v,onViewRequest:y}),e.jsx(uI,{agingWorkflows:g.agingWorkflows,loading:g.loading,loadingPage:g.loadingPage,error:g.error,pagination:g.pagination,threshold:p.threshold,thresholdError:p.thresholdError,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,showCustomDatePicker:m.showCustomDatePicker,tempCustomStartDate:m.tempCustomStartDate,tempCustomEndDate:m.tempCustomEndDate,searchQuery:a,exporting:f.exportingAging,onThresholdChange:p.handleThresholdChange,onThresholdBlur:p.handleThresholdBlur,onDateRangeChange:m.handleDateRangeChange,onShowCustomDatePickerChange:m.setShowCustomDatePicker,onStartDateChange:m.handleStartDateChange,onEndDateChange:m.handleEndDateChange,onApplyCustomDate:m.handleApplyCustomDate,onCancelCustomDate:m.handleCancelCustomDate,onSearchChange:r,onPageChange:g.fetchData,onExport:w,onViewRequest:y})]})})}function Vi({className:t,...s}){return e.jsx("div",{"data-slot":"skeleton",className:Oe("bg-accent animate-pulse rounded-md",t),...s})}function AI(){const t=fs(),[s,a]=u.useState(()=>Ph()||[]),[r,n]=u.useState(()=>!Ph()),[i,l]=u.useState(""),o=async()=>{try{s.length===0&&n(!0);const m=await ql();a(m||[])}catch(m){console.error("Failed to fetch templates:",m),Y.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(os,{className:"w-4 h-4 mr-2"}),"Create New Template"]})]}),e.jsx("div",{className:"flex items-center gap-4 bg-white p-4 rounded-lg border border-gray-200 shadow-sm",children:e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ee,{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(q,{className:"h-48",children:[e.jsxs(me,{children:[e.jsx(Vi,{className:"h-6 w-3/4 mb-2"}),e.jsx(Vi,{className:"h-4 w-1/2"})]}),e.jsxs(se,{children:[e.jsx(Vi,{className:"h-4 w-full mb-2"}),e.jsx(Vi,{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(Pe,{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(q,{className:"hover:shadow-md transition-shadow duration-200 group",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex justify-between items-start gap-2",children:[e.jsx("div",{className:"p-2 bg-blue-50 rounded-lg text-blue-600 mb-2 w-fit",children:e.jsx(Pe,{className:"w-5 h-5"})}),e.jsx(le,{variant:"outline",className:d(m.priority),children:m.priority})]}),e.jsx(ue,{className:"line-clamp-1 text-lg",children:m.name}),e.jsx(Se,{className:"line-clamp-3 min-h-[4.5rem]",children:m.description})]}),e.jsxs(se,{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(Cy,{className:"w-4 h-4 mr-2"}),"Edit"]})})]})]},m.id)})})]})}function Qh(){const t=fs(),{templateId:s}=Sa(),a=!!s,[r,n]=u.useState(!1),[i,l]=u.useState(!1),{searchResults:o,searchLoading:c,searchUsersDebounced:d,clearSearch:m}=T0(),[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 C=(await ql()).find(F=>F.id===s);C?g({name:C.name,description:C.description,category:C.category,priority:C.priority,estimatedTime:C.estimatedTime,suggestedSLA:C.suggestedSLA,approvers:C.approvers||[]}):(Y.error("Template not found"),t("/admin/templates"))}catch(k){console.error("Failed to load template:",k),Y.error("Failed to load template details")}finally{l(!1)}})()},[a,s,t]);const f=D=>{const{name:k,value:C}=D.target;g(F=>({...F,[k]:C}))},b=(D,k)=>{g(C=>({...C,[D]:k}))},y=D=>{if(x(D),D.startsWith("@")&&D.slice(1).length>=1){d(D,5);return}m()},j=D=>{if(h.approvers.some(k=>k.userId===D.userId)){Y.error("Approver already added");return}g(k=>({...k,approvers:[...k.approvers,{userId:D.userId,name:D.displayName||D.email,email:D.email,level:k.approvers.length+1,tat:24,tatType:"hours"}]})),x(""),m()},v=D=>{const k=[...h.approvers];k.splice(D,1),k.forEach((C,F)=>C.level=F+1),g(C=>({...C,approvers:k}))},w=async D=>{if(D.preventDefault(),!h.name||!h.description){Y.error("Please fill in required fields");return}if(h.approvers.length===0){Y.error("Please add at least one approver");return}const k={...h,approvers:h.approvers.map(C=>({...C,tat:C.tatType==="days"?parseInt(C.tat)*24:parseInt(C.tat)}))};try{n(!0),a&&s?(await tk(s,k),Y.success("Template updated successfully")):(await ek(k),Y.success("Template created successfully")),t("/admin/templates")}catch(C){Y.error(a?"Failed to update template":"Failed to create template"),console.error(C)}finally{n(!1)}};if(i)return e.jsx("div",{className:"flex h-96 items-center justify-center",children:e.jsx(We,{className:"h-8 w-8 animate-spin text-gray-400"})});const S=h.name&&h.description&&h.approvers.length>0&&h.approvers.every(D=>{const k=parseInt(String(D.tat))||0,C=D.tatType==="days"?7:24;return k>=1&&k<=C});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(Ss,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:a?"Edit Workflow Template":"Create Workflow Template"}),e.jsx("p",{className:"text-gray-500",children:a?"Update existing workflow configuration":"Define a new standardized request workflow"})]})]}),e.jsxs("form",{onSubmit:w,className:"space-y-6",children:[e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Basic Information"}),e.jsx(Se,{children:"General details about the template"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"name",children:"Template Name *"}),e.jsx(Ee,{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(ne,{htmlFor:"category",children:"Category"}),e.jsx("div",{className:"relative",children:e.jsx(Ee,{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(ne,{htmlFor:"description",children:"Description *"}),e.jsx(Ws,{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(ne,{htmlFor:"priority",children:"Default Priority"}),e.jsxs(Ke,{name:"priority",value:h.priority,onValueChange:D=>b("priority",D),children:[e.jsx(Xe,{children:e.jsx(Qe,{placeholder:"Select priority"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"low",children:"Low"}),e.jsx(J,{value:"medium",children:"Medium"}),e.jsx(J,{value:"high",children:"High"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"estimatedTime",children:"Estimated Time"}),e.jsx(Ee,{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(ne,{htmlFor:"suggestedSLA",children:"SLA (Hours)"}),e.jsx(Ee,{id:"suggestedSLA",name:"suggestedSLA",type:"number",placeholder:"24",value:h.suggestedSLA,onChange:f,className:"border-gray-200"})]})]})]})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Approver Workflow"}),e.jsx(Se,{children:"Define static approvers for this template"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[h.approvers.map((D,k)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsxs(le,{variant:"outline",className:"bg-white",children:["Level ",D.level]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:D.name}),e.jsx("div",{className:"text-sm text-gray-500",children:D.email})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(ne,{htmlFor:`tat-${k}`,className:"text-xs whitespace-nowrap",children:"TAT"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ee,{id:`tat-${k}`,type:"number",className:"h-8 w-16 border-gray-200",value:D.tat||"",min:1,max:D.tatType==="days"?7:24,placeholder:D.tatType==="days"?"1":"24",onChange:C=>{if((parseInt(C.target.value)||0)<0)return;const N=[...h.approvers];N[k].tat=C.target.value,g(E=>({...E,approvers:N}))}}),e.jsxs(Ke,{value:D.tatType||"hours",onValueChange:C=>{const F=[...h.approvers];F[k].tatType=C,F[k].tat=1,g(N=>({...N,approvers:F}))},children:[e.jsx(Xe,{className:"h-8 w-20 text-xs px-2",children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{value:"days",children:"Days"})]})]})]})]})}),e.jsx(O,{type:"button",variant:"ghost",size:"sm",onClick:()=>v(k),children:e.jsx(Nt,{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(ne,{children:"Add Approver"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Ee,{placeholder:"Type '@' to search user by name or email...",value:p,onChange:D=>y(D.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(D=>e.jsxs("div",{className:"p-2 hover:bg-gray-50 cursor-pointer flex items-center gap-3",onClick:()=>j(D),children:[e.jsx(ms,{className:"h-8 w-8",children:e.jsx(us,{children:(D.displayName||"U").substring(0,2)})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:D.displayName}),e.jsx("div",{className:"text-xs text-gray-500",children:D.email})]})]},D.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(ot,{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 D=h.approvers.reduce((C,F)=>{const N=Number(F.tat||0);return(F.tatType||"hours")==="days"?C+N:C+N/24},0)||0,k=Math.ceil(D);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((D,k)=>{const C=Number(D.tat||0),N=(D.tatType||"hours")==="days"?C*24:C;return C?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:[N," ",N===1?"hour":"hours"]})]})},k):null})}),(()=>{const D=h.approvers.reduce((C,F)=>{const N=Number(F.tat||0);return(F.tatType||"hours")==="days"?C+N*24:C+N},0)||0,k=Math.ceil(D/8);return D===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:[D,"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||!S,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 TI({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(q,{className:"shadow-sm",children:e.jsxs(se,{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(q,{children:e.jsxs(se,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"requestTitle",children:"Request Title *"}),e.jsx(Ee,{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(ne,{htmlFor:"justification",className:"text-base font-semibold",children:"Request Detail *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Explain what you need approval for, why it's needed, and any relevant details."}),e.jsx(Si,{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(q,{children:e.jsxs(se,{className:"pt-6 space-y-4",children:[e.jsx(ne,{children:"Supporting Documents"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>{var h;return(h=i.current)==null?void 0:h.click()},children:[e.jsx(Ns,{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(Pe,{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(Nt,{className:"w-4 h-4 text-gray-500 hover:text-red-500"})})]})]},g))})]})}),l&&e.jsx(en,{fileName:l.file.name,fileType:l.file.type,fileUrl:l.url,fileSize:l.file.size,open:!!l,onClose:p})]})}function kI({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(tt,{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(q,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-lg",children:"Request Overview"})}),e.jsx(se,{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(le,{variant:"secondary",className:"pl-1 pr-2 py-1 flex items-center gap-1.5 h-auto",children:[e.jsx(Pe,{className:"w-3 h-3 text-gray-500"}),e.jsx("span",{className:"truncate max-w-[150px]",children:n.name})]},i))})]})]})})]}),e.jsxs(q,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-lg",children:"Approval Workflow"})}),e.jsx(se,{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(le,{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(q,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(ue,{className:"text-sm uppercase text-gray-500",children:"Properties"})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Template"}),e.jsx("span",{className:"text-sm font-medium text-right",children:t.name})]}),e.jsx(qt,{}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Priority"}),e.jsx(le,{className:t.priority==="high"?"bg-red-100 text-red-700 hover:bg-red-100":t.priority==="medium"?"bg-orange-100 text-orange-700 hover:bg-orange-100":"bg-green-100 text-green-700 hover:bg-green-100",children:t.priority.toUpperCase()})]}),e.jsx(qt,{}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Est. Time"}),e.jsx("span",{className:"text-sm text-gray-900",children:t.estimatedTime})]})]})]})})]})]})}function DI(){const{templateId:t}=Sa(),s=fs(),{user:a}=xs(),[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 ql()).find(w=>w.id===t);if(v){const w={id:v.id,name:v.name,description:v.description,category:v.category,icon:Pe,estimatedTime:v.estimatedTime,commonApprovers:v.approvers.map(S=>S.name),workflowApprovers:v.approvers,suggestedSLA:v.suggestedSLA,priority:v.priority,fields:v.fields||{}};c(w),g({title:w.name,description:w.description})}else Y.error("Template not found")}catch(j){console.error("Error loading template:",j),Y.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(w=>({email:w.email,name:w.name,tat:w.tat,tatType:"hours"})),spectators:[],ccList:[]},v=await ud(j,p);v&&v.id&&await Bg(v.id),Y.success("Request Submitted Successfully",{description:`Your request "${h.title}" has been created.`}),s("/my-requests")}catch(j){console.error("Submission failed:",j),Y.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(Ss,{className:"w-5 h-5 text-gray-500"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold text-gray-900",children:"New Request"}),e.jsx("p",{className:"text-sm text-gray-500",children:o.name})]})]}),e.jsx(O,{variant:"outline",onClick:()=>s("/dashboard"),children:"Cancel Request"})]}),e.jsx(A0,{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(TI,{template:o,formData:h,setFormData:g,documents:p,setDocuments:x}):e.jsx(kI,{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(Pe,{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 RI({defaultPeriod:t,refreshInterval:s,onDefaultPeriodChange:a,onRefreshIntervalChange:r}){const n=["Today","This Week","This Month","Last Month","This Quarter","This Year","Custom Range"];return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(Ke,{value:t,onValueChange:a,children:[e.jsx(Xe,{id:"default-period",children:e.jsx(Qe,{})}),e.jsx(Je,{children:n.map(i=>e.jsx(J,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(Ee,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function II({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(ds,{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(ds,{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(ds,{checked:a,onCheckedChange:i})]})]})}const FI=["CSV","Excel","PDF","JSON"];function PI({exportFormats:t,onExportFormatsChange:s}){const a=(r,n)=>{s(n?[...t,r]:t.filter(i=>i!==r))};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:FI.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Jd,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(ne,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function EI({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(Ee,{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 _I(){const[t,s]=u.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{Y.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Analytics & Reporting Configuration"}),e.jsx(Se,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(RI,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(qt,{}),e.jsx(II,{autoRefresh:t.autoRefresh,realTimeUpdates:t.realTimeUpdates,dataExport:t.dataExport,onAutoRefreshChange:n=>r({autoRefresh:n}),onRealTimeUpdatesChange:n=>r({realTimeUpdates:n}),onDataExportChange:n=>r({dataExport:n})}),e.jsx(qt,{}),e.jsx(PI,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(EI,{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 MI=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"}},LI=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function OI({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{children:[e.jsx(De,{children:"User"}),e.jsx(De,{children:"Role"}),e.jsx(De,{children:"Department"}),e.jsx(De,{children:"Status"}),e.jsx(De,{className:"text-right",children:"Actions"})]})}),e.jsx(Ps,{children:t.length===0?e.jsx(rt,{children:e.jsx(Ne,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(rt,{className:"hover:bg-muted/50",children:[e.jsx(Ne,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ms,{className:"size-10",children:e.jsx(us,{className:"bg-re-green text-white",children:LI(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(Ne,{children:e.jsx(le,{className:MI(n.role),children:n.role})}),e.jsx(Ne,{children:n.department}),e.jsx(Ne,{children:e.jsxs(le,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(gs,{className:"w-3 h-3 mr-1"}),n.status]})}),e.jsx(Ne,{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($l,{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(Sy,{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(Nr,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function $I({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 UI(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function BI(){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),[w,S]=u.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[D,k]=u.useState("ELEVATED"),[C,F]=u.useState(1),[N,E]=u.useState(1),[_,z]=u.useState(0),R=10,L=u.useRef(null),V=u.useCallback(UI(async Z=>{var te,ae,xe;if(!Z||!Z.startsWith("@")||Z.length<2){r([]),i(!1);return}i(!0);try{const be=Z.slice(1),Be=((te=(await ma.searchUsers(be,20)).data)==null?void 0:te.data)||[];r(Be)}catch(be){console.error("Search failed:",be),f({type:"error",text:((xe=(ae=be.response)==null?void 0:ae.data)==null?void 0:xe.message)||"Failed to search users"})}finally{i(!1)}},300),[]),I=Z=>{const te=Z.target.value;s(te),V(te)},A=async Z=>{var te,ae;try{const xe=b.find(_e=>_e.email.toLowerCase()===Z.toLowerCase());if(xe)return xe.role;const Be=(((ae=(te=(await ma.getUsersByRole("ALL",1,1e3)).data)==null?void 0:te.data)==null?void 0:ae.users)||[]).find(_e=>{var Re;return((Re=_e.email)==null?void 0:Re.toLowerCase())===Z.toLowerCase()});return Be&&Be.role?Be.role:null}catch(xe){return console.error("Failed to fetch user role:",xe),null}},G=async Z=>{o(Z),s(Z.email),r([]),h(!0);try{const te=await A(Z.email);d(te||"USER")}catch(te){console.error("Failed to fetch user role:",te),d("USER")}finally{h(!1)}},$=async()=>{var Z,te;if(!l||!c){f({type:"error",text:"Please select a user and role"});return}p(!0),f(null);try{await ma.assignRole(l.email,c),f({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await M(),await T(),Y.success("Role assigned successfully")}catch(ae){console.error("Role assignment failed:",ae);const xe=((te=(Z=ae.response)==null?void 0:Z.data)==null?void 0:te.error)||"Failed to assign role";f({type:"error",text:xe}),Y.error(xe)}finally{p(!1)}},M=async(Z=C)=>{var te,ae,xe,be,Ge,Be;v(!0);try{const _e=await ma.getUsersByRole(D,Z,R),Re=((ae=(te=_e.data)==null?void 0:te.data)==null?void 0:ae.users)||[],ce=(be=(xe=_e.data)==null?void 0:xe.data)==null?void 0:be.pagination,je=(Be=(Ge=_e.data)==null?void 0:Ge.data)==null?void 0:Be.summary;y(Re.map(re=>({userId:re.userId,email:re.email,displayName:re.displayName||re.email,role:re.role||"USER",department:re.department,designation:re.designation,isActive:re.isActive!==!1}))),ce&&(F(ce.currentPage),E(ce.totalPages),z(ce.totalUsers)),je&&S(re=>({...re,admins:je.ADMIN||0,management:je.MANAGEMENT||0,users:je.USER||0,total:(je.ADMIN||0)+(je.MANAGEMENT||0)+(je.USER||0)}))}catch(_e){console.error("Failed to fetch users:",_e),Y.error("Failed to load users")}finally{v(!1)}},T=async()=>{var Z,te,ae,xe,be,Ge;try{const Be=await ma.getRoleStatistics(),_e=((te=(Z=Be.data)==null?void 0:Z.data)==null?void 0:te.statistics)||((ae=Be.data)==null?void 0:ae.statistics)||[],Re={admins:parseInt(((xe=_e.find(ce=>ce.role==="ADMIN"))==null?void 0:xe.count)||"0"),management:parseInt(((be=_e.find(ce=>ce.role==="MANAGEMENT"))==null?void 0:be.count)||"0"),users:parseInt(((Ge=_e.find(ce=>ce.role==="USER"))==null?void 0:Ge.count)||"0")};S(ce=>({...ce,...Re,total:Re.admins+Re.management+Re.users,active:ce.active||Re.admins+Re.management+Re.users,inactive:ce.inactive||0}))}catch(Be){console.error("Failed to fetch statistics:",Be)}};u.useEffect(()=>{M(1),T()},[D]);const U=Z=>{k(Z),F(1)},H=Z=>{M(Z)},W=async(Z,te)=>{var ae,xe;try{await ma.updateUserRole(Z,te),Y.success("User role updated successfully"),await M(),await T()}catch(be){console.error("Failed to update user role:",be),Y.error(((xe=(ae=be.response)==null?void 0:ae.data)==null?void 0:xe.error)||"Failed to update user role")}},P=async Z=>{b.find(ae=>ae.userId===Z)&&Y.info("User status toggle functionality coming soon")},B=async Z=>{const te=b.find(ae=>ae.userId===Z);if(te){if(te.role==="ADMIN"){Y.error("Cannot delete admin user");return}Y.info("User deletion functionality coming soon")}};u.useEffect(()=>{const Z=te=>{L.current&&!L.current.contains(te.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",Z),()=>{document.removeEventListener("mousedown",Z)}},[a]);const K={total:w.total,active:w.active,inactive:w.inactive,admins:w.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx($I,{stats:K}),e.jsxs(q,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Assign User Role"}),e.jsx(Se,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(O,{onClick:$,disabled:!l||m,className:"bg-re-green hover:bg-re-green/90",children:m?e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(os,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",ref:L,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(Ee,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:I,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx(We,{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(Z=>e.jsxs("button",{onClick:()=>G(Z),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:Z.displayName||Z.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Z.email}),Z.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[Z.department,Z.designation?` • ${Z.designation}`:""]})]},Z.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(We,{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(Ke,{value:c,onValueChange:Z=>d(Z),disabled:x,children:[e.jsx(Xe,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Qe,{placeholder:x?"Loading current role...":"Select role"})}),e.jsxs(Je,{className:"rounded-lg",children:[e.jsx(J,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(J,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(J,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dn,{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(He,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(tt,{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(q,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(Se,{children:["View and manage user accounts and roles (",_," ",D!=="ALL"&&D!=="ELEVATED"?D.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Ke,{value:D,onValueChange:U,children:[e.jsx(Xe,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Qe,{placeholder:"Filter by role"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",w.admins+w.management,")"]})]})}),e.jsx(J,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",w.admins,")"]})]})}),e.jsx(J,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",w.management,")"]})]})}),e.jsx(J,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",w.users,")"]})]})}),e.jsx(J,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",w.admins+w.management+w.users,")"]})]})})]})]})})]})}),e.jsx(se,{className:"pt-6",children:j?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(We,{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(es,{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:D==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(OI,{users:b.map(Z=>({id:Z.userId,name:Z.displayName,email:Z.email,role:Z.role,department:Z.department||"N/A",status:Z.isActive?"active":"inactive"})),onEdit:Z=>{const te=b.find(ae=>ae.userId===Z);if(te){const ae=te.role==="USER"?"MANAGEMENT":te.role==="MANAGEMENT"?"ADMIN":"USER";W(Z,ae)}},onToggleStatus:P,onDelete:B}),N>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t mt-4",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(C-1)*R+1," to ",Math.min(C*R,_)," of ",_," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{variant:"outline",size:"sm",onClick:()=>H(C-1),disabled:C===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,N)},(Z,te)=>{let ae;return N<=5||C<=3?ae=te+1:C>=N-2?ae=N-4+te:ae=C-2+te,e.jsx(O,{variant:C===ae?"default":"outline",size:"sm",onClick:()=>H(ae),className:`w-9 h-9 p-0 ${C===ae?"bg-re-green hover:bg-re-green/90":""}`,children:ae},ae)})}),e.jsx(O,{variant:"outline",size:"sm",onClick:()=>H(C+1),disabled:C===N,children:"Next"})]})]})]})})]})]})}function zI({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(q,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Il,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(Se,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(se,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(Ee,{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(ot,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(Ee,{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(ot,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function VI({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(q,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($s,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(Se,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(se,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{htmlFor:"reminder-threshold-1",className:"text-sm font-medium",children:"First Reminder Threshold"}),e.jsxs("span",{className:"text-lg font-semibold text-re-green",children:[t,"%"]})]}),e.jsx(Ec,{id:"reminder-threshold-1",value:[t],min:1,max:100,step:1,onValueChange:([n])=>{n!==void 0&&a(n)},className:"w-full"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx($s,{className:"w-3 h-3"}),"Send first gentle reminder when ",t,"% of TAT elapsed"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{htmlFor:"reminder-threshold-2",className:"text-sm font-medium",children:"Second Reminder Threshold (Escalation)"}),e.jsxs("span",{className:"text-lg font-semibold text-re-green",children:[s,"%"]})]}),e.jsx(Ec,{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(as,{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 WI({workStartHour:t,workEndHour:s,workStartDay:a,workEndDay:r,onWorkStartHourChange:n,onWorkEndHourChange:i,onWorkStartDayChange:l,onWorkEndDayChange:o}){var c,d,m;return e.jsxs(q,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(Se,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(Ee,{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(ot,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(Ee,{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(ot,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 6 PM"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(Ke,{value:a.toString(),onValueChange:p=>l(parseInt(p)),children:[e.jsx(Xe,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Qe,{placeholder:"Select start day"})}),e.jsx(Je,{children:Wn.map(p=>e.jsx(J,{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(ne,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(Ke,{value:r.toString(),onValueChange:p=>o(parseInt(p)),children:[e.jsx(Xe,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Qe,{placeholder:"Select end day"})}),e.jsx(Je,{children:Wn.map(p=>e.jsx(J,{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 HI(){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 Zl("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),Y.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())]),Y.success("TAT configuration saved successfully"),await l()}catch(p){console.error("Failed to save TAT configuration:",p),Y.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(q,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(We,{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(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(ot,{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(Se,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(zI,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx(qt,{}),e.jsx(WI,{workStartHour:n.workStartHour,workEndHour:n.workEndHour,workStartDay:n.workStartDay,workEndDay:n.workEndDay,onWorkStartHourChange:d=>c({workStartHour:d}),onWorkEndHourChange:d=>c({workEndHour:d}),onWorkStartDayChange:d=>c({workStartDay:d}),onWorkEndDayChange:d=>c({workEndDay:d})}),e.jsx(qt,{}),e.jsx(VI,{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(We,{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 GI({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(ds,{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(ds,{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(ds,{checked:a,onCheckedChange:i})]})]})}function YI({notificationFrequency:t,reminderFrequency:s,onNotificationFrequencyChange:a,onReminderFrequencyChange:r}){return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(Ke,{value:t,onValueChange:a,children:[e.jsx(Xe,{id:"notification-frequency",children:e.jsx(Qe,{placeholder:"Select frequency"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"Immediate",children:"Immediate"}),e.jsx(J,{value:"Hourly",children:"Hourly"}),e.jsx(J,{value:"Daily",children:"Daily"}),e.jsx(J,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(Ee,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function KI({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(Ws,{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 QI(){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=()=>{Y.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Notification Configuration"}),e.jsx(Se,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(GI,{emailNotifications:t.emailNotifications,inAppNotifications:t.inAppNotifications,autoReminders:t.autoReminders,onEmailNotificationsChange:n=>r({emailNotifications:n}),onInAppNotificationsChange:n=>r({inAppNotifications:n}),onAutoRemindersChange:n=>r({autoReminders:n})}),e.jsx(qt,{}),e.jsx(YI,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(KI,{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 XI({maxFileSizeMB:t,retentionDays:s,onMaxFileSizeChange:a,onRetentionDaysChange:r}){const n=Math.round(s/365*10)/10;return e.jsxs(q,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(Se,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(se,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(Ee,{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(Ns,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(Ee,{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(Ul,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const JI=[{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 ZI({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(q,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gc,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(Se,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:JI.map(l=>{const o=n(l.extensions);return e.jsxs("div",{onClick:()=>r(l.extensions,!o),className:`flex items-center justify-between p-3 rounded-md border-2 cursor-pointer transition-all ${o?"bg-re-green/5 border-re-green/30 hover:border-re-green/50":"bg-gray-50 border-gray-200 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-4 h-4 rounded border-2 flex items-center justify-center ${o?"bg-re-green border-re-green":"bg-white border-gray-300"}`,children:o&&e.jsx("svg",{className:"w-3 h-3 text-white",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})}),e.jsx("span",{className:`text-sm font-medium ${o?"text-re-green":"text-gray-600"}`,children:l.label})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:l.extensions.join(", ")})]},l.label)})}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(ne,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(Ee,{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 qI(){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 Zl("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),Y.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)]),Y.success("Document policy saved successfully"),await l()}catch(p){console.error("Failed to save document configuration:",p),Y.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(q,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(We,{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(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Pe,{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(Se,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(XI,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx(qt,{}),e.jsx(ZI,{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(We,{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 e3(){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 t3=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],s3=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 a3({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(le,{className:s3(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:t3.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Jd,{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 r3(){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=()=>{Y.success("Dashboard layout saved successfully")},r=(i,l,o)=>{s(c=>({...c,[i]:{...c[i],[l]:o}}))},n=["Initiator","Approver","Spectator"];return e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Dashboard Layout Configuration"}),e.jsx(Se,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsx(e3,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(a3,{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 n3({aiEnabled:t,onAiEnabledChange:s}){return e.jsxs(q,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vp,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"Vertex AI Gemini Configuration"})]}),e.jsx(Se,{className:"text-sm",children:"Configure AI features. Model and region are configured via environment variables."})]}),e.jsx(se,{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(ds,{checked:t,onCheckedChange:s})]})})]})}function i3({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(q,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fl,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(Se,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(se,{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(ds,{checked:t,onCheckedChange:s})]})})})]})}function l3({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(q,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bp,{className:"w-5 h-5 text-re-green"}),e.jsx(ue,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(Se,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Length"}),e.jsx(Ee,{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 o3(){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 Zl("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),Y.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())]),Y.success("AI configuration saved successfully"),await l()}catch(p){console.error("Failed to save AI configuration:",p),Y.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(q,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(We,{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(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Fl,{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(Se,{className:"text-sm text-gray-600",children:"Configure Vertex AI Gemini settings and enable/disable AI-powered features"})]})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(n3,{aiEnabled:n.aiEnabled,onAiEnabledChange:d=>c({aiEnabled:d})}),e.jsx(qt,{}),e.jsx(i3,{aiRemarkGeneration:n.aiRemarkGeneration,onRemarkGenerationChange:d=>c({aiRemarkGeneration:d})}),e.jsx(qt,{}),e.jsx(l3,{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(We,{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 Xh=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function c3({spectatorPermission:t,linkSharingPermission:s,onSpectatorPermissionChange:a,onLinkSharingPermissionChange:r}){return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(Ke,{value:t,onValueChange:a,children:[e.jsx(Xe,{id:"spectator-permission",children:e.jsx(Qe,{placeholder:"Select permission"})}),e.jsx(Je,{children:Xh.map(n=>e.jsx(J,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(Ke,{value:s,onValueChange:r,children:[e.jsx(Xe,{id:"link-sharing-permission",children:e.jsx(Qe,{placeholder:"Select permission"})}),e.jsx(Je,{children:Xh.map(n=>e.jsx(J,{value:n,children:n},n))})]})]})]})}function d3({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(ds,{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(ds,{checked:s,onCheckedChange:r})]})]})}function m3(){const[t,s]=u.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{Y.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Workflow Sharing Policy"}),e.jsx(Se,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(c3,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(qt,{}),e.jsx(d3,{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 u3(){const{user:t}=xs(),[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(js,{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:()=>Y.info("COB&NDC Coming soon"),children:"COB&NDC"}),e.jsxs(le,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(js,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]})]}),e.jsx(qt,{}),e.jsxs(Ii,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(Fi,{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(Bt,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(xl,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(Bt,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(Bt,{value:"users",className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Bt,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(ot,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(Bt,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx($s,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(Bt,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(Bt,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(Ay,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(Bt,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(Vp,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(Bt,{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(zt,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(q,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"KPI Configuration"}),e.jsx(Se,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(le,{className:"bg-blue-50 text-blue-700",children:[o," / ",o," KPIs Active"]})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(Ee,{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(Vt,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:d.name}),e.jsxs(le,{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(le,{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(Ty,{className:"w-3 h-3"}):e.jsx(ky,{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(le,{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(tt,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},m.id))})]},d.name))]})]})}),e.jsx(zt,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(_I,{})}),e.jsx(zt,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(BI,{})}),e.jsx(zt,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(HI,{})}),e.jsx(zt,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(QI,{})}),e.jsx(zt,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(qI,{})}),e.jsx(zt,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(r3,{})}),e.jsx(zt,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(o3,{})}),e.jsx(zt,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(m3,{})})]})]})}function x3(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)}const Ho={totalCreditNotes:0,totalAmount:0,activeDealersCount:0};function h3(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function p3(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 g3(){const[t,s]=u.useState([]),[a,r]=u.useState(Ho),[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 bg(j);s(v.creditNotes),r(v.summary??Ho)}catch(v){console.error("[Form16CreditNotes] Failed to fetch:",v),Y.error(v instanceof Error?v.message:"Failed to load credit notes"),s([]),r(Ho)}finally{i(!1)}},[]);u.useEffect(()=>{g()},[g]);const f=u.useCallback(async(j,v)=>{var w;d(!0),p(!0),h(null);try{const S=await rd(j),D=(v||`credit-note-${j}`).trim()+".csv",k=h3(S.sapResponse),C=t.find(E=>Number(E.id)===Number(j)),F=Wo((C==null?void 0:C.amount)??null),N=p3((C==null?void 0:C.issueDate)??null);h({fileName:D,row:k,meta:{amountText:F,issuedAtText:N},downloadUrl:S.url||null})}catch(S){const D=((w=S==null?void 0:S.response)==null?void 0:w.status)===409?"The credit note is being generated, wait.":S instanceof Error?S.message:"Failed to load SAP response";Y.error(String(D)),d(!1)}finally{p(!1)}},[t]),b=u.useCallback(async()=>{if(!(x!=null&&x.downloadUrl)){Y.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 w;return v.creditNoteNumber&&v.creditNoteNumber.toLowerCase().includes(j)||v.dealerName&&v.dealerName.toLowerCase().includes(j)||v.dealerCode&&v.dealerCode.toLowerCase().includes(j)||((w=v.submission)==null?void 0:w.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(gt,{open:c,onOpenChange:j=>{d(j),j||h(null)},children:e.jsxs(ht,{className:"sm:max-w-2xl",children:[e.jsxs(ft,{children:[e.jsx(pt,{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(We,{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(Pe,{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(Vs,{className:"w-4 h-4 text-amber-700"}),e.jsx("p",{className:"text-xs font-semibold text-amber-800 tracking-wide uppercase",children:"Credit Note Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4"})," Amount"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children: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(Bl,{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(Rt,{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(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Total Credit Notes Issued"}),e.jsx(ue,{className:"text-3xl",children:n?"...":a.totalCreditNotes})]})}),e.jsx(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Total Credit Amount"}),e.jsx(ue,{className:"text-3xl text-green-600",children:n?"...":Wo(a.totalAmount)})]})}),e.jsx(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Active Dealers"}),e.jsx(ue,{className:"text-3xl",children:n?"...":a.activeDealersCount})]})})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"All Credit Notes"}),e.jsx(Se,{children:"Search by credit note number, dealer name, or Form 16A number"}),e.jsxs("div",{className:"relative max-w-md mt-2",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(Ee,{type:"search",placeholder:"Search credit notes...",value:l,onChange:j=>o(j.target.value),className:"pl-9"})]})]}),e.jsx(se,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{children:[e.jsx(De,{children:"Credit Note No."}),e.jsx(De,{children:"Dealer Name"}),e.jsx(De,{children:"Form 16A No."}),e.jsx(De,{children:"Amount"}),e.jsx(De,{children:"Issue Date"}),e.jsx(De,{children:"Status"}),e.jsx(De,{className:"text-right",children:"Actions"})]})}),e.jsx(Ps,{children:n?e.jsx(rt,{children:e.jsxs(Ne,{colSpan:7,className:"text-center py-12",children:[e.jsx(We,{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(rt,{children:e.jsxs(Ne,{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,w,S;return e.jsxs(rt,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(Ne,{className:"font-medium",children:j.creditNoteNumber?j.creditNoteNumber.startsWith("CN")?j.creditNoteNumber:`CN #${j.creditNoteNumber}`:""}),e.jsx(Ne,{children:j.dealerName??j.dealerCode??""}),e.jsx(Ne,{children:((v=j.submission)==null?void 0:v.form16aNumber)??""}),e.jsx(Ne,{children:Wo(j.amount)}),e.jsx(Ne,{children:x3(j.issueDate)}),e.jsx(Ne,{children:e.jsx(le,{className:((w=j.status)==null?void 0:w.toLowerCase())==="issued"||((S=j.status)==null?void 0:S.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(Ne,{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()=>{Y.loading("Pulling credit note...",{id:`pull-cn-${j.id}`});try{await we.post("/form16/sap/pull"),await g(),Y.success("Refreshed.",{id:`pull-cn-${j.id}`})}catch{Y.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 Go(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 Yo(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function f3(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function b3(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 j3(){var F;const t=fs(),{id:s}=Sa(),[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 N=s?parseInt(s,10):NaN;if(Number.isNaN(N)){i(!1);return}let E=!1;return ax(N).then(_=>{E||r(_)}).catch(_=>{E||(Y.error(_ instanceof Error?_.message:"Failed to load credit note"),t("/form16/credit-notes"))}).finally(()=>{E||i(!1)}),()=>{E=!0}},[s,t]);const b=()=>{Y.info("Resend to dealer integration pending")},y=async()=>{var E;const N=s?parseInt(s,10):NaN;if(!Number.isNaN(N)){o(!0);try{const _=await ax(N);r(_),(E=_.creditNote)!=null&&E.sapResponseAvailable?Y.success("Credit note is available to download."):Y.info("Credit note is being generated. Please wait.")}catch(_){Y.error(_ instanceof Error?_.message:"Failed to pull credit note")}finally{o(!1)}}},j=async()=>{var E;const N=s?parseInt(s,10):NaN;if(!Number.isNaN(N))try{d(!0),p(!0),h(null),f(null);const _=await rd(N),z=f3(_.sapResponse);h(z),f(_.url||null)}catch(_){const z=((E=_==null?void 0:_.response)==null?void 0:E.status)===409?"The credit note is being generated, wait.":_ instanceof Error?_.message:"Failed to download";Y.error(String(z))}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(We,{className:"w-8 h-8 animate-spin text-teal-600"})});if(!a)return null;const{creditNote:v,dealerName:w,dealerEmail:S,dealerContact:D,dealerCreditNotes:k}=a,C=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(gt,{open:c,onOpenChange:N=>{d(N),N||(h(null),f(null))},children:e.jsxs(ht,{className:"sm:max-w-2xl",children:[e.jsxs(ft,{children:[e.jsx(pt,{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(We,{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(Pe,{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(Vs,{className:"w-4 h-4 text-amber-700"}),e.jsx("p",{className:"text-xs font-semibold text-amber-800 tracking-wide uppercase",children:"Credit Note Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4"})," Amount"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:Yo(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(Bl,{className:"w-4 h-4"})," Issued Date"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:b3(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(Rt,{className:"gap-2 sm:gap-0",children:[e.jsx(O,{variant:"outline",onClick:()=>d(!1),children:"Close"}),e.jsxs(O,{onClick:()=>{if(!g){Y.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(Ss,{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(wa,{className:"w-4 h-4 mr-2"}),"Resend to Dealer"]})})]}),e.jsx(q,{className:"mb-6",children:e.jsxs(se,{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:C}),e.jsx(le,{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 ",Go(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:Yo(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(We,{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:w||""})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide",children:"Form 16A Number"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:((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:S||""})]}),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:D||""})]})]})]})}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Dealer Transaction History"}),e.jsxs(Se,{children:["All credit notes issued to ",w||"this dealer"]})]}),e.jsx(se,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{children:[e.jsx(De,{children:"Submission Date"}),e.jsx(De,{children:"Form 16A No."}),e.jsx(De,{children:"Amount"}),e.jsx(De,{children:"Credit Note Issued"}),e.jsx(De,{children:"Credit Note No."}),e.jsx(De,{children:"CN Issue Date"}),e.jsx(De,{children:"Status"})]})}),e.jsx(Ps,{children:k.length===0?e.jsx(rt,{children:e.jsx(Ne,{colSpan:7,className:"text-center py-8 text-gray-500",children:"No other credit notes for this dealer"})}):k.map(N=>{var E,_;return e.jsxs(rt,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(Ne,{children:Go(N.submittedDate)}),e.jsx(Ne,{children:N.form16aNumber??""}),e.jsx(Ne,{children:Yo(N.amount)}),e.jsx(Ne,{children:e.jsx(le,{className:"bg-green-100 text-green-800 border-green-200",children:"Yes"})}),e.jsx(Ne,{children:N.creditNoteNumber?N.creditNoteNumber.startsWith("CN")?N.creditNoteNumber:`CN #${N.creditNoteNumber}`:""}),e.jsx(Ne,{children:Go(N.issueDate)}),e.jsx(Ne,{children:e.jsx(le,{className:((E=N.status)==null?void 0:E.toLowerCase())==="withdrawn"?"bg-red-50 text-red-700 border-red-200":"bg-green-100 text-green-800 border-green-200",children:((_=N.status)==null?void 0:_.toLowerCase())==="withdrawn"?"Withdrawn":"Completed"})})]},N.id)})})]})})})]})]})]})}function y3(t){if(!t)return"";try{const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}catch{return t}}function Ko(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function v3(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 N3(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}const Qo={totalDebitNotes:0,totalAmount:0,impactedDealersCount:0};function w3(){const[t,s]=u.useState([]),[a,r]=u.useState(Qo),[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 D=>{try{i(!0);const k=await jg(D);s(k.debitNotes),r(k.summary??Qo)}catch(k){console.error("[Form16DebitNotes] Failed to fetch:",k),Y.error(k instanceof Error?k.message:"Failed to load debit notes"),s([]),r(Qo)}finally{i(!1)}},[]);u.useEffect(()=>{j()},[j]);const v=u.useMemo(()=>{if(!l.trim())return t;const D=l.trim().toLowerCase();return t.filter(k=>k.debitNoteNumber&&k.debitNoteNumber.toLowerCase().includes(D)||k.creditNoteNumber&&k.creditNoteNumber.toLowerCase().includes(D)||k.dealerName&&k.dealerName.toLowerCase().includes(D)||k.dealerCode&&k.dealerCode.toLowerCase().includes(D)||k.form16aNumber&&k.form16aNumber.toLowerCase().includes(D))},[t,l]),w=u.useCallback(async D=>{var k;d(!0),p(!0),h(null),f({amountText:Ko(D.amount),issuedAtText:v3(D.issueDate)});try{const C=await yg(Number(D.id));h(N3(C.sapResponse))}catch(C){const F=((k=C==null?void 0:C.response)==null?void 0:k.status)===409?"The debit note is being generated, wait.":C instanceof Error?C.message:"Failed to load SAP response";Y.error(String(F)),d(!1)}finally{p(!1)}},[]),S=u.useCallback(async()=>{var D;y(!0),Y.loading("Pulling SAP responses...",{id:"pull-debit"});try{const k=await we.post("/form16/sap/pull");await j();const C=(D=k.data)==null?void 0:D.data,F=typeof(C==null?void 0:C.debitProcessed)=="number"?C.debitProcessed:C==null?void 0:C.processed;typeof F=="number"&&F>0?Y.success(`Pulled. ${F} debit response(s) processed. List refreshed.`,{id:"pull-debit"}):Y.success("Pulled. List refreshed. (No new debit responses in folder.)",{id:"pull-debit"})}catch{Y.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(gt,{open:c,onOpenChange:D=>{d(D),D||(h(null),f(null))},children:e.jsxs(ht,{className:"sm:max-w-2xl",children:[e.jsxs(ft,{children:[e.jsx(pt,{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(We,{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(Pe,{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(Vs,{className:"w-4 h-4 text-amber-700"}),e.jsx("p",{className:"text-xs font-semibold text-amber-800 tracking-wide uppercase",children:"Debit Note Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4"})," Amount"]}),e.jsx("p",{className:"text-base font-semibold text-amber-900 mt-1",children:(g==null?void 0:g.amountText)??""})]}),e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-white/70 p-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Bl,{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(Rt,{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(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Total Debit Notes Issued"}),e.jsx(ue,{className:"text-3xl",children:n?"...":a.totalDebitNotes})]})}),e.jsx(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Total Debit Amount"}),e.jsx(ue,{className:"text-3xl text-red-600",children:n?"...":Ko(a.totalAmount)})]})}),e.jsx(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Impacted Dealers"}),e.jsx(ue,{className:"text-3xl",children:n?"...":a.impactedDealersCount})]})})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"All Debit Notes"}),e.jsx(Se,{children:"Search by debit note number, credit note number, dealer, or Form 16A number"}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(Ee,{type:"search",placeholder:"Search debit notes...",value:l,onChange:D=>o(D.target.value),className:"pl-9"})]})]}),e.jsx(se,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{children:[e.jsx(De,{children:"Debit Note No."}),e.jsx(De,{children:"Credit Note No."}),e.jsx(De,{children:"Dealer"}),e.jsx(De,{children:"Form 16A No."}),e.jsx(De,{children:"Amount"}),e.jsx(De,{children:"Issue Date"}),e.jsx(De,{children:"Status"}),e.jsx(De,{className:"text-right",children:"Actions"})]})}),e.jsx(Ps,{children:n?e.jsx(rt,{children:e.jsxs(Ne,{colSpan:8,className:"text-center py-12",children:[e.jsx(We,{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(rt,{children:e.jsxs(Ne,{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(D=>{var k,C;return e.jsxs(rt,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(Ne,{className:"font-medium",children:D.debitNoteNumber??""}),e.jsx(Ne,{className:"font-medium",children:D.creditNoteNumber??""}),e.jsx(Ne,{children:D.dealerName??D.dealerCode??""}),e.jsx(Ne,{children:D.form16aNumber??""}),e.jsx(Ne,{children:Ko(D.amount)}),e.jsx(Ne,{children:y3(D.issueDate)}),e.jsx(Ne,{children:e.jsx(le,{className:((k=D.status)==null?void 0:k.toLowerCase())==="issued"||((C=D.status)==null?void 0:C.toLowerCase())==="completed"?"bg-green-100 text-green-800 border-green-200":"bg-gray-100 text-gray-700 border-gray-200",children:D.status??""})}),e.jsx(Ne,{className:"text-right",children:e.jsx("div",{className:"flex items-center justify-end gap-2",children:D.sapResponseAvailable?e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>w(D),children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"View"]}):e.jsxs(O,{variant:"outline",size:"sm",onClick:S,disabled:b,children:[b?e.jsx(We,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(_t,{className:"w-4 h-4 mr-2"}),"Pull"]})})})]},D.id)})})]})})})]})]})]})}function C3(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 S3(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 Jh(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function A3(t){return{TRNS_UNIQ_NO:t.trnsUniqNo||"",TDS_TRNS_ID:t.tdsTransId||"",DOC_NO:t.sapDocumentNumber||"",MSG_TYP:t.msgTyp||"",MESSAGE:t.message||""}}function T3(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 k3(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 D3(){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([bg(),jg()]),w=[...j.creditNotes.map(T3),...v.debitNotes.map(k3)].sort((S,D)=>{const k=S.issueDate?new Date(S.issueDate).getTime():0;return(D.issueDate?new Date(D.issueDate).getTime():0)-k});o(w)}catch(j){console.error("[Form16Transactions] Failed to fetch:",j),Y.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 rd(j.id):await yg(j.id);h({type:j.type,referenceNumber:j.referenceNumber,amountText:Jh(j.amount),issuedAtText:S3(j.issueDate),row:A3(v.sapResponse)})}catch(v){const w=v instanceof Error?v.message:"Failed to load SAP response";Y.error(w),d(!1)}finally{p(!1)}},[]),y=u.useCallback(async()=>{r(!0),Y.loading("Pulling SAP responses...",{id:"pull-transactions"});try{await we.post("/form16/sap/pull"),await g(),Y.success("Pulled and refreshed transactions.",{id:"pull-transactions"})}catch{Y.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(gt,{open:c,onOpenChange:j=>{d(j),j||h(null)},children:e.jsxs(ht,{className:"sm:max-w-2xl",children:[e.jsxs(ft,{children:[e.jsx(pt,{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(We,{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(Pe,{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(Vs,{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(Vs,{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(Bl,{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(Rt,{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(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"All Transactions"}),e.jsx(Se,{children:"CR/DB reference number, dealer, amount, issue date, and SAP status"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"relative max-w-md w-full",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(Ee,{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(We,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(_t,{className:"w-4 h-4 mr-2"}),"Pull SAP Response"]})]})]}),e.jsx(se,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{children:[e.jsx(De,{children:"TDS_TRANS_ID"}),e.jsx(De,{children:"Dealer"}),e.jsx(De,{children:"Transaction Amount"}),e.jsx(De,{children:"Issued Date"}),e.jsx(De,{children:"Status"}),e.jsx(De,{className:"text-right",children:"Actions"})]})}),e.jsx(Ps,{children:t?e.jsx(rt,{children:e.jsxs(Ne,{colSpan:6,className:"text-center py-12",children:[e.jsx(We,{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(rt,{children:e.jsxs(Ne,{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(rt,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(Ne,{className:"font-medium",children:j.referenceNumber}),e.jsx(Ne,{children:j.dealer}),e.jsx(Ne,{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(Dy,{className:"w-4 h-4"}):e.jsx(Ry,{className:"w-4 h-4"}),e.jsxs("span",{children:[j.type==="credit"?"+ ":"- ",Jh(j.amount)]})]})}),e.jsx(Ne,{children:C3(j.issueDate)}),e.jsx(Ne,{children:j.sapResponseAvailable?e.jsx(le,{className:"bg-green-100 text-green-800 border-green-200",children:"Completed"}):e.jsx(le,{className:"bg-orange-100 text-orange-800 border-orange-200",children:"OUTGOING"})}),e.jsx(Ne,{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(We,{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 R3({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:Ns,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:Ns,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:We,text:"Validating Form 16A...",subtext:"Please wait",bgColor:"bg-blue-50",borderColor:"border-blue-300",iconColor:"text-blue-600 animate-spin"},extracting:{icon:We,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:gs,text:"Form 16A uploaded successfully",subtext:"Document ready for submission",bgColor:"bg-green-50",borderColor:"border-green-300",iconColor:"text-green-600"},error:{icon:tt,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 Wi=10;function I3(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 F3(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 P3(){const t=fs(),[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,w]=u.useState(!1),[S,D]=u.useState(""),[k,C]=u.useState(""),[F,N]=u.useState(null),[E,_]=u.useState(!1);u.useEffect(()=>{let W=!1;return Ng().then(P=>{W||(a(Array.isArray(P)?P:[]),l(0))}).catch(()=>{W||a([])}).finally(()=>{W||n(!1)}),()=>{W=!0}},[]);const z=Math.max(1,Math.ceil(s.length/Wi)),R=i>0,L=i<z-1,V=Math.max(0,Math.min(i-4,z-9)),I=Math.min(z-1,V+8),A=Array.from({length:I-V+1},(W,P)=>V+P),G=s.slice(i*Wi,(i+1)*Wi),$=u.useCallback(()=>{if(!p)return;const W=URL.createObjectURL(p);N(W),_(!0)},[p]),M=u.useCallback(()=>{_(!1),F&&(URL.revokeObjectURL(F),N(null))},[F]),T=u.useCallback(async W=>{if(!W.name.toLowerCase().endsWith(".pdf")){Y.error("Please upload a PDF file");return}x(W),b(null),j(null),g("extracting");try{Y.loading("Extracting data with Google Gemini...",{id:"form16-ocr"});const P=await fN(W);b(P.extractedData),j(P.ocrProvider||null),D(P.extractedData.tanNumber??P.extractedData.tanOfDeductor??""),C(P.extractedData.deductorName??P.extractedData.nameAndAddressOfDeductor??""),c(P.extractedData.financialYear??""),m(P.extractedData.quarter??""),g("success"),Y.success(P.ocrProvider?`Data extracted via ${P.ocrProvider}`:"Data extracted",{id:"form16-ocr"})}catch(P){g("error");const B=P instanceof Error?P.message:"Failed to extract data from PDF";Y.error(B,{id:"form16-ocr"})}},[]),U=async()=>{var te;if(!o||!d){Y.error("Financial year and quarter could not be extracted from the PDF. Please ensure you upload a valid Form 16A certificate.");return}if(!p){Y.error("Please upload Form 16A PDF");return}const W=((f==null?void 0:f.form16aNumber)??"").trim()||`F16-${o}-${d}-${Date.now()}`,P=(f==null?void 0:f.tdsAmount)??(f==null?void 0:f.totalTaxDeducted)??0,B=(f==null?void 0:f.totalAmount)??(f==null?void 0:f.totalAmountPaid)??0,K=(S||((f==null?void 0:f.tanNumber)??(f==null?void 0:f.tanOfDeductor)??"")).trim(),Z=(k||((f==null?void 0:f.deductorName)??(f==null?void 0:f.nameAndAddressOfDeductor)??"")).trim();if(!K||!Z){Y.error("TAN and Deductor name are required. Please enter or correct them below.");return}w(!0);try{const ae=await bN({financialYear:o,quarter:d,form16aNumber:W,tdsAmount:Number(P)||0,totalAmount:Number(B)||0,tanNumber:K,deductorName:Z,file:p,extractedData:f??void 0}),xe=ae.validationStatus,be=xe==="success"?"success":xe==="duplicate"?"duplicate":xe==="failed"?"mismatch":"error",Ge=be==="duplicate"?"A credit note has already been issued for this financial year and quarter. This submission is recorded as a new version.":void 0,Be=be==="mismatch"?ae.validationNotes||"Form 16A details did not match with 26AS data.":void 0;Y.success(be==="success"?"Form 16A matched with 26AS. Credit note generated.":"Form 16A submitted successfully"),t("/form16/submit/result",{state:{status:be,requestId:ae.requestId,requestNumber:ae.requestNumber,creditNoteNumber:ae.creditNoteNumber??void 0,message:Ge??Be}})}catch(ae){const xe=ae&&typeof ae=="object"&&"response"in ae?ae.response:void 0,be=((te=xe==null?void 0:xe.data)==null?void 0:te.message)??(ae instanceof Error?ae.message:"Failed to submit");(xe==null?void 0:xe.status)===400&&typeof be=="string"&&(be.toLowerCase().includes("duplicate")||be.toLowerCase().includes("already exist"))?t("/form16/submit/result",{state:{status:"duplicate",requestId:"",message:be}}):Y.error(String(be))}finally{w(!1)}},H=!!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(Ss,{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(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Upload Form 16A Certificate"}),e.jsx(Se,{children:"PDF only. Financial year and quarter are taken from the certificate via OCR; no need to enter them manually."})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsx(R3,{state:h==="extracting"?"extracting":h==="error"?"error":h==="success"?"success":"idle",onFileSelect:T,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(We,{className:"w-5 h-5 text-blue-600 shrink-0 animate-spin"}):h==="error"?e.jsx(tt,{className:"w-5 h-5 text-red-600 shrink-0"}):e.jsx(gs,{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),D(""),C(""),c(""),m(""),g("idle"),M()},disabled:h==="extracting",children:"Remove"})]}),p&&e.jsxs(O,{type:"button",variant:"outline",className:"w-full",onClick:$,disabled:h==="extracting",children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"View Uploaded Form 16A"]})]})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Quarters Pending Submission"}),e.jsx(Se,{children:"These quarters don't have completed Form 16A submissions. Please submit Form 16A for these quarters."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{className:"bg-gray-50",children:[e.jsx(De,{children:"Dealer Name"}),e.jsx(De,{children:"Financial Year"}),e.jsx(De,{children:"Quarter"}),e.jsx(De,{children:"Version"}),e.jsx(De,{children:"Status"}),e.jsx(De,{children:"26AS start date"}),e.jsx(De,{children:"Days Status"}),e.jsx(De,{className:"text-right",children:"Action"})]})}),e.jsx(Ps,{children:r?e.jsx(rt,{children:e.jsxs(Ne,{colSpan:8,className:"text-center py-12 text-gray-500",children:[e.jsx(We,{className:"w-8 h-8 animate-spin mx-auto mb-2"}),e.jsx("p",{children:"Loading..."})]})}):s.length===0?e.jsx(rt,{children:e.jsx(Ne,{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(Pe,{className:"w-12 h-12 text-gray-300"}),e.jsx("p",{children:"No pending submissions. All quarters are complete."})]})})}):G.map(W=>e.jsxs(rt,{className:"hover:bg-gray-50",children:[e.jsx(Ne,{className:"text-sm text-gray-900",children:W.dealer_name??"Your submission"}),e.jsx(Ne,{children:e.jsxs("span",{className:"text-sm text-gray-900",children:["FY ",W.financial_year]})}),e.jsx(Ne,{children:e.jsx(le,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:W.quarter})}),e.jsx(Ne,{children:e.jsx(le,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:W.has_submission?"V1":"—"})}),e.jsx(Ne,{children:e.jsx(le,{variant:"outline",className:W.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":W.has_submission?"bg-slate-50 text-slate-600 border-slate-200":"bg-gray-100 text-gray-600 border-gray-200",children:W.latest_submission_status==="failed"?"Failed":W.has_submission?"Under review":"Not Submitted"})}),e.jsx(Ne,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-700",children:I3(W.twenty_six_as_start_date??W.audit_start_date)})]})}),e.jsx(Ne,{children:W.days_since_26as_uploaded!=null&&W.days_since_26as_uploaded>=0?e.jsxs("span",{className:"text-sm font-medium text-gray-700",children:["due from ",W.days_since_26as_uploaded," days"]}):e.jsx("span",{className:"text-sm text-gray-500",children:"—"})}),e.jsx(Ne,{className:"text-right",children:e.jsx(O,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>t("/form16/submit"),children:"Submit Now"})})]},`${W.financial_year}|${W.quarter}`))})]})}),!r&&s.length>Wi&&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 ",z," (",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:!R,onClick:()=>l(W=>W-1),children:[e.jsx(Nn,{className:"w-4 h-4"}),"Previous"]}),A.map(W=>e.jsx(O,{variant:W===i?"default":"outline",size:"sm",className:W===i?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>l(W),children:W+1},W)),e.jsxs(O,{variant:"outline",size:"sm",disabled:!L,onClick:()=>l(W=>W+1),children:["Next",e.jsx(Wa,{className:"w-4 h-4"})]})]})]})]})]}),e.jsxs(q,{className:"border-blue-200 bg-blue-50",children:[e.jsx(me,{children:e.jsxs(ue,{className:"text-blue-900 flex items-center gap-2",children:[e.jsx(Zr,{className:"w-5 h-5"}),"Important Notes"]})}),e.jsx(se,{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"})]})})]}),H&&e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-blue-600"}),e.jsx(ue,{children:"Form 16A Extracted Details"})]}),e.jsx(Se,{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(se,{className:"space-y-6",children:h==="extracting"?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(We,{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(tt,{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:F3(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(ne,{htmlFor:"form16-tan",children:"TAN of deductor *"}),e.jsx(Ee,{id:"form16-tan",value:S,onChange:W=>D(W.target.value),placeholder:"e.g. BLRH07660C",maxLength:10})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(ne,{htmlFor:"form16-deductor",children:"Deductor name *"}),e.jsx(Ee,{id:"form16-deductor",value:k,onChange:W=>C(W.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(gs,{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(We,{className:"w-4 h-4 animate-spin mr-2"}):null,"Submit Form 16A"]})]})]}):null})]}),e.jsx(gt,{open:E,onOpenChange:W=>!W&&M(),children:e.jsxs(ht,{className:"max-w-4xl max-h-[90vh] flex flex-col","aria-describedby":"form16-pdf-description",children:[e.jsxs(ft,{children:[e.jsx(pt,{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 E3={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 _3({variant:t,label:s,showIcon:a=!0}){const r=t==="success"?gs:t==="failed"?At:ot;return e.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm font-medium ${E3[t]}`,children:[a&&e.jsx(r,{className:"h-4 w-4 shrink-0"}),s]})}function M3({step:t,label:s,state:a,isLast:r}){const n=a==="completed"?gs:a==="failed"?At:Vc,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 L3({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(Yt.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{duration:.4},className:"w-full max-w-2xl",children:e.jsx(q,{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(se,{className:"pt-12 pb-10",children:[e.jsx(Yt.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{delay:.15},className:"flex justify-center mb-6",children:e.jsx(_3,{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(Yt.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(gs,{className:"w-12 h-12 text-teal-600"}):x?e.jsx(Iy,{className:"w-12 h-12 text-red-600"}):h?e.jsx(tt,{className:"w-12 h-12 text-gray-500"}):e.jsx(tt,{className:"w-12 h-12 text-amber-600"})})}),e.jsx(Yt.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(Yt.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(Yt.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(M3,{step:b+1,label:f.label,state:f.state,isLast:b===g.length-1},b))})]}),e.jsx(Yt.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 O3(){const t=fs(),a=zl().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(L3,{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,Hi=10,$3=["Q1","Q2","Q3","Q4"],U3=[{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 Zh(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 Gi(t){return t==null?"":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function B3(){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 z3(t){switch((t||"").trim().toUpperCase().slice(0,1)){case"F":return e.jsx(le,{className:"bg-green-100 text-green-700 border-green-300",children:"F"});case"O":return e.jsx(le,{className:"bg-orange-100 text-orange-700 border-orange-300",children:"O"});case"M":return e.jsx(le,{className:"bg-blue-100 text-blue-700 border-blue-300",children:"M"});case"U":return e.jsx(le,{className:"bg-red-100 text-red-700 border-red-300",children:"U"});case"P":return e.jsx(le,{className:"bg-amber-100 text-amber-700 border-amber-300",children:"P"});default:return t?e.jsx(le,{variant:"secondary",children:t}):null}}function V3(){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,w]=u.useState([]),[S,D]=u.useState(0),[k,C]=u.useState({totalRecords:0,booked:0,notBooked:0,pending:0,totalTaxDeducted:0}),[F,N]=u.useState(!0),[E,_]=u.useState(0),[z,R]=u.useState([]),[L,V]=u.useState(0),[I,A]=u.useState(0),[G,$]=u.useState(!1),M=B3(),T=u.useCallback(async(re=0)=>{try{$(!0);const{history:pe,total:ie}=await yN({limit:Hi,offset:re*Hi});R(pe),V(ie),A(re)}catch(pe){console.error("[Form16_26AS] upload history",pe),R([]),V(0),A(0)}finally{$(!1)}},[]),U=u.useCallback(async(re=0)=>{try{N(!0);const pe={limit:Gn,offset:re*Gn};a.assessmentYear!=="all"&&(pe.financialYear=a.assessmentYear),a.quarter!=="all"&&(pe.quarter=a.quarter),a.section!=="all"&&(pe.sectionCode=a.section),a.tanNumber.trim()&&(pe.tanNumber=a.tanNumber.trim()),a.deductor.trim()&&(pe.search=a.deductor.trim()),a.status!=="all"&&(pe.status=a.status);const ie=await jN(pe);w(ie.entries),D(ie.total),C(ie.summary),_(re)}catch(pe){console.error("[Form16_26AS]",pe),Y.error(pe instanceof Error?pe.message:"Failed to load 26AS entries"),w([]),D(0),C({totalRecords:0,booked:0,notBooked:0,pending:0,totalTaxDeducted:0})}finally{N(!1)}},[a.assessmentYear,a.quarter,a.section,a.tanNumber,a.deductor,a.status]);u.useEffect(()=>{U(0)},[U]),u.useEffect(()=>{T(0)},[T]),u.useEffect(()=>(l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{r(re=>({...re,deductor:n.trim()}))},300),()=>{l.current&&clearTimeout(l.current)}),[n]),u.useEffect(()=>()=>{j.current&&(clearInterval(j.current),j.current=null)},[]);const H=re=>{var ie;const pe=(ie=re.target.files)==null?void 0:ie[0];if(pe){if(pe.size>50*1024*1024){Y.error("File size must be less than 50MB");return}if(!pe.name.toLowerCase().endsWith(".txt")){Y.error("Only .txt files are supported");return}b(pe)}},W=async()=>{var re,pe;if(!f){Y.error("Please select a file");return}m(!0),x(0),g(0),j.current&&(clearInterval(j.current),j.current=null);try{const ie=await NN(f,fe=>{if(x(fe),fe>=100&&!j.current){g(0);let Ie=0;j.current=setInterval(()=>{Ie+=1,g($e=>Math.min(99,$e+4+Math.floor(Ie/3)))},300)}});j.current&&(clearInterval(j.current),j.current=null),g(100),ie.imported>0?(Y.success(`Successfully imported ${ie.imported} entries.${(re=ie.errors)!=null&&re.length?` ${ie.errors.length} warnings.`:""}`),c(!1),b(null),y.current&&(y.current.value=""),U(0),T(0)):(pe=ie.errors)!=null&&pe.length&&Y.error(ie.errors[0]||"Upload failed")}catch(ie){j.current&&(clearInterval(j.current),j.current=null),Y.error(ie instanceof Error?ie.message:"Upload failed")}finally{m(!1),x(0),g(0)}},P=()=>{r({assessmentYear:"all",quarter:"all",section:"all",tanNumber:"",deductor:"",status:"all"}),i("")},B=a.assessmentYear!=="all"||a.quarter!=="all"||a.section!=="all"||a.tanNumber!==""||a.deductor!==""||a.status!=="all",K=Math.max(1,Math.ceil(S/Gn)),Z=E>0,te=E<K-1,ae=Math.max(0,Math.min(E-4,K-9)),xe=Math.min(K-1,ae+8),be=Array.from({length:xe-ae+1},(re,pe)=>ae+pe),Ge=Math.max(1,Math.ceil(L/Hi)),Be=I>0,_e=I<Ge-1,Re=Math.max(0,Math.min(I-4,Ge-9)),ce=Math.min(Ge-1,Re+8),je=Array.from({length:ce-Re+1},(re,pe)=>Re+pe);return e.jsx("div",{className:"min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden",children:e.jsxs("div",{className:"w-full max-w-[98vw] xl:max-w-[1920px] mx-auto space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-1",children:"Form 26AS - TDS Data"}),e.jsx("p",{className:"text-gray-600 text-sm",children:"View and manage TDS deduction records from Form 26AS"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[180px] max-w-[280px]",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(Ee,{placeholder:"Search...",value:n,onChange:re=>i(re.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(Ns,{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",B&&e.jsx(le,{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(re=>re!==""&&re!=="all").length}),t?e.jsx(Dl,{className:"w-4 h-4"}):e.jsx(Qr,{className:"w-4 h-4"})]})]})]}),e.jsx(gt,{open:o,onOpenChange:c,children:e.jsxs(ht,{className:"max-w-md",children:[e.jsxs(ft,{children:[e.jsxs(pt,{className:"flex items-center gap-2",children:[e.jsx(Ns,{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(ne,{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:H,disabled:d,className:"hidden"}),e.jsxs(O,{variant:"outline",onClick:()=>{var re;return(re=y.current)==null?void 0:re.click()},disabled:d,className:"gap-2",children:[e.jsx(Pe,{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(la,{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(la,{value:h,className:"h-2",indicatorClassName:"bg-teal-600"})]})]})]}),e.jsxs(Rt,{children:[e.jsx(O,{variant:"outline",onClick:()=>{c(!1),b(null),y.current&&(y.current.value="")},disabled:d,children:"Cancel"}),e.jsx(O,{onClick:W,disabled:!f||d,className:"bg-teal-600 hover:bg-teal-700 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-4 h-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"w-4 h-4"}),"Upload"]})})]})]})}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Management"}),e.jsxs(Se,{children:["History of 26AS file uploads: when and which user added or uploaded 26AS data",L>0?` (${L} total)`:""]})]}),e.jsxs(se,{children:[e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{children:[e.jsx(De,{children:"Date & Time"}),e.jsx(De,{children:"User"}),e.jsx(De,{children:"File Name"}),e.jsx(De,{className:"text-right",children:"Records Imported"}),e.jsx(De,{className:"text-right",children:"Errors"})]})}),e.jsx(Ps,{children:G?e.jsx(rt,{children:e.jsxs(Ne,{colSpan:5,className:"text-center py-8",children:[e.jsx(We,{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..."})]})}):z.length===0?e.jsx(rt,{children:e.jsx(Ne,{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."})}):z.map(re=>e.jsxs(rt,{className:"hover:bg-gray-50",children:[e.jsx(Ne,{className:"text-sm whitespace-nowrap",children:re.uploadedAt?new Date(re.uploadedAt).toLocaleString("en-IN",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):""}),e.jsx(Ne,{className:"text-sm",children:re.uploadedByDisplayName||re.uploadedByEmail||re.uploadedBy||""}),e.jsx(Ne,{className:"text-sm text-gray-600 max-w-[200px] truncate",title:re.fileName||void 0,children:re.fileName||""}),e.jsx(Ne,{className:"text-right font-medium",children:re.recordsImported}),e.jsx(Ne,{className:"text-right",children:re.errorsCount>0?re.errorsCount:""})]},re.id))})]})}),!G&&L>Hi&&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 ",I+1," of ",Ge," (",L," 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:!Be,onClick:()=>T(I-1),children:[e.jsx(Nn,{className:"w-4 h-4"}),"Previous"]}),je.map(re=>e.jsx(O,{variant:re===I?"default":"outline",size:"sm",className:re===I?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>T(re),children:re+1},re)),e.jsxs(O,{variant:"outline",size:"sm",disabled:!_e,onClick:()=>T(I+1),children:["Next",e.jsx(Wa,{className:"w-4 h-4"})]})]})]})]})]}),t&&e.jsxs(q,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Filter TDS Records"}),B&&e.jsxs(O,{variant:"ghost",size:"sm",onClick:P,className:"gap-2 text-gray-600",children:[e.jsx(Nt,{className:"w-4 h-4"}),"Clear All"]})]})}),e.jsx(se,{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(ne,{children:"Assessment Year"}),e.jsxs(Ke,{value:a.assessmentYear,onValueChange:re=>r(pe=>({...pe,assessmentYear:re})),children:[e.jsx(Xe,{children:e.jsx(Qe,{placeholder:"Select year"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Years"}),M.map(re=>e.jsx(J,{value:re,children:re},re))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Quarter"}),e.jsxs(Ke,{value:a.quarter,onValueChange:re=>r(pe=>({...pe,quarter:re})),children:[e.jsx(Xe,{children:e.jsx(Qe,{placeholder:"Select quarter"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Quarters"}),$3.map(re=>e.jsx(J,{value:re,children:re},re))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Section"}),e.jsxs(Ke,{value:a.section,onValueChange:re=>r(pe=>({...pe,section:re})),children:[e.jsx(Xe,{children:e.jsx(Qe,{placeholder:"Select section"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Sections"}),U3.map(re=>e.jsx(J,{value:re.value,children:re.label},re.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"TAN"}),e.jsx(Ee,{placeholder:"Search TAN...",value:a.tanNumber,onChange:re=>r(pe=>({...pe,tanNumber:re.target.value})),className:"h-9 font-mono"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Deductor"}),e.jsx(Ee,{placeholder:"Search deductor / TAN...",value:a.deductor,onChange:re=>r(pe=>({...pe,deductor:re.target.value})),className:"h-9"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Status"}),e.jsxs(Ke,{value:a.status,onValueChange:re=>r(pe=>({...pe,status:re})),children:[e.jsx(Xe,{children:e.jsx(Qe,{placeholder:"Select status"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"F",children:"F Final (Booked)"}),e.jsx(J,{value:"O",children:"O Overbooked"}),e.jsx(J,{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(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Total Records"}),e.jsx(ue,{className:"text-2xl",children:k.totalRecords})]})}),e.jsx(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Booked"}),e.jsx(ue,{className:"text-2xl text-green-600",children:k.booked})]})}),e.jsx(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Not Booked"}),e.jsx(ue,{className:"text-2xl text-red-600",children:k.notBooked})]})}),e.jsx(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Pending"}),e.jsx(ue,{className:"text-2xl text-amber-600",children:k.pending})]})}),e.jsx(q,{className:"lg:col-span-1",children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Total Tax Deducted"}),e.jsx(ue,{className:"text-xl",children:Gi(k.totalTaxDeducted)})]})})]}),e.jsxs(q,{children:[e.jsx(me,{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(Se,{children:B?`Showing ${v.length} of ${S} records`:`Complete list of TDS deduction records (${S} total)`})]}),e.jsxs(O,{variant:"outline",size:"sm",disabled:!0,children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Export"]})]})}),e.jsxs(se,{className:"p-0",children:[e.jsx("div",{className:"overflow-auto min-h-[320px]",style:{maxHeight:"calc(100vh - 380px)"},children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{className:"bg-gray-50",children:[e.jsx(De,{className:"w-14",children:"Sr No"}),e.jsx(De,{className:"min-w-[180px]",children:"Name of Deductor"}),e.jsx(De,{className:"text-right min-w-[110px]",children:"Total Amount Paid"}),e.jsx(De,{className:"text-right min-w-[110px]",children:"Total Tax Deducted"}),e.jsx(De,{className:"text-right min-w-[110px]",children:"Total TDS Deposited"}),e.jsx(De,{className:"min-w-[100px]",children:"TAN of Deductor"}),e.jsx(De,{className:"min-w-[72px]",children:"Section"}),e.jsx(De,{className:"min-w-[64px]",children:"Quarter"}),e.jsx(De,{className:"min-w-[90px]",children:"Assessment Year"}),e.jsx(De,{className:"min-w-[90px]",children:"Financial Year"}),e.jsx(De,{className:"min-w-[100px]",children:"Transaction Date"}),e.jsx(De,{className:"min-w-[64px]",children:"Status"}),e.jsx(De,{className:"min-w-[100px]",children:"Date of Booking"})]})}),e.jsx(Ps,{children:F?e.jsx(rt,{children:e.jsx(Ne,{colSpan:13,className:"text-center py-12",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(We,{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(rt,{children:e.jsxs(Ne,{colSpan:13,className:"text-center py-12 text-gray-500",children:[B?"No records match your filters":"No TDS records found. Upload a 26AS file to get started.",B&&e.jsx(O,{variant:"outline",size:"sm",onClick:P,className:"mt-2",children:"Clear Filters"})]})}):v.map((re,pe)=>e.jsxs(rt,{className:"hover:bg-gray-50",children:[e.jsx(Ne,{className:"text-center text-sm text-gray-900",children:E*Gn+pe+1}),e.jsx(Ne,{className:"text-sm text-gray-900",children:re.deductorName||""}),e.jsx(Ne,{className:"text-right text-sm text-gray-900",children:Gi(re.amountPaid??0)}),e.jsx(Ne,{className:"text-right text-sm text-gray-900",children:Gi(re.taxDeducted)}),e.jsx(Ne,{className:"text-right text-sm text-gray-900",children:Gi(re.totalTdsDeposited??0)}),e.jsx(Ne,{className:"text-sm text-gray-700 font-mono",children:re.tanNumber}),e.jsx(Ne,{children:e.jsx(le,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:re.sectionCode||""})}),e.jsx(Ne,{children:e.jsx(le,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:re.quarter})}),e.jsx(Ne,{className:"text-sm text-gray-700 font-medium",children:re.assessmentYear||""}),e.jsx(Ne,{className:"text-sm text-gray-700 font-medium",children:re.financialYear||""}),e.jsx(Ne,{className:"text-sm text-gray-700",children:Zh(re.transactionDate)}),e.jsx(Ne,{children:z3(re.statusOltas)}),e.jsx(Ne,{className:"text-sm text-gray-700",children:Zh(re.dateOfBooking)})]},re.id))})]})}),!F&&S>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 ",E+1," of ",K," (",S," 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:!Z,onClick:()=>U(E-1),children:[e.jsx(Nn,{className:"w-4 h-4"}),"Previous"]}),be.map(re=>e.jsx(O,{variant:re===E?"default":"outline",size:"sm",className:re===E?"bg-teal-600 hover:bg-teal-700 text-white min-w-[2rem]":"min-w-[2rem]",onClick:()=>U(re),children:re+1},re)),e.jsxs(O,{variant:"outline",size:"sm",disabled:!te,onClick:()=>U(E+1),children:["Next",e.jsx(Wa,{className:"w-4 h-4"})]})]})]})]})]})]})})}function Ds(t){const s=Number(t??0);return Number.isFinite(s)?new Intl.NumberFormat("en-IN",{maximumFractionDigits:0}).format(s):"0"}const qh={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 ep({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(rt,{className:"bg-gray-50 font-semibold",children:[e.jsx(Ne,{children:s}),e.jsx(Ne,{className:"text-right",children:Ds(a.totalAmount)}),e.jsx(Ne,{className:"text-right",children:Ds(a.dealerCount)}),e.jsx(Ne,{className:"text-right text-green-700",children:Ds(a.submittedAmount)}),e.jsx(Ne,{className:"text-right",children:Ds(a.submittedDealerCount)}),e.jsx(Ne,{className:"text-right text-red-700",children:Ds(a.pendingAmount)})]})}function W3(){const[t,s]=u.useState(qh),[a,r]=u.useState(!0);return u.useEffect(()=>{let n=!0;return(async()=>{try{r(!0);const i=await hN();if(!n)return;s(i)}catch(i){if(!n)return;console.error("[Form16Dashboard] fetch error:",i),Y.error(i instanceof Error?i.message:"Failed to load Form16A dashboard"),s(qh)}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(We,{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(q,{className:"bg-green-500 text-white",children:e.jsxs(se,{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(q,{className:"bg-red-500 text-white",children:e.jsxs(se,{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(q,{className:"bg-green-50 border-green-200",children:e.jsxs(se,{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(q,{className:"bg-red-500 text-white",children:e.jsxs(se,{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(q,{children:[e.jsx(me,{children:e.jsx(ue,{children:"Overall Summary"})}),e.jsxs(se,{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:Ds(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:Ds(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:Ds(t.overall.pendingAmount)})]})]})]}),e.jsxs(q,{children:[e.jsx(me,{children:e.jsx(ue,{children:"Year-wise Breakdown"})}),e.jsx(se,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{className:"bg-gray-50",children:[e.jsx(De,{children:"Year"}),e.jsx(De,{className:"text-right",children:"Total Amount"}),e.jsx(De,{className:"text-right",children:"Dealer Count"}),e.jsx(De,{className:"text-right",children:"Submitted Amount"}),e.jsx(De,{className:"text-right",children:"Submitted Dealer Count"}),e.jsx(De,{className:"text-right",children:"Pending Amount"})]})}),e.jsx(Ps,{children:t.yearWise.length===0?e.jsx(rt,{children:e.jsx(Ne,{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(rt,{children:[e.jsx(Ne,{className:"font-medium",children:n.label}),e.jsx(Ne,{className:"text-right",children:Ds(n.totalAmount)}),e.jsx(Ne,{className:"text-right",children:Ds(n.dealerCount)}),e.jsx(Ne,{className:"text-right text-green-700",children:Ds(n.submittedAmount)}),e.jsx(Ne,{className:"text-right",children:Ds(n.submittedDealerCount)}),e.jsx(Ne,{className:"text-right text-red-700",children:Ds(n.pendingAmount)})]},n.label)),e.jsx(ep,{rows:t.yearWise})]})})]})})})]}),e.jsxs(q,{children:[e.jsx(me,{children:e.jsx(ue,{children:"Zone-wise Breakdown"})}),e.jsx(se,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{className:"bg-gray-50",children:[e.jsx(De,{children:"Zone"}),e.jsx(De,{className:"text-right",children:"Total Amount"}),e.jsx(De,{className:"text-right",children:"Dealer Count"}),e.jsx(De,{className:"text-right",children:"Submitted Amount"}),e.jsx(De,{className:"text-right",children:"Submitted Dealer Count"}),e.jsx(De,{className:"text-right",children:"Pending Amount"})]})}),e.jsx(Ps,{children:t.zoneWise.length===0?e.jsx(rt,{children:e.jsx(Ne,{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(rt,{children:[e.jsx(Ne,{className:"font-medium",children:n.label}),e.jsx(Ne,{className:"text-right",children:Ds(n.totalAmount)}),e.jsx(Ne,{className:"text-right",children:Ds(n.dealerCount)}),e.jsx(Ne,{className:"text-right text-green-700",children:Ds(n.submittedAmount)}),e.jsx(Ne,{className:"text-right",children:Ds(n.submittedDealerCount)}),e.jsx(Ne,{className:"text-right text-red-700",children:Ds(n.pendingAmount)})]},n.label)),e.jsx(ep,{rows:t.zoneWise})]})})]})})})]})]})})}const H3="".trim().replace(/\/$/,"");let nl="https://reflow-uat.royalenfield.com/api/v1".trim().replace(/\/$/,"");/\/cpc-(cdc|csd)$/i.test(nl)&&(nl=nl.replace(/\/cpc-(cdc|csd)$/i,""));const G3=t=>t?t.replace(/\/v1\/?$/i,""):"",Y3=H3||G3(nl)||"/api",Pa=bi.create({baseURL:Y3,withCredentials:!0});Pa.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 wl(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 Sb(t){return Array.isArray(t)?t.map(wl):[]}function K3(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 Ab={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},tp=ua.createContext&&ua.createContext(Ab),Q3=["attr","size","title"];function X3(t,s){if(t==null)return{};var a,r,n=J3(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 J3(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 Cl(){return Cl=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},Cl.apply(null,arguments)}function sp(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 Sl(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?sp(Object(a),!0).forEach(function(r){Z3(t,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):sp(Object(a)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(a,r))})}return t}function Z3(t,s,a){return(s=q3(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function q3(t){var s=eF(t,"string");return typeof s=="symbol"?s:s+""}function eF(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 Tb(t){return t&&t.map((s,a)=>ua.createElement(s.tag,Sl({key:a},s.attr),Tb(s.child)))}function Hs(t){return s=>ua.createElement(tF,Cl({attr:Sl({},t.attr)},s),Tb(t.child))}function tF(t){var s=a=>{var{attr:r,size:n,title:i}=t,l=X3(t,Q3),o=n||a.size||"1em",c;return a.className&&(c=a.className),t.className&&(c=(c?c+" ":"")+t.className),ua.createElement("svg",Cl({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},a.attr,r,l,{className:c,style:Sl(Sl({color:t.color||a.color},a.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),i&&ua.createElement("title",null,i),t.children)};return tp!==void 0?ua.createElement(tp.Consumer,null,a=>s(a)):s(Ab)}function Yi(t){return Hs({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 _c(t){return Hs({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 sF(t){return Hs({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 aF(t){return Hs({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 kb(t){return Hs({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 ap(t){return Hs({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 Xo(t){return Hs({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 rp(t){return Hs({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 gi(t){return Hs({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 np(t){return Hs({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 Jo(t){return Hs({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 Al(t){return Hs({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 ai(t){return Hs({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 rF(t){return Hs({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 Kr(t){return Hs({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 fi(t){return Hs({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 nF=()=>{var Dt;const t=fs(),s=zl(),[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(1),j=15,[v,w]=u.useState("all"),[S,D]=u.useState({total:0,pages:0,page:1,limit:j}),[k,C]=u.useState(null),[F,N]=u.useState(!0),[E,_]=u.useState([]),[z,R]=u.useState("GEMINI_VERTEX"),[L,V]=u.useState(""),[I,A]=u.useState("CPC"),G=I==="CSD"?1:2,[$,M]=u.useState(null),T=Q=>Q==="AADHAAR"?[{key:"customer_name",value:"",label:"Customer Name"},{key:"aadhar_number",value:"",label:"Aadhar Number"}]:Q==="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"}]:Q==="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"}]:Q==="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"}],U=Q=>{const de=Array.from(Q.target.files),ee=I==="CSD"?"CSD_PO":"CPC_AUTH",Ae=de.map(Ue=>({id:Math.random().toString(36).substring(7),file:Ue,documentType:ee,expectedFields:T(ee)}));_([...E,...Ae]),Ae.length>0&&!$&&M(Ae[0].id)},H=(Q,de)=>{_(ee=>ee.map(Ae=>{if(Ae.id===Q){const Ue={...Ae,...de};return de.documentType&&de.documentType!==Ae.documentType&&(Ue.expectedFields=T(de.documentType)),Ue}return Ae}))},W=(Q,de,ee,Ae)=>{_(Ue=>Ue.map(et=>{if(et.id!==Q)return et;const ze=[...et.expectedFields];let qe=Ae;if(ee==="value"){const Ze=(ze[de].key||"").toLowerCase();Ze.includes("name")||Ze.includes("surname")?qe=Ae.replace(/\b\w/g,nt=>nt.toUpperCase()):Ze==="gender"?qe=Ae.charAt(0).toUpperCase()+Ae.slice(1).toLowerCase():Ze==="dob"?qe=Ae.replace(/\D/g,""):(Ze==="invoice_value"||Ze==="tax_amount"||Ze==="po_amount"||Ze==="letter_amount"||Ze.length>0&&Ze.endsWith("amount"))&&(qe=Ae.replace(/\D/g,""))}return ze[de][ee]=qe,{...et,expectedFields:ze}}))},P=Q=>{_(de=>de.map(ee=>ee.id===Q?{...ee,expectedFields:[...ee.expectedFields,{key:"",value:""}]}:ee))},B=(Q,de)=>{_(ee=>ee.map(Ae=>Ae.id===Q?{...Ae,expectedFields:Ae.expectedFields.filter((Ue,et)=>et!==de)}:Ae))},K=Q=>{const de=E.filter(ee=>ee.id!==Q);_(de),$===Q&&M(de.length>0?de[0].id:null)},[Z,te]=u.useState(null),[ae,xe]=u.useState(!1),[be,Ge]=u.useState(0),Be={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(()=>{const Q=setTimeout(()=>{f(x.trim())},400);return()=>clearTimeout(Q)},[x]);const _e=u.useCallback(async()=>{N(!0);try{const{data:Q}=await Pa.get("/documents/analytics");C(Q)}catch(Q){console.error(Q),C(null)}finally{N(!1)}},[]);u.useEffect(()=>{_e()},[_e]),u.useEffect(()=>{var Q,de;((Q=s.state)!=null&&Q.openCpcCsdNewRequest||(de=s.state)!=null&&de.openCpcCdcNewRequest)&&(p(!0),t(`${s.pathname}${s.search}`,{replace:!0,state:{}}))},[s.state,s.pathname,s.search,t]);const Re=u.useCallback(async Q=>{var ee,Ae,Ue,et;const de=Math.max(1,parseInt(String(Q),10)||1);i(!0),o(null);try{const ze={page:de,limit:j,sortBy:"createdAt",order:"desc"};g&&(ze.search=g),v==="rejected"&&(ze.status="UNSUCCESSFUL");const{data:qe}=await Pa.get("/documents/recent",{params:ze});Array.isArray(qe)&&console.warn("[CPC Dashboard] /documents/recent returned a bare array; expected { items, meta }. Backend pagination metadata may be missing.");const Ze=Array.isArray(qe)?qe:qe.items||[];r(Sb(Ze));const nt=qe==null?void 0:qe.meta;if(nt&&typeof nt.total=="number"){const rs=nt.limit||j,Ot=Math.max(1,nt.pages||Math.ceil(nt.total/rs)||1),xt=Math.min(Math.max(1,nt.page||de),Ot);D({total:nt.total,pages:Ot,page:xt,limit:rs}),xt!==de&&y(xt)}else D({total:Ze.length,pages:1,page:de,limit:j})}catch(ze){console.error(ze);const qe=((Ae=(ee=ze.response)==null?void 0:ee.data)==null?void 0:Ae.message)||((et=(Ue=ze.response)==null?void 0:Ue.data)==null?void 0:et.error)||ze.message||"Could not load CPC documents.";o(qe),r([]),D({total:0,pages:0,page:1,limit:j})}finally{i(!1)}},[g,v]);u.useEffect(()=>{Re(b)},[b,Re]);const ce=async Q=>{var de;if(Q.preventDefault(),E.length===0)return alert("Please select at least one file");if(E.length<G)return alert(I==="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 ee=new FormData,Ae=[];E.forEach(qe=>{ee.append("files",qe.file);const Ze=qe.expectedFields.reduce((rs,Ot)=>{const xt=(Ot.key||"").trim();return xt&&(rs[xt]=Ot.value==null?"":Ot.value),rs},{}),nt=[...new Set(qe.expectedFields.map(rs=>(rs.key||"").trim()).filter(Boolean))];Ae.push({document_type:qe.documentType,msd_payload:Ze,expected_field_keys:nt})});const Ue=L.replace(/^(CPC|CSD)-?/i,""),et=`${I}-${Ue}`;ee.append("booking_id",et),ee.append("booking_type",I),ee.append("provider",z),ee.append("metadata_queue",JSON.stringify(Ae));const{data:ze}=await Pa.post("/v1/ocr/upload",ee);te(ze),Ge(0),p(!1),xe(!0),y(1),Re(1),_e(),_([]),M(null),V("")}catch(ee){const Ae=(de=ee.response)==null?void 0:de.data,Ue=(Ae==null?void 0:Ae.message)||(Ae==null?void 0:Ae.error_message)||(Ae==null?void 0:Ae.error)||ee.message;alert(`Process Failed: ${Ue}`)}finally{d(!1)}},je=K3(a),re=Q=>String(Q.validationStatus||"").toUpperCase(),pe=(Q,de)=>de.reduce((ee,Ae)=>ee+Number(Q&&Q[Ae]||0),0),ie=(k==null?void 0:k.distribution)||{},fe=k?{total:Number(k.totalDocs)||0,open:pe(ie,["PENDING","PROCESSING","NEED_MANUAL","REVIEW"]),completed:pe(ie,["MATCH","SUCCESSFUL","APPROVED"]),failed:pe(ie,["MISMATCH","UNSUCCESSFUL","REJECTED"])}:null,Ie={total:je.length,open:je.filter(Q=>Q.docs.some(de=>["PENDING","NEED_MANUAL","REVIEW","PROCESSING"].includes(re(de)))).length,completed:je.filter(Q=>Q.docs.length>0&&Q.docs.every(de=>["MATCH","SUCCESSFUL","APPROVED"].includes(re(de)))).length,failed:je.filter(Q=>Q.docs.some(de=>["MISMATCH","UNSUCCESSFUL","REJECTED"].includes(re(de)))).length},$e=fe||Ie,ye=(Q,de=0)=>{const ee=Q?Q.toUpperCase():"UNKNOWN",Ae=Number(de||0);return["MISMATCH","FAILED","UNSUCCESSFUL","REJECTED"].includes(ee)?e.jsxs("span",{className:"status-pill danger",children:[e.jsx(fi,{className:"status-icon"})," Mismatch"]}):["NEED_MANUAL","REVIEW"].includes(ee)?e.jsxs("span",{className:"status-pill warning",children:[e.jsx(gi,{className:"status-icon"})," Needs Review"]}):["PENDING","PROCESSING"].includes(ee)?e.jsxs("span",{className:"status-pill info",children:[e.jsx(Jo,{className:"status-icon ani-spin"})," Processing"]}):["MATCH","COMPLETED","SUCCESS","SUCCESSFUL","APPROVED"].includes(ee)?e.jsxs("span",{className:"status-pill success",children:[e.jsx(Kr,{className:"status-icon"})," Match"]}):Ae>=95?e.jsxs("span",{className:"status-pill success",children:[e.jsx(Kr,{className:"status-icon"})," Match"]}):e.jsx("span",{className:"status-pill neutral",children:Q})},oe=(Q,de)=>{const ee=String(de||"").toUpperCase();return["MISMATCH","UNSUCCESSFUL","REJECTED","NEED_MANUAL","REVIEW","PENDING","PROCESSING"].includes(ee)?!1:["MATCH","SUCCESSFUL","APPROVED"].includes(ee)?!0:Number(Q||0)>=95},ke=S.total??0,st=Math.max(1,S.pages||1),at=b>1,ct=b<st;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:()=>{Re(b),_e()},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.jsx("div",{style:{display:"flex",alignItems:"center",gap:"1rem"},children:e.jsxs("button",{className:"btn-new-request",onClick:()=>p(!0),children:[e.jsx(ap,{})," 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 documents"}),e.jsx("div",{className:"stat-value",children:F&&!k?"—":$e.total})]}),e.jsx("div",{style:{color:"#3b82f6",background:"#eff6ff",padding:"0.75rem",borderRadius:"12px"},children:e.jsx(Xo,{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:F&&!k?"—":$e.open})]}),e.jsx("div",{style:{color:"#f59e0b",background:"#fffbeb",padding:"0.75rem",borderRadius:"12px"},children:e.jsx(Jo,{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:"Matched / approved"}),e.jsx("div",{className:"stat-value",children:F&&!k?"—":$e.completed})]}),e.jsx("div",{style:{color:"#10b981",background:"#ecfdf5",padding:"0.75rem",borderRadius:"12px"},children:e.jsx(Kr,{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:"Rejected / mismatch"}),e.jsx("div",{className:"stat-value",children:F&&!k?"—":$e.failed})]}),e.jsx("div",{style:{color:"#ef4444",background:"#fef2f2",padding:"0.75rem",borderRadius:"12px"},children:e.jsx(fi,{style:{fontSize:"1.5rem"}})})]})})]}),e.jsxs("div",{className:"table-container",children:[e.jsxs("div",{className:"table-header-actions",style:{flexWrap:"wrap",gap:"0.75rem",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"0.75rem"},children:[e.jsx("div",{className:"table-title",style:{margin:0},children:v==="rejected"?"Rejected / mismatch":"All submissions"}),e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem"},children:[e.jsx("button",{type:"button",onClick:()=>{w("all"),y(1)},style:{padding:"0.45rem 0.9rem",borderRadius:"8px",border:v==="all"?"1px solid #059669":"1px solid #e2e8f0",background:v==="all"?"#ecfdf5":"white",color:v==="all"?"#047857":"#64748b",fontWeight:600,fontSize:"0.85rem",cursor:"pointer"},children:"All submissions"}),e.jsx("button",{type:"button",onClick:()=>{w("rejected"),y(1)},style:{padding:"0.45rem 0.9rem",borderRadius:"8px",border:v==="rejected"?"1px solid #dc2626":"1px solid #e2e8f0",background:v==="rejected"?"#fef2f2":"white",color:v==="rejected"?"#b91c1c":"#64748b",fontWeight:600,fontSize:"0.85rem",cursor:"pointer"},children:"Rejected / mismatch"})]})]}),e.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",maxWidth:"min(100vw - 2rem, 280px)"},children:[e.jsx(kb,{style:{position:"absolute",left:"10px",color:"#94a3b8",fontSize:"1rem",pointerEvents:"none"}}),e.jsx("input",{type:"search",enterKeyHint:"search",placeholder:"Booking or claim ID…",value:x,onChange:Q=>{h(Q.target.value),y(1)},"aria-label":"Search by booking ID or claim ID across all stored documents",style:{padding:"8px 12px 8px 34px",border:"1px solid #e2e8f0",borderRadius:"8px",outline:"none",width:"100%",fontSize:"0.875rem",backgroundColor:"white",lineHeight:"normal"}})]})]}),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…"})}):je.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:"6",style:{textAlign:"center",padding:"2rem"},children:"No matching documents found."})}):je.map(Q=>{var de,ee;return e.jsxs("tr",{children:[e.jsx("td",{style:{fontWeight:600},children:(ee=(de=Q.docs)==null?void 0:de[0])!=null&&ee.id?e.jsx(li,{to:`/cpc-csd/documents/${Q.docs[0].id}`,state:{from:"/cpc-csd/dashboard",title:"CPC-CSD Dashboard"},title:Q.docs.length>1?`Open review (first of ${Q.docs.length} documents — use Actions for others)`:"Open review",style:{color:"#2563eb",textDecoration:"none",cursor:"pointer"},className:"dashboard-booking-id-link",children:Q.displayId}):e.jsx("span",{style:{color:"#2563eb"},children:Q.displayId})}),e.jsxs("td",{style:{fontSize:"0.85rem",lineHeight:1.35},children:[Q.typesLabel,Q.docs.length>1&&e.jsxs("span",{style:{display:"block",color:"#64748b",fontSize:"0.75rem",marginTop:"2px"},children:[Q.docs.length," documents"]})]}),e.jsx("td",{children:new Date(Q.sortTime).toLocaleDateString()}),e.jsx("td",{children:ye(Q.aggregateStatus,Q.aggregateMatchPct)}),e.jsx("td",{style:{fontWeight:700,color:oe(Q.aggregateMatchPct,Q.aggregateStatus)?"#059669":"#dc2626"},children:Q.matchPctLabel}),e.jsx("td",{children:e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem",alignItems:"center"},children:Q.docs.map(Ae=>e.jsxs(li,{to:`/cpc-csd/documents/${Ae.id}`,state:{from:"/cpc-csd/dashboard",title:"CPC-CSD Dashboard"},title:Ae.bookingId||Ae.documentType,style:{color:"#059669",textDecoration:"none",fontWeight:600,display:"inline-flex",alignItems:"center",gap:"0.2rem",fontSize:Q.docs.length>1?"0.8rem":"0.9rem"},children:[e.jsx(gi,{})," ",Q.docs.length>1?(Ae.documentType||"Doc").replace(/_/g," "):"View"]},Ae.id))})})]},Q.key)})})]})}),!n&&e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:"0.75rem",padding:"0.85rem 1rem",borderTop:"1px solid #e5e7eb",background:"#f8fafc",fontSize:"0.85rem",color:"#475569"},children:[e.jsxs("span",{children:["Page ",b," of ",st,e.jsxs("span",{style:{color:"#94a3b8",marginLeft:"0.5rem"},children:[" · ",j," records per page · ",ke," document",ke===1?"":"s"," total",g?` · Search: “${g}”`:""]})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.35rem"},children:[e.jsx("button",{type:"button",disabled:!at,onClick:()=>y(Q=>Math.max(1,Q-1)),"aria-label":"Previous page",title:"Previous page",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:"2.25rem",height:"2.25rem",borderRadius:"8px",border:"1px solid #cbd5e1",background:at?"white":"#f1f5f9",color:at?"#334155":"#94a3b8",cursor:at?"pointer":"not-allowed"},children:e.jsx(ai,{size:22})}),e.jsx("button",{type:"button",disabled:!ct,onClick:()=>y(Q=>Q+1),"aria-label":"Next page",title:"Next page",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:"2.25rem",height:"2.25rem",borderRadius:"8px",border:"1px solid #cbd5e1",background:ct?"white":"#f1f5f9",color:ct?"#334155":"#94a3b8",cursor:ct?"pointer":"not-allowed"},children:e.jsx(Al,{size:22})})]})]})]}),ae&&Z&&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:()=>xe(!1),style:{position:"static"},children:e.jsx(Yi,{})})]}),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:Z.booking_id||((Dt=Z.document_id)==null?void 0:Dt.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"}),Z.results?e.jsxs("span",{className:"status-pill success",children:[Z.count," Files Processed"]}):ye(Z.validation_status,Z.overall_match_percentage||Z.match_percentage)]})]}),Z.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:Z.results.map((Q,de)=>e.jsxs("div",{onClick:()=>Ge(de),style:{padding:"0.6rem 0.75rem",background:be===de?"#eff6ff":"white",border:be===de?"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:be===de?"#1d4ed8":"#111827"},children:Q.filename||`Document ${de+1}`}),e.jsxs("div",{style:{fontSize:"0.75rem",color:"#6b7280"},children:["ID: ",Q.booking_id]})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[ye(Q.validation_status,Q.overall_match_percentage||Q.match_percentage),e.jsxs("span",{style:{fontWeight:700,fontSize:"0.875rem"},children:[Q.overall_match_percentage,"%"]})]})]},de))})]}),!Z.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:oe(Z.overall_match_percentage||Z.match_percentage,Z.validation_status||Z.status)?"#059669":"#dc2626"},children:[Z.overall_match_percentage||Z.match_percentage||0,"%"]})]}),(()=>{const Q=Z.results?Z.results[be]:Z,de=Q==null?void 0:Q.mismatch_summary;return de?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:de.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:de.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:de.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:de.mismatched})]})]}):null})(),(()=>{const Q=Z.results?Z.results[be]:Z;return Q!=null&&Q.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:Z.results?"Extraction Details":"Validation Details"}),Z.results&&e.jsx("span",{style:{fontSize:"0.8rem",fontWeight:500,color:"#2563eb",background:"#eff6ff",border:"1px solid #bfdbfe",borderRadius:"4px",padding:"2px 8px"},children:Q.filename||`Document ${be+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:(Q.field_results||[]).map((de,ee)=>e.jsxs("tr",{style:{borderBottom:"1px solid #f3f4f6"},children:[e.jsx("td",{style:{padding:"0.5rem",fontWeight:500},children:de.field||de.key}),e.jsx("td",{style:{padding:"0.5rem"},children:de.expected}),e.jsx("td",{style:{padding:"0.5rem",color:de.status==="MISSING"?"#9ca3af":"inherit"},children:de.extracted||de.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:oe(de.match_percentage,de.status)?"#d1fae5":"#fee2e2",color:oe(de.match_percentage,de.status)?"#065f46":"#991b1b"},children:[de.match_percentage,"%"]})})]},ee))})]})})]}):null})(),(()=>{const Q=Z.results?Z.results[be]:Z,de=Q==null?void 0:Q.mismatch_reasons;return!de||de.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:de.map((ee,Ae)=>e.jsx("li",{style:{whiteSpace:"pre-wrap"},children:typeof ee=="string"?ee:`${ee.field}: ${ee.reason||"Mismatch"}`},Ae))})]})})(),e.jsx("div",{style:{marginTop:"1.5rem",display:"flex",gap:"1rem"},children:e.jsx("button",{onClick:()=>xe(!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:E.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(Yi,{})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("form",{onSubmit:ce,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:L,onChange:Q=>V(Q.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:I,onChange:Q=>A(Q.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:U,accept:".pdf,.jpg,.jpeg,.png"}),e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx(sF,{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: ",E.length]})," — ",I==="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."]})]}),E.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"}),E.map(Q=>e.jsxs("div",{onClick:()=>M(Q.id),className:`queue-item ${$===Q.id?"active":""}`,children:[e.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"flex",alignItems:"center",gap:"0.5rem"},children:[e.jsx(Xo,{style:{flexShrink:0}})," ",Q.file.name]}),e.jsx("button",{type:"button",onClick:de=>{de.stopPropagation(),K(Q.id)},style:{color:"#94a3b8",border:"none",background:"none",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center"},children:e.jsx(Yi,{})})]},Q.id))]}),e.jsxs("div",{style:{padding:"1.5rem",overflowY:"auto",backgroundColor:"#ffffff"},children:[$&&E.find(Q=>Q.id===$)&&e.jsx("div",{children:(()=>{const Q=E.find(de=>de.id===$);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:Q.documentType,onChange:de=>H(Q.id,{documentType:de.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:[Q.expectedFields.length," rules defined"]})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginTop:"0.5rem"},children:[Q.expectedFields.map((de,ee)=>e.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[e.jsx("div",{style:{flex:1},children:de.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:de.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:de.key,onChange:Ae=>W(Q.id,ee,"key",Ae.target.value),list:`suggestions-${Q.id}-${ee}`}),e.jsx("datalist",{id:`suggestions-${Q.id}-${ee}`,children:(Be[Q.documentType]||[]).map(Ae=>e.jsx("option",{value:Ae},Ae))})]})}),e.jsx("div",{style:{flex:1.5},children:e.jsx("input",{type:"text",inputMode:de.key&&(de.key==="invoice_value"||de.key==="tax_amount"||de.key==="po_amount"||de.key==="letter_amount"||String(de.key).toLowerCase().endsWith("amount"))?"numeric":void 0,placeholder:"Expected Value",className:"premium-input",style:{padding:"0.5rem 0.75rem",fontSize:"0.85rem"},value:de.value,onChange:Ae=>W(Q.id,ee,"value",Ae.target.value)})}),e.jsx("button",{type:"button",onClick:()=>B(Q.id,ee),style:{color:"#ef4444",border:"none",background:"none",cursor:"pointer",padding:"0.5rem"},children:e.jsx(Yi,{})})]},ee)),e.jsxs("button",{type:"button",onClick:()=>P(Q.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(ap,{})," Add New Rule"]})]})]})]})})()}),!$&&e.jsxs("div",{style:{textAlign:"center",color:"#94a3b8",marginTop:"4rem"},children:[e.jsx(Xo,{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||E.length===0||E.length<G?"not-allowed":"pointer",opacity:c||E.length===0||E.length<G?.7:1,boxShadow:"0 4px 6px -1px rgba(16, 185, 129, 0.2)",transition:"all 0.2s"},disabled:c||E.length===0||E.length<G,children:c?e.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"0.5rem"},children:[e.jsx(Jo,{className:"ani-spin"})," Processing Documents..."]}):`Submit ${E.length} file(s) (${G} required for ${I})`})})]})})]})})]})};function Db(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 Pa.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 Zo(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 ip(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 iF=()=>{const[t,s]=u.useState("GLOBAL"),[a,r]=u.useState([]),n=50,[i,l]=u.useState({total:0,page:1,limit:n,pages:1}),[o,c]=u.useState(""),[d,m]=u.useState(""),[p,x]=u.useState("ALL"),[h,g]=u.useState("ALL"),[f,b]=u.useState(null),[y,j]=u.useState(!1),[v,w]=u.useState(null),[S,D]=u.useState(null),[k,C]=u.useState("ALL"),F=t==="DOCUMENT_DETAIL"&&(S!=null&&S.id)?S.id:void 0,{previewUrl:N,previewLoading:E,previewError:_}=Db(F);u.useEffect(()=>{if(t==="GLOBAL"){const $=setTimeout(()=>z(1),300);return()=>clearTimeout($)}},[t,d,p,h]);const z=async($=1)=>{j(!0);try{const M={page:$,limit:n,sortBy:"createdAt",order:"desc"};d&&(M.search=d),p!=="ALL"&&(M.type=p),h!=="ALL"&&(M.status=h);const{data:T}=await Pa.get("/documents/recent",{params:M}),H=(Array.isArray(T)?T:T.items||[]).map(W=>R(wl(W)));if(r(H),T.meta){const W=T.meta,P=W.limit||n,B=Math.max(1,W.pages||Math.ceil((W.total||0)/P)||1);l({...W,pages:B,limit:P})}}catch(M){console.error("Failed to fetch global history:",M)}finally{j(!1)}},R=$=>{const M=$.summary||{f1:{},f2:{},f3:{},f4:{},f5:{}};return{...$,groups:{cust:M.f1,ref:M.f2,ident:M.f3,fin:M.f4,comp:M.f5},fields:{f1:M.f1,f2:M.f2,f3:M.f3,f4:M.f4,f5:M.f5},field_results:$.fieldResults||$.field_results||M.field_results||[]}},L=async()=>{try{const{data:$}=await Pa.get("/v1/ocr/report/all/download",{params:{search:d,status:h,type:p},responseType:"blob"}),M=window.URL.createObjectURL(new Blob([$])),T=document.createElement("a");T.href=M,T.setAttribute("download","Master_Audit_Report.xlsx"),document.body.appendChild(T),T.click(),T.remove()}catch($){console.error("Download failed:",$)}},V=async $=>{const M=o||(f==null?void 0:f.claimId);try{const{data:T}=await Pa.get(`/v1/ocr/report/${M}/download`,{params:{attempt:$},responseType:"blob"}),U=window.URL.createObjectURL(new Blob([T])),H=document.createElement("a");H.href=U,H.setAttribute("download",`Report_${M}_Attempt_${$}.xlsx`),document.body.appendChild(H),H.click(),H.remove()}catch(T){console.error("Download failed:",T)}},I=({rows:$,showAttemptCol:M=!1})=>{const T={padding:"12px 10px",border:"1px solid #334155",fontSize:"11px",textTransform:"uppercase",backgroundColor:"#1e293b",color:"white",whiteSpace:"nowrap",textAlign:"left"},U={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:[M&&e.jsx("th",{rowSpan:"2",style:T,children:"Attempt"}),e.jsx("th",{rowSpan:"2",style:T,children:"Booking Type"}),e.jsx("th",{rowSpan:"2",style:T,children:"Booking Number"}),e.jsx("th",{rowSpan:"2",style:T,children:"Document Count"}),e.jsx("th",{rowSpan:"2",style:T,children:"Document Name"}),e.jsx("th",{colSpan:"5",style:T,children:"Customer Name"}),e.jsx("th",{colSpan:"5",style:T,children:"PO Number /Authorisation Letter Number"}),e.jsx("th",{colSpan:"5",style:T,children:"Aadhar Number"}),e.jsx("th",{colSpan:"5",style:T,children:"PO Amount / Authorisation Letter Amount"}),e.jsx("th",{colSpan:"5",style:T,children:"Signature & Stamp Availability"}),e.jsx("th",{rowSpan:"2",style:T,children:"Final Validation"})]}),e.jsx("tr",{children:[0,1,2,3,4].map(H=>e.jsxs(ua.Fragment,{children:[e.jsx("th",{style:{...T,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"MSD"}),e.jsx("th",{style:{...T,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"OCR"}),e.jsx("th",{style:{...T,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:H===4?"Accuracy Matching Availability":"Accuracy Matching %"}),e.jsx("th",{style:{...T,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"Accuracy Criteria"}),e.jsx("th",{style:{...T,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:H===4?"Success Ratio":"Is Match the Accuracy"})]},H))})]}),e.jsx("tbody",{children:$.map((H,W)=>e.jsxs("tr",{children:[M&&e.jsx("td",{style:{...U,fontWeight:500,backgroundColor:"#f8fafc",color:"#475569"},children:H.attempt_no}),e.jsx("td",{style:U,children:H.booking_type}),e.jsx("td",{style:U,children:H.booking_number}),e.jsx("td",{style:U,children:H.document_count}),e.jsx("td",{style:U,children:H.document_name}),H.summary?[H.summary.f1,H.summary.f2,H.summary.f3,H.summary.f4,H.summary.f5].map((P,B)=>e.jsxs(ua.Fragment,{children:[e.jsx("td",{style:{...U,color:P!=null&&P.isNA?"#94a3b8":"inherit",fontWeight:(P!=null&&P.isNA,400)},children:(P==null?void 0:P.msd)||"-"}),e.jsx("td",{style:{...U,color:P!=null&&P.isNA?"#94a3b8":"inherit",fontWeight:(P!=null&&P.isNA,400)},children:(P==null?void 0:P.ocr)||"-"}),e.jsx("td",{style:{...U,color:P!=null&&P.isNA?"#94a3b8":"inherit",fontWeight:P!=null&&P.isNA?400:500},children:(P==null?void 0:P.accuracy_pct)||(P==null?void 0:P.pct)||"0%"}),e.jsx("td",{style:{...U,color:P!=null&&P.isNA?"#94a3b8":"#64748b",fontSize:"10px",fontWeight:400},children:(P==null?void 0:P.criteria)||(P==null?void 0:P.crit)}),e.jsx("td",{style:{...U,verticalAlign:"middle"},children:Zo((P==null?void 0:P.is_match)||(P==null?void 0:P.match)||"-")})]},B)):[H.customer_name_group,H.reference_group,H.identity_group,H.financial_group,H.compliance_group].map((P,B)=>{const K=(P==null?void 0:P.msd)==="N.A."||(P==null?void 0:P.expected)==="N.A.";return e.jsxs(ua.Fragment,{children:[e.jsx("td",{style:{...U,color:K?"#94a3b8":"inherit",fontWeight:400},children:(P==null?void 0:P.msd)||(P==null?void 0:P.expected)||"-"}),e.jsx("td",{style:{...U,color:K?"#94a3b8":"inherit",fontWeight:400},children:(P==null?void 0:P.ocr)||(P==null?void 0:P.extracted)||"-"}),e.jsx("td",{style:{...U,color:K?"#94a3b8":"inherit",fontWeight:K?400:500},children:(P==null?void 0:P.accuracy_pct)||(P==null?void 0:P.pct)||"0%"}),e.jsx("td",{style:{...U,color:K?"#94a3b8":"#64748b",fontSize:"10px",fontWeight:400},children:(P==null?void 0:P.criteria)||(P==null?void 0:P.crit)}),e.jsx("td",{style:{...U,verticalAlign:"middle"},children:Zo((P==null?void 0:P.is_match)||(P==null?void 0:P.match)||"-")})]},B)}),e.jsx("td",{style:{...U,verticalAlign:"middle"},children:ip(H.final_validation==="Successful"||H.final_validation==="SUCCESSFUL")})]},W))})]})})},A=()=>{const $={padding:"12px 10px",border:"1px solid #334155",fontSize:"11px",textTransform:"uppercase",backgroundColor:"#1e293b",color:"white",whiteSpace:"nowrap",textAlign:"left"},M={padding:"12px 10px",border:"1px solid #e2e8f0",fontSize:"13px",textAlign:"left",whiteSpace:"nowrap"},T=[{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:$,children:"Booking Type"}),e.jsx("th",{rowSpan:"2",style:$,children:"Booking Number"}),e.jsx("th",{rowSpan:"2",style:$,children:"Doc Count"}),e.jsx("th",{rowSpan:"2",style:$,children:"Document Name"}),T.map(U=>e.jsx("th",{colSpan:"5",style:$,children:U.label},U.id)),e.jsx("th",{rowSpan:"2",style:$,children:"Final Validation"}),e.jsx("th",{rowSpan:"2",style:$,children:"Actions"})]}),e.jsx("tr",{children:T.map((U,H)=>e.jsxs(ua.Fragment,{children:[e.jsx("th",{style:{...$,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"MSD"}),e.jsx("th",{style:{...$,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"OCR"}),e.jsx("th",{style:{...$,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:H===4?"Accuracy Matching Availability":"Accuracy Matching %"}),e.jsx("th",{style:{...$,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:"Accuracy Criteria"}),e.jsx("th",{style:{...$,backgroundColor:"#334155",fontSize:"10px",color:"#cbd5e1"},children:H===4?"Success Ratio":"Is Match the Accuracy"})]},U.id))})]}),e.jsx("tbody",{children:a.map((U,H)=>{var W,P,B,K,Z,te;return e.jsxs("tr",{style:{backgroundColor:H%2===0?"white":"#f8fafc"},children:[e.jsx("td",{style:M,children:((W=U.summary)==null?void 0:W.booking_type)||U.booking_type||((P=U.claimId)!=null&&P.startsWith("CPC")?"CPC":"CSD")}),e.jsx("td",{style:{...M,fontWeight:500,color:"#2563eb"},children:((B=U.summary)==null?void 0:B.booking_number)||U.bookingId||U.claimId}),e.jsx("td",{style:M,children:((K=U.summary)==null?void 0:K.document_count)||1}),e.jsx("td",{style:M,children:((Z=U.summary)==null?void 0:Z.document_name)||((te=U.documentType)==null?void 0:te.replace(/_/g," "))}),T.map((ae,xe)=>{var Be,_e;const be=((Be=U.summary)==null?void 0:Be[ae.id])||((_e=U.groups)==null?void 0:_e[ae.id]),Ge={...M};return be!=null&&be.isNA&&(Ge.color="#94a3b8"),Ge.fontWeight=400,e.jsxs(ua.Fragment,{children:[e.jsx("td",{style:Ge,children:(be==null?void 0:be.msd)||"-"}),e.jsx("td",{style:Ge,children:(be==null?void 0:be.ocr)||"-"}),e.jsx("td",{style:{...Ge,fontWeight:be!=null&&be.isNA?400:500},children:(be==null?void 0:be.accuracy_pct)||(be==null?void 0:be.pct)||"-"}),e.jsx("td",{style:{...Ge,fontSize:"10px",opacity:be!=null&&be.isNA?.5:.85,fontWeight:400},children:(be==null?void 0:be.criteria)||(be==null?void 0:be.crit)||"-"}),e.jsx("td",{style:{...Ge,verticalAlign:"middle"},children:Zo((be==null?void 0:be.is_match)||(be==null?void 0:be.match)||"-")})]},xe)}),e.jsx("td",{style:{...M,verticalAlign:"middle"},children:ip(U.validationStatus==="SUCCESSFUL"||U.validationStatus==="MATCH"||U.validationStatus==="APPROVED")}),e.jsx("td",{style:M,children:e.jsxs("button",{type:"button",onClick:()=>{s("DOCUMENT_DETAIL"),D(U)},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(gi,{style:{opacity:.85}})," View Details"]})})]},U.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:i.total})]}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[e.jsx("button",{disabled:i.page<=1,onClick:()=>z(i.page-1),style:{padding:"6px 12px",border:"1px solid #e2e8f0",borderRadius:"6px",cursor:"pointer",backgroundColor:"white"},children:e.jsx(ai,{})}),e.jsxs("span",{style:{fontSize:"0.8rem",fontWeight:700,display:"flex",alignItems:"center"},children:["Page ",i.page," of ",i.pages]}),e.jsx("button",{disabled:i.page>=i.pages,onClick:()=>z(i.page+1),style:{padding:"6px 12px",border:"1px solid #e2e8f0",borderRadius:"6px",cursor:"pointer",backgroundColor:"white"},children:e.jsx(Al,{})})]})]})]})},G=({doc:$})=>{var U;const M={padding:"10px",borderBottom:"2px solid #e2e8f0",fontSize:"11px",textTransform:"uppercase",textAlign:"left",color:"#64748b"},T={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:$.documentType.replace(/_/g," ")}),e.jsxs("span",{style:{padding:"4px 12px",borderRadius:"20px",fontSize:"11px",fontWeight:700,backgroundColor:$.validationStatus==="SUCCESSFUL"?"#dcfce7":"#fee2e2",color:$.validationStatus==="SUCCESSFUL"?"#166534":"#991b1b"},children:[$.matchPercentage,"% Batch Score"]})]}),e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:M,children:"Field"}),e.jsx("th",{style:M,children:"MSD"}),e.jsx("th",{style:M,children:"Extracted"}),e.jsx("th",{style:M,children:"Accuracy"}),e.jsx("th",{style:M,children:"Criteria"}),e.jsx("th",{style:M,children:"Status"}),e.jsx("th",{style:M,children:"Message"})]})}),e.jsx("tbody",{children:(((U=$.summary)==null?void 0:U.field_results)||$.field_results||[]).map((H,W)=>e.jsxs("tr",{children:[e.jsx("td",{style:{...T,fontWeight:600,color:"#334155"},children:H.field.replace(/_/g," ")}),e.jsx("td",{style:T,children:H.expected}),e.jsx("td",{style:{...T,color:H.extracted===null||H.extracted==="-"?"#94a3b8":"#1e293b"},children:H.extracted||"Not extracted"}),e.jsx("td",{style:T,children:H.accuracy||H.match_percentage||(H.match_percentage!==void 0?`${H.match_percentage}%`:"0%")}),e.jsx("td",{style:{...T,fontSize:"10px",color:"#64748b"},children:H.criteria}),e.jsx("td",{style:T,children:H.pass||H.status==="SUCCESSFUL"||H.status==="MATCH"?e.jsx(Kr,{style:{color:"#16a34a"}}):e.jsx(_c,{style:{color:"#dc2626"}})}),e.jsx("td",{style:{...T,fontSize:"11px",fontStyle:"italic",color:H.pass||H.status==="SUCCESSFUL"?"#16a34a":"#ef4444"},children:H.message})]},W))})]})]})};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: ${o}`})]}),e.jsx("div",{style:{display:"flex",gap:"1rem"},children:t==="GLOBAL"?e.jsxs("button",{onClick:L,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(np,{})," Download Master Excel"]}):e.jsxs("button",{onClick:()=>{s("GLOBAL"),b(null),c(""),m("")},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(ai,{})," 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:p,onChange:$=>x($.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:h,onChange:$=>g($.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"})]})]}),h==="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."]})]})}),y&&e.jsx("div",{style:{textAlign:"center",padding:"3rem"},children:"Processing record retrieval..."}),!y&&t==="GLOBAL"&&e.jsx(A,{}),!y&&t==="DOCUMENT_DETAIL"&&S&&(()=>{var P;const $=((P=S.summary)==null?void 0:P.field_results)||S.field_results||[],M=$.filter(B=>B.pass).length,T=$.filter(B=>!B.pass&&B.extracted!=="N/A"&&B.extracted!=="-").length,U=$.filter(B=>!B.pass&&(B.extracted==="N/A"||B.extracted==="-"||!B.extracted)).length,H=$.length||1,W=Math.round(M/H*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:B=>B.currentTarget.style.backgroundColor="#f8fafc",onMouseOut:B=>B.currentTarget.style.backgroundColor="white",children:[e.jsx(ai,{})," 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(rp,{})," ",S.document_name||S.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(aF,{})," ID: ",S.booking_number||S.bookingId||o]})]})]}),e.jsx("span",{style:{padding:"8px 20px",borderRadius:"12px",fontSize:"13px",fontWeight:800,backgroundColor:W>=90?"#10b981":"#ef4444",color:"white",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.1)",textTransform:"uppercase",letterSpacing:"0.025em"},children:W>=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:[E&&e.jsx("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#94a3b8",fontSize:"0.9rem"},children:"Loading document preview…"}),!E&&_&&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."}),!E&&N&&e.jsx("iframe",{src:N,style:{width:"100%",height:"100%",border:"none"},title:"Audit Evidence Viewer"}),!E&&!N&&!_&&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: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:M,color:"#166534",bg:"#f0fdf4",border:"#d1fae5"},{label:"Mismatch",val:T,color:"#b91c4c",bg:"#fdf2f5",border:"#fce7ec"},{label:"Missing",val:U,color:"#b45309",bg:"#fffbeb",border:"#fde68a"}].map(B=>e.jsxs("div",{style:{padding:"10px 8px",backgroundColor:B.bg,borderRadius:"10px",border:`1px solid ${B.border}`,textAlign:"center"},children:[e.jsx("div",{style:{fontSize:"0.625rem",fontWeight:500,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"6px"},children:B.label}),e.jsx("div",{style:{fontSize:"1.25rem",fontWeight:600,color:B.color,fontVariantNumeric:"tabular-nums"},children:B.val})]},B.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:$.map((B,K)=>{const Z=B.extracted==="undefined"||B.extracted==="null"||!B.extracted?"-":B.extracted,te=B.pass?"MATCH":Z==="-"||Z==="N/A"?"MISSING":"MISMATCH";let ae="#166534",xe="#ecfdf5",be=e.jsx(Kr,{style:{opacity:.82}});te==="MISMATCH"?(ae="#b91c4c",xe="#fdf2f5",be=e.jsx(_c,{style:{opacity:.8}})):te==="MISSING"&&(ae="#b45309",xe="#fffbeb",be=e.jsx(fi,{style:{opacity:.8}}));const Ge=te==="MATCH"?"#166534":te==="MISSING"?"#92400e":"#9f1239";return e.jsxs("tr",{style:{borderBottom:"1px solid #f8fafc",backgroundColor:K%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:B.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:B.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:B.expected})]}),e.jsx("div",{style:{fontSize:"0.8125rem",fontWeight:500,color:Ge,overflowWrap:"anywhere",lineHeight:1.45},children:Z})]}),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:xe,color:ae,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:[be," ",e.jsx("span",{style:{flexShrink:0},children:te})]})})]},K)})})]})})]}),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(S.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"})]})]})]})]})]})]})]})})(),!y&&t==="CLAIM_DETAIL"&&f&&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(rp,{style:{color:"#3b82f6"}})," Multi-Attempt Audit Summary: ",o]}),e.jsx(I,{rows:f.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:f.attempts.map($=>e.jsxs("button",{onClick:()=>w($),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"1.25rem",backgroundColor:(v==null?void 0:v.attempt_no)===$.attempt_no?"#1e293b":"white",color:(v==null?void 0:v.attempt_no)===$.attempt_no?"white":"#1e293b",border:"1px solid #e2e8f0",borderRadius:"12px",cursor:"pointer",textAlign:"left",boxShadow:(v==null?void 0:v.attempt_no)===$.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 ",$.attempt_no]}),e.jsx("div",{style:{fontSize:"10px",opacity:.6,marginTop:"2px"},children:new Date($.created_at).toLocaleString()})]}),(v==null?void 0:v.attempt_no)===$.attempt_no?e.jsx(Al,{}):e.jsx(rF,{style:{opacity:.2}})]},$.attempt_no))})]}),v&&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 ",v.attempt_no]}),e.jsxs("button",{onClick:()=>V(v.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(np,{})," Export Attempt ",v.attempt_no]})]}),e.jsx(I,{rows:v.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($=>e.jsx("button",{onClick:()=>C($),style:{padding:"6px 14px",fontSize:"10px",fontWeight:800,borderRadius:"8px",border:"1px solid #e2e8f0",backgroundColor:k===$?"#1e293b":"white",color:k===$?"white":"#64748b",cursor:"pointer"},children:$==="ALL"?"All":$.split("_")[0]},$))})]}),v.documents.filter($=>k==="ALL"||$.documentType===k).map(($,M)=>e.jsx(G,{doc:$},M))]})]})]})]})},lF=()=>{var D,k;const{id:t}=Sa(),s=zl(),a=fs(),[r,n]=u.useState(null),[i,l]=u.useState(!0),[o,c]=u.useState([]),{previewUrl:d,previewLoading:m,previewError:p}=Db(t),x=((D=s.state)==null?void 0:D.from)||"/cpc-csd/dashboard",h=((k=s.state)==null?void 0:k.title)||"Dashboard";if(u.useEffect(()=>{let C=!1;return(async()=>{l(!0),n(null),c([]);try{const{data:N}=await Pa.get(`/documents/${t}`);if(C)return;const E=wl(N);n(E);const _=String(E.claimId||"").trim();if(_)try{const{data:z}=await Pa.get("/documents/history",{params:{claimId:_}});if(C)return;const R=Number(E.attemptNo??1)||1,L=(z.attempts||[]).find($=>Number($.attempt_no)===R),I=((L==null?void 0:L.documents)||[]).map($=>wl($)).filter($=>$==null?void 0:$.id),A=new Set,G=I.filter($=>{const M=String($.id);return A.has(M)?!1:(A.add(M),!0)});G.sort(($,M)=>new Date(M.createdAt||0)-new Date($.createdAt||0)),C||c(G.length?G:[E])}catch{C||c([E])}else C||c([E])}catch(N){console.error(N),C||n(null)}finally{C||l(!1)}})(),()=>{C=!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(li,{to:"/cpc-csd/dashboard",style:{color:"#2563eb",marginTop:"1rem",display:"inline-block"},children:"Return to Dashboard"})]});const g=r.field_results||[],f=C=>C.pass===!0||C.status==="SUCCESSFUL"||C.status==="MATCH",b=C=>{const F=C.match_percentage??C.matchPercentage;if(F!=null&&F!==""&&!Number.isNaN(Number(F)))return Math.round(Number(F));if(typeof C.accuracy=="string"){const N=C.accuracy.trim().match(/^(\d+(?:\.\d+)?)\s*%?$/);if(N)return Math.round(Number(N[1]))}return null},y=g.filter(f).length,j=g.filter(C=>!f(C)&&C.extracted!=="N/A"&&C.extracted!=="-").length,v=g.filter(C=>!f(C)&&(C.extracted==="N/A"||C.extracted==="-"||!C.extracted)).length,w=g.length||1,S=Math.round(y/w*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(li,{to:x,className:"inline-block",style:{textDecoration:"none",color:"#6b7280",display:"flex",alignItems:"center",gap:"0.5rem",fontWeight:500},children:["← Back to ",h]}),e.jsx("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center",flexWrap:"wrap"},children: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(C=>{const F=String(C.id)===String(t),N=o.filter(z=>z.documentType===C.documentType).length>1,E=(C.documentType||"Document").replace(/_/g," "),_=N&&C.bookingId?`${E} · ${C.bookingId}`:E;return e.jsxs("button",{type:"button",onClick:()=>{F||a(`/cpc-csd/documents/${C.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:F?"default":"pointer",border:F?"1px solid #166534":"1px solid #e2e8f0",backgroundColor:F?"#ecfdf5":"#fff",color:F?"#166534":"#475569",transition:"background-color 0.15s, border-color 0.15s"},children:[e.jsx(gi,{style:{opacity:F?1:.65}}),_]},C.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 C=o.findIndex(F=>String(F.id)===String(t));return o.length>1&&C>=0?`${C+1} of ${o.length}`:"Secure preview"})()})]}),e.jsxs("div",{style:{flex:1,backgroundColor:"#1e293b",position:"relative"},children:[m&&e.jsx("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#94a3b8",fontSize:"0.9rem"},children:"Loading document preview…"}),!m&&p&&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."}),!m&&d&&e.jsx("iframe",{src:d,style:{width:"100%",height:"100%",border:"none"},title:"Audit Evidence Viewer"}),!m&&!d&&!p&&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:S>=75?"#34d399":"#fb7185",strokeWidth:"6",strokeDasharray:`${2*Math.PI*42}`,strokeDashoffset:`${2*Math.PI*42*(1-S/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:[S,"%"]})})]}),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:y,color:"#166534",bg:"#f0fdf4",border:"#d1fae5"},{label:"Mismatch",val:j,color:"#b91c4c",bg:"#fdf2f5",border:"#fce7ec"},{label:"Missing",val:v,color:"#b45309",bg:"#fffbeb",border:"#fde68a"}].map(C=>e.jsxs("div",{style:{padding:"10px 8px",backgroundColor:C.bg,borderRadius:"10px",border:`1px solid ${C.border}`,textAlign:"center"},children:[e.jsx("div",{style:{fontSize:"0.625rem",fontWeight:500,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"6px"},children:C.label}),e.jsx("div",{style:{fontSize:"1.25rem",fontWeight:600,color:C.color,fontVariantNumeric:"tabular-nums"},children:C.val})]},C.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:g.map((C,F)=>{const N=C.extracted==="undefined"||C.extracted==="null"||!C.extracted?"-":C.extracted,E=f(C),_=String(C.status||"").toUpperCase(),z=_==="MISSING"?"MISSING":E||_==="SUCCESSFUL"||_==="MATCH"?"MATCH":N==="-"||N==="N/A"||N==="N/A."?"MISSING":"MISMATCH",R=b(C);let L="#166534",V="#ecfdf5",I=e.jsx(Kr,{style:{opacity:.82}});z==="MISMATCH"?(L="#b91c4c",V="#fdf2f5",I=e.jsx(_c,{style:{opacity:.8}})):z==="MISSING"?(L="#b45309",V="#fffbeb",I=e.jsx(fi,{style:{opacity:.8}})):I=e.jsx(Kr,{style:{opacity:.82}});const A=z==="MATCH"?"#166534":z==="MISSING"?"#92400e":"#9f1239",G=R==null?"#94a3b8":z==="MATCH"?"#15803d":z==="MISSING"?"#b45309":"#be185d";return e.jsxs("tr",{style:{borderBottom:"1px solid #f8fafc",backgroundColor:F%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:C.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:C.expected})]}),e.jsx("div",{style:{fontSize:"0.8125rem",fontWeight:500,color:A,wordBreak:"break-word",overflowWrap:"anywhere",lineHeight:1.45},children:N})]}),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:G},children:R!=null?`${R}%`:"—"})}),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:V,color:L,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:[I,e.jsx("span",{style:{flexShrink:0},children:z})]})})]},F)})})]})})]})]})]})]})},dr=50,oF=()=>{const[t,s]=u.useState([]),[a,r]=u.useState(!0),[n,i]=u.useState(null),[l,o]=u.useState(1),[c,d]=u.useState({total:0,pages:1,page:1,limit:dr}),[m,p]=u.useState(""),[x,h]=u.useState("");u.useEffect(()=>{const j=setTimeout(()=>h(m.trim()),400);return()=>clearTimeout(j)},[m]),u.useEffect(()=>{o(1)},[x]);const g=u.useCallback(async()=>{var j,v;r(!0),i(null);try{const w={page:l,limit:dr,status:"UNSUCCESSFUL",sortBy:"createdAt",order:"desc"};x&&(w.search=x);const{data:S}=await Pa.get("/documents/recent",{params:w}),D=Array.isArray(S)?S:S.items||[];s(Sb(D)),S!=null&&S.meta&&typeof S.meta.total=="number"?d({total:S.meta.total,pages:Math.max(1,S.meta.pages||Math.ceil(S.meta.total/(S.meta.limit||dr))||1),page:S.meta.page||l,limit:S.meta.limit||dr}):d({total:D.length,pages:1,page:l,limit:dr})}catch(w){console.error(w),i(((v=(j=w.response)==null?void 0:j.data)==null?void 0:v.message)||w.message||"Failed to load rejected documents."),s([]),d({total:0,pages:1,page:1,limit:dr})}finally{r(!1)}},[l,x]);u.useEffect(()=>{g()},[g]);const f=Math.max(1,c.pages||1),b=l>1,y=l<f;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.jsxs("p",{className:"page-subtitle",children:[dr," records per page · same scope as the dashboard “Rejected / mismatch” tab. Search runs against the full dataset (e.g. booking or claim ID)."]})]})}),n&&e.jsx("div",{role:"alert",style:{marginBottom:"1rem",padding:"0.75rem 1rem",borderRadius:"8px",background:"#fef2f2",border:"1px solid #fecaca",color:"#991b1b",fontSize:"0.9rem"},children:n}),e.jsxs("div",{className:"table-container",children:[e.jsx("div",{className:"table-header-actions",style:{flexWrap:"wrap",gap:"0.65rem",alignItems:"center",justifyContent:"flex-end",paddingBottom:"0.5rem"},children:e.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",width:"min(100%, 280px)"},children:[e.jsx(kb,{style:{position:"absolute",left:"10px",color:"#94a3b8",fontSize:"1rem",pointerEvents:"none"}}),e.jsx("input",{type:"search",placeholder:"Booking or claim ID…",value:m,onChange:j=>p(j.target.value),"aria-label":"Search rejected documents in database",style:{padding:"8px 12px 8px 34px",border:"1px solid #e2e8f0",borderRadius:"8px",outline:"none",width:"100%",fontSize:"0.875rem",backgroundColor:"white"}})]})}),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.jsxs("td",{colSpan:"5",style:{textAlign:"center",padding:"2rem"},children:["No rejected documents found",x?` for “${x}”.`:"."]})}):t.map(j=>{var v;return e.jsxs("tr",{children:[e.jsx("td",{style:{fontWeight:600,color:"#dc2626"},children:j.bookingId}),e.jsx("td",{style:{textTransform:"capitalize"},children:(v=j.documentType)==null?void 0:v.replace("_"," ")}),e.jsx("td",{children:new Date(j.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(fi,{})," ",j.validationStatus]})}),e.jsx("td",{children:e.jsxs(li,{to:`/cpc-csd/documents/${j.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(gi,{})," Review"]})})]},j.id)})})]}),!a&&e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:"0.75rem",padding:"0.85rem 1rem",borderTop:"1px solid #e5e7eb",background:"#f8fafc",fontSize:"0.85rem",color:"#475569"},children:[e.jsxs("span",{children:["Page ",l," of ",f,e.jsxs("span",{style:{color:"#94a3b8",marginLeft:"0.5rem"},children:[" · ",dr," records per page · ",c.total," document",c.total===1?"":"s"," total"]})]}),e.jsxs("div",{style:{display:"flex",gap:"0.35rem"},children:[e.jsx("button",{type:"button",disabled:!b,onClick:()=>o(j=>Math.max(1,j-1)),"aria-label":"Previous page",title:"Previous page",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:"2.25rem",height:"2.25rem",borderRadius:"8px",border:"1px solid #cbd5e1",background:b?"white":"#f1f5f9",color:b?"#334155":"#94a3b8",cursor:b?"pointer":"not-allowed"},children:e.jsx(ai,{size:22})}),e.jsx("button",{type:"button",disabled:!y,onClick:()=>o(j=>j+1),"aria-label":"Next page",title:"Next page",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:"2.25rem",height:"2.25rem",borderRadius:"8px",border:"1px solid #cbd5e1",background:y?"white":"#f1f5f9",color:y?"#334155":"#94a3b8",cursor:y?"pointer":"not-allowed"},children:e.jsx(Al,{size:22})})]})]})]})]})};function lp(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 cF=[{value:"2024-25",label:"2024-25"},{value:"2023-24",label:"2023-24"},{value:"2022-23",label:"2022-23"},{value:"",label:"All Years"}];function dF(){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 wN(c||void 0);r(x.dealers),i(x.summary)}catch(x){console.error("Error fetching non-submitted dealers:",x),Y.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 CN({dealerCode:x.dealerCode,dealerId:x.id,email:x.email,financialYear:c||void 0}),Y.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),Y.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:cF.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(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Non-Submitted / Total Dealers"}),e.jsx(ue,{className:"text-3xl text-red-600",children:l?"...":`${n.nonSubmittedCount}/${n.totalDealers}`})]})}),e.jsx(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Never Submitted"}),e.jsx(ue,{className:"text-3xl text-amber-600",children:l?"...":n.neverSubmittedCount})]})}),e.jsx(q,{children:e.jsxs(me,{className:"pb-3",children:[e.jsx(Se,{children:"Overdue (90+ days)"}),e.jsx(ue,{className:"text-3xl text-orange-600",children:l?"...":n.overdue90Count})]})})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Dealer List"}),e.jsx(Se,{children:"Dealers with missing Form 16A submissions"})]}),e.jsx(se,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{children:[e.jsx(De,{children:"Dealer Details"}),e.jsx(De,{children:"Contact Information"}),e.jsx(De,{children:"Location"}),e.jsx(De,{children:"Missing Quarters"}),e.jsx(De,{children:"Last Submission"}),e.jsx(De,{children:"Last Notified"}),e.jsx(De,{className:"text-right",children:"Action"})]})}),e.jsx(Ps,{children:l?e.jsx(rt,{children:e.jsxs(Ne,{colSpan:7,className:"text-center py-12",children:[e.jsx(We,{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(rt,{children:e.jsxs(Ne,{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(rt,{className:"hover:bg-gray-50 transition-colors",children:[e.jsx(Ne,{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(Ne,{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(wa,{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(ji,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:x.phone||"—"})]})]})}),e.jsx(Ne,{className:"text-sm",children:x.location||"—"}),e.jsx(Ne,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:x.missingQuarters.map((g,f)=>e.jsx(le,{variant:"destructive",className:"text-xs",children:g},f))})}),e.jsx(Ne,{children:x.lastSubmissionDate?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:lp(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(le,{variant:"outline",className:"text-xs bg-red-50 text-red-700 border-red-200",children:"Never Submitted"})}),e.jsx(Ne,{children:x.lastNotifiedDate?e.jsx(Jn,{children:e.jsxs(Zi,{children:[e.jsx(qi,{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(jt,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:lp(x.lastNotifiedDate)})]}),x.notificationCount>1&&e.jsxs(le,{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(Ht,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{children:x.lastNotifiedBy})]})]})}),e.jsx(el,{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(le,{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(le,{variant:"outline",className:"text-xs bg-gray-50 text-gray-600 border-gray-200",children:"Never Notified"})}),e.jsx(Ne,{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($s,{className:"w-4 h-4 mr-1"}),t===x.id?"Sending...":"Notify"]})})]},x.id)})})]})})})]})]})})}function mF(){const t=fs(),[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 D=!1;return(async()=>{l(!0);try{const[k,C]=await Promise.all([Ng(),SN({status:"pending,failed,completed"})]);D||(a(Array.isArray(k)?k:[]),n(Array.isArray(C)?C:[]))}catch{D||(Y.error("Failed to load pending submissions"),a([]),n([]))}finally{D||l(!1)}})(),()=>{D=!0}},[]);const p=s.filter(D=>!(d.financialYear!=="all"&&D.financial_year!==d.financialYear||d.quarter!=="all"&&D.quarter!==d.quarter)),x=p.length,h=p.filter(D=>(D.days_overdue??0)>0).length,g=p.filter(D=>(D.days_remaining??0)>0).length,f=()=>m({financialYear:"all",quarter:"all"}),b=d.financialYear!=="all"||d.quarter!=="all",y=D=>{if(!D)return"—";try{return new Date(D).toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}catch{return D}},j=D=>D==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(D),v=D=>{const k=(D||"").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"},w=D=>{t("/form16/submit")},S=[...new Set(s.map(D=>D.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(le,{variant:"default",className:"ml-1 bg-teal-600 hover:bg-teal-700",children:[d.financialYear,d.quarter].filter(D=>D!=="all").length}),o?e.jsx(Dl,{className:"w-4 h-4"}):e.jsx(Qr,{className:"w-4 h-4"})]})]})]}),o&&e.jsxs(q,{children:[e.jsx(me,{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(Nt,{className:"w-4 h-4"}),"Clear All"]})]})}),e.jsx(se,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Financial Year"}),e.jsxs(Ke,{value:d.financialYear,onValueChange:D=>m(k=>({...k,financialYear:D})),children:[e.jsx(Xe,{children:e.jsx(Qe,{placeholder:"All years"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Years"}),S.map(D=>e.jsx(J,{value:D,children:D},D))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Quarter"}),e.jsxs(Ke,{value:d.quarter,onValueChange:D=>m(k=>({...k,quarter:D})),children:[e.jsx(Xe,{children:e.jsx(Qe,{placeholder:"All quarters"})}),e.jsxs(Je,{children:[e.jsx(J,{value:"all",children:"All Quarters"}),e.jsx(J,{value:"Q1",children:"Q1"}),e.jsx(J,{value:"Q2",children:"Q2"}),e.jsx(J,{value:"Q3",children:"Q3"}),e.jsx(J,{value:"Q4",children:"Q4"})]})]})]})]})})]}),h>0&&e.jsx(q,{className:"border-red-200 bg-red-50",children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(as,{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(q,{children:e.jsx(se,{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(Pe,{className:"w-6 h-6 text-gray-600"})})]})})}),e.jsx(q,{children:e.jsx(se,{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(as,{className:"w-6 h-6 text-red-600"})})]})})}),e.jsx(q,{children:e.jsx(se,{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(jt,{className:"w-6 h-6 text-amber-600"})})]})})})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Pending Form 16A Submissions"}),e.jsx(Se,{children:"Complete list of quarters awaiting submission."})]}),e.jsx(se,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{className:"bg-gray-50",children:[e.jsx(De,{children:"Dealer Name"}),e.jsx(De,{children:"Financial Year"}),e.jsx(De,{children:"Quarter"}),e.jsx(De,{children:"Version"}),e.jsx(De,{children:"Status"}),e.jsx(De,{children:"26AS start date"}),e.jsx(De,{children:"Days Status"}),e.jsx(De,{className:"text-right",children:"Action"})]})}),e.jsx(Ps,{children:i?e.jsx(rt,{children:e.jsxs(Ne,{colSpan:8,className:"text-center py-12 text-gray-500",children:[e.jsx(We,{className:"w-8 h-8 animate-spin mx-auto mb-2"}),e.jsx("p",{children:"Loading..."})]})}):p.length===0?e.jsx(rt,{children:e.jsx(Ne,{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(Pe,{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(D=>e.jsxs(rt,{className:"hover:bg-gray-50",children:[e.jsx(Ne,{className:"text-sm text-gray-900",children:D.dealer_name??"Your submission"}),e.jsx(Ne,{children:e.jsxs("span",{className:"text-sm text-gray-900",children:["FY ",D.financial_year]})}),e.jsx(Ne,{children:e.jsx(le,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:D.quarter})}),e.jsx(Ne,{children:e.jsx(le,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200",children:D.has_submission?"V1":"—"})}),e.jsx(Ne,{children:e.jsx(le,{variant:"outline",className:D.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":D.has_submission?"bg-slate-50 text-slate-600 border-slate-200":"bg-gray-100 text-gray-600 border-gray-200",children:D.latest_submission_status==="failed"?"Failed":D.has_submission?"Under review":"Not Submitted"})}),e.jsx(Ne,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-700",children:y(D.twenty_six_as_start_date??D.audit_start_date)})]})}),e.jsx(Ne,{children:D.days_since_26as_uploaded!=null&&D.days_since_26as_uploaded>=0?e.jsxs("span",{className:"text-sm font-medium text-gray-700",children:["due from ",D.days_since_26as_uploaded," days"]}):e.jsx("span",{className:"text-sm text-gray-500",children:"—"})}),e.jsx(Ne,{className:"text-right",children:e.jsx(O,{size:"sm",className:"bg-teal-600 hover:bg-teal-700",onClick:()=>w(),children:"Submit Now"})})]},`${D.financial_year}|${D.quarter}`))})]})})})]}),e.jsxs(q,{children:[e.jsxs(me,{children:[e.jsx(ue,{children:"Your Form 16 Submissions"}),e.jsx(Se,{children:"Requests you have submitted. Total amount and credit note (when issued) are shown. Status is never shown as Pending."})]}),e.jsx(se,{children:e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs(Is,{children:[e.jsx(Fs,{children:e.jsxs(rt,{className:"bg-gray-50",children:[e.jsx(De,{children:"Request ID"}),e.jsx(De,{children:"Financial Year"}),e.jsx(De,{children:"Quarter"}),e.jsx(De,{className:"text-right",children:"Total Amount"}),e.jsx(De,{children:"Credit Note No."}),e.jsx(De,{children:"Status"}),e.jsx(De,{children:"Submitted"}),e.jsx(De,{className:"text-right",children:"Action"})]})}),e.jsx(Ps,{children:i?e.jsx(rt,{children:e.jsx(Ne,{colSpan:8,className:"text-center py-8 text-gray-500",children:e.jsx(We,{className:"w-6 h-6 animate-spin mx-auto"})})}):r.length===0?e.jsx(rt,{children:e.jsx(Ne,{colSpan:8,className:"text-center py-8 text-gray-500",children:'No Form 16 submissions yet. Use "New Submission" to submit.'})}):r.map(D=>e.jsxs(rt,{className:"hover:bg-gray-50",children:[e.jsx(Ne,{className:"font-mono text-sm",children:D.requestId?String(D.requestId).slice(0,8)+"…":"—"}),e.jsxs(Ne,{children:["FY ",D.financial_year]}),e.jsx(Ne,{children:e.jsx(le,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:D.quarter})}),e.jsx(Ne,{className:"text-right font-medium",children:j(D.total_amount)}),e.jsx(Ne,{children:D.credit_note_number??"—"}),e.jsx(Ne,{children:e.jsx(le,{variant:"outline",className:v(D.display_status),children:D.display_status??(D.status==="completed"?"Completed":D.status==="failed"?"Failed":"Under review")})}),e.jsx(Ne,{className:"text-sm text-gray-600",children:y(D.submitted_date)}),e.jsx(Ne,{className:"text-right",children:e.jsx(O,{variant:"outline",size:"sm",onClick:()=>t(`/request/${D.requestId}`),children:"View Request"})})]},D.id))})]})})})]}),s.length>0&&e.jsxs(q,{className:"border-amber-200 bg-amber-50/50",children:[e.jsxs(me,{children:[e.jsx(ue,{className:"text-amber-900",children:"Quarters Pending Submission"}),e.jsx(Se,{className:"text-amber-700",children:"These quarters don't have completed Form 16A submissions. Please submit Form 16A for these quarters."})]}),e.jsx(se,{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(D=>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:D.quarter}),e.jsx("p",{className:"text-sm text-gray-600",children:D.financial_year}),D.has_submission&&D.latest_submission_status&&e.jsx(le,{variant:"outline",className:`mt-1 text-xs ${D.latest_submission_status==="failed"?"bg-red-50 text-red-700 border-red-200":"bg-slate-50 text-slate-600 border-slate-200"}`,children:D.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"})]})},`${D.financial_year}|${D.quarter}`))})})]})]})}function uF({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:He,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(gt,{open:t,onOpenChange:p,children:e.jsxs(ht,{className:"max-w-2xl bg-white",children:[e.jsxs(ft,{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(pt,{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(le,{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(le,{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(ne,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(Ws,{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(as,{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(as,{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(He,{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(Rt,{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 xF=(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{}},hF=u.createContext(void 0),pF={setTheme:t=>{},themes:[]},gF=()=>{var t;return(t=u.useContext(hF))!=null?t:pF};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:`(${xF.toString()})(${m})`}})});const fF=({...t})=>{const{theme:s="system"}=gF();return e.jsx(Fy,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function bF({open:t,onClose:s,onSelect:a,managers:r=[],errorType:n,message:i,isLoading:l=!1}){const o=c=>{a(c)};return e.jsx(gt,{open:t,onOpenChange:s,children:e.jsxs(ht,{className:"sm:max-w-[600px]",children:[e.jsxs(ft,{children:[e.jsx(pt,{className:"flex items-center gap-2",children:n==="NO_MANAGER_FOUND"?e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"w-5 h-5 text-amber-500"}),"Manager Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(gs,{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(tt,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-amber-900",children:"Unable to Proceed"}),e.jsx("p",{className:"text-sm text-amber-700 mt-1",children:"We couldn't find your reporting manager in the system. The claim request cannot be created without a valid manager assigned."})]})]})}):e.jsx("div",{className:"space-y-3 max-h-[400px] overflow-y-auto",children:r.map(c=>e.jsx("div",{className:"border rounded-lg p-4 hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>!l&&o(c.email),children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-1",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Ht,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsx("p",{className:"font-medium text-gray-900",children:c.displayName||`${c.firstName||""} ${c.lastName||""}`.trim()||"Unknown"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(wa,{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(zc,{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 jF(){const{id:t}=Sa();return e.jsx(mr,{to:`/cpc-csd/documents/${encodeURIComponent(t??"")}`,replace:!0})}function op({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 ad();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 Ki({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 wg();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 yF({onViewRequest:t}){const{user:s}=xs();return Vl(s)?e.jsx(pR,{onViewRequest:t}):e.jsx(bR,{onViewRequest:t})}function cp({onNavigate:t,onNewRequest:s}){const[a,r]=u.useState(!1),[n,i]=u.useState(!0);return u.useEffect(()=>{try{const l=lt.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(E6,{onNavigate:t,onNewRequest:s}):e.jsx(Z1,{onNavigate:t,onNewRequest:s})}function vF({onLogout:t}){const s=fs(),a=zl(),[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 C=JSON.parse(k);l(C)}catch(C){console.error("Error parsing dynamic requests:",C)}},[]),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,C,F,N)=>{c(k),m(C||"Unknown Request"),Nl({requestId:k,status:F,request:N,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 N,E,_,z,R,L,V,I,A,G,$;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:((N=k.approvers)==null?void 0:N.length)||1,currentApprover:((_=(E=k.approvers)==null?void 0:E[0])==null?void 0:_.name)||((L=(R=(z=k.approvers)==null?void 0:z[0])==null?void 0:R.email)==null?void 0:L.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((V=k.approvers)==null?void 0:V.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(M=>M).map((M,T)=>{var W;const U=(M==null?void 0:M.name)||((W=M==null?void 0:M.email)==null?void 0:W.split("@")[0])||`Approver ${T+1}`,H=(M==null?void 0:M.email)||"";return{step:T+1,approver:`${U}${H?` (${H})`:""}`,role:(M==null?void 0:M.role)||`Level ${(M==null?void 0:M.level)||T+1} Approver`,status:T===0?"pending":"waiting",tatHours:M!=null&&M.tat?typeof M.tat=="string"?parseInt(M.tat):M.tat:48,elapsedHours:0,assignedAt:T===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(k.spectators||[]).filter(M=>M&&(M.name||M.email)).map(M=>{var U;const T=(M==null?void 0:M.name)||((U=M==null?void 0:M.email)==null?void 0:U.split("@")[0])||"Observer";return{name:T,role:(M==null?void 0:M.role)||(M==null?void 0:M.department)||"Observer",avatar:T.split(" ").map(H=>H[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 ${((A=(I=k.approvers)==null?void 0:I[0])==null?void 0:A.name)||(($=(G=k.approvers)==null?void 0:G[0])==null?void 0:$.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")},w=(k,C)=>new Promise(F=>{setTimeout(()=>{k==="approve"?Y.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):Y.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),n(null),F(!0)},1e3)}),S=()=>{n(null)},D=async(k,C)=>{var F,N,E,_,z,R,L;try{const V={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||[]},I=await n6(V);if(!I||!I.request)throw new Error("Invalid response from server: Request object not found");const A=I.request;if(!A.requestNumber&&!A.requestId)throw new Error("Invalid response from server: Request identifier not found");x(!1),g(null),Y.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),A.requestNumber?s(`/request/${A.requestNumber}`):A.requestId?s(`/request/${A.requestId}`):s("/my-requests")}catch(V){console.error("[App] Error creating claim request:",V);const I=(F=V==null?void 0:V.response)==null?void 0:F.data,A=(I==null?void 0:I.code)||((N=I==null?void 0:I.error)==null?void 0:N.code);if(A==="NO_MANAGER_FOUND"){g({errorType:"NO_MANAGER_FOUND",message:(I==null?void 0:I.message)||((E=I==null?void 0:I.error)==null?void 0:E.message)||"No reporting manager found. Please ensure your manager is correctly configured in the system.",pendingClaimData:k}),x(!0);return}if(A==="MULTIPLE_MANAGERS_FOUND"){const $=(I==null?void 0:I.managers)||((_=I==null?void 0:I.error)==null?void 0:_.managers)||[];g({errorType:"MULTIPLE_MANAGERS_FOUND",managers:$,message:(I==null?void 0:I.message)||((z=I==null?void 0:I.error)==null?void 0:z.message)||"Multiple managers found. Please select one.",pendingClaimData:k}),x(!0);return}const G=((L=(R=V==null?void 0:V.response)==null?void 0:R.data)==null?void 0:L.message)||(V==null?void 0:V.message)||"Failed to create claim request";Y.error("Failed to Submit Claim Request",{description:G})}};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(My,{children:[e.jsx(dt,{path:"/login/callback",element:e.jsx(lg,{})}),e.jsx(dt,{path:"/",element:e.jsx(Lt,{currentPage:"dashboard",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(cp,{onNavigate:f,onNewRequest:j})})}),e.jsx(dt,{path:"/dashboard",element:e.jsx(Lt,{currentPage:"dashboard",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(cp,{onNavigate:f,onNewRequest:j})})}),e.jsxs(dt,{element:e.jsx(Lt,{currentPage:"admin",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(Ly,{})}),children:[e.jsx(dt,{path:"/admin",element:e.jsx(u3,{})}),e.jsx(dt,{path:"/admin/create-template",element:e.jsx(Qh,{})}),e.jsx(dt,{path:"/admin/edit-template/:templateId",element:e.jsx(Qh,{})}),e.jsx(dt,{path:"/admin/templates",element:e.jsx(AI,{})})]}),e.jsx(dt,{path:"/create-admin-request/:templateId",element:e.jsx(DI,{})}),e.jsx(dt,{path:"/open-requests",element:e.jsx(Lt,{currentPage:"open-requests",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(W6,{onViewRequest:b})})}),e.jsx(dt,{path:"/closed-requests",element:e.jsx(Lt,{currentPage:"closed-requests",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(hD,{onViewRequest:b})})}),e.jsx(dt,{path:"/shared-summaries",element:e.jsx(Lt,{currentPage:"shared-summaries",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(vD,{})})}),e.jsx(dt,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(Lt,{currentPage:"shared-summaries",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(ND,{})})}),e.jsx(dt,{path:"/form16/credit-notes",element:e.jsx(Lt,{currentPage:"form16-credit-notes",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(g3,{})})}),e.jsx(dt,{path:"/form16/credit-notes/:id",element:e.jsx(Lt,{currentPage:"form16-credit-notes",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(j3,{})})}),e.jsx(dt,{path:"/form16/debit-notes",element:e.jsx(Lt,{currentPage:"form16-debit-notes",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(w3,{})})}),e.jsx(dt,{path:"/form16/transactions",element:e.jsx(Lt,{currentPage:"form16-transactions",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(D3,{})})}),e.jsx(dt,{path:"/form16/submit",element:e.jsx(Lt,{currentPage:"form16-submit",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(P3,{})})}),e.jsx(dt,{path:"/form16/submit/result",element:e.jsx(Lt,{currentPage:"form16-submit",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(O3,{})})}),e.jsx(dt,{path:"/form16/dashboard",element:e.jsx(Lt,{currentPage:"form16-dashboard",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(op,{children:e.jsx(W3,{})})})}),e.jsx(dt,{path:"/form16/26as",element:e.jsx(Lt,{currentPage:"form16-26as",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(op,{children:e.jsx(V3,{})})})}),e.jsx(dt,{path:"/form16/pending-submissions",element:e.jsx(Lt,{currentPage:"form16-pending-submissions",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(mF,{})})}),e.jsx(dt,{path:"/form16/non-submitted-dealers",element:e.jsx(Lt,{currentPage:"form16-non-submitted-dealers",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(dF,{})})}),e.jsx(dt,{path:"/cpc-csd/dashboard",element:e.jsx(Lt,{currentPage:"cpc-csd-dashboard",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(Ki,{children:e.jsx(nF,{})})})}),e.jsx(dt,{path:"/cpc-csd/history",element:e.jsx(Lt,{currentPage:"cpc-csd-history",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(Ki,{children:e.jsx(iF,{})})})}),e.jsx(dt,{path:"/cpc-csd/analytics",element:e.jsx(mr,{to:"/cpc-csd/dashboard",replace:!0})}),e.jsx(dt,{path:"/cpc-csd/submissions",element:e.jsx(mr,{to:"/cpc-csd/history",replace:!0})}),e.jsx(dt,{path:"/cpc-csd/rejected",element:e.jsx(Lt,{currentPage:"cpc-csd-rejected",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(Ki,{children:e.jsx(oF,{})})})}),e.jsx(dt,{path:"/cpc-csd/documents/:id",element:e.jsx(Lt,{currentPage:"cpc-csd-detail",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(Ki,{children:e.jsx(lF,{})})})}),e.jsx(dt,{path:"/cpc-cdc/dashboard",element:e.jsx(mr,{to:"/cpc-csd/dashboard",replace:!0})}),e.jsx(dt,{path:"/cpc-cdc/history",element:e.jsx(mr,{to:"/cpc-csd/history",replace:!0})}),e.jsx(dt,{path:"/cpc-cdc/analytics",element:e.jsx(mr,{to:"/cpc-csd/dashboard",replace:!0})}),e.jsx(dt,{path:"/cpc-cdc/submissions",element:e.jsx(mr,{to:"/cpc-csd/history",replace:!0})}),e.jsx(dt,{path:"/cpc-cdc/rejected",element:e.jsx(mr,{to:"/cpc-csd/rejected",replace:!0})}),e.jsx(dt,{path:"/cpc-cdc/documents/:id",element:e.jsx(jF,{})}),e.jsx(dt,{path:"/my-requests",element:e.jsx(Lt,{currentPage:"my-requests",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(BD,{onViewRequest:b,dynamicRequests:i})})}),e.jsx(dt,{path:"/requests",element:e.jsx(Lt,{currentPage:"requests",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(yF,{onViewRequest:b})})}),e.jsx(dt,{path:"/approver-performance",element:e.jsx(Lt,{currentPage:"approver-performance",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(FR,{})})}),e.jsx(dt,{path:"/request/:requestId",element:e.jsx(Lt,{currentPage:"request-detail",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(yD,{requestId:"",onBack:y,dynamicRequests:i})})}),e.jsx(dt,{path:"/work-notes/:requestId",element:e.jsx(wD,{})}),e.jsx(dt,{path:"/new-request",element:e.jsx(Mh,{onBack:y,onSubmit:v})}),e.jsx(dt,{path:"/edit-request/:requestId",element:e.jsx(Mh,{onBack:y,onSubmit:v,requestId:void 0,isEditMode:!0})}),e.jsx(dt,{path:"/claim-management",element:e.jsx(w6,{onBack:y,onSubmit:D})}),e.jsx(dt,{path:"/profile",element:e.jsx(Lt,{currentPage:"profile",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(PR,{})})}),e.jsx(dt,{path:"/settings",element:e.jsx(Lt,{currentPage:"settings",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(qR,{})})}),e.jsx(dt,{path:"/settings/security",element:e.jsx(Lt,{currentPage:"settings",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(nI,{})})}),e.jsx(dt,{path:"/notifications",element:e.jsx(Lt,{currentPage:"notifications",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(iI,{onNavigate:f})})}),e.jsx(dt,{path:"/detailed-reports",element:e.jsx(Lt,{currentPage:"detailed-reports",onNavigate:f,onNewRequest:j,onLogout:t,children:e.jsx(SI,{})})})]}),e.jsx(fF,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),e.jsx(bF,{open:p,onClose:()=>{x(!1),g(null)},onSelect:async k=>{h!=null&&h.pendingClaimData&&await D(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(uF,{isOpen:!!r,onClose:S,action:r,requestId:o,requestTitle:d,onSubmit:w})]})}function NF(t){const{onLogout:s}=t||{};return e.jsx(_y,{children:e.jsx(vF,{onLogout:s})})}function wF(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=xs(),[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(oN,{}):e.jsx(lg,{}):s&&lt.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(NF,{onLogout:c}),i&&e.jsx(dN,{isOpen:i,onClose:()=>l(!1)})]}):e.jsx(lN,{})}const il=()=>{try{return!0}catch{return!1}},CF=()=>{if(il())return null;try{return localStorage.getItem("token")}catch{return null}},SF={user:null,token:CF(),isAuthenticated:!1,isLoading:!1,error:null},Rb=An({name:"auth",initialState:SF,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,!il())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,!il())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!il())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:OF,loginSuccess:$F,loginFailure:UF,logout:BF,clearError:zF,updateUser:VF}=Rb.actions,AF=Ey({reducer:{auth:Rb.reducer,dashboard:Cg.reducer,requests:xb.reducer,myRequests:cb.reducer,openRequests:Mg.reducer,closedRequests:ib.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});nc.createRoot(document.getElementById("root")).render(e.jsx(ua.StrictMode,{children:e.jsx(av,{store:AF,children:e.jsx(kv,{children:e.jsx(wF,{})})})}));export{we as a};