Re_Backend/build/assets/index-DRwsycIY.js

44 lines
885 KiB
JavaScript
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-LySNBiVn.js","assets/radix-vendor-CbkudDDo.js","assets/charts-vendor-Cji9-Yri.js","assets/utils-vendor-DHm03ykU.js","assets/ui-vendor-i7LKlA3D.js","assets/socket-vendor-TjCxX7sJ.js","assets/router-vendor-1fSSvDCY.js"])))=>i.map(i=>d[i]);
var Cu=Object.defineProperty;var Su=(t,s,a)=>s in t?Cu(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Vr=(t,s,a)=>Su(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as uc,R as hc,I as pc,F as xc,a as Au,T as Tu,P as ku,C as Ru,b as Pu,O as gc,c as fc,d as Du,e as Eu,f as Mu,D as Iu,g as Lu,A as Fu,h as _u,i as Ou,k as $u,V as Uu,l as Vu,m as Bu,n as zu,o as Hu,p as Wu,q as qu,r as Ku,s as Gu,t as Yu,u as Zu,v as Xu,w as Ju,x as Qu,y as eh,z as th,B as sh,E as ah,L as rh,G as nh,H as ih,J as oh,K as lh,M as ch,N as dh,Q as mh,U as uh,W as yc,X as vc,Y as hh,Z as bc,_ as jc,$ as ph,a0 as xh,a1 as gh,a2 as fh,a3 as yh,a4 as vh,a5 as bh,a6 as jh,a7 as Nh,a8 as wh,a9 as Ch,aa as Sh,ab as Ah}from"./radix-vendor-CbkudDDo.js";import{a as Th,r as g,c as Nc,d as ai,B as kh,C as wc,X as Cc,Y as Sc,T as ri,L as Ac,e as Br,P as Rh,f as Ph,g as Dh,h as Eh,i as po,j as ni,k as ii,b as Mh}from"./charts-vendor-Cji9-Yri.js";import{a as Tc,f as kc,b as ye,d as Ih,c as Lh,e as Fh,s as Vt,g as oi,h as xo,i as _h,j as cs,k as _a,l as li,m as Rc,n as Lt,o as Ut,p as zr,q as fs,r as Oh,t as wn,u as $h,v as Cn,w as Uh,x as Vh,y as Bh,z as zh,A as Hr,B as go,C as Hh,D as Pc,E as Dc,F as ci,G as di,H as Wh,I as qh,J as Ec}from"./utils-vendor-DHm03ykU.js";import{S as At,L as Kh,C as Re,a as Sn,b as $e,X as jt,H as Gh,c as Yh,U as xt,F as we,d as xe,P as Ps,e as Zh,f as Xh,g as ns,B as Ft,h as aa,i as Wr,Z as br,A as Bt,j as Mc,k as fa,l as Jh,m as jr,n as qe,R as Ot,I as Nr,T as Qe,o as Pe,p as is,q as Qh,r as mt,s as as,M as Ns,t as wr,u as ep,D as ts,v as Xe,w as Ic,x as Lc,y as et,z as Me,E as Cr,G as An,O as Tn,J as ra,K as Fc,N as _c,Q as fo,V as er,W as tp,Y as sp,_ as Ms,$ as Tt,a0 as pa,a1 as ap,a2 as rp,a3 as np,a4 as mi,a5 as Sr,a6 as ip,a7 as op,a8 as lp,a9 as cp,aa as dp,ab as mp,ac as Ar,ad as kn,ae as up,af as Oc,ag as hp,ah as pp,ai as xp,aj as ui,ak as $c,al as gp,am as fp,an as Wa,ao as hi,ap as pi,aq as yp,ar as Uc,as as yo,at as vp,au as Is,av as bp,aw as Vc,ax as jp,ay as xi,az as na,aA as Np,aB as Bc,aC as vo,aD as wp,aE as Cp,aF as Sp,aG as Ap,aH as zc,aI as Tp,aJ as qr,aK as kp,aL as Rp,aM as Pp,aN as Dp}from"./ui-vendor-i7LKlA3D.js";import{l as Ep}from"./socket-vendor-TjCxX7sJ.js";import{u as Tr,a as kr,b as ya,B as Mp,R as Ip,c as pt}from"./router-vendor-1fSSvDCY.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 o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).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 Rn={},bo=Th;Rn.createRoot=bo.createRoot,Rn.hydrateRoot=bo.hydrateRoot;var Pn=function(t,s){return Pn=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])},Pn(t,s)};function Lp(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");Pn(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var ur=function(){return ur=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},ur.apply(this,arguments)};var Bs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function gi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function fi(t,s){return t(s={exports:{}},s.exports),s.exports}var Os=fi(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,o){var l=n.locked.get(i);l===void 0?o===void 0?n.locked.set(i,[]):n.locked.set(i,[o]):o!==void 0&&(l.unshift(o),n.locked.set(i,l))},this.isLocked=function(i){return n.locked.has(i)},this.lock=function(i){return new Promise(function(o,l){n.isLocked(i)?n.addToLocked(i,o):(n.addToLocked(i),o())})},this.unlock=function(i){var o=n.locked.get(i);if(o!==void 0&&o.length!==0){var l=o.pop();n.locked.set(i,o),l!==void 0&&setTimeout(l,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()}});gi(Os);var Fp=gi(fi(function(t,s){var a=Bs&&Bs.__awaiter||function(d,u,h,x){return new(h||(h=Promise))(function(p,f){function v(w){try{y(x.next(w))}catch(N){f(N)}}function j(w){try{y(x.throw(w))}catch(N){f(N)}}function y(w){w.done?p(w.value):new h(function(N){N(w.value)}).then(v,j)}y((x=x.apply(d,u||[])).next())})},r=Bs&&Bs.__generator||function(d,u){var h,x,p,f,v={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return f={next:j(0),throw:j(1),return:j(2)},typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function j(y){return function(w){return function(N){if(h)throw new TypeError("Generator is already executing.");for(;v;)try{if(h=1,x&&(p=2&N[0]?x.return:N[0]?x.throw||((p=x.return)&&p.call(x),0):x.next)&&!(p=p.call(x,N[1])).done)return p;switch(x=0,p&&(N=[2&N[0],p.value]),N[0]){case 0:case 1:p=N;break;case 4:return v.label++,{value:N[1],done:!1};case 5:v.label++,x=N[1],N=[0];continue;case 7:N=v.ops.pop(),v.trys.pop();continue;default:if(p=v.trys,!((p=p.length>0&&p[p.length-1])||N[0]!==6&&N[0]!==2)){v=0;continue}if(N[0]===3&&(!p||N[1]>p[0]&&N[1]<p[3])){v.label=N[1];break}if(N[0]===6&&v.label<p[1]){v.label=p[1],p=N;break}if(p&&v.label<p[2]){v.label=p[2],v.ops.push(N);break}p[2]&&v.ops.pop(),v.trys.pop();continue}N=u.call(d,v)}catch(S){N=[6,S],x=0}finally{h=p=0}if(5&N[0])throw N[1];return{value:N[0]?N[1]:void 0,done:!0}}([y,w])}}},n=Bs;Object.defineProperty(s,"__esModule",{value:!0});var i="browser-tabs-lock-key",o={key:function(d){return a(n,void 0,void 0,function(){return r(this,function(u){throw new Error("Unsupported")})})},getItem:function(d){return a(n,void 0,void 0,function(){return r(this,function(u){throw new Error("Unsupported")})})},clear:function(){return a(n,void 0,void 0,function(){return r(this,function(d){return[2,window.localStorage.clear()]})})},removeItem:function(d){return a(n,void 0,void 0,function(){return r(this,function(u){throw new Error("Unsupported")})})},setItem:function(d,u){return a(n,void 0,void 0,function(){return r(this,function(h){throw new Error("Unsupported")})})},keySync:function(d){return window.localStorage.key(d)},getItemSync:function(d){return window.localStorage.getItem(d)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(d){return window.localStorage.removeItem(d)},setItemSync:function(d,u){return window.localStorage.setItem(d,u)}};function l(d){return new Promise(function(u){return setTimeout(u,d)})}function c(d){for(var u="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",h="",x=0;x<d;x++)h+=u[Math.floor(Math.random()*u.length)];return h}var m=function(){function d(u){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=u,d.waiters===void 0&&(d.waiters=[])}return d.prototype.acquireLock=function(u,h){return h===void 0&&(h=5e3),a(this,void 0,void 0,function(){var x,p,f,v,j,y,w;return r(this,function(N){switch(N.label){case 0:x=Date.now()+c(4),p=Date.now()+h,f=i+"-"+u,v=this.storageHandler===void 0?o:this.storageHandler,N.label=1;case 1:return Date.now()<p?[4,l(30)]:[3,8];case 2:return N.sent(),v.getItemSync(f)!==null?[3,5]:(j=this.id+"-"+u+"-"+x,[4,l(Math.floor(25*Math.random()))]);case 3:return N.sent(),v.setItemSync(f,JSON.stringify({id:this.id,iat:x,timeoutKey:j,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,l(30)];case 4:return N.sent(),(y=v.getItemSync(f))!==null&&(w=JSON.parse(y)).id===this.id&&w.iat===x?(this.acquiredIatSet.add(x),this.refreshLockWhileAcquired(f,x),[2,!0]):[3,7];case 5:return d.lockCorrector(this.storageHandler===void 0?o:this.storageHandler),[4,this.waitForSomethingToChange(p)];case 6:N.sent(),N.label=7;case 7:return x=Date.now()+c(4),[3,1];case 8:return[2,!1]}})})},d.prototype.refreshLockWhileAcquired=function(u,h){return a(this,void 0,void 0,function(){var x=this;return r(this,function(p){return setTimeout(function(){return a(x,void 0,void 0,function(){var f,v,j;return r(this,function(y){switch(y.label){case 0:return[4,Os.default().lock(h)];case 1:return y.sent(),this.acquiredIatSet.has(h)?(f=this.storageHandler===void 0?o:this.storageHandler,(v=f.getItemSync(u))===null?(Os.default().unlock(h),[2]):((j=JSON.parse(v)).timeRefreshed=Date.now(),f.setItemSync(u,JSON.stringify(j)),Os.default().unlock(h),this.refreshLockWhileAcquired(u,h),[2])):(Os.default().unlock(h),[2])}})})},1e3),[2]})})},d.prototype.waitForSomethingToChange=function(u){return a(this,void 0,void 0,function(){return r(this,function(h){switch(h.label){case 0:return[4,new Promise(function(x){var p=!1,f=Date.now(),v=!1;function j(){if(v||(window.removeEventListener("storage",j),d.removeFromWaiting(j),clearTimeout(y),v=!0),!p){p=!0;var w=50-(Date.now()-f);w>0?setTimeout(x,w):x(null)}}window.addEventListener("storage",j),d.addToWaiting(j);var y=setTimeout(j,Math.max(0,u-Date.now()))})];case 1:return h.sent(),[2]}})})},d.addToWaiting=function(u){this.removeFromWaiting(u),d.waiters!==void 0&&d.waiters.push(u)},d.removeFromWaiting=function(u){d.waiters!==void 0&&(d.waiters=d.waiters.filter(function(h){return h!==u}))},d.notifyWaiters=function(){d.waiters!==void 0&&d.waiters.slice().forEach(function(u){return u()})},d.prototype.releaseLock=function(u){return a(this,void 0,void 0,function(){return r(this,function(h){switch(h.label){case 0:return[4,this.releaseLock__private__(u)];case 1:return[2,h.sent()]}})})},d.prototype.releaseLock__private__=function(u){return a(this,void 0,void 0,function(){var h,x,p,f;return r(this,function(v){switch(v.label){case 0:return h=this.storageHandler===void 0?o:this.storageHandler,x=i+"-"+u,(p=h.getItemSync(x))===null?[2]:(f=JSON.parse(p)).id!==this.id?[3,2]:[4,Os.default().lock(f.iat)];case 1:v.sent(),this.acquiredIatSet.delete(f.iat),h.removeItemSync(x),Os.default().unlock(f.iat),d.notifyWaiters(),v.label=2;case 2:return[2]}})})},d.lockCorrector=function(u){for(var h=Date.now()-5e3,x=u,p=[],f=0;;){var v=x.keySync(f);if(v===null)break;p.push(v),f++}for(var j=!1,y=0;y<p.length;y++){var w=p[y];if(w.includes(i)){var N=x.getItemSync(w);if(N!==null){var S=JSON.parse(N);(S.timeRefreshed===void 0&&S.timeAcquired<h||S.timeRefreshed!==void 0&&S.timeRefreshed<h)&&(x.removeItemSync(w),j=!0)}}}j&&d.notifyWaiters()},d.waiters=void 0,d}();s.default=m}));new TextEncoder;new TextDecoder;var Hs=fi(function(t,s){var a=Bs&&Bs.__assign||function(){return a=Object.assign||function(c){for(var m,d=1,u=arguments.length;d<u;d++)for(var h in m=arguments[d])Object.prototype.hasOwnProperty.call(m,h)&&(c[h]=m[h]);return c},a.apply(this,arguments)};function r(c,m){if(!m)return"";var d="; "+c;return m===!0?d:d+"="+m}function n(c,m,d){return encodeURIComponent(c).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(m).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(u){if(typeof u.expires=="number"){var h=new Date;h.setMilliseconds(h.getMilliseconds()+864e5*u.expires),u.expires=h}return r("Expires",u.expires?u.expires.toUTCString():"")+r("Domain",u.domain)+r("Path",u.path)+r("Secure",u.secure)+r("SameSite",u.sameSite)}(d)}function i(c){for(var m={},d=c?c.split("; "):[],u=/(%[\dA-F]{2})+/gi,h=0;h<d.length;h++){var x=d[h].split("="),p=x.slice(1).join("=");p.charAt(0)==='"'&&(p=p.slice(1,-1));try{m[x[0].replace(u,decodeURIComponent)]=p.replace(u,decodeURIComponent)}catch{}}return m}function o(){return i(document.cookie)}function l(c,m,d){document.cookie=n(c,m,a({path:"/"},d))}s.__esModule=!0,s.encode=n,s.parse=i,s.getAll=o,s.get=function(c){return o()[c]},s.set=l,s.remove=function(c,m){l(c,"",a(a({},m),{expires:-1}))}});gi(Hs),Hs.encode,Hs.parse,Hs.getAll;Hs.get;Hs.set;Hs.remove;var jo;(function(t){t.Code="code",t.ConnectCode="connect_code"})(jo||(jo={}));var No;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(No||(No={}));new Fp;var _p={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Mt=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},Op=ur(ur({},_p),{buildAuthorizeUrl:Mt,buildLogoutUrl:Mt,getAccessTokenSilently:Mt,getAccessTokenWithPopup:Mt,getIdTokenClaims:Mt,loginWithRedirect:Mt,loginWithPopup:Mt,connectAccountWithRedirect:Mt,logout:Mt,handleRedirectCallback:Mt,getDpopNonce:Mt,setDpopNonce:Mt,generateDpopProof:Mt,createFetcher:Mt}),$p=g.createContext(Op);(function(t){Lp(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 Up=function(t){return t===void 0&&(t=$p),g.useContext(t)};const Ts="accessToken",ks="refreshToken",$s="idToken",Pa="userData",Cs={set(t,s,a=7){const r=new Date;r.setTime(r.getTime()+a*24*60*60*1e3);const n=`${t}=${encodeURIComponent(s)}; expires=${r.toUTCString()}; path=/; SameSite=Lax`;document.cookie=n},get(t){const s=t+"=",a=document.cookie.split(";");for(let r=0;r<a.length;r++){let n=a[r];if(n){for(;n.charAt(0)===" ";)n=n.substring(1,n.length);if(n.indexOf(s)===0)return decodeURIComponent(n.substring(s.length,n.length))}}return null},remove(t){document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`},clearAll(){[Ts,ks,$s,Pa].forEach(s=>{this.remove(s),document.cookie=`${s}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;const a=window.location.hostname;a!=="localhost"&&a!=="127.0.0.1"&&(document.cookie=`${s}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${a};`,document.cookie=`${s}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=.${a};`)})}};class Fe{static setAccessToken(s){this.isLocalhost()?(localStorage.setItem(Ts,s),Cs.set(Ts,s,1)):localStorage.setItem(Ts,s)}static getAccessToken(){return this.isLocalhost()&&Cs.get(Ts)||localStorage.getItem(Ts)}static setRefreshToken(s){this.isLocalhost()?(localStorage.setItem(ks,s),Cs.set(ks,s,7)):localStorage.setItem(ks,s)}static getRefreshToken(){return this.isLocalhost()&&Cs.get(ks)||localStorage.getItem(ks)}static setIdToken(s){localStorage.setItem($s,s),this.isLocalhost()&&Cs.set($s,s,1)}static getIdToken(){return this.isLocalhost()&&Cs.get($s)||localStorage.getItem($s)}static setUserData(s){localStorage.setItem(Pa,JSON.stringify(s)),this.isLocalhost()&&Cs.set(Pa,JSON.stringify(s),7)}static getUserData(){const s=localStorage.getItem(Pa);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(o){console.warn("Could not set logout flags:",o)}[Ts,ks,$s,Pa,"oktaToken","authToken","user","authState","access_token","refresh_token","id_token","idToken","token","accessToken","refreshToken","userData","auth","authentication","persist:root","persist:auth","redux-persist"].forEach(o=>{try{localStorage.removeItem(o),sessionStorage.removeItem(o)}catch(l){console.warn(`Error removing ${o}:`,l)}});try{const o=[];for(let l=0;l<localStorage.length;l++){const c=localStorage.key(l);c&&o.push(c)}o.forEach(l=>{try{localStorage.removeItem(l)}catch(c){console.warn(`Error removing localStorage key ${l}:`,c)}}),localStorage.clear()}catch(o){console.error("Error clearing localStorage:",o)}try{const o=[];for(let l=0;l<sessionStorage.length;l++){const c=sessionStorage.key(l);c&&o.push(c)}o.forEach(l=>{try{sessionStorage.removeItem(l)}catch(c){console.warn(`Error removing sessionStorage key ${l}:`,c)}}),sessionStorage.clear()}catch(o){console.error("Error clearing sessionStorage:",o)}Cs.clearAll();const a=["accessToken","refreshToken","userData","oktaToken","authToken","id_token","token","access_token","refresh_token"],r=window.location.hostname,n=["/","/login","/login/callback","/api","/api/v1"],i=["",r,`.${r}`];a.forEach(o=>{n.forEach(l=>{i.forEach(c=>{try{let m=`${o}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${l}; SameSite=Lax;`;c&&c!=="localhost"&&c!=="127.0.0.1"&&!c.startsWith(".")&&(m+=` domain=${c};`),document.cookie=m}catch{}try{let m=`${o}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${l}; SameSite=None; Secure;`;c&&c!=="localhost"&&c!=="127.0.0.1"&&(m+=` domain=${c};`),document.cookie=m}catch{}try{let m=`${o}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${l}; SameSite=Strict;`;c&&c!=="localhost"&&c!=="127.0.0.1"&&!c.startsWith(".")&&(m+=` domain=${c};`),document.cookie=m}catch{}})})}),(localStorage.length>0||sessionStorage.length>0)&&console.warn("WARNING: Storage not fully cleared!")}static hasAccessToken(){return!!this.getAccessToken()}static hasRefreshToken(){return!!this.getRefreshToken()}static isLocalhost(){return window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"||window.location.hostname===""}}function tr(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(),o=s*60*1e3;return n-i<o}catch{return!0}}const Hc="https://re-workflow-nt-api-dev.siplsolutions.com/api/v1",oe=Tc.create({baseURL:Hc,headers:{"Content-Type":"application/json"},withCredentials:!0});oe.interceptors.request.use(t=>{const s=Fe.getAccessToken();return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t));oe.interceptors.response.use(t=>t,async t=>{var a;const s=t.config;if(((a=t.response)==null?void 0:a.status)===401&&!s._retry){s._retry=!0;try{const r=Fe.getRefreshToken();if(!r)throw new Error("No refresh token available");const n=await Tc.post(`${Hc}/auth/refresh`,{refreshToken:r},{withCredentials:!0}),{accessToken:i}=n.data.data||n.data;if(i)return Fe.setAccessToken(i),s.headers.Authorization=`Bearer ${i}`,oe(s)}catch(r){return Fe.clearAll(),window.location.href="/",Promise.reject(r)}}return Promise.reject(t)});async function Vp(t,s){var a,r;try{const n=await oe.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,o=i.data||i;return o.accessToken&&o.refreshToken?(Fe.setAccessToken(o.accessToken),Fe.setRefreshToken(o.refreshToken),Fe.setUserData(o.user),o.idToken&&Fe.setIdToken(o.idToken)):console.warn("⚠️ Tokens missing in response",{result:o}),o}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 Bp(){var n;const t=Fe.getRefreshToken();if(!t)throw new Error("No refresh token available");const a=(await oe.post("/auth/refresh",{refreshToken:t})).data,r=((n=a.data)==null?void 0:n.accessToken)||a.accessToken;if(r)return Fe.setAccessToken(r),r;throw new Error("Failed to refresh token")}async function wo(){const s=(await oe.get("/auth/me")).data;return s.data||s}async function zp(){var t,s;try{await oe.post("/auth/logout",{},{withCredentials:!0})}catch(a){console.error("📡 Logout API error:",a),console.error("📡 Error details:",{message:a.message,status:(t=a.response)==null?void 0:t.status,data:(s=a.response)==null?void 0:s.data})}}const Wc=g.createContext(void 0);function Hp({children:t}){const[s,a]=g.useState(!1),[r,n]=g.useState(!0),[i,o]=g.useState(null),[l,c]=g.useState(null),[m,d]=g.useState(!1);g.useEffect(()=>{const y=sessionStorage.getItem("__logout_in_progress__"),w=sessionStorage.getItem("__force_logout__");if(y==="true"||w==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),Fe.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(M){console.error("Error clearing storage:",M)}a(!1),o(null),n(!1),c(null);return}const N=new URLSearchParams(window.location.search);if(N.has("logout")||N.has("okta_logged_out")){Fe.clearAll(),localStorage.clear(),sessionStorage.clear(),a(!1),o(null),n(!1);const M=new URLSearchParams;N.has("okta_logged_out")&&M.set("okta_logged_out","true");const b=M.toString()?`/?${M.toString()}`:"/";window.history.replaceState({},document.title,b);return}const S=Fe.getAccessToken(),T=Fe.getRefreshToken(),F=Fe.getUserData();if(!(S||T||F)){a(!1),o(null),n(!1);return}m?n(!1):h()},[m]),g.useEffect(()=>{if(!s)return;const w=setInterval(async()=>{const N=Fe.getAccessToken();if(N&&tr(N,5))try{await v()}catch(S){console.error("Silent refresh failed:",S)}},5*60*1e3);return()=>clearInterval(w)},[s]);const u=g.useRef(!1);g.useEffect(()=>{if(u.current||window.location.pathname!=="/login/callback")return;(async()=>{u.current=!0;const w=new URLSearchParams(window.location.search),N=w.get("code"),S=w.get("error");if(window.history.replaceState({},document.title,"/login/callback"),S){c(new Error(`Authentication error: ${S}`)),n(!1);return}if(!N){n(!1);return}try{n(!0),a(!1),c(null);const T=`${window.location.origin}/login/callback`,F=await Vp(N,T);o(F.user),a(!0),c(null),window.history.replaceState({},document.title,"/")}catch(T){console.error("❌ Token exchange error in AuthContext:",T),c(T),a(!1),o(null),u.current=!1}finally{n(!1)}})()},[]);const h=async()=>{if(m){n(!1);return}try{n(!0);const y=Fe.getAccessToken(),w=Fe.getUserData();if(!y){a(!1),o(null),n(!1);return}if(tr(y))try{await v();const N=Fe.getAccessToken();if(N&&!tr(N)){const S=Fe.getUserData();if(S)o(S),a(!0);else try{const T=await wo();o(T),Fe.setUserData(T),a(!0)}catch{Fe.clearAll(),a(!1),o(null)}}else Fe.clearAll(),a(!1),o(null)}catch{Fe.clearAll(),a(!1),o(null)}else if(w)o(w),a(!0);else try{const N=await wo();o(N),Fe.setUserData(N),a(!0)}catch{Fe.clearAll(),a(!1),o(null)}}catch(y){console.error("Error checking auth status:",y),c(y),Fe.clearAll(),a(!1),o(null)}finally{n(!1)}},x=async()=>{try{c(null);const y="https://dev-830839.oktapreview.com",w="0oa2j8slwj5S4bG5k0h8",N=`${window.location.origin}/login/callback`,S="code",T="openid profile email",F=Math.random().toString(36).substring(7),R=new URLSearchParams(window.location.search),M=R.has("logout")||R.has("okta_logged_out");let b=`${y}/oauth2/default/v1/authorize?client_id=${w}&redirect_uri=${encodeURIComponent(N)}&response_type=${S}&scope=${encodeURIComponent(T)}&state=${F}`;M&&(b+="&prompt=login"),window.location.href=b}catch(y){throw c(y),y}},p=async()=>{try{Fe.getIdToken(),sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),d(!0),a(!1),o(null),c(null),n(!0);try{await zp()}catch(S){console.error("🚪 Logout API error:",S),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const y=sessionStorage.getItem("__logout_in_progress__"),w=sessionStorage.getItem("__force_logout__");Fe.clearAll(),y&&sessionStorage.setItem("__logout_in_progress__",y),w&&sessionStorage.setItem("__force_logout__",w),await new Promise(S=>setTimeout(S,100));const N=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(N)}catch(y){console.error("🚪 Logout error:",y);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const w=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(w)}catch{window.location.replace("/?logout="+Date.now())}}},f=async()=>{const y=Fe.getAccessToken();if(y&&!tr(y))return y;try{return await v(),Fe.getAccessToken()}catch{return null}},v=async()=>{try{if(await Bp())return;throw new Error("Failed to refresh token")}catch(y){throw Fe.clearAll(),a(!1),o(null),y}},j={isAuthenticated:s,isLoading:r,user:i,error:l,login:x,logout:p,getAccessTokenSilently:f,refreshTokenSilently:v};return e.jsx(Wc.Provider,{value:j,children:t})}function Wp({children:t}){return e.jsx(Hp,{children:t})}function Zt(){const t=g.useContext(Wc);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Us(t){return(t==null?void 0:t.role)==="ADMIN"}function Sa(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function Rr(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Co=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,So=Nc,qc=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return So(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,o=Object.keys(n).map(m=>{const d=a==null?void 0:a[m],u=i==null?void 0:i[m];if(d===null)return null;const h=Co(d)||Co(u);return n[m][h]}),l=a&&Object.entries(a).reduce((m,d)=>{let[u,h]=d;return h===void 0||(m[u]=h),m},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((m,d)=>{let{class:u,className:h,...x}=d;return Object.entries(x).every(p=>{let[f,v]=p;return Array.isArray(v)?v.includes({...i,...l}[f]):{...i,...l}[f]===v})?[...m,u,h]:m},[]);return So(t,o,c,a==null?void 0:a.class,a==null?void 0:a.className)},yi="-",qp=t=>{const s=Gp(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:o=>{const l=o.split(yi);return l[0]===""&&l.length!==1&&l.shift(),Kc(l,s)||Kp(o)},getConflictingClassGroupIds:(o,l)=>{const c=a[o]||[];return l&&r[o]?[...c,...r[o]]:c}}},Kc=(t,s)=>{var o;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Kc(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(yi);return(o=s.validators.find(({validator:l})=>l(i)))==null?void 0:o.classGroupId},Ao=/^\[(.+)\]$/,Kp=t=>{if(Ao.test(t)){const s=Ao.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Gp=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Zp(Object.entries(t.classGroups),a).forEach(([i,o])=>{Dn(o,r,i,s)}),r},Dn=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:To(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Yp(n)){Dn(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,o])=>{Dn(o,To(s,i),a,r)})})},To=(t,s)=>{let a=t;return s.split(yi).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Yp=t=>t.isThemeGetter,Zp=(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(([o,l])=>[s+o,l])):i);return[a,n]}):t,Xp=t=>{if(t<1)return{get:()=>{},set:()=>{}};let s=0,a=new Map,r=new Map;const n=(i,o)=>{a.set(i,o),s++,s>t&&(s=0,r=a,a=new Map)};return{get(i){let o=a.get(i);if(o!==void 0)return o;if((o=r.get(i))!==void 0)return n(i,o),o},set(i,o){a.has(i)?a.set(i,o):n(i,o)}}},Gc="!",Jp=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,o=l=>{const c=[];let m=0,d=0,u;for(let v=0;v<l.length;v++){let j=l[v];if(m===0){if(j===n&&(r||l.slice(v,v+i)===s)){c.push(l.slice(d,v)),d=v+i;continue}if(j==="/"){u=v;continue}}j==="["?m++:j==="]"&&m--}const h=c.length===0?l:l.substring(d),x=h.startsWith(Gc),p=x?h.substring(1):h,f=u&&u>d?u-d:void 0;return{modifiers:c,hasImportantModifier:x,baseClassName:p,maybePostfixModifierPosition:f}};return a?l=>a({className:l,parseClassName:o}):o},Qp=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},ex=t=>({cache:Xp(t.cacheSize),parseClassName:Jp(t),...qp(t)}),tx=/\s+/,sx=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],o=t.trim().split(tx);let l="";for(let c=o.length-1;c>=0;c-=1){const m=o[c],{modifiers:d,hasImportantModifier:u,baseClassName:h,maybePostfixModifierPosition:x}=a(m);let p=!!x,f=r(p?h.substring(0,x):h);if(!f){if(!p){l=m+(l.length>0?" "+l:l);continue}if(f=r(h),!f){l=m+(l.length>0?" "+l:l);continue}p=!1}const v=Qp(d).join(":"),j=u?v+Gc:v,y=j+f;if(i.includes(y))continue;i.push(y);const w=n(f,p);for(let N=0;N<w.length;++N){const S=w[N];i.push(j+S)}l=m+(l.length>0?" "+l:l)}return l};function ax(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=Yc(s))&&(r&&(r+=" "),r+=a);return r}const Yc=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=Yc(t[r]))&&(a&&(a+=" "),a+=s);return a};function rx(t,...s){let a,r,n,i=o;function o(c){const m=s.reduce((d,u)=>u(d),t());return a=ex(m),r=a.cache.get,n=a.cache.set,i=l,l(c)}function l(c){const m=r(c);if(m)return m;const d=sx(c,a);return n(c,d),d}return function(){return i(ax.apply(null,arguments))}}const He=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},Zc=/^\[(?:([a-z-]+):)?(.+)\]$/i,nx=/^\d+\/\d+$/,ix=new Set(["px","full","screen"]),ox=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,lx=/\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$/,cx=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,dx=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,mx=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ps=t=>ma(t)||ix.has(t)||nx.test(t),Ss=t=>va(t,"length",vx),ma=t=>!!t&&!Number.isNaN(Number(t)),Kr=t=>va(t,"number",ma),Aa=t=>!!t&&Number.isInteger(Number(t)),ux=t=>t.endsWith("%")&&ma(t.slice(0,-1)),Ce=t=>Zc.test(t),As=t=>ox.test(t),hx=new Set(["length","size","percentage"]),px=t=>va(t,hx,Xc),xx=t=>va(t,"position",Xc),gx=new Set(["image","url"]),fx=t=>va(t,gx,jx),yx=t=>va(t,"",bx),Ta=()=>!0,va=(t,s,a)=>{const r=Zc.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},vx=t=>lx.test(t)&&!cx.test(t),Xc=()=>!1,bx=t=>dx.test(t),jx=t=>mx.test(t),Nx=()=>{const t=He("colors"),s=He("spacing"),a=He("blur"),r=He("brightness"),n=He("borderColor"),i=He("borderRadius"),o=He("borderSpacing"),l=He("borderWidth"),c=He("contrast"),m=He("grayscale"),d=He("hueRotate"),u=He("invert"),h=He("gap"),x=He("gradientColorStops"),p=He("gradientColorStopPositions"),f=He("inset"),v=He("margin"),j=He("opacity"),y=He("padding"),w=He("saturate"),N=He("scale"),S=He("sepia"),T=He("skew"),F=He("space"),R=He("translate"),M=()=>["auto","contain","none"],b=()=>["auto","hidden","clip","visible","scroll"],A=()=>["auto",Ce,s],P=()=>[Ce,s],B=()=>["",ps,Ss],E=()=>["auto",ma,Ce],L=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],C=()=>["solid","dashed","dotted","double","none"],k=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],D=()=>["start","end","center","between","around","evenly","stretch"],z=()=>["","0",Ce],K=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Y=()=>[ma,Ce];return{cacheSize:500,separator:":",theme:{colors:[Ta],spacing:[ps,Ss],blur:["none","",As,Ce],brightness:Y(),borderColor:[t],borderRadius:["none","","full",As,Ce],borderSpacing:P(),borderWidth:B(),contrast:Y(),grayscale:z(),hueRotate:Y(),invert:z(),gap:P(),gradientColorStops:[t],gradientColorStopPositions:[ux,Ss],inset:A(),margin:A(),opacity:Y(),padding:P(),saturate:Y(),scale:Y(),sepia:z(),skew:Y(),space:P(),translate:P()},classGroups:{aspect:[{aspect:["auto","square","video",Ce]}],container:["container"],columns:[{columns:[As]}],"break-after":[{"break-after":K()}],"break-before":[{"break-before":K()}],"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(),Ce]}],overflow:[{overflow:b()}],"overflow-x":[{"overflow-x":b()}],"overflow-y":[{"overflow-y":b()}],overscroll:[{overscroll:M()}],"overscroll-x":[{"overscroll-x":M()}],"overscroll-y":[{"overscroll-y":M()}],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",Aa,Ce]}],basis:[{basis:A()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Ce]}],grow:[{grow:z()}],shrink:[{shrink:z()}],order:[{order:["first","last","none",Aa,Ce]}],"grid-cols":[{"grid-cols":[Ta]}],"col-start-end":[{col:["auto",{span:["full",Aa,Ce]},Ce]}],"col-start":[{"col-start":E()}],"col-end":[{"col-end":E()}],"grid-rows":[{"grid-rows":[Ta]}],"row-start-end":[{row:["auto",{span:[Aa,Ce]},Ce]}],"row-start":[{"row-start":E()}],"row-end":[{"row-end":E()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Ce]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Ce]}],gap:[{gap:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...D()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...D(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...D(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[v]}],mx:[{mx:[v]}],my:[{my:[v]}],ms:[{ms:[v]}],me:[{me:[v]}],mt:[{mt:[v]}],mr:[{mr:[v]}],mb:[{mb:[v]}],ml:[{ml:[v]}],"space-x":[{"space-x":[F]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[F]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Ce,s]}],"min-w":[{"min-w":[Ce,s,"min","max","fit"]}],"max-w":[{"max-w":[Ce,s,"none","full","min","max","fit","prose",{screen:[As]},As]}],h:[{h:[Ce,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Ce,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Ce,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Ce,s,"auto","min","max","fit"]}],"font-size":[{text:["base",As,Ss]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Kr]}],"font-family":[{font:[Ta]}],"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",Ce]}],"line-clamp":[{"line-clamp":["none",ma,Kr]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",ps,Ce]}],"list-image":[{"list-image":["none",Ce]}],"list-style-type":[{list:["none","disc","decimal",Ce]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[j]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...C(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",ps,Ss]}],"underline-offset":[{"underline-offset":["auto",ps,Ce]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:P()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ce]}],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",Ce]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[j]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...L(),xx]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",px]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},fx]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[p]}],"gradient-via-pos":[{via:[p]}],"gradient-to-pos":[{to:[p]}],"gradient-from":[{from:[x]}],"gradient-via":[{via:[x]}],"gradient-to":[{to:[x]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[j]}],"border-style":[{border:[...C(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[j]}],"divide-style":[{divide:C()}],"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:["",...C()]}],"outline-offset":[{"outline-offset":[ps,Ce]}],"outline-w":[{outline:[ps,Ss]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:B()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[ps,Ss]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",As,yx]}],"shadow-color":[{shadow:[Ta]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...k(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":k()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",As,Ce]}],grayscale:[{grayscale:[m]}],"hue-rotate":[{"hue-rotate":[d]}],invert:[{invert:[u]}],saturate:[{saturate:[w]}],sepia:[{sepia:[S]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[m]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[d]}],"backdrop-invert":[{"backdrop-invert":[u]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[S]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Ce]}],duration:[{duration:Y()}],ease:[{ease:["linear","in","out","in-out",Ce]}],delay:[{delay:Y()}],animate:[{animate:["none","spin","ping","pulse","bounce",Ce]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[N]}],"scale-x":[{"scale-x":[N]}],"scale-y":[{"scale-y":[N]}],rotate:[{rotate:[Aa,Ce]}],"translate-x":[{"translate-x":[R]}],"translate-y":[{"translate-y":[R]}],"skew-x":[{"skew-x":[T]}],"skew-y":[{"skew-y":[T]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Ce]}],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",Ce]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":P()}],"scroll-mx":[{"scroll-mx":P()}],"scroll-my":[{"scroll-my":P()}],"scroll-ms":[{"scroll-ms":P()}],"scroll-me":[{"scroll-me":P()}],"scroll-mt":[{"scroll-mt":P()}],"scroll-mr":[{"scroll-mr":P()}],"scroll-mb":[{"scroll-mb":P()}],"scroll-ml":[{"scroll-ml":P()}],"scroll-p":[{"scroll-p":P()}],"scroll-px":[{"scroll-px":P()}],"scroll-py":[{"scroll-py":P()}],"scroll-ps":[{"scroll-ps":P()}],"scroll-pe":[{"scroll-pe":P()}],"scroll-pt":[{"scroll-pt":P()}],"scroll-pr":[{"scroll-pr":P()}],"scroll-pb":[{"scroll-pb":P()}],"scroll-pl":[{"scroll-pl":P()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Ce]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[ps,Ss,Kr]}],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"]}}},wx=rx(Nx);function ce(...t){return wx(Nc(t))}const Oa=qc("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"}}),I=g.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const o=r?uc:"button";return e.jsx(o,{"data-slot":"button",className:ce(Oa({variant:s,size:a,className:t})),ref:i,...n})});I.displayName="Button";function W({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:ce("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function Q({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:ce("@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 ee({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:ce("leading-none",t),...s})}function le({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:ce("text-muted-foreground",t),...s})}function q({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:ce("px-6 [&:last-child]:pb-6",t),...s})}function Cx(){const{login:t,isLoading:s,error:a}=Zt(),r=async()=>{localStorage.clear(),sessionStorage.clear();try{await t()}catch(n){console.error("========================================"),console.error("LOGIN ERROR"),console.error("Error details:",n),console.error("Error message:",n==null?void 0:n.message),console.error("Error stack:",n==null?void 0:n.stack),console.error("========================================")}};return a&&console.error("Auth0 Error in Auth Component:",{message:a.message,error:a}),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 p-4",children:e.jsxs(W,{className:"w-full max-w-md shadow-xl",children:[e.jsxs(Q,{className:"space-y-1 text-center pb-6",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-slate-800 to-slate-900 rounded-2xl flex items-center justify-center shadow-lg",children:e.jsx(At,{className:"w-8 h-8 text-white"})})}),e.jsx(ee,{className:"text-3xl font-bold text-gray-900",children:"Royal Enfield"}),e.jsx(le,{className:"text-lg text-gray-600 mt-2",children:"Approval & Request Management Portal"})]}),e.jsxs(q,{className:"space-y-4",children:[a&&e.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium",children:"Authentication Error"}),e.jsx("p",{className:"text-sm",children:a.message})]}),e.jsx(I,{onClick:r,disabled:s,className:"w-full h-12 text-base font-semibold bg-slate-900 hover:bg-slate-800",size:"lg",children:s?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-background border-t-transparent"}),"Logging in..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Kh,{className:"mr-2 h-5 w-5"}),"SSO Login"]})}),e.jsxs("div",{className:"text-center text-sm text-gray-500 mt-4",children:[e.jsx("p",{children:"Secure Single Sign-On"}),e.jsx("p",{className:"text-xs mt-1",children:"Powered by Auth0"})]})]})]})})}function Jc(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Zt(),[n,i]=g.useState("exchanging");g.useEffect(()=>{if(a){i("error");return}if(s){const c=new URLSearchParams(window.location.search).get("code");i(c&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else if(r&&t){i("complete");const l=setTimeout(()=>{window.location.href="/"},1500);return()=>clearTimeout(l)}},[t,s,a,r]);const o=()=>{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.jsxs("div",{className:"mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-20 h-20 mb-4 rounded-2xl bg-gradient-to-br from-orange-500 to-red-600 shadow-lg shadow-orange-500/20",children:e.jsx("svg",{className:"w-12 h-12 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),e.jsx("h1",{className:"text-2xl font-bold text-white mb-2",children:"Royal Enfield"}),e.jsx("p",{className:"text-slate-400 text-sm",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(Re,{className:"w-16 h-16 text-red-500"})}),e.jsx(Re,{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(Sn,{className:"w-16 h-16 text-green-500"})}),e.jsx(Sn,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx($e,{className:"w-16 h-16 text-orange-500 animate-spin"}),e.jsx("div",{className:"absolute inset-0 border-4 border-orange-500/20 rounded-full"}),e.jsx("div",{className:"absolute inset-0 border-4 border-transparent border-t-orange-500 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:o()})]}),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-orange-500 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-orange-500 animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Loading your profile"})]}),n==="complete"&&e.jsxs("div",{className:"flex items-center gap-3 text-sm transition-all duration-500 text-white",children:[e.jsx("div",{className:"w-2 h-2 rounded-full transition-all duration-500 bg-green-500"}),e.jsx("span",{children:"Setting up your session"})]})]}),n==="error"&&a&&e.jsxs("div",{className:"mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx("p",{className:"text-red-400 text-sm",children:a.message||"An error occurred during authentication"}),e.jsx("button",{onClick:()=>{window.location.href="/"},className:"mt-4 text-sm text-red-400 hover:text-red-300 underline",children:"Return to login"})]}),n!=="error"&&n!=="complete"&&e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"h-1.5 bg-slate-700/50 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-orange-500 to-red-600 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"?"Redirecting to 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-orange-500/5 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-1/4 right-1/4 w-96 h-96 bg-red-500/5 rounded-full blur-3xl animate-pulse delay-1000"})]})]})}const Sx=qc("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 J({className:t,variant:s,asChild:a=!1,...r}){const n=a?uc:"span";return e.jsx(n,{"data-slot":"badge",className:ce(Sx({variant:s}),t),...r})}function Ax({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=Up();return g.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(W,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(Q,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Authentication Debug Information"}),e.jsx(I,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(jt,{className:"h-4 w-4"})})]})}),e.jsxs(q,{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(J,{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}function me({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:ce("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})}const gt=g.forwardRef(({className:t,...s},a)=>e.jsx(hc,{ref:a,"data-slot":"avatar",className:ce("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));gt.displayName=hc.displayName;const Pr=g.forwardRef(({className:t,...s},a)=>e.jsx(pc,{ref:a,"data-slot":"avatar-image",className:ce("aspect-square size-full",t),...s}));Pr.displayName=pc.displayName;const ft=g.forwardRef(({className:t,...s},a)=>e.jsx(xc,{ref:a,"data-slot":"avatar-fallback",className:ce("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));ft.displayName=xc.displayName;function ko({...t}){return e.jsx(Au,{"data-slot":"dropdown-menu",...t})}function Ro({...t}){return e.jsx(Tu,{"data-slot":"dropdown-menu-trigger",...t})}function Po({className:t,sideOffset:s=4,...a}){return e.jsx(ku,{children:e.jsx(Ru,{"data-slot":"dropdown-menu-content",sideOffset:s,className:ce("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 Gr({className:t,inset:s,variant:a="default",...r}){return e.jsx(Pu,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:ce("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 Tx({...t}){return e.jsx(Eu,{"data-slot":"alert-dialog",...t})}function kx({...t}){return e.jsx(Du,{"data-slot":"alert-dialog-portal",...t})}const Qc=g.forwardRef(({className:t,...s},a)=>e.jsx(gc,{"data-slot":"alert-dialog-overlay",className:ce("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}));Qc.displayName=gc.displayName;const ed=g.forwardRef(({className:t,...s},a)=>e.jsxs(kx,{children:[e.jsx(Qc,{}),e.jsx(fc,{"data-slot":"alert-dialog-content",ref:a,className:ce("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...s})]}));ed.displayName=fc.displayName;function Rx({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:ce("flex flex-col gap-2 text-center sm:text-left",t),...s})}function Px({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:ce("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function Dx({className:t,...s}){return e.jsx(Mu,{"data-slot":"alert-dialog-title",className:ce("text-lg font-semibold",t),...s})}function Ex({className:t,...s}){return e.jsx(Iu,{"data-slot":"alert-dialog-description",className:ce("text-muted-foreground text-sm",t),...s})}function Mx({className:t,...s}){return e.jsx(Fu,{className:ce(Oa(),t),...s})}function Ix({className:t,...s}){return e.jsx(Lu,{className:ce(Oa({variant:"outline"}),t),...s})}const Lx="/assets/royal_enfield_logo-DcpkTndU.png";class Fx{async list(s){return(await oe.get("/notifications",{params:s})).data}async getUnreadCount(){return(await oe.get("/notifications/unread-count")).data.data.unreadCount}async markAsRead(s){return(await oe.patch(`/notifications/${s}/read`)).data}async markAllAsRead(){return(await oe.post("/notifications/mark-all-read")).data}async delete(s){return(await oe.delete(`/notifications/${s}`)).data}}const Ws=new Fx;let Fs=null;function _x(){return"https://re-workflow-nt-api-dev.siplsolutions.com"}function hr(t){const s=_x();return Fs||(Fs=Ep(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),Fs.on("connect",()=>{}),Fs.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),Fs.on("disconnect",a=>{}),Fs)}function En(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function td(t,s){t.emit("leave:request",s)}function Ox(t,s){t.emit("join:user",{userId:s})}function It({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,o]=g.useState(!1),[l,c]=g.useState(!1),[m,d]=g.useState([]),[u,h]=g.useState(0),[x,p]=g.useState(!1),{user:f}=Zt(),v=()=>{var T,F;try{if(f!=null&&f.displayName&&typeof f.displayName=="string"){const R=f.displayName.split(" ").filter(Boolean);return R.length>=2?`${((T=R[0])==null?void 0:T[0])||""}${((F=R[R.length-1])==null?void 0:F[0])||""}`.toUpperCase():f.displayName.substring(0,2).toUpperCase()}return f!=null&&f.email&&typeof f.email=="string"?f.email.substring(0,2).toUpperCase():"U"}catch(R){return console.error("[PageLayout] Error getting user initials:",R),"U"}},j=g.useMemo(()=>Rr(f),[f]),y=g.useMemo(()=>{const T=[{id:"dashboard",label:"Dashboard",icon:Gh}];return j&&T.push({id:"requests",label:"All Requests",icon:Yh}),T.push({id:"my-requests",label:"My Requests",icon:xt},{id:"open-requests",label:"Open Requests",icon:we},{id:"closed-requests",label:"Closed Requests",icon:xe}),T},[j]),w=()=>{o(!i)},N=async T=>{var F;try{if(T.isRead||(await Ws.markAsRead(T.notificationId),d(R=>R.map(M=>M.notificationId===T.notificationId?{...M,isRead:!0}:M)),h(R=>Math.max(0,R-1))),T.actionUrl&&a){const R=(F=T.metadata)==null?void 0:F.requestNumber;if(R){let M=`request/${R}`;(T.notificationType==="mention"||T.notificationType==="comment"||T.notificationType==="worknote")&&(M+="?tab=worknotes"),a(M)}}p(!1)}catch(R){console.error("[PageLayout] Error handling notification click:",R)}},S=async()=>{try{await Ws.markAllAsRead(),d(T=>T.map(F=>({...F,isRead:!0}))),h(0)}catch(T){console.error("[PageLayout] Error marking all as read:",T)}};return g.useEffect(()=>{const T=f==null?void 0:f.userId;if(!T)return;let F=!0;(async()=>{var b,A;try{const P=await Ws.list({page:1,limit:4,unreadOnly:!1});if(!F)return;const B=((b=P.data)==null?void 0:b.notifications)||[];d(B),h(((A=P.data)==null?void 0:A.unreadCount)||0)}catch(P){console.error("[PageLayout] Failed to fetch notifications:",P)}})();const M=hr();if(M){Ox(M,T);const b=A=>{F&&(d(P=>[A.notification,...P].slice(0,4)),h(P=>P+1))};return M.on("notification:new",b),()=>{F=!1,M.off("notification:new",b)}}return()=>{F=!1}},[f]),g.useEffect(()=>{const T=()=>{window.innerWidth>=768?o(!0):o(!1)};return T(),window.addEventListener("resize",T),()=>window.removeEventListener("resize",T)},[]),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:()=>o(!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 items-center gap-3",children:[e.jsx("img",{src:Lx,alt:"Royal Enfield Logo",className:"w-10 h-10 shrink-0 object-contain"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h2",{className:"text-base font-semibold text-white truncate",children:"Royal Enfield"}),e.jsx("p",{className:"text-sm text-gray-400 truncate",children:"Approval Portal"})]})]})}),e.jsxs("div",{className:"p-3 flex-1 overflow-y-auto",children:[e.jsx("div",{className:"space-y-2",children:y.map(T=>e.jsxs("button",{onClick:()=>{a==null||a(T.id),window.innerWidth<768&&o(!1)},className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${s===T.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(T.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:T.label})]},T.id))}),e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(I,{onClick:r,className:"w-full bg-re-green hover:bg-re-green/90 text-white text-sm font-medium",size:"sm",children:[e.jsx(Ps,{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.jsxs("div",{className:"flex items-center gap-4 min-w-0 flex-1",children:[e.jsx(I,{variant:"ghost",size:"icon",onClick:w,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(Zh,{className:"w-5 h-5 text-gray-600"}):e.jsx(Xh,{className:"w-5 h-5 text-gray-600"})}),e.jsxs("div",{className:"relative max-w-md flex-1",children:[e.jsx(ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(me,{placeholder:"Search...",className:"pl-10 bg-white border-gray-300 hover:border-gray-400 focus:border-re-green focus:ring-1 focus:ring-re-green w-full text-sm h-10"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[e.jsxs(I,{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(Ps,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(ko,{open:x,onOpenChange:p,children:[e.jsx(Ro,{asChild:!0,children:e.jsxs(I,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(Ft,{className:"w-5 h-5"}),u>0&&e.jsx(J,{className:"absolute -top-1 -right-1 w-5 h-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center p-0",children:u>9?"9+":u})]})}),e.jsxs(Po,{align:"end",className:"w-96 max-h-[500px]",children:[e.jsxs("div",{className:"p-3 border-b flex items-center justify-between sticky top-0 bg-white z-10",children:[e.jsx("h4",{className:"font-semibold text-base",children:"Notifications"}),u>0&&e.jsx(I,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:T=>{T.stopPropagation(),S()},children:"Mark all as read"})]}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:m.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(Ft,{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:m.map(T=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${T.isRead?"":"bg-blue-50"}`,onClick:()=>N(T),children:e.jsxs("div",{className:"flex gap-2",children:[!T.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 ${T.isRead?"font-medium":"font-semibold"}`,children:T.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:T.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:kc(new Date(T.createdAt),{addSuffix:!0})})]})]})},T.notificationId))})}),m.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(I,{variant:"ghost",className:"w-full text-sm text-blue-600 hover:text-blue-700",onClick:()=>{p(!1),a==null||a("notifications")},children:"View all notifications"})})]})]}),e.jsxs(ko,{children:[e.jsx(Ro,{asChild:!0,children:e.jsxs(gt,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Pr,{src:(f==null?void 0:f.picture)||""}),e.jsx(ft,{className:"bg-re-green text-white text-sm",children:v()})]})}),e.jsxs(Po,{align:"end",children:[e.jsxs(Gr,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(xt,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(Gr,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(aa,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(Gr,{onClick:()=>c(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(Wr,{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(Tx,{open:l,onOpenChange:c,children:e.jsxs(ed,{children:[e.jsxs(Rx,{children:[e.jsxs(Dx,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(Ex,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(Px,{children:[e.jsx(Ix,{onClick:()=>c(!1),children:"Cancel"}),e.jsxs(Mx,{onClick:async()=>{if(c(!1),n)try{await n()}catch(T){console.error("🔴 Error calling onLogout:",T)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(Wr,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}function $x(){const[t,s]=g.useState("month"),[a,r]=g.useState(void 0),[n,i]=g.useState(void 0),[o,l]=g.useState(!1),c=g.useCallback(u=>{const h=u;s(h),h!=="custom"?(r(void 0),i(void 0),l(!1)):l(!0)},[]),m=g.useCallback(u=>{if(a&&n){if(a>n){const h=a;r(n),i(h),u(n,h)}else u(a,n);l(!1)}},[a,n]),d=g.useCallback(()=>{r(void 0),i(void 0),l(!1),s("month")},[]);return{dateRange:t,customStartDate:a,customEndDate:n,showCustomDatePicker:o,setDateRange:s,setCustomStartDate:r,setCustomEndDate:i,setShowCustomDatePicker:l,handleDateRangeChange:c,handleApplyCustomDate:m,resetCustomDates:d}}function Ux(){const[t,s]=g.useState({page:1,totalPages:1,totalRecords:0}),[a,r]=g.useState({page:1,totalPages:1,totalRecords:0}),[n,i]=g.useState({page:1,totalPages:1,totalRecords:0}),[o,l]=g.useState({page:1,totalPages:1,totalRecords:0}),c=g.useCallback((v,j,y)=>{s({page:v,totalPages:j,totalRecords:y})},[]),m=g.useCallback((v,j,y)=>{r({page:v,totalPages:j,totalRecords:y})},[]),d=g.useCallback((v,j,y)=>{i({page:v,totalPages:j,totalRecords:y})},[]),u=g.useCallback((v,j,y)=>{l({page:v,totalPages:j,totalRecords:y})},[]),h=g.useCallback((v,j)=>{v>=1&&v<=t.totalPages&&(s(y=>({...y,page:v})),j(v))},[t.totalPages]),x=g.useCallback((v,j)=>{v>=1&&v<=a.totalPages&&(r(y=>({...y,page:v})),j(v))},[a.totalPages]),p=g.useCallback((v,j)=>{v>=1&&v<=n.totalPages&&(i(y=>({...y,page:v})),j(v))},[n.totalPages]),f=g.useCallback((v,j)=>{v>=1&&v<=o.totalPages&&(l(y=>({...y,page:v})),j(v))},[o.totalPages]);return{activity:t,critical:a,deadlines:n,approver:o,updateActivityPagination:c,updateCriticalPagination:m,updateDeadlinesPagination:d,updateApproverPagination:u,handleActivityPageChange:h,handleCriticalPageChange:x,handleDeadlinesPageChange:p,handleApproverPageChange:f}}class Vx{async getKPIs(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await oe.get("/dashboard/kpis",{params:n})).data.data}catch(n){throw console.error("Failed to fetch KPIs:",n),n}}async getRequestStats(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a,n.endDate=r),(await oe.get("/dashboard/stats/requests",{params:n})).data.data}catch(n){throw console.error("Failed to fetch request stats:",n),n}}async getTATEfficiency(s){try{return(await oe.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 oe.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 oe.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 oe.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){try{const r=await oe.get("/dashboard/activity/recent",{params:{page:s,limit:a}});return{activities:r.data.data,pagination:r.data.pagination}}catch(r){throw console.error("Failed to fetch recent activity:",r),r}}async getCriticalRequests(s=1,a=10){try{const r=await oe.get("/dashboard/requests/critical",{params:{page:s,limit:a}});return{criticalRequests:r.data.data,pagination:r.data.pagination}}catch(r){throw console.error("Failed to fetch critical requests:",r),r}}async getUpcomingDeadlines(s=1,a=10){try{const r=await oe.get("/dashboard/deadlines/upcoming",{params:{page:s,limit:a}});return{deadlines:r.data.data,pagination:r.data.pagination}}catch(r){throw console.error("Failed to fetch upcoming deadlines:",r),r}}async getDepartmentStats(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await oe.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 oe.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 oe.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){try{const o={dateRange:s,page:a,limit:r};s==="custom"&&n&&i&&(o.startDate=n.toISOString(),o.endDate=i.toISOString());const l=await oe.get("/dashboard/stats/approver-performance",{params:o});return{performance:l.data.data,pagination:l.data.pagination}}catch(o){throw console.error("Failed to fetch approver performance:",o),o}}async getLifecycleReport(s=1,a=50,r,n,i){try{const o={page:s,limit:a};r&&(o.dateRange=r),r==="custom"&&n&&i&&(o.startDate=n.toISOString(),o.endDate=i.toISOString());const l=await oe.get("/dashboard/reports/lifecycle",{params:o});return{lifecycleData:l.data.data,pagination:l.data.pagination}}catch(o){throw console.error("Failed to fetch lifecycle report:",o),o}}async getActivityLogReport(s=1,a=50,r,n,i,o,l,c,m){try{const d={page:s,limit:a,filterUserId:n,filterType:i,filterCategory:o,filterSeverity:l};r&&(d.dateRange=r),r==="custom"&&c&&m&&(d.startDate=c.toISOString(),d.endDate=m.toISOString());const u=await oe.get("/dashboard/reports/activity-log",{params:d});return{activities:u.data.data,pagination:u.data.pagination}}catch(d){throw console.error("Failed to fetch activity log report:",d),d}}async getDepartments(){try{return(await oe.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,o){try{const l={threshold:s,page:a,limit:r};n&&(l.dateRange=n),n==="custom"&&i&&o&&(l.startDate=i.toISOString(),l.endDate=o.toISOString());const c=await oe.get("/dashboard/reports/workflow-aging",{params:l});return{agingData:c.data.data,pagination:c.data.pagination}}catch(l){throw console.error("Failed to fetch workflow aging report:",l),l}}async getRequestsByApprover(s,a=1,r=50,n,i,o,l,c,m,d){try{const u={approverId:s,page:a,limit:r};n&&(u.dateRange=n),n==="custom"&&i&&o&&(u.startDate=i.toISOString(),u.endDate=o.toISOString()),l&&(u.status=l),c&&(u.priority=c),m&&(u.slaCompliance=m),d&&(u.search=d);const h=await oe.get("/dashboard/requests/by-approver",{params:u});return{requests:h.data.data,pagination:h.data.pagination}}catch(u){throw console.error("Failed to fetch requests by approver:",u),u}}}const We=new Vx;function Bx({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,onPaginationUpdate:n}){const[i,o]=g.useState(null),[l,c]=g.useState([]),[m,d]=g.useState([]),[u,h]=g.useState([]),[x,p]=g.useState([]),[f,v]=g.useState([]),[j,y]=g.useState(null),[w,N]=g.useState([]),[S,T]=g.useState(!0),[F,R]=g.useState(!1),M=g.useRef(n);M.current=n;const b=g.useCallback(async(L=!1)=>{try{L?R(!0):T(!0);const C=[We.getKPIs(s,a,r),We.getRecentActivity(1,10),We.getCriticalRequests(1,10),We.getUpcomingDeadlines(1,10)],k=t?[We.getDepartmentStats(s,a,r),We.getPriorityDistribution(s,a,r),We.getAIRemarkUtilization(s,a,r),We.getApproverPerformance(s,1,10,a,r)]:[],D=await Promise.all([...C,...k]),z=D[0],K=D[1],Y=D[2],de=D[3];if(o(z),c(K.activities),M.current.activity(K.pagination.currentPage,K.pagination.totalPages,K.pagination.totalRecords),d(Y.criticalRequests),M.current.critical(Y.pagination.currentPage,Y.pagination.totalPages,Y.pagination.totalRecords),v(de.deadlines),M.current.deadlines(de.pagination.currentPage,de.pagination.totalPages,de.pagination.totalRecords),t&&D.length>=8){const Z=D[4],je=D[5],ve=D[6],U=D[7];h(Z),p(je),y(ve),N(U.performance),M.current.approver(U.pagination.currentPage,U.pagination.totalPages,U.pagination.totalRecords)}else t||(h([]),p([]),y(null),N([]))}catch(C){console.error("Failed to fetch dashboard data:",C)}finally{T(!1),R(!1)}},[t,s,a,r]),A=g.useCallback(async(L=1)=>{try{const C=await We.getRecentActivity(L,10);c(C.activities),M.current.activity(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch recent activities:",C)}},[]),P=g.useCallback(async(L=1)=>{try{const C=await We.getCriticalRequests(L,10);d(C.criticalRequests),M.current.critical(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch critical requests:",C)}},[]),B=g.useCallback(async(L=1)=>{try{const C=await We.getUpcomingDeadlines(L,10);v(C.deadlines),M.current.deadlines(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch upcoming deadlines:",C)}},[]),E=g.useCallback(async(L=1)=>{try{const C=await We.getApproverPerformance(s,L,10,a,r);N(C.performance),M.current.approver(C.pagination.currentPage,C.pagination.totalPages,C.pagination.totalRecords)}catch(C){console.error("Failed to fetch approver performance:",C)}},[s,a,r]);return{kpis:i,recentActivity:l,criticalRequests:m,departmentStats:u,priorityDistribution:x,upcomingDeadlines:f,aiRemarkUtilization:j,approverPerformance:w,loading:S,refreshing:F,fetchDashboardData:b,fetchRecentActivities:A,fetchCriticalRequests:P,fetchUpcomingDeadlines:B,fetchApproverPerformance:E}}const xs={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 zx{constructor(){Vr(this,"config",null);Vr(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 oe.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...xs,...r,workingHours:{...xs.workingHours,...r.workingHours},tat:{...xs.tat,...r.tat},upload:{...xs.upload,...r.upload},workflow:{...xs.workflow,...r.workflow},workNotes:{...xs.workNotes,...r.workNotes},features:{...xs.features,...r.features},ui:{...xs.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),xs}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const Hx=new zx;let Wx=9,qx=18,Kx=1,Gx=5,Do=!1;async function Yx(){if(!Do)try{const t=await Hx.getConfig();Wx=t.workingHours.START_HOUR,qx=t.workingHours.END_HOUR,Kx=t.workingHours.START_DAY,Gx=t.workingHours.END_DAY,Do=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}Yx().catch(()=>{});function Je(t){if(t==null||t<0||t===0)return"0 hours";const s=8;if(t<1){const l=Math.round(t*60);return l>0?`${l}m`:"0 hours"}const a=Math.floor(t/s),r=Math.floor(t%s),n=Math.round(t%1*60);if(a>0){const l=a===1?"day":"days",c=r===1?"hour":"hours",m=n===1?"min":"m";return n>0?`${a} ${l} ${r} ${c} ${n}${m}`:`${a} ${l} ${r} ${c}`}const i=r===1?"hour":"hours",o=n===1?"min":"m";return n>0?`${r} ${i} ${n}${o}`:`${r} ${i}`}async function Zx(t,s,a){const r=[];let n=1,i=!0;const o=100;for(;i&&n<=o;){const h=await We.getApproverPerformance(t,n,100,s,a);h.performance&&h.performance.length>0?(r.push(...h.performance),n++,i=n<=h.pagination.totalPages):i=!1}const l=[["Approver Name","Total Approved","TAT Compliance (%)","Avg Response Time","Pending Count"].join(",")];r.forEach(h=>{const x=[`"${(h.approverName||"Unknown").replace(/"/g,'""')}"`,h.totalApproved||0,h.tatCompliancePercent||0,Je(h.avgResponseHours),h.pendingCount||0];l.push(x.join(","))});const c=l.join(`
`),m=new Blob([c],{type:"text/csv;charset=utf-8;"}),d=document.createElement("a"),u=URL.createObjectURL(m);d.setAttribute("href",u),d.setAttribute("download",`approver-performance-report-${new Date().toISOString().split("T")[0]}.csv`),d.style.visibility="hidden",document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(u)}async function Xx(t,s,a){const r=await We.getDepartmentStats(t,s,a),n=[["Department","Total Requests","Approved","Rejected","In Progress","Approval Rate (%)"].join(",")];r.forEach(m=>{const d=[`"${(m.department||"Unknown").replace(/"/g,'""')}"`,m.totalRequests||0,m.approved||0,m.rejected||0,m.inProgress||0,m.approvalRate||0];n.push(d.join(","))});const i=n.join(`
`),o=new Blob([i],{type:"text/csv;charset=utf-8;"}),l=document.createElement("a"),c=URL.createObjectURL(o);l.setAttribute("href",c),l.setAttribute("download",`department-workflow-summary-${new Date().toISOString().split("T")[0]}.csv`),l.style.visibility="hidden",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(c)}function Jx(){const[t,s]=g.useState(!1),[a,r]=g.useState(!1),n=g.useCallback(async(o,l,c)=>{try{s(!0),await Xx(o,l,c)}catch(m){console.error("Failed to export department stats:",m),alert("Failed to export department statistics. Please try again.")}finally{s(!1)}},[]),i=g.useCallback(async(o,l,c)=>{try{r(!0),await Zx(o,l,c)}catch(m){console.error("Failed to export approver performance:",m),alert("Failed to export approver performance data. Please try again.")}finally{r(!1)}},[]);return{exportingDeptStats:t,exportingApproverPerformance:a,handleExportDepartmentStats:n,handleExportApproverPerformance:i}}function Qx({isAdmin:t,quickActions:s}){return e.jsxs(W,{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.jsx(q,{className:"relative z-10 p-4 sm:p-6 lg:p-12",children:e.jsxs("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",children:[e.jsxs("div",{className:"flex items-center gap-3 sm:gap-4 mb-4 sm:mb-6",children:[e.jsx("div",{className:"w-12 h-12 sm:w-16 sm:h-16 bg-yellow-400 rounded-xl flex items-center justify-center shadow-lg","data-testid":"hero-icon",children:e.jsx(At,{className:"w-6 h-6 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 mb-1 sm:mb-2 text-white","data-testid":"hero-title",children:t?"Management Dashboard":"My Dashboard"}),e.jsx("p",{className:"text-sm sm:text-lg lg:text-xl text-gray-200","data-testid":"hero-subtitle",children:t?"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:s.map((a,r)=>e.jsxs(I,{onClick:a.action,className:`${a.color} text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200`,size:window.innerWidth<640?"sm":"lg","data-testid":`quick-action-${a.label.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsx(a.icon,{className:"w-4 h-4 sm:w-5 sm:h-5 mr-1 sm:mr-2"}),a.label]},r))})]}),e.jsxs("div",{className:"hidden lg:flex items-center gap-4","data-testid":"hero-decorations",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(br,{className:"w-8 h-8 text-yellow-400"})})}),e.jsx("div",{className:"w-16 h-16 bg-white/10 rounded-full flex items-center justify-center",children:e.jsx(Bt,{className:"w-6 h-6 text-white/80"})})]})]})})]})}function Se({...t}){return e.jsx(_u,{"data-slot":"select",...t})}function Ae({...t}){return e.jsx(Uu,{"data-slot":"select-value",...t})}function Te({className:t,size:s="default",children:a,...r}){return e.jsxs(Ou,{"data-slot":"select-trigger","data-size":s,className:ce("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($u,{asChild:!0,children:e.jsx(Mc,{className:"size-4 opacity-50"})})]})}function ke({className:t,children:s,position:a="popper",...r}){return e.jsx(Vu,{children:e.jsxs(Bu,{"data-slot":"select-content",className:ce("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(eg,{}),e.jsx(zu,{className:ce("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(tg,{})]})})}function H({className:t,children:s,...a}){return e.jsxs(Hu,{"data-slot":"select-item",className:ce("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(Wu,{children:e.jsx(fa,{className:"size-4"})})}),e.jsx(qu,{children:s})]})}function eg({className:t,...s}){return e.jsx(Ku,{"data-slot":"select-scroll-up-button",className:ce("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Jh,{className:"size-4"})})}function tg({className:t,...s}){return e.jsx(Gu,{"data-slot":"select-scroll-down-button",className:ce("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Mc,{className:"size-4"})})}function Nt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(Yu,{"data-slot":"separator-root",decorative:a,orientation:s,className:ce("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 Zs({...t}){return e.jsx(Zu,{"data-slot":"popover",...t})}function Xs({...t}){return e.jsx(Xu,{"data-slot":"popover-trigger",...t})}function Js({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(Ju,{children:e.jsx(Qu,{"data-slot":"popover-content",align:s,sideOffset:a,className:ce("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})})}function X({className:t,...s}){return e.jsx(eh,{"data-slot":"label",className:ce("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 sg({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,showCustomDatePicker:n,refreshing:i,onDateRangeChange:o,onCustomStartDateChange:l,onCustomEndDateChange:c,onShowCustomDatePickerChange:m,onApplyCustomDate:d,onResetCustomDates:u,onRefresh:h}){return e.jsx(W,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(q,{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(jr,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(J,{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(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Se,{value:s,onValueChange:o,"data-testid":"date-range-select",children:[e.jsx(Te,{className:"w-[140px]",children:e.jsx(Ae,{placeholder:"Select period"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"today",children:"Today"}),e.jsx(H,{value:"week",children:"This Week"}),e.jsx(H,{value:"month",children:"This Month"}),e.jsx(H,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(Zs,{open:n,onOpenChange:m,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(qe,{className:"w-4 h-4"}),a&&r?`${ye(a,"MMM d, yyyy")} - ${ye(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Js,{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(X,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(me,{id:"start-date",type:"date",value:a?ye(a,"yyyy-MM-dd"):"",onChange:x=>{const p=x.target.value?new Date(x.target.value):void 0;p?(l(p),r&&p>r&&c(p)):l(void 0)},max:ye(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(me,{id:"end-date",type:"date",value:r?ye(r,"yyyy-MM-dd"):"",onChange:x=>{const p=x.target.value?new Date(x.target.value):void 0;p?(c(p),a&&p<a&&l(p)):c(void 0)},min:a?ye(a,"yyyy-MM-dd"):void 0,max:ye(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":"end-date-input"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(I,{size:"sm",onClick:d,disabled:!a||!r,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-custom-date",children:"Apply"}),e.jsx(I,{size:"sm",variant:"outline",onClick:u,"data-testid":"cancel-custom-date",children:"Cancel"})]})]})})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Se,{value:s,onValueChange:x=>o(x),"data-testid":"date-range-select-user",children:[e.jsx(Te,{className:"w-[140px]",children:e.jsx(Ae,{placeholder:"Select period"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"today",children:"Today"}),e.jsx(H,{value:"week",children:"This Week"}),e.jsx(H,{value:"month",children:"This Month"})]})]})]}),e.jsx(Nt,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(I,{variant:"outline",size:"sm",onClick:h,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx(Ot,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function qs({title:t,value:s,icon:a,iconBgColor:r,iconColor:n,subtitle:i,children:o,testId:l="kpi-card",onClick:c,onJustifyClick:m,showJustifyButton:d=!1}){const u=h=>{h.stopPropagation(),m==null||m()};return e.jsxs(W,{className:"hover:shadow-lg transition-all duration-200 shadow-md cursor-pointer h-full flex flex-col",onClick:c,"data-testid":l,children:[e.jsxs(Q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ee,{className:"text-sm font-medium text-muted-foreground","data-testid":`${l}-title`,children:t}),e.jsxs("div",{className:"flex items-center gap-2",children:[d&&m&&e.jsx("button",{type:"button",onClick:u,className:"p-1.5 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-colors","data-testid":`${l}-justify-button`,title:"View detailed breakdown of numbers","aria-label":"View detailed breakdown",children:e.jsx(Nr,{className:"h-4 w-4"})}),e.jsx("div",{className:`p-1.5 sm:p-2 rounded-lg ${r}`,"data-testid":`${l}-icon-wrapper`,children:e.jsx(a,{className:`h-4 w-4 sm:h-4 sm:w-4 ${n}`,"data-testid":`${l}-icon`})})]})]}),e.jsxs(q,{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":`${l}-value`,children:s}),i&&e.jsx("div",{className:"text-xs text-muted-foreground mb-2","data-testid":`${l}-subtitle`,children:i}),o&&e.jsx("div",{className:"flex-1 flex flex-col","data-testid":`${l}-children`,children:o})]})]})}function Ct({label:t,value:s,bgColor:a,textColor:r,testId:n="stat-card",children:i,onClick:o}){return e.jsxs("div",{className:`${a} rounded-lg p-2 sm:p-3 ${o?"cursor-pointer hover:shadow-md transition-shadow":""}`,"data-testid":n,onClick:o,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 ds({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(th,{"data-slot":"progress",className:ce("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(sh,{"data-slot":"progress-indicator",className:ce("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function ag({kpis:t,priorityDistribution:s,dateRange:a,customStartDate:r,customEndDate:n,onKPIClick:i}){const o=()=>({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(qs,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:we,iconBgColor:"bg-blue-50",iconColor:"text-blue-600",testId:"kpi-total-requests",onClick:()=>i(o()),children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[e.jsx(Ct,{label:"Approved",value:(t==null?void 0:t.requestVolume.approvedRequests)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-approved",onClick:l=>{l.stopPropagation(),i({...o(),status:"approved"})}}),e.jsx(Ct,{label:"Rejected",value:(t==null?void 0:t.requestVolume.rejectedRequests)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-rejected",onClick:l=>{l.stopPropagation(),i({...o(),status:"rejected"})}})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ct,{label:"Pending",value:(t==null?void 0:t.requestVolume.openRequests)||0,bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-pending",onClick:l=>{l.stopPropagation(),i({...o(),status:"pending"})}}),e.jsx(Ct,{label:"Closed",value:(t==null?void 0:t.requestVolume.closedRequests)||0,bgColor:"bg-gray-50",textColor:"text-gray-600",testId:"stat-closed",onClick:l=>{l.stopPropagation(),i({...o(),status:"closed"})}})]})]}),e.jsx(qs,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:Qe,iconBgColor:"bg-green-50",iconColor:"text-green-600",testId:"kpi-sla-compliance",onClick:()=>i(o()),children:e.jsxs("div",{className:"flex flex-col flex-1",children:[e.jsx(ds,{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(Ct,{label:"Compliant",value:(t==null?void 0:t.tatEfficiency.compliantWorkflows)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-compliant",onClick:l=>{l.stopPropagation(),i({...o(),slaCompliance:"compliant"})}}),e.jsx(Ct,{label:"Breached",value:(t==null?void 0:t.tatEfficiency.delayedWorkflows)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-breached",onClick:l=>{l.stopPropagation(),i({...o(),slaCompliance:"breached"})}})]})]})}),e.jsx(qs,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?Je(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:Pe,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(o()),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(Ct,{label:"Express",value:(()=>{const l=s.find(m=>m.priority==="express"),c=l?Number(l.avgCycleTimeHours):0;return c>0?Je(c):"N/A"})(),bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-express-time",onClick:l=>{l.stopPropagation(),i({...o(),priority:"express"})}}),e.jsx(Ct,{label:"Standard",value:(()=>{const l=s.find(m=>m.priority==="standard"),c=l?Number(l.avgCycleTimeHours):0;return c>0?Je(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:l=>{l.stopPropagation(),i({...o(),priority:"standard"})}})]})})})]})}function rg({kpis:t,criticalRequests:s,dateRange:a,customStartDate:r,customEndDate:n,onKPIClick:i,onNavigate:o,userId:l,userDisplayName:c}){const m=()=>({dateRange:a,startDate:r,endDate:n}),d=()=>{if(!l)return;const h=new URLSearchParams;h.set("approverId",l),h.set("approverName",c||"My Performance"),h.set("dateRange",a),a==="custom"&&r&&n&&(h.set("startDate",r.toISOString()),h.set("endDate",n.toISOString())),o==null||o(`/approver-performance?${h.toString()}`)},u=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(qs,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:we,iconBgColor:"bg-blue-50",iconColor:"text-blue-600",testId:"kpi-my-requests",onClick:()=>i(m()),children:e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 sm:gap-2",children:[e.jsx(Ct,{label:"Approved",value:(t==null?void 0:t.requestVolume.approvedRequests)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-user-approved",onClick:h=>{h.stopPropagation(),i({...m(),status:"approved"})}}),e.jsx(Ct,{label:"Pending",value:(t==null?void 0:t.requestVolume.openRequests)||0,bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-user-pending",onClick:h=>{h.stopPropagation(),i({...m(),status:"pending"})}}),e.jsx(Ct,{label:"Rejected",value:(t==null?void 0:t.requestVolume.rejectedRequests)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-user-rejected",onClick:h=>{h.stopPropagation(),i({...m(),status:"rejected"})}}),e.jsx(Ct,{label:"Closed",value:(t==null?void 0:t.requestVolume.closedRequests)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-user-closed",onClick:h=>{h.stopPropagation(),i({...m(),status:"closed"})}})]})}),e.jsx(qs,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:Pe,iconBgColor:"bg-orange-50",iconColor:"text-orange-600",subtitle:"at current level",testId:"kpi-pending-actions",onClick:()=>i({...m(),targetPage:"open-requests",status:"pending"}),onJustifyClick:d,showJustifyButton:!!l,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(Ct,{label:"Approved Today",value:(t==null?void 0:t.approverLoad.completedToday)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-today",onClick:h=>{h.stopPropagation(),i({...m(),targetPage:"open-requests",status:"pending"})}}),e.jsx(Ct,{label:"This Week",value:(t==null?void 0:t.approverLoad.completedThisWeek)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-week",onClick:h=>{h.stopPropagation(),i({...m(),targetPage:"open-requests",status:"pending"})}})]})}),e.jsx(qs,{title:"Critical Alerts",value:s.length,icon:is,iconBgColor:"bg-red-50",iconColor:"text-red-600",testId:"kpi-user-critical",onClick:()=>i({...m(),targetPage:"open-requests"}),onJustifyClick:d,showJustifyButton:!!l,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(Ct,{label:"Breached",value:s.filter(h=>h.breachCount>0).length,bgColor:"bg-orange-50",textColor:"text-red-600",testId:"stat-user-breached",onClick:h=>{h.stopPropagation(),i({...m(),targetPage:"open-requests"})}}),e.jsx(Ct,{label:"Warning",value:s.filter(h=>h.breachCount===0).length,bgColor:"bg-yellow-50",textColor:"text-orange-600",testId:"stat-user-warning",onClick:h=>{h.stopPropagation(),i({...m(),targetPage:"open-requests"})}})]})}),e.jsx(qs,{title:"Success Rate",value:`${u.toFixed(0)}%`,icon:xe,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(ds,{value:u,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 ng=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)))},ig=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 og({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=ng(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(Qh,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(J,{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(J,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:ig(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(ds,{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 lg(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 cg(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function dg(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 mg(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 sd(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 o=n;o<=i;o++)r.push(o);return r}function ug({isAdmin:t,breachedRequests:s,pagination:a,onPageChange:r,onNavigate:n}){return e.jsxs(W,{className:"lg:col-span-2 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden",style:{height:"100%"},"data-testid":"critical-alerts-section",children:[e.jsx(Q,{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(is,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(le,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(J,{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(q,{className:"overflow-y-auto flex-1 p-4",style:{maxHeight:a.totalPages>1?"calc(100% - 140px)":"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(xe,{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(og,{alert:i,onNavigate:o=>n==null?void 0:n(`request/${o}`),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(I,{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(mt,{className:"h-3 w-3 rotate-180"})}),sd(a.page,a.totalPages,3).map(i=>e.jsx(I,{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(I,{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(mt,{className:"h-3 w-3"})})]})]})})]})}const hg=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"}},pg=t=>{const s=new Date,a=new Date(t),r=Ih(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=Lh(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=Fh(s,a);return`${i} day${i>1?"s":""} ago`},xg=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()},gg=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(xe,{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(Ns,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(is,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(we,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(wr,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(Bt,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function fg({activity:t,currentUserId:s,currentUserDisplayName:a,currentUserEmail:r,onNavigate:n,testId:i="activity-feed-item"}){const o=t.userId===s,l=o?"You":t.userName||"System",c=o?(a||r||"ME").split(" ").map(m=>m[0]).join("").toUpperCase().substring(0,2):t.userName?t.userName.split(" ").map(m=>m[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(gt,{className:`h-8 w-8 sm:h-10 sm:w-10 ring-2 shadow-sm ${o?"ring-blue-200":"ring-white"}`,"data-testid":`${i}-avatar`,children:[e.jsx(Pr,{src:""}),e.jsx(ft,{className:`text-white font-semibold text-xs sm:text-sm ${o?"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:gg(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(J,{variant:"outline",className:`text-xs ${hg(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:xg(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] ${o?"text-blue-600":"text-gray-900"}`,"data-testid":`${i}-user-name`,children:l}),e.jsx("span",{children:"•"}),e.jsx("span",{className:"whitespace-nowrap","data-testid":`${i}-timestamp`,children:pg(t.timestamp)})]})]}),e.jsx(mt,{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 yg({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:o,currentUserId:l,currentUserDisplayName:c,currentUserEmail:m}){return e.jsxs(W,{className:"lg:col-span-1 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden",style:{height:"100%"},"data-testid":"recent-activity-section",children:[e.jsx(Q,{className:"pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-blue-100 rounded-lg",children:e.jsx(Bt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(ee,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(le,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(I,{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(Ot,{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(q,{className:"overflow-y-auto flex-1 p-4",style:{maxHeight:a.totalPages>1?"calc(100% - 140px)":"calc(100% - 80px)"},children:e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-recent-activity",children:[e.jsx(Bt,{className:"w-10 h-10 sm:w-12 sm:h-12 mx-auto mb-2 text-gray-400"}),e.jsx("p",{className:"text-sm",children:"No recent activity"}),e.jsx("p",{className:"text-xs",children:"Activity will appear here once requests are processed"})]}):s.map(d=>e.jsx(fg,{activity:d,currentUserId:l,currentUserDisplayName:c,currentUserEmail:m,onNavigate:u=>o==null?void 0:o(`request/${u}`),testId:"dashboard-activity"},d.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(I,{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(mt,{className:"h-3 w-3 rotate-180"})}),sd(a.page,a.totalPages,3).map(d=>e.jsx(I,{variant:d===a.page?"default":"outline",size:"sm",onClick:()=>n(d),className:`h-7 w-7 p-0 text-xs ${d===a.page?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`activity-pagination-page-${d}`,children:d},d)),e.jsx(I,{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(mt,{className:"h-3 w-3"})})]})]})})]})}function vg({kpis:t,upcomingDeadlines:s,criticalRequests:a,departmentStats:r,dateRange:n,customStartDate:i,customEndDate:o,exportingDeptStats:l,onKPIClick:c,onExportDepartmentStats:m}){if(!t)return null;const d=()=>({dateRange:n,startDate:i,endDate:o});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(W,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(Q,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Bt,{className:"h-4 w-4 text-blue-600"})}),e.jsx(ee,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(q,{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(Nt,{}),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(u=>u.breachCount>0).length})]})]})]})})]}),e.jsxs(W,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(Q,{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(Ns,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ee,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(q,{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(Nt,{}),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(W,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(Q,{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(ep,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(le,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2 self-start sm:self-auto",onClick:()=>m(n,i,o),disabled:l,"data-testid":"export-dept-stats-button",children:[e.jsx(ts,{className:`w-3 h-3 sm:w-4 sm:h-4 ${l?"animate-pulse":""}`}),e.jsx("span",{className:"text-xs sm:text-sm",children:l?"Exporting...":"Export"})]})]})}),e.jsx(q,{children:e.jsx(ai,{width:"100%",height:400,children:e.jsxs(kh,{data:r,children:[e.jsx(wc,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Cc,{dataKey:"department",stroke:"#999",tick:u=>{const{x:h,y:x,payload:p}=u;return e.jsx("g",{transform:`translate(${h},${x})`,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({...d(),department:p.value})},children:p.value})})}}),e.jsx(Sc,{stroke:"#999",tick:{fontSize:11}}),e.jsx(ri,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Ac,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Br,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(Br,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(Br,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function bg({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(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(Q,{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(Ns,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ee,{className:"text-sm",children:"My Activity"})]})}),e.jsx(q,{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(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(Q,{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(Pe,{className:"h-4 w-4 text-purple-600"})}),e.jsx(ee,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(q,{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:Je(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(Nt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function jg({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(Q,{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(Qe,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(le,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(q,{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",o=i?"bg-red-50":"bg-blue-50",l=i?"bg-red-500":"bg-blue-500";return e.jsxs("div",{className:`${o} 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 ${l} 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: ",Je(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(ai,{width:"100%",height:300,children:e.jsxs(Rh,{children:[e.jsx(Ph,{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:o,percentage:l})=>{const c=Math.PI/180,m=i+35,d=a+m*Math.cos(-n*c),u=r+m*Math.sin(-n*c);return e.jsx("text",{x:d,y:u,fill:"#1f2937",textAnchor:d>a?"start":"end",dominantBaseline:"central",style:{fontSize:"14px",fontWeight:"600",pointerEvents:"none"},children:`${o}: ${l}%`})},outerRadius:90,fill:"#8884d8",dataKey:"value",onClick:a=>{a&&a.priority&&s&&s(`requests?priority=${a.priority}`)},style:{cursor:"pointer"},children:t.map((a,r)=>e.jsx(Dh,{fill:a.priority==="express"?"#ef4444":"#3b82f6",style:{cursor:"pointer"}},`cell-${r}`))}),e.jsx(ri,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"},formatter:(a,r,n)=>{var o;const i=((o=n.payload)==null?void 0:o.priority)||"";return[`${a} requests`,`Click for ${i}`]}})]})})})]})]})}function ba({currentPage:t,totalPages:s,itemsPerPage:a,totalRecords:r,onPageChange:n,loading:i=!1,itemLabel:o="items",testIdPrefix:l="pagination"}){const c=()=>{const u=[];let x=Math.max(1,t-Math.floor(2.5)),p=Math.min(s,x+5-1);p-x<4&&(x=Math.max(1,p-5+1));for(let f=x;f<=p;f++)u.push(f);return u},m=r>0?(t-1)*a+1:0,d=Math.min(t*a,r);return s<=1?e.jsx(W,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(q,{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":`${l}-info`,children:i?`Loading ${o}...`:r===0?`No ${o} found`:r===1?`Showing 1 ${o.slice(0,-1)}`:m===d?`Showing ${m} of ${r} ${o}`:`Showing ${m} to ${d} of ${r} ${o}`})})})}):e.jsx(W,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(q,{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":`${l}-info`,children:["Showing ",m," to ",d," of ",r," ",o]}),e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${l}-controls`,children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(t-1),disabled:t===1,className:"h-8 w-8 p-0","data-testid":`${l}-prev-btn`,"aria-label":"Previous page",children:e.jsx(mt,{className:"h-4 w-4 rotate-180"})}),t>3&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(1),className:"h-8 w-8 p-0","data-testid":`${l}-page-1`,children:"1"}),e.jsx("span",{className:"text-muted-foreground","data-testid":`${l}-ellipsis-start`,children:"..."})]}),c().map(u=>e.jsx(I,{variant:u===t?"default":"outline",size:"sm",onClick:()=>n(u),className:`h-8 w-8 p-0 ${u===t?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`${l}-page-${u}`,"aria-current":u===t?"page":void 0,children:u},u)),t<s-2&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground","data-testid":`${l}-ellipsis-end`,children:"..."}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${l}-page-${s}`,children:s})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(t+1),disabled:t===s,className:"h-8 w-8 p-0","data-testid":`${l}-next-btn`,"aria-label":"Next page",children:e.jsx(mt,{className:"h-4 w-4"})})]})]})})})}function Ng({breachedRequests:t,pagination:s,dateRange:a,customStartDate:r,customEndDate:n,onPageChange:i,onKPIClick:o,onNavigate:l}){if(t.length===0)return null;const c=()=>({dateRange:a,startDate:r,endDate:n});return e.jsxs(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(Q,{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(ee,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsx(le,{className:"text-xs sm:text-sm",children:"Requests that breached defined turnaround time"})]})]}),e.jsxs(J,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[t.length," ",t.length===1?"Breach":"Breaches"]})]})}),e.jsxs(q,{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",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",children:"Breach Time"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 min-w-[200px] max-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((m,d)=>{const u=m.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:()=>l==null?void 0:l(`request/${m.requestNumber}`),"data-testid":`breach-request-${m.requestNumber}`,children:m.requestNumber}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-900 max-w-xs truncate",title:m.title,children:m.title}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{m.department&&m.department!=="Unknown"&&o({...c(),department:m.department})},children:m.department||"Unknown"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:m.approverId?e.jsx("span",{className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{if(l){const h=new URLSearchParams;h.set("approver",m.approverId),h.set("approverType","current"),h.set("slaCompliance","breached"),l(`requests?${h.toString()}`)}},title:"Click to view all requests for this approver",children:m.approver||"N/A"}):m.approver||"N/A"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:m.currentLevel&&m.totalLevels?e.jsxs("span",{className:"font-medium",children:[m.currentLevel,"/",m.totalLevels]}):m.currentLevel?e.jsxs("span",{className:"font-medium",children:[m.currentLevel,"/—"]}):e.jsx("span",{className:"text-gray-400",children:"—"})}),e.jsx("td",{className:"py-3 px-4",children:e.jsx("span",{className:"bg-red-500 text-white px-2 py-1 rounded text-xs font-medium",children:dg(u)})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 min-w-[200px] max-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:m.breachReason||"TAT Exceeded"})})}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(J,{variant:"outline",className:`text-xs font-medium ${m.priority==="express"?"bg-orange-100 text-orange-800 border-orange-200":"bg-blue-100 text-blue-800 border-blue-200"}`,children:m.priority})})]},d)})})]})}),e.jsx("div",{className:"mt-4",children:e.jsx(ba,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function wg({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(Q,{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(qe,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(le,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(q,{children:[e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.map((i,o)=>{const l=Number(i.tatPercentageUsed)||0,c=Number(i.elapsedHours)||0,m=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(J,{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(J,{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 ${l>=80?"text-red-600":l>=50?"text-orange-600":"text-green-600"}`,children:[l.toFixed(0),"%"]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ds,{value:l,className:`h-1.5 sm:h-2 ${l>=80?"bg-red-100":l>=50?"bg-orange-100":"bg-green-100"}`}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[Je(c)," elapsed"]}),e.jsxs("span",{children:[Je(m)," left"]})]})]})]},o)})}),e.jsx("div",{className:"mt-4",children:e.jsx(ba,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function Cg({aiRemarkUtilization:t}){return t?e.jsxs(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(Q,{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(br,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(le,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(q,{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(ai,{width:"100%",height:250,children:e.jsxs(Eh,{data:t.monthlyTrends,children:[e.jsx(wc,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Cc,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(Sc,{stroke:"#999",tick:{fontSize:11}}),e.jsx(ri,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Ac,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(po,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(po,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function Sg({approverPerformance:t,pagination:s,dateRange:a,customStartDate:r,customEndDate:n,loading:i,exportingApproverPerformance:o,onPageChange:l,onExport:c,onNavigate:m}){return t.length===0?null:e.jsxs(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(Q,{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(Xe,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(le,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(I,{onClick:()=>c(a,r,n),disabled:o||i,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-approver-performance-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(q,{children:[e.jsx("div",{className:"space-y-3",children:t.map((d,u)=>{const h=d.tatCompliancePercent;return e.jsxs("div",{className:"border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{const x=new URLSearchParams;x.set("approverId",d.approverId),x.set("approverName",d.approverName),x.set("dateRange",a),a==="custom"&&r&&n&&(x.set("startDate",r.toISOString()),x.set("endDate",n.toISOString())),m==null||m(`/approver-performance?${x.toString()}`)},"data-testid":`approver-item-${d.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:u+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-gray-900 truncate",children:d.approverName}),e.jsxs("div",{className:"text-xs text-gray-500",children:[d.totalApproved," requests approved"]})]})]}),e.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium ${mg(h)} flex-shrink-0`,children:[h,"% 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:Je(d.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:d.pendingCount})})]})]})]},u)})}),e.jsx("div",{className:"mt-4",children:e.jsx(ba,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:l,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function Ag(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 Tg(t,s,a){const r=[{label:"New Request",icon:we,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"},{label:"View Pending",icon:Pe,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:aa,action:()=>a==null?void 0:a("settings"),color:"bg-slate-600 hover:bg-slate-700"}];return t&&r.splice(2,0,{label:"Reports",icon:Bt,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),r}function Eo({onNavigate:t,onNewRequest:s}){const{user:a}=Zt(),r=g.useMemo(()=>Rr(a),[a]),n=$x(),{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,handleDateRangeChange:m,handleApplyCustomDate:d,resetCustomDates:u,setCustomStartDate:h,setCustomEndDate:x,setShowCustomDatePicker:p}=n,f=Ux(),{activity:v,critical:j,deadlines:y,approver:w,updateActivityPagination:N,updateCriticalPagination:S,updateDeadlinesPagination:T,updateApproverPagination:F,handleActivityPageChange:R,handleCriticalPageChange:M,handleDeadlinesPageChange:b,handleApproverPageChange:A}=f,P=Bx({isAdmin:r,dateRange:i,customStartDate:o,customEndDate:l,onPaginationUpdate:{activity:N,critical:S,deadlines:T,approver:F}}),{kpis:B,recentActivity:E,criticalRequests:L,departmentStats:C,priorityDistribution:k,upcomingDeadlines:D,aiRemarkUtilization:z,approverPerformance:K,loading:Y,refreshing:de,fetchDashboardData:Z,fetchRecentActivities:je,fetchCriticalRequests:ve,fetchUpcomingDeadlines:U,fetchApproverPerformance:V}=P,te=Jx(),{exportingDeptStats:$,exportingApproverPerformance:G,handleExportDepartmentStats:ae,handleExportApproverPerformance:he}=te,be=g.useMemo(()=>lg(L),[L]),_e=g.useMemo(()=>cg(D),[D]),Oe=g.useCallback(()=>{Z(!0)},[i,o,l,Z]),Ue=g.useCallback(()=>{d(()=>{o&&l&&Z(!1)})},[o,l,d,Z]),tt=g.useCallback(Rt=>{R(Rt,je)},[R,je]),Be=g.useCallback(Rt=>{M(Rt,ve)},[M,ve]),kt=g.useCallback(Rt=>{b(Rt,U)},[b,U]),Le=g.useCallback(Rt=>{A(Rt,()=>V(Rt))},[A,V]);g.useEffect(()=>{i==="custom"?o&&l&&Z(!1):Z(!1)},[i,o,l]);const Ca=g.useMemo(()=>Tg(r,s,t),[r,s,t]),ws=g.useCallback(Rt=>{const Pt=Ag(Rt);t==null||t(Pt)},[t]);return Y?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(Ot,{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(Qx,{isAdmin:r,quickActions:Ca}),e.jsx(sg,{isAdmin:r,dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,refreshing:de,onDateRangeChange:m,onCustomStartDateChange:h,onCustomEndDateChange:x,onShowCustomDatePickerChange:p,onApplyCustomDate:Ue,onResetCustomDates:u,onRefresh:Oe}),r?e.jsx(ag,{kpis:B,priorityDistribution:k,dateRange:i,customStartDate:o,customEndDate:l,onKPIClick:ws}):e.jsx(rg,{kpis:B,criticalRequests:L,dateRange:i,customStartDate:o,customEndDate:l,onKPIClick:ws,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(ug,{isAdmin:r,breachedRequests:be,pagination:j,onPageChange:Be,onNavigate:t}),e.jsx(yg,{isAdmin:r,recentActivity:E,pagination:v,refreshing:de,onPageChange:tt,onRefresh:Oe,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),r&&B&&e.jsx(vg,{kpis:B,upcomingDeadlines:D,criticalRequests:L,departmentStats:C,dateRange:i,customStartDate:o,customEndDate:l,exportingDeptStats:$,onKPIClick:ws,onExportDepartmentStats:ae}),!r&&B&&e.jsx(bg,{kpis:B}),r&&k.length>0&&e.jsx(jg,{priorityDistribution:k,onNavigate:t}),r&&be.length>0&&e.jsx(Ng,{breachedRequests:be,pagination:j,dateRange:i,customStartDate:o,customEndDate:l,onPageChange:Be,onKPIClick:ws,onNavigate:t}),_e.length>0&&e.jsx(wg,{isAdmin:r,upcomingDeadlines:_e,pagination:y,onPageChange:kt,onNavigate:t}),r&&z&&e.jsx(Cg,{aiRemarkUtilization:z}),r&&K.length>0&&e.jsx(Sg,{approverPerformance:K,pagination:w,dateRange:i,customStartDate:o,customEndDate:l,loading:Y,exportingApproverPerformance:G,onPageChange:Le,onExport:he,onNavigate:t})]})}function Yr(){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 kg(t){var l;const s=t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",a=Array.from({length:t.approverCount||1},(c,m)=>{const d=m,u=t.approvers[d]||{},h=d+1,x=u.tat??"";let p=0;typeof x=="number"&&(p=u.tatType==="days"?x*24:x);const f=u.email||"",v=u.name&&u.name.trim()||f.split("@")[0]||`Approver ${h}`;return{levelNumber:h,levelName:`Level ${h}`,approverId:Yr(),approverEmail:f,approverName:v,tatHours:p>0?p:24,isFinalApprover:h===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:Yr(),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:Yr(),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},i=await oe.post("/workflows",n),o=((l=i.data)==null?void 0:l.data)||i.data;return{id:o.id||o.workflowId||""}}async function ad(t,s,a="SUPPORTING"){var m;const r=d=>typeof d=="string"&&/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/.test(d.trim()),n={templateType:t.templateType,title:t.title,description:t.description,priority:t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",approvalLevels:Array.from({length:t.approverCount||1},(d,u)=>{const h=t.approvers[u]||{},x=typeof h.tat=="number"?h.tat:0,p=(h.userId||"").trim();if(!r(p))throw new Error(`Invalid approverId for level ${u+1}. Please pick an approver via @ search.`);return{levelNumber:u+1,levelName:`Level ${u+1}`,approverId:p,approverEmail:h.email||"",approverName:h.name||(h.email?h.email.split("@")[0]:`Approver ${u+1}`),tatHours:h.tatType==="days"?x*24:x||24,isFinalApprover:u+1===(t.approverCount||1)}})},i=t.participants;Array.isArray(i)&&i.length&&(n.participants=i);const o=new FormData;o.append("payload",JSON.stringify(n)),o.append("category",a),s.forEach(d=>o.append("files",d));const l=await oe.post("/workflows/multipart",o,{headers:{"Content-Type":"multipart/form-data"}}),c=((m=l.data)==null?void 0:m.data)||l.data;return{id:c==null?void 0:c.requestId}}async function Rg(t={}){var n;const{page:s=1,limit:a=20}=t,r=await oe.get("/workflows",{params:{page:s,limit:a}});return((n=r.data)==null?void 0:n.data)||r.data}async function Pg(t={}){var l,c,m,d,u;const{page:s=1,limit:a=20,search:r,status:n,priority:i}=t,o=await oe.get("/workflows/my",{params:{page:s,limit:a,search:r,status:n,priority:i}});return{data:((c=(l=o.data)==null?void 0:l.data)==null?void 0:c.data)||((m=o.data)==null?void 0:m.data)||[],pagination:((u=(d=o.data)==null?void 0:d.data)==null?void 0:u.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Dg(t={}){var m,d,u,h,x;const{page:s=1,limit:a=20,search:r,status:n,priority:i,sortBy:o,sortOrder:l}=t,c=await oe.get("/workflows/open-for-me",{params:{page:s,limit:a,search:r,status:n,priority:i,sortBy:o,sortOrder:l}});return{data:((d=(m=c.data)==null?void 0:m.data)==null?void 0:d.data)||((u=c.data)==null?void 0:u.data)||[],pagination:((x=(h=c.data)==null?void 0:h.data)==null?void 0:x.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Eg(t={}){var m,d,u,h,x;const{page:s=1,limit:a=20,search:r,status:n,priority:i,sortBy:o,sortOrder:l}=t,c=await oe.get("/workflows/closed-by-me",{params:{page:s,limit:a,search:r,status:n,priority:i,sortBy:o,sortOrder:l}});return{data:((d=(m=c.data)==null?void 0:m.data)==null?void 0:d.data)||((u=c.data)==null?void 0:u.data)||[],pagination:((x=(h=c.data)==null?void 0:h.data)==null?void 0:x.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Ks(t){var a;const s=await oe.get(`/workflows/${t}/details`);return((a=s.data)==null?void 0:a.data)||s.data}async function ua(t){var a;const s=await oe.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function rd(t,s,a=[]){var i;const r=new FormData;r.append("payload",JSON.stringify(s||{})),a.forEach(o=>r.append("files",o));const n=await oe.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 nd(t,s,a,r){var i;const n=await oe.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 Mg(t,s,a){var n;const r=await oe.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function id(t,s){var r;const a=await oe.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}function Ig(t){return`https://re-workflow-nt-api-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function od(t){return`https://re-workflow-nt-api-dev.siplsolutions.com/api/v1/workflows/documents/${t}/preview`}async function Mn(t){var n;const s="https://re-workflow-nt-api-dev.siplsolutions.com",a=localStorage.getItem("accessToken"),r=`${s}/api/v1/workflows/documents/${t}/download`;try{const i=await fetch(r,{headers:{Authorization:`Bearer ${a}`}});if(!i.ok){const h=await i.text();throw new Error(`Download failed: ${i.status} - ${h}`)}const o=await i.blob(),l=window.URL.createObjectURL(o),c=i.headers.get("Content-Disposition"),d=((n=c==null?void 0:c.split("filename=")[1])==null?void 0:n.replace(/"/g,""))||"download",u=document.createElement("a");u.href=l,u.download=d,document.body.appendChild(u),u.click(),document.body.removeChild(u),window.URL.revokeObjectURL(l)}catch(i){throw console.error("[Download] Failed:",i),i}}async function Mo(t){var n;const s="https://re-workflow-nt-api-dev.siplsolutions.com",a=localStorage.getItem("accessToken"),r=`${s}/api/v1/workflows/work-notes/attachments/${t}/download`;try{const i=await fetch(r,{headers:{Authorization:`Bearer ${a}`}});if(!i.ok){const h=await i.text();throw new Error(`Download failed: ${i.status} - ${h}`)}const o=await i.blob(),l=window.URL.createObjectURL(o),c=i.headers.get("Content-Disposition"),d=((n=c==null?void 0:c.split("filename=")[1])==null?void 0:n.replace(/"/g,""))||"download",u=document.createElement("a");u.href=l,u.download=d,document.body.appendChild(u),u.click(),document.body.removeChild(u),window.URL.revokeObjectURL(l)}catch(i){throw console.error("[Download] Failed:",i),i}}const Gt={createWorkflowFromForm:kg,createWorkflowMultipart:ad,listWorkflows:Rg,listMyWorkflows:Pg,listOpenForMe:Dg,listClosedByMe:Eg,submitWorkflow:ld,getWorkflowDetails:Ks,getWorkNotes:ua,createWorkNoteMultipart:rd};async function ld(t){var a;const s=await oe.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function Lg(t,s){var r;const a=await oe.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function Fg(t,s,a,r){var l;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 o=await oe.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((l=o.data)==null?void 0:l.data)||o.data}async function _g(t,s,a){var n;const r=await oe.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function Og(t,s,a,r){var i;const n=await oe.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 $g(t,s){const a=await oe.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}function qt(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 cd(t){return qt(t,{includeTime:!1,format:"short"})}function ms(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()],o=a.getFullYear();if(s){const l=a.getHours(),c=l%12||12,m=String(a.getMinutes()).padStart(2,"0"),d=String(a.getSeconds()).padStart(2,"0"),u=l>=12?"PM":"AM";return`${r} ${i} ${o}, ${c}:${m}:${d} ${u}`}return`${r} ${i} ${o}`}catch(a){return console.error("Error formatting date:",a),String(t)}}const Ug=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:is,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Qe,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Qe,iconColor:"text-gray-600"}}},Vg=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Pe,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Re,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:et,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:xe,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600",label:t}}};function Bg({onViewRequest:t}){const[s]=Tr(),[a,r]=g.useState(s.get("search")||""),[n,i]=g.useState(s.get("priority")||"all"),[o,l]=g.useState(s.get("status")||"all"),[c,m]=g.useState(s.get("sortBy")||"created"),[d,u]=g.useState(s.get("sortOrder")||"desc"),[h,x]=g.useState([]),[p,f]=g.useState(!1),[v,j]=g.useState(!1),[y,w]=g.useState(1),[N,S]=g.useState(1),[T,F]=g.useState(0),[R]=g.useState(10),M=g.useCallback(async(k=1,D)=>{try{k===1&&(f(!0),x([]));const z=await Gt.listOpenForMe({page:k,limit:R,search:D==null?void 0:D.search,status:D==null?void 0:D.status,priority:D==null?void 0:D.priority,sortBy:D==null?void 0:D.sortBy,sortOrder:D==null?void 0:D.sortOrder}),K=Array.isArray(z==null?void 0:z.data)?z.data:[],Y=z==null?void 0:z.pagination;Y&&(w(Y.page||1),S(Y.totalPages||1),F(Y.total||0));const de=K.map(Z=>{var ve,U,V,te;const je=Z.submittedAt||Z.submitted_at||Z.createdAt||Z.created_at;return{id:Z.requestNumber||Z.request_number||Z.requestId,requestId:Z.requestId,displayId:Z.requestNumber||Z.request_number||Z.requestId,title:Z.title,description:Z.description,status:(Z.status||"").toString().toLowerCase().replace("_","-"),priority:(Z.priority||"").toString().toLowerCase(),initiator:{name:((ve=Z.initiator)==null?void 0:ve.displayName)||((U=Z.initiator)==null?void 0:U.email)||"—",avatar:(((V=Z.initiator)==null?void 0:V.displayName)||((te=Z.initiator)==null?void 0:te.email)||"NA").split(" ").map($=>$[0]).join("").slice(0,2).toUpperCase()},currentApprover:Z.currentApprover?{name:Z.currentApprover.name||Z.currentApprover.email||"—",avatar:(Z.currentApprover.name||Z.currentApprover.email||"CA").split(" ").map($=>$[0]).join("").slice(0,2).toUpperCase(),sla:Z.currentApprover.sla}:void 0,createdAt:je||"—",approvalStep:Z.currentLevel?`Step ${Z.currentLevel} of ${Z.totalLevels||"?"}`:void 0,department:Z.department,currentLevelSLA:Z.currentLevelSLA}});x(de)}finally{f(!1),j(!1)}},[R]),b=()=>{j(!0),M(y,{search:a||void 0,status:o!=="all"?o:void 0,priority:n!=="all"?n:void 0,sortBy:c,sortOrder:d})},A=k=>{k>=1&&k<=N&&(w(k),M(k,{search:a||void 0,status:o!=="all"?o:void 0,priority:n!=="all"?n:void 0,sortBy:c,sortOrder:d}))},P=()=>{const k=[];let z=Math.max(1,y-Math.floor(2.5)),K=Math.min(N,z+5-1);K-z<4&&(z=Math.max(1,K-5+1));for(let Y=z;Y<=K;Y++)k.push(Y);return k},B=g.useRef(!0);g.useEffect(()=>{B.current&&(B.current=!1,M(1,{search:a||void 0,status:o!=="all"?o:void 0,priority:n!=="all"?n:void 0,sortBy:c,sortOrder:d}))},[]),g.useEffect(()=>{if(B.current)return;const k=setTimeout(()=>{w(1),M(1,{search:a||void 0,status:o!=="all"?o:void 0,priority:n!=="all"?n:void 0,sortBy:c,sortOrder:d})},a?500:0);return()=>clearTimeout(k)},[a,o,n,c,d,M]);const E=h,L=()=>{r(""),i("all"),l("all")},C=[a,n!=="all"?n:null,o!=="all"?o:null].filter(Boolean).length;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(we,{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(J,{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:[p?"Loading…":`${T||h.length} open`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:b,disabled:v,children:[e.jsx(Ot,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${v?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:v?"Refreshing...":"Refresh"})]})]})]}),e.jsxs(W,{className:"shadow-lg border-0",children:[e.jsx(Q,{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(jr,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(le,{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(I,{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(jt,{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(q,{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(ns,{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(me,{placeholder:"Search requests, IDs...",value:a,onChange:k=>r(k.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(Se,{value:n,onValueChange:i,children:[e.jsx(Te,{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(Ae,{placeholder:"All Priorities"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Priorities"}),e.jsx(H,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(H,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qe,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Se,{value:o,onValueChange:l,children:[e.jsx(Te,{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(Ae,{placeholder:"All Statuses"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Statuses"}),e.jsx(H,{value:"pending",children:"Pending (In Approval)"}),e.jsx(H,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Se,{value:c,onValueChange:k=>m(k),children:[e.jsx(Te,{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(Ae,{placeholder:"Sort by"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"due",children:"Due Date"}),e.jsx(H,{value:"created",children:"Date Created"}),e.jsx(H,{value:"priority",children:"Priority"}),e.jsx(H,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>u(d==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:d==="asc"?e.jsx(Ic,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Lc,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]}),e.jsx("div",{className:"space-y-3",children:E.map(k=>{const D=Ug(k.priority),z=Vg(k.status);return e.jsx(W,{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(k.id,k.title),children:e.jsx(q,{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 ${D.color} border shadow-sm`,children:e.jsx(D.icon,{className:`w-5 h-5 ${D.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:k.displayId||k.id}),e.jsxs(J,{variant:"outline",className:`${z.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(z.icon,{className:"w-3.5 h-3.5 mr-1"}),z.label||k.status]}),k.department&&e.jsx(J,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:k.department}),e.jsx(J,{variant:"outline",className:`${D.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:k.priority})]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:k.title}),k.currentLevelSLA&&e.jsxs("div",{className:`p-2 rounded-md ${k.currentLevelSLA.status==="breached"?"bg-red-50 border border-red-200":k.currentLevelSLA.status==="critical"?"bg-orange-50 border border-orange-200":k.currentLevelSLA.status==="approaching"?"bg-yellow-50 border border-yellow-200":"bg-green-50 border border-green-200"}`,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:[e.jsx(Pe,{className:"w-3.5 h-3.5 text-gray-600"}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",k.currentLevelSLA.percentageUsed,"%"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:k.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${k.currentLevelSLA.status==="breached"?"text-red-600":k.currentLevelSLA.status==="critical"?"text-orange-600":"text-gray-700"}`,children:[k.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(ds,{value:k.currentLevelSLA.percentageUsed,className:`h-1.5 ${k.currentLevelSLA.status==="breached"?"[&>div]:bg-red-600":k.currentLevelSLA.status==="critical"?"[&>div]:bg-orange-600":k.currentLevelSLA.status==="approaching"?"[&>div]:bg-yellow-600":"[&>div]:bg-green-600"}`})]}),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(gt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ft,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:k.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:k.initiator.name})]}),k.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(gt,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(ft,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:k.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:k.currentApprover.name})]}),k.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Re,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:k.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(qe,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",k.createdAt!=="—"?ms(k.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(mt,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},k.id)})}),E.length===0&&e.jsx(W,{className:"shadow-lg border-0",children:e.jsxs(q,{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(we,{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:a||C>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),C>0&&e.jsx(I,{variant:"outline",className:"mt-4",onClick:L,children:"Clear all filters"})]})}),N>1&&!p&&e.jsx(W,{className:"shadow-md",children:e.jsx(q,{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 ",(y-1)*R+1," to ",Math.min(y*R,T)," of ",T," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>A(y-1),disabled:y===1,className:"h-8 w-8 p-0",children:e.jsx(mt,{className:"h-4 w-4 rotate-180"})}),y>3&&N>5&&e.jsxs(e.Fragment,{children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>A(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),P().map(k=>e.jsx(I,{variant:k===y?"default":"outline",size:"sm",onClick:()=>A(k),className:`h-8 w-8 p-0 ${k===y?"bg-re-green text-white hover:bg-re-green/90":""}`,children:k},k)),y<N-2&&N>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>A(N),className:"h-8 w-8 p-0",children:N})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>A(y+1),disabled:y===N,className:"h-8 w-8 p-0",children:e.jsx(mt,{className:"h-4 w-4"})})]})]})})})]})}function zg({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(we,{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(J,{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(I,{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(Ot,{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 Hg({searchTerm:t,priorityFilter:s,statusFilter:a,sortBy:r,sortOrder:n,activeFiltersCount:i,onSearchChange:o,onPriorityChange:l,onStatusChange:c,onSortByChange:m,onSortOrderChange:d,onClearFilters:u}){return e.jsxs(W,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(Q,{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(jr,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(le,{className:"text-xs sm:text-sm",children:i>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[i," filter",i>1?"s":""," active"]})})]})]}),i>0&&e.jsxs(I,{variant:"ghost",size:"sm",onClick:u,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(jt,{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(q,{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(ns,{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(me,{placeholder:"Search requests, IDs...",value:t,onChange:h=>o(h.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(Se,{value:s,onValueChange:l,children:[e.jsx(Te,{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(Ae,{placeholder:"All Priorities"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Priorities"}),e.jsx(H,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(H,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qe,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Se,{value:a,onValueChange:c,children:[e.jsx(Te,{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(Ae,{placeholder:"All Statuses"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Statuses"}),e.jsx(H,{value:"closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"Closed"})]})}),e.jsx(H,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(et,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Rejected"})]})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Se,{value:r,onValueChange:h=>m(h),children:[e.jsx(Te,{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(Ae,{placeholder:"Sort by"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"due",children:"Due Date"}),e.jsx(H,{value:"created",children:"Date Created"}),e.jsx(H,{value:"priority",children:"Priority"})]})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:d,className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11","data-testid":"closed-requests-sort-order",children:n==="asc"?e.jsx(Ic,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Lc,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function Wg(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:is,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Qe,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Qe,iconColor:"text-gray-600"}}}function qg(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:xe,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:et,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600",label:t,description:""}}}function Kg({request:t,onViewRequest:s}){const a=Wg(t.priority),r=qg(t.status),n=a.icon,i=r.icon;return e.jsx(W,{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(q,{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(J,{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(J,{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(J,{variant:"outline",className:`${a.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:t.priority})]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:t.title}),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(gt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ft,{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(xe,{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(qe,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?ms(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(xe,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",ms(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(mt,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function Gg({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(Kg,{request:r,onViewRequest:a},r.id))})}function Yg({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(W,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(q,{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(we,{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(I,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function Zg(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 o=n;o<=i;o++)a.push(o);return a}function Xg({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const o=Zg(a,r);return e.jsx(W,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(q,{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(I,{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(mt,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(I,{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:"..."})]}),o.map(l=>e.jsx(I,{variant:l===a?"default":"outline",size:"sm",onClick:()=>s(l),className:`h-8 w-8 p-0 ${l===a?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`closed-requests-pagination-page-${l}`,children:l},l)),a<r-2&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(I,{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(mt,{className:"h-4 w-4"})})]})]})})})}function Jg(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}}function Qg(t){return t.map(Jg)}function ef({itemsPerPage:t=10,initialFilters:s}={}){const[a,r]=g.useState([]),[n,i]=g.useState(!1),[o,l]=g.useState(!1),[c,m]=g.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=g.useRef(!0),u=g.useCallback(async(x=1,p)=>{try{x===1&&(i(!0),r([]));let f=p==null?void 0:p.status;if(f==="approved"){r([]),m({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),i(!1),l(!1);return}const v=await Gt.listClosedByMe({page:x,limit:t,search:p==null?void 0:p.search,status:f&&f!=="all"?f:void 0,priority:p==null?void 0:p.priority,sortBy:p==null?void 0:p.sortBy,sortOrder:p==null?void 0:p.sortOrder}),j=Array.isArray(v==null?void 0:v.data)?v.data:[],w=Qg(j).filter(S=>S.status==="rejected"||S.status==="closed");r(w);const N=v==null?void 0:v.pagination;N&&m({currentPage:N.page||1,totalPages:N.totalPages||1,totalRecords:N.total||0,itemsPerPage:t})}catch(f){console.error("[ClosedRequests] Error fetching requests:",f),r([])}finally{i(!1),l(!1)}},[t]);g.useEffect(()=>{d.current&&(u(1,s),d.current=!1)},[]);const h=g.useCallback(x=>{l(!0),u(c.currentPage,x)},[u,c.currentPage]);return{requests:a,loading:n,refreshing:o,pagination:c,fetchRequests:u,handleRefresh:h}}function tf({onFiltersChange:t,debounceMs:s=500}={}){const[a,r]=g.useState(""),[n,i]=g.useState("all"),[o,l]=g.useState("all"),[c,m]=g.useState("due"),[d,u]=g.useState("desc"),h=g.useRef(null),x=g.useRef(!0),p=g.useCallback(()=>({search:a,status:o,priority:n,sortBy:c,sortOrder:d}),[a,o,n,c,d]);g.useEffect(()=>{if(x.current){x.current=!1;return}h.current&&clearTimeout(h.current);const j=setTimeout(()=>{t&&t(p())},a?s:0);return h.current=j,()=>{h.current&&clearTimeout(h.current)}},[a,o,n,c,d,t,p,s]);const f=g.useCallback(()=>{r(""),i("all"),l("all")},[]),v=[a,n!=="all"?n:null,o!=="all"?o:null].filter(Boolean).length;return{searchTerm:a,priorityFilter:n,statusFilter:o,sortBy:c,sortOrder:d,setSearchTerm:r,setPriorityFilter:i,setStatusFilter:l,setSortBy:m,setSortOrder:u,clearFilters:f,activeFiltersCount:v,getFilters:p}}function sf({onViewRequest:t}){const s=ef({itemsPerPage:10}),a=g.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=tf({onFiltersChange:g.useCallback(o=>{a.current(1,{search:o.search||void 0,status:o.status!=="all"?o.status:void 0,priority:o.priority!=="all"?o.priority:void 0,sortBy:o.sortBy,sortOrder:o.sortOrder})},[])}),n=g.useCallback(o=>{o>=1&&o<=s.pagination.totalPages&&s.fetchRequests(o,{search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:r.priorityFilter!=="all"?r.priorityFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder})},[s,r]),i=g.useCallback(()=>{s.handleRefresh({search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:r.priorityFilter!=="all"?r.priorityFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder})},[s,r]);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(zg,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:i}),e.jsx(Hg,{searchTerm:r.searchTerm,priorityFilter:r.priorityFilter,statusFilter:r.statusFilter,sortBy:r.sortBy,sortOrder:r.sortOrder,activeFiltersCount:r.activeFiltersCount,onSearchChange:r.setSearchTerm,onPriorityChange:r.setPriorityFilter,onStatusChange:r.setStatusFilter,onSortByChange:r.setSortBy,onSortOrderChange:()=>r.setSortOrder(r.sortOrder==="asc"?"desc":"asc"),onClearFilters:r.clearFilters}),e.jsx(Gg,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(Yg,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(Xg,{pagination:s.pagination,onPageChange:n})]})}function Dr({className:t,...s}){return e.jsx(ah,{"data-slot":"tabs",className:ce("flex flex-col gap-2",t),...s})}function Er({className:t,...s}){return e.jsx(rh,{"data-slot":"tabs-list",className:ce("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function lt({className:t,...s}){return e.jsx(nh,{"data-slot":"tabs-trigger",className:ce("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 ct({className:t,...s}){return e.jsx(ih,{"data-slot":"tabs-content",className:ce("flex-1 outline-none",t),...s})}const dd={"RE-REQ-2024-001":{id:"RE-REQ-2024-001",title:"Himalayan 450 Launch Campaign - Digital Media Blitz",description:`Comprehensive digital marketing campaign for Himalayan 450 adventure motorcycle launch. Includes social media campaigns, influencer partnerships, performance marketing, content creation, and digital advertising across platforms. Target: Reach 10M adventure enthusiasts across India.
Equipment Specifications:
• 10x MacBook Pro 16-inch (M2 Pro chip)
• 5x Professional Camera Kits (Canon EOS R5)
• Video Editing Workstations
• Social Media Management Tools`,category:"Marketing & Campaigns",subcategory:"Digital Marketing",status:"pending",priority:"express",amount:"₹3,75,00,000",slaProgress:65,slaRemaining:"8 hours 45 minutes",slaEndDate:"Oct 9, 2024 5:00 PM",currentStep:1,totalSteps:3,template:"custom",initiator:{name:"Priya Sharma",role:"Senior Digital Marketing Manager",department:"Marketing",email:"priya.sharma@royalenfield.com",phone:"+91 98765 43210",avatar:"PS"},department:"Marketing",createdAt:"Oct 6, 2024 10:30 AM",updatedAt:"Oct 7, 2024 2:15 PM",dueDate:"2024-10-09T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Rajesh Kumar",role:"Marketing Director - India",status:"pending",tatHours:24,elapsedHours:22,assignedAt:"2024-10-06T10:30:00Z",comment:null,timestamp:null},{step:2,approver:"Amit Desai",role:"VP Product Marketing",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Himalayan_450_Digital_Strategy.pdf",size:"5.2 MB",type:"PDF",uploadedBy:"Priya Sharma",uploadedAt:"Oct 6, 2024 10:45 AM"},{name:"Budget_Breakdown_Q4_2024.xlsx",size:"980 KB",type:"Excel",uploadedBy:"Priya Sharma",uploadedAt:"Oct 6, 2024 11:15 AM"},{name:"Influencer_Partnership_List.xlsx",size:"450 KB",type:"Excel",uploadedBy:"Marketing Team",uploadedAt:"Oct 6, 2024 2:30 PM"},{name:"Creative_Campaign_Assets.zip",size:"125 MB",type:"ZIP",uploadedBy:"Creative Team",uploadedAt:"Oct 6, 2024 4:15 PM"}],spectators:[{name:"Sarah Khan",role:"Brand Strategy Lead",avatar:"SK"},{name:"Finance Team",role:"Budget Approval",avatar:"FT"}],auditTrail:[{type:"created",action:"Request Created",details:"New digital marketing campaign request submitted",user:"Priya Sharma",timestamp:"Oct 6, 2024 10:30 AM"},{type:"assignment",action:"Assigned to Rajesh Kumar",details:"Forwarded to Marketing Director for review",user:"System",timestamp:"Oct 6, 2024 10:31 AM"},{type:"comment",action:"Work Note Added",details:"Reviewed budget allocation and target metrics",user:"Rajesh Kumar",timestamp:"Oct 7, 2024 2:15 PM"},{type:"reminder",action:"SLA Reminder",details:"TAT approaching - 8 hours remaining",user:"System",timestamp:"Oct 7, 2024 8:15 AM"}],tags:["digital-marketing","launch-campaign","himalayan-450","high-priority"]},"RE-REQ-2024-002":{id:"RE-REQ-2024-002",title:"New Laptop Procurement - Design Team Expansion",description:"Purchase of 10 high-performance laptops for the newly expanded Product Design team. Required specifications: Latest generation processor, 32GB RAM, dedicated graphics card for 3D modeling and rendering work.",category:"IT & Infrastructure",subcategory:"Hardware Procurement",status:"in-review",priority:"standard",amount:"₹12,50,000",slaProgress:45,slaRemaining:"2 days 8 hours",slaEndDate:"Oct 11, 2024 5:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Vikram Singh",role:"Head - IT Operations",department:"Information Technology",email:"vikram.singh@royalenfield.com",phone:"+91 98765 43221",avatar:"VS"},department:"Information Technology",createdAt:"Oct 5, 2024 9:15 AM",updatedAt:"Oct 7, 2024 3:45 PM",dueDate:"2024-10-11T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Meera Patel",role:"IT Manager",status:"approved",tatHours:24,actualHours:18,assignedAt:"2024-10-05T09:15:00Z",comment:"Technical specifications verified. Hardware meets design team requirements.",timestamp:"2024-10-06T03:15:00Z"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"in-review",tatHours:48,elapsedHours:32,assignedAt:"2024-10-06T03:15:00Z",comment:null,timestamp:null},{step:3,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Laptop_Specifications.pdf",size:"850 KB",type:"PDF",uploadedBy:"Vikram Singh",uploadedAt:"Oct 5, 2024 9:20 AM"},{name:"Vendor_Quotations.xlsx",size:"1.2 MB",type:"Excel",uploadedBy:"Procurement Team",uploadedAt:"Oct 5, 2024 11:45 AM"},{name:"Team_Expansion_Plan.pdf",size:"620 KB",type:"PDF",uploadedBy:"Design Team",uploadedAt:"Oct 5, 2024 2:30 PM"}],spectators:[{name:"Design Team Lead",role:"End Users",avatar:"DT"},{name:"Procurement Team",role:"Vendor Management",avatar:"PT"}],auditTrail:[{type:"created",action:"Request Created",details:"Laptop procurement request for design team",user:"Vikram Singh",timestamp:"Oct 5, 2024 9:15 AM"},{type:"assignment",action:"Assigned to Meera Patel",details:"IT Manager to verify specifications",user:"System",timestamp:"Oct 5, 2024 9:16 AM"},{type:"approval",action:"Approved by Meera Patel",details:"Technical specifications approved",user:"Meera Patel",timestamp:"Oct 6, 2024 3:15 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance for budget approval",user:"System",timestamp:"Oct 6, 2024 3:15 AM"}],tags:["hardware","procurement","design-team","laptops"]},"RE-REQ-2024-003":{id:"RE-REQ-2024-003",title:"Annual Service Center Expansion - Western Region",description:"Proposal for opening 15 new authorized service centers across tier-2 cities in Western region. Includes infrastructure setup, technician training, spare parts inventory, and marketing support. Expected to improve service accessibility by 35% in the target region.",category:"Operations & Expansion",subcategory:"Service Network",status:"pending",priority:"standard",amount:"₹8,75,00,000",slaProgress:78,slaRemaining:"1 day 4 hours",slaEndDate:"Oct 10, 2024 5:00 PM",currentStep:1,totalSteps:4,template:"custom",initiator:{name:"Sanjay Reddy",role:"Regional Service Manager - West",department:"After Sales Service",email:"sanjay.reddy@royalenfield.com",phone:"+91 98765 43232",avatar:"SR"},department:"After Sales Service",createdAt:"Oct 3, 2024 8:45 AM",updatedAt:"Oct 6, 2024 5:45 PM",dueDate:"2024-10-10T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Ramesh Kulkarni",role:"Head - After Sales Service",status:"pending",tatHours:72,elapsedHours:85,assignedAt:"2024-10-03T08:45:00Z",comment:null,timestamp:null},{step:2,approver:"Finance Team",role:"Budget Allocation",status:"waiting",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Legal Team",role:"Compliance Review",status:"waiting",tatHours:120,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Western_Region_Expansion_Plan.pdf",size:"7.5 MB",type:"PDF",uploadedBy:"Sanjay Reddy",uploadedAt:"Oct 3, 2024 9:00 AM"},{name:"Service_Center_Requirements.xlsx",size:"2.8 MB",type:"Excel",uploadedBy:"Planning Team",uploadedAt:"Oct 3, 2024 11:30 AM"},{name:"Customer_Demand_Analysis.pptx",size:"4.2 MB",type:"PowerPoint",uploadedBy:"Analytics Team",uploadedAt:"Oct 4, 2024 2:15 PM"},{name:"ROI_Projections_Service_Network.xlsx",size:"1.9 MB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Oct 5, 2024 10:45 AM"}],spectators:[{name:"Regional Managers",role:"Service Operations",avatar:"RM"},{name:"Training Team",role:"Technician Development",avatar:"TT"}],auditTrail:[{type:"created",action:"Request Created",details:"Service center expansion proposal submitted",user:"Sanjay Reddy",timestamp:"Oct 3, 2024 8:45 AM"},{type:"assignment",action:"Assigned to Ramesh Kulkarni",details:"Forwarded to Head of After Sales Service",user:"System",timestamp:"Oct 3, 2024 8:46 AM"},{type:"reminder",action:"Reminder Sent",details:"TAT breach reminder sent to approver",user:"System",timestamp:"Oct 6, 2024 5:45 PM"},{type:"updated",action:"Additional Documents",details:"ROI projections added by finance team",user:"Finance Team",timestamp:"Oct 5, 2024 10:45 AM"}],tags:["service-expansion","western-region","tier2-cities","overdue"]},"RE-REQ-2024-004":{id:"RE-REQ-2024-004",title:"Employee Training Program - Advanced Motorcycle Mechanics",description:"Comprehensive training program for 50 service center technicians covering advanced diagnostics, electrical systems, fuel injection troubleshooting, and customer service excellence. Program duration: 3 weeks. Includes certification upon completion.",category:"Human Resources",subcategory:"Training & Development",status:"approved",priority:"standard",amount:"₹18,50,000",slaProgress:100,slaRemaining:"Completed",slaEndDate:"Oct 5, 2024 5:00 PM",currentStep:3,totalSteps:3,template:"custom",initiator:{name:"Kavita Menon",role:"Training Manager",department:"Human Resources",email:"kavita.menon@royalenfield.com",phone:"+91 98765 43243",avatar:"KM"},department:"Human Resources",createdAt:"Sep 28, 2024 11:00 AM",updatedAt:"Oct 5, 2024 4:30 PM",dueDate:"2024-10-05T17:00:00Z",submittedDate:"2024-09-28T11:00:00Z",estimatedCompletion:"Oct 5, 2024",currentApprover:"Completed",approverLevel:"3 of 3",conclusionRemark:"All approvals completed. Training program scheduled for November 2024.",approvalFlow:[{step:1,approver:"Ramesh Kulkarni",role:"Head - After Sales Service",status:"approved",tatHours:48,actualHours:36,assignedAt:"2024-09-28T11:00:00Z",comment:"Excellent initiative. Training content approved.",timestamp:"Sep 29, 2024 11:00 PM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"approved",tatHours:72,actualHours:48,assignedAt:"2024-09-29T23:00:00Z",comment:"Budget approved. Cost per participant is reasonable.",timestamp:"Oct 1, 2024 11:00 PM"},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"approved",tatHours:96,actualHours:72,assignedAt:"2024-10-01T23:00:00Z",comment:"Final approval granted. Proceed with program execution.",timestamp:"Oct 5, 2024 4:30 PM"}],documents:[{name:"Training_Curriculum.pdf",size:"3.2 MB",type:"PDF",uploadedBy:"Kavita Menon",uploadedAt:"Sep 28, 2024 11:15 AM"},{name:"Trainer_Profiles.pdf",size:"1.8 MB",type:"PDF",uploadedBy:"HR Team",uploadedAt:"Sep 28, 2024 2:45 PM"},{name:"Budget_Training_Program.xlsx",size:"680 KB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Sep 29, 2024 10:30 AM"}],spectators:[{name:"Service Center Managers",role:"Participant Coordination",avatar:"SC"},{name:"Quality Assurance",role:"Training Quality",avatar:"QA"}],auditTrail:[{type:"created",action:"Request Created",details:"Training program proposal submitted",user:"Kavita Menon",timestamp:"Sep 28, 2024 11:00 AM"},{type:"assignment",action:"Assigned to Ramesh Kulkarni",details:"Forwarded to After Sales Service Head",user:"System",timestamp:"Sep 28, 2024 11:01 AM"},{type:"approval",action:"Approved by Ramesh Kulkarni",details:"Level 1 approval completed",user:"Ramesh Kulkarni",timestamp:"Sep 29, 2024 11:00 PM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Sep 29, 2024 11:01 PM"},{type:"approval",action:"Approved by Anil Kapoor",details:"Budget approval completed",user:"Anil Kapoor",timestamp:"Oct 1, 2024 11:00 PM"},{type:"assignment",action:"Assigned to Deepika Sharma",details:"Forwarded to VP for final approval",user:"System",timestamp:"Oct 1, 2024 11:01 PM"},{type:"approval",action:"Approved by Deepika Sharma",details:"Final approval - Request completed",user:"Deepika Sharma",timestamp:"Oct 5, 2024 4:30 PM"},{type:"completed",action:"Request Completed",details:"All approvals obtained. Training scheduled.",user:"System",timestamp:"Oct 5, 2024 4:31 PM"}],tags:["training","technicians","approved","completed"]},"RE-REQ-2024-005":{id:"RE-REQ-2024-005",title:"Showroom Renovation - Chennai Flagship Store",description:"Complete renovation of Chennai flagship showroom including modern interior design, interactive display zones, customer lounge upgrade, motorcycle test ride facility, and digital experience center. Project timeline: 8 weeks.",category:"Infrastructure",subcategory:"Retail & Showroom",status:"rejected",priority:"standard",amount:"₹65,00,000",slaProgress:100,slaRemaining:"Rejected",slaEndDate:"Oct 4, 2024 5:00 PM",currentStep:2,totalSteps:4,template:"custom",initiator:{name:"Arjun Nair",role:"Showroom Manager - South",department:"Retail Operations",email:"arjun.nair@royalenfield.com",phone:"+91 98765 43254",avatar:"AN"},department:"Retail Operations",createdAt:"Oct 1, 2024 9:30 AM",updatedAt:"Oct 4, 2024 3:15 PM",dueDate:"2024-10-04T17:00:00Z",submittedDate:"2024-10-01T09:30:00Z",estimatedCompletion:"N/A",currentApprover:"Rejected by Anil Kapoor",approverLevel:"2 of 4",conclusionRemark:"Request rejected due to insufficient budget justification. Please revise with detailed ROI analysis.",approvalFlow:[{step:1,approver:"Suresh Iyer",role:"Regional Manager - South",status:"approved",tatHours:48,actualHours:24,assignedAt:"2024-10-01T09:30:00Z",comment:"Renovation is necessary. Current showroom needs upgrade.",timestamp:"Oct 2, 2024 9:30 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"rejected",tatHours:72,actualHours:48,assignedAt:"2024-10-02T09:30:00Z",comment:"Budget allocation not justified. Need detailed ROI analysis and comparison with alternative renovation options. Please revise and resubmit with comprehensive financial projections.",timestamp:"Oct 4, 2024 3:15 PM"},{step:3,approver:"Legal Team",role:"Compliance & Contracts",status:"cancelled",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Ramesh Kulkarni",role:"VP Operations",status:"cancelled",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Showroom_Renovation_Plan.pdf",size:"12.5 MB",type:"PDF",uploadedBy:"Arjun Nair",uploadedAt:"Oct 1, 2024 9:45 AM"},{name:"Interior_Design_Mockups.zip",size:"85 MB",type:"ZIP",uploadedBy:"Design Team",uploadedAt:"Oct 1, 2024 2:30 PM"},{name:"Contractor_Quotations.xlsx",size:"2.1 MB",type:"Excel",uploadedBy:"Procurement Team",uploadedAt:"Oct 2, 2024 11:15 AM"}],spectators:[{name:"Marketing Team",role:"Brand Experience",avatar:"MT"},{name:"Customer Experience",role:"Feedback & Analysis",avatar:"CX"}],auditTrail:[{type:"created",action:"Request Created",details:"Showroom renovation request submitted",user:"Arjun Nair",timestamp:"Oct 1, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Suresh Iyer",details:"Forwarded to Regional Manager",user:"System",timestamp:"Oct 1, 2024 9:31 AM"},{type:"approval",action:"Approved by Suresh Iyer",details:"Level 1 approval completed",user:"Suresh Iyer",timestamp:"Oct 2, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 2, 2024 9:31 AM"},{type:"rejection",action:"Rejected by Anil Kapoor",details:"Budget justification insufficient",user:"Anil Kapoor",timestamp:"Oct 4, 2024 3:15 PM"},{type:"completed",action:"Request Rejected",details:"Workflow terminated. Requires resubmission with revisions.",user:"System",timestamp:"Oct 4, 2024 3:16 PM"}],tags:["showroom","renovation","rejected","south-region"]},"RE-REQ-2024-006":{id:"RE-REQ-2024-006",title:"Spare Parts Inventory Optimization System",description:"Implementation of AI-powered inventory management system for spare parts across all service centers. Features include demand forecasting, automated reordering, stock level optimization, and real-time tracking. Expected to reduce inventory costs by 20% and improve part availability.",category:"Technology & Innovation",subcategory:"Software Implementation",status:"pending",priority:"express",amount:"₹42,00,000",slaProgress:35,slaRemaining:"1 day 16 hours",slaEndDate:"Oct 12, 2024 5:00 PM",currentStep:1,totalSteps:4,template:"custom",initiator:{name:"Rahul Deshmukh",role:"Head - Supply Chain Technology",department:"Supply Chain",email:"rahul.deshmukh@royalenfield.com",phone:"+91 98765 43265",avatar:"RD"},department:"Supply Chain",createdAt:"Oct 7, 2024 10:00 AM",updatedAt:"Oct 8, 2024 9:15 AM",dueDate:"2024-10-12T17:00:00Z",submittedDate:"2024-10-07T10:00:00Z",estimatedCompletion:"Oct 12, 2024",currentApprover:"Vikram Singh",approverLevel:"1 of 4",conclusionRemark:"",approvalFlow:[{step:1,approver:"Vikram Singh",role:"Head - IT Operations",status:"pending",tatHours:48,elapsedHours:23,assignedAt:"2024-10-07T10:00:00Z",comment:null,timestamp:null},{step:2,approver:"Supply Chain Director",role:"Operations Approval",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Anil Kapoor",role:"Finance Manager",status:"waiting",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"AI_Inventory_System_Proposal.pdf",size:"8.9 MB",type:"PDF",uploadedBy:"Rahul Deshmukh",uploadedAt:"Oct 7, 2024 10:15 AM"},{name:"Vendor_Comparison_Analysis.xlsx",size:"3.4 MB",type:"Excel",uploadedBy:"IT Procurement",uploadedAt:"Oct 7, 2024 2:45 PM"},{name:"Cost_Benefit_Analysis.pptx",size:"6.2 MB",type:"PowerPoint",uploadedBy:"Analytics Team",uploadedAt:"Oct 7, 2024 4:30 PM"},{name:"Implementation_Timeline.pdf",size:"1.5 MB",type:"PDF",uploadedBy:"Project Management",uploadedAt:"Oct 8, 2024 9:15 AM"}],spectators:[{name:"Service Center Network",role:"End Users",avatar:"SN"},{name:"Data Analytics Team",role:"System Integration",avatar:"DA"}],auditTrail:[{type:"created",action:"Request Created",details:"AI inventory system proposal submitted",user:"Rahul Deshmukh",timestamp:"Oct 7, 2024 10:00 AM"},{type:"assignment",action:"Assigned to Vikram Singh",details:"Forwarded to IT Operations Head",user:"System",timestamp:"Oct 7, 2024 10:01 AM"},{type:"updated",action:"Documents Added",details:"Implementation timeline document uploaded",user:"Project Management",timestamp:"Oct 8, 2024 9:15 AM"}],tags:["technology","ai","inventory","supply-chain","high-priority"]},"RE-REQ-2024-007":{id:"RE-REQ-2024-007",title:"Dealer Network Meeting - Q4 Business Review",description:"Quarterly business review meeting for all authorized dealers across India. Venue: Bangalore. Topics include Q3 performance review, Q4 targets, new model launches, marketing initiatives, service excellence programs, and dealer support policies. Expected attendance: 250 dealers.",category:"Events & Conferences",subcategory:"Dealer Meetings",status:"in-review",priority:"standard",amount:"₹28,50,000",slaProgress:58,slaRemaining:"1 day 12 hours",slaEndDate:"Oct 11, 2024 5:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Neha Kapoor",role:"Dealer Network Manager",department:"Sales & Distribution",email:"neha.kapoor@royalenfield.com",phone:"+91 98765 43276",avatar:"NK"},department:"Sales & Distribution",createdAt:"Oct 6, 2024 2:00 PM",updatedAt:"Oct 8, 2024 11:30 AM",dueDate:"2024-10-11T17:00:00Z",submittedDate:"2024-10-06T14:00:00Z",estimatedCompletion:"Oct 11, 2024",currentApprover:"Anil Kapoor",approverLevel:"2 of 3",conclusionRemark:"",approvalFlow:[{step:1,approver:"Suresh Mehta",role:"Sales Director",status:"approved",tatHours:48,actualHours:36,assignedAt:"2024-10-06T14:00:00Z",comment:"Dealer meeting approved. Agenda looks comprehensive.",timestamp:"Oct 8, 2024 2:00 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"in-review",tatHours:72,elapsedHours:33,assignedAt:"2024-10-08T02:00:00Z",comment:null,timestamp:null},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Q4_Dealer_Meeting_Agenda.pdf",size:"2.8 MB",type:"PDF",uploadedBy:"Neha Kapoor",uploadedAt:"Oct 6, 2024 2:15 PM"},{name:"Venue_Booking_Confirmation.pdf",size:"980 KB",type:"PDF",uploadedBy:"Events Team",uploadedAt:"Oct 6, 2024 4:45 PM"},{name:"Event_Budget_Breakdown.xlsx",size:"1.2 MB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Oct 7, 2024 10:30 AM"},{name:"Dealer_Invitations_List.xlsx",size:"580 KB",type:"Excel",uploadedBy:"Sales Team",uploadedAt:"Oct 7, 2024 3:15 PM"}],spectators:[{name:"Marketing Team",role:"Presentation Support",avatar:"MT"},{name:"Events Management",role:"Logistics Coordination",avatar:"EM"}],auditTrail:[{type:"created",action:"Request Created",details:"Dealer meeting proposal submitted",user:"Neha Kapoor",timestamp:"Oct 6, 2024 2:00 PM"},{type:"assignment",action:"Assigned to Suresh Mehta",details:"Forwarded to Sales Director",user:"System",timestamp:"Oct 6, 2024 2:01 PM"},{type:"approval",action:"Approved by Suresh Mehta",details:"Sales approval completed",user:"Suresh Mehta",timestamp:"Oct 8, 2024 2:00 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 8, 2024 2:01 AM"},{type:"updated",action:"Documents Added",details:"Dealer invitations list uploaded",user:"Sales Team",timestamp:"Oct 7, 2024 3:15 PM"}],tags:["dealer-meeting","q4-review","event","bangalore"]},"RE-REQ-2024-008":{id:"RE-REQ-2024-008",title:"Cybersecurity Infrastructure Upgrade",description:"Comprehensive upgrade of cybersecurity infrastructure including next-gen firewall, intrusion detection system, endpoint protection for 500+ devices, security information and event management (SIEM) system, and employee security awareness training. Critical for protecting customer data and business operations.",category:"IT & Infrastructure",subcategory:"Security & Compliance",status:"pending",priority:"urgent",amount:"₹52,00,000",slaProgress:82,slaRemaining:"4 hours 20 minutes",slaEndDate:"Oct 8, 2024 6:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Sameer Joshi",role:"Chief Information Security Officer",department:"Information Technology",email:"sameer.joshi@royalenfield.com",phone:"+91 98765 43287",avatar:"SJ"},department:"Information Technology",createdAt:"Oct 5, 2024 11:30 AM",updatedAt:"Oct 8, 2024 12:45 PM",dueDate:"2024-10-08T18:00:00Z",submittedDate:"2024-10-05T11:30:00Z",estimatedCompletion:"Oct 8, 2024",currentApprover:"Anil Kapoor",approverLevel:"2 of 3",conclusionRemark:"",approvalFlow:[{step:1,approver:"Vikram Singh",role:"Head - IT Operations",status:"approved",tatHours:24,actualHours:18,assignedAt:"2024-10-05T11:30:00Z",comment:"Critical security upgrade. Approve immediately.",timestamp:"Oct 6, 2024 5:30 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"pending",tatHours:48,elapsedHours:55,assignedAt:"2024-10-06T05:30:00Z",comment:null,timestamp:null},{step:3,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Security_Assessment_Report.pdf",size:"15.3 MB",type:"PDF",uploadedBy:"Sameer Joshi",uploadedAt:"Oct 5, 2024 11:45 AM"},{name:"Vendor_Solutions_Comparison.xlsx",size:"4.8 MB",type:"Excel",uploadedBy:"IT Security Team",uploadedAt:"Oct 5, 2024 3:30 PM"},{name:"Implementation_Roadmap.pptx",size:"7.6 MB",type:"PowerPoint",uploadedBy:"Project Management",uploadedAt:"Oct 6, 2024 10:15 AM"},{name:"Risk_Analysis_Report.pdf",size:"5.9 MB",type:"PDF",uploadedBy:"Security Consultant",uploadedAt:"Oct 6, 2024 4:45 PM"}],spectators:[{name:"Legal & Compliance",role:"Data Protection",avatar:"LC"},{name:"IT Infrastructure",role:"System Integration",avatar:"IT"}],auditTrail:[{type:"created",action:"Request Created",details:"Cybersecurity upgrade proposal submitted",user:"Sameer Joshi",timestamp:"Oct 5, 2024 11:30 AM"},{type:"assignment",action:"Assigned to Vikram Singh",details:"Forwarded to IT Operations Head",user:"System",timestamp:"Oct 5, 2024 11:31 AM"},{type:"approval",action:"Approved by Vikram Singh",details:"IT approval - marked as critical",user:"Vikram Singh",timestamp:"Oct 6, 2024 5:30 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 6, 2024 5:31 AM"},{type:"reminder",action:"Urgent Reminder",details:"TAT breach warning - 4 hours remaining",user:"System",timestamp:"Oct 8, 2024 12:45 PM"}],tags:["cybersecurity","urgent","critical","infrastructure","overdue"]}},af={"RE-REQ-2024-CM-001":{id:"RE-REQ-2024-CM-001",title:"Dealer Marketing Activity Claim - Diwali Festival Campaign",description:"Claim request for dealer-led Diwali festival marketing campaign including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution. Activity conducted at Royal Motors Mumbai dealership.",category:"Dealer Operations",subcategory:"Claim Management",status:"pending",priority:"standard",amount:"TBD",slaProgress:35,slaRemaining:"4 days 12 hours",slaEndDate:"Oct 16, 2024 5:00 PM",currentStep:1,totalSteps:8,template:"claim-management",templateName:"Claim Management",initiator:{name:"Sneha Patil",role:"Regional Marketing Coordinator",department:"Marketing - West Zone",email:"sneha.patil@royalenfield.com",phone:"+91 98765 43250",avatar:"SP"},department:"Marketing - West Zone",createdAt:"Oct 7, 2024 9:30 AM",updatedAt:"Oct 7, 2024 9:30 AM",dueDate:"2024-10-16T17:00:00Z",conclusionRemark:"",claimDetails:{activityName:"Diwali Festival Campaign 2024",activityType:"Marketing Activity",activityDate:"Oct 5, 2024",location:"Mumbai, Maharashtra",dealerCode:"RE-MH-001",dealerName:"Royal Motors Mumbai",dealerEmail:"dealer@royalmotorsmumbai.com",dealerPhone:"+91 98765 12345",dealerAddress:"123 Main Street, Andheri West, Mumbai, Maharashtra 400053",requestDescription:"Marketing campaign for Diwali festival including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution at Royal Motors Mumbai dealership.",estimatedBudget:"₹2,45,000",periodStart:"Oct 1, 2024",periodEnd:"Oct 10, 2024"},approvalFlow:[{step:1,approver:"Royal Motors Mumbai (Dealer)",role:"Dealer - Document Upload",status:"pending",tatHours:72,elapsedHours:12,assignedAt:"2024-10-07T09:30:00Z",comment:null,timestamp:null,description:"Dealer uploads proposal document, cost breakup, timeline for closure, and other supporting documents"},{step:2,approver:"Sneha Patil (Initiator)",role:"Initiator Evaluation",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator reviews dealer documents and approves or requests modifications"},{step:3,approver:"System Auto-Process",role:"IO Confirmation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Automatic IO (Internal Order) confirmation generated upon initiator approval"},{step:4,approver:"Rajesh Kumar",role:"Department Lead Approval",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Department head approves and blocks budget in IO for this activity"},{step:5,approver:"Royal Motors Mumbai (Dealer)",role:"Dealer - Completion Documents",status:"waiting",tatHours:120,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Dealer submits activity completion documents and description"},{step:6,approver:"Sneha Patil (Initiator)",role:"Initiator Verification",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator verifies completion documents and can modify approved amount"},{step:7,approver:"System Auto-Process",role:"E-Invoice Generation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Auto-generate e-invoice based on final approved amount"},{step:8,approver:"Meera Patel",role:"Finance - Credit Note Issuance",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Finance team issues credit note to dealer"}],documents:[{name:"Claim_Proposal_Diwali_2024.pdf",size:"1.8 MB",type:"PDF",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:35 AM"},{name:"Cost_Breakup_Detailed.xlsx",size:"450 KB",type:"Excel",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:38 AM"},{name:"Activity_Timeline.pdf",size:"320 KB",type:"PDF",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:40 AM"}],spectators:[{name:"Arjun Menon",role:"Brand Manager",avatar:"AM"},{name:"Finance Team",role:"Budget Monitoring",avatar:"FT"}],auditTrail:[{type:"created",action:"Claim Request Created",details:"Diwali festival campaign claim initiated using Claim Management template",user:"Sneha Patil",timestamp:"Oct 7, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Dealer",details:"Dealer Royal Motors Mumbai assigned for document upload",user:"System",timestamp:"Oct 7, 2024 9:31 AM"},{type:"status_change",action:"Workflow Started",details:"Step 1: Dealer document upload phase initiated",user:"System",timestamp:"Oct 7, 2024 9:31 AM"}],tags:["claim-management","dealer-activity","marketing","diwali-campaign","template"]}};function rf(t,s=[],a){const[r,n]=g.useState(null),[i,o]=g.useState(!1),[l,c]=g.useState(null),[m,d]=g.useState(!1),u=(j,y)=>(j||y||"NA").toString().split(" ").map(N=>N[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),h=j=>{const y=(j||"").toUpperCase();return y==="IN_PROGRESS"?"in-review":y==="PENDING"?"pending":y==="APPROVED"?"approved":y==="REJECTED"?"rejected":y==="CLOSED"?"closed":y==="SKIPPED"?"skipped":(j||"").toLowerCase()},x=async()=>{var j,y,w,N,S,T,F,R,M;o(!0);try{const b=await Gt.getWorkflowDetails(t);if(!b){console.warn("[useRequestDetails] No details returned from API");return}const A=b.workflow||{},P=Array.isArray(b.approvals)?b.approvals:[],B=Array.isArray(b.participants)?b.participants:[],E=Array.isArray(b.documents)?b.documents:[],L=b.summary||{},C=Array.isArray(b.tatAlerts)?b.tatAlerts:[];C.length>0;const k=(L==null?void 0:L.currentLevel)||A.currentLevel||1,D=P.map(V=>{const te=V.levelNumber||0,$=(V.status||"").toString().toUpperCase(),G=V.levelId||V.level_id;let ae=h(V.status);te>k&&$!=="APPROVED"&&$!=="REJECTED"?ae="waiting":te===k&&$==="PENDING"&&(ae="pending");const he=C.filter(be=>be.levelId===G);return{step:te,levelId:G,role:V.levelName||V.approverName||"Approver",status:ae,approver:V.approverName||V.approverEmail,approverId:V.approverId||V.approver_id,approverEmail:V.approverEmail,tatHours:Number(V.tatHours||0),elapsedHours:Number(V.elapsedHours||0),remainingHours:Number(V.remainingHours||0),tatPercentageUsed:Number(V.tatPercentageUsed||0),actualHours:V.levelEndTime&&V.levelStartTime?Math.max(0,(new Date(V.levelEndTime).getTime()-new Date(V.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:V.comments||void 0,timestamp:V.actionDate||void 0,levelStartTime:V.levelStartTime||V.tatStartTime,tatAlerts:he,skipReason:V.skipReason||void 0,isSkipped:$==="SKIPPED"||V.isSkipped||!1}}),z=B.filter(V=>(V.participantType||V.participant_type||"").toUpperCase()==="SPECTATOR").map(V=>({name:V.userName||V.user_name||V.userEmail||V.user_email,role:"Spectator",email:V.userEmail||V.user_email,avatar:u(V.userName||V.user_name,V.userEmail||V.user_email)})),K=V=>{var $,G;if(!V)return;const te=B.find(ae=>ae.userId===V||ae.user_id===V);return te!=null&&te.userName||te!=null&&te.user_name?te.userName||te.user_name:A.initiatorId===V?(($=A.initiator)==null?void 0:$.displayName)||((G=A.initiator)==null?void 0:G.email):V},Y=E.map(V=>{const te=Number(V.fileSize||V.file_size||0),$=(te/(1024*1024)).toFixed(2)+" MB";return{documentId:V.documentId||V.document_id,name:V.originalFileName||V.fileName||V.file_name,fileType:V.fileType||V.file_type||"",size:$,sizeBytes:te,uploadedBy:K(V.uploadedBy||V.uploaded_by),uploadedAt:V.uploadedAt||V.uploaded_at}}),de=Array.isArray(b.activities)?b.activities.filter(V=>(V.type||"").toLowerCase()!=="sla_warning"):[],Z={...A,id:A.requestNumber||A.requestId,requestId:A.requestId,requestNumber:A.requestNumber,title:A.title,description:A.description,status:h(A.status),priority:(A.priority||"").toString().toLowerCase(),approvalFlow:D,approvals:P,participants:B,documents:Y,spectators:z,summary:L,initiator:{name:((j=A.initiator)==null?void 0:j.displayName)||((y=A.initiator)==null?void 0:y.email),role:((w=A.initiator)==null?void 0:w.designation)||void 0,department:((N=A.initiator)==null?void 0:N.department)||void 0,email:((S=A.initiator)==null?void 0:S.email)||void 0,phone:((T=A.initiator)==null?void 0:T.phone)||void 0,avatar:u((F=A.initiator)==null?void 0:F.displayName,(R=A.initiator)==null?void 0:R.email)},createdAt:A.createdAt,updatedAt:A.updatedAt,totalSteps:A.totalLevels||1,currentStepRaw:(L==null?void 0:L.currentLevel)||A.currentLevel||1,currentStep:Math.min(Math.max(1,(L==null?void 0:L.currentLevel)||A.currentLevel||1),A.totalLevels||1),auditTrail:de,conclusionRemark:A.conclusionRemark||null,closureDate:A.closureDate||null};n(Z);const je=(M=a==null?void 0:a.email)==null?void 0:M.toLowerCase(),ve=P.find(V=>{const te=(V.status||"").toString().toUpperCase(),$=(V.approverEmail||"").toLowerCase();return(te==="PENDING"||te==="IN_PROGRESS")&&$===je});c(ve||null);const U=a==null?void 0:a.userId;if(U){const V=B.some(te=>(te.participantType||te.participant_type||"").toUpperCase()==="SPECTATOR"&&(te.userId||te.user_id)===U);d(V)}else d(!1)}catch(b){console.error("[useRequestDetails] Error refreshing details:",b),alert("Failed to refresh request details. Please try again.")}finally{o(!1)}};g.useEffect(()=>{if(!t)return;let j=!0;return(async()=>{var y,w,N,S,T,F,R,M,b;try{const A=await Gt.getWorkflowDetails(t);if(!j||!A)return;const P=A.workflow||{},B=Array.isArray(A.approvals)?A.approvals:[],E=Array.isArray(A.participants)?A.participants:[],L=Array.isArray(A.documents)?A.documents:[],C=A.summary||{},k=Array.isArray(A.tatAlerts)?A.tatAlerts:[],D=(P.priority||"").toString().toLowerCase(),z=(C==null?void 0:C.currentLevel)||P.currentLevel||1,K=B.map($=>{const G=$.levelNumber||0,ae=($.status||"").toString().toUpperCase(),he=$.levelId||$.level_id;let be=h($.status);G>z&&ae!=="APPROVED"&&ae!=="REJECTED"?be="waiting":G===z&&ae==="PENDING"&&(be="pending");const _e=k.filter(Oe=>Oe.levelId===he);return{step:G,levelId:he,role:$.levelName||$.approverName||"Approver",status:be,approver:$.approverName||$.approverEmail,approverId:$.approverId||$.approver_id,approverEmail:$.approverEmail,tatHours:Number($.tatHours||0),elapsedHours:Number($.elapsedHours||0),remainingHours:Number($.remainingHours||0),tatPercentageUsed:Number($.tatPercentageUsed||0),actualHours:$.elapsedHours!==void 0&&$.elapsedHours!==null?Number($.elapsedHours):void 0,comment:$.comments||void 0,timestamp:$.actionDate||void 0,levelStartTime:$.levelStartTime||$.tatStartTime,tatAlerts:_e}}),Y=E.filter($=>($.participantType||"").toUpperCase()==="SPECTATOR").map($=>({name:$.userName||$.userEmail,role:"Spectator",avatar:u($.userName,$.userEmail)})),de=$=>{var ae,he;if(!$)return;const G=E.find(be=>be.userId===$);return G!=null&&G.userName?G.userName:P.initiatorId===$?((ae=P.initiator)==null?void 0:ae.displayName)||((he=P.initiator)==null?void 0:he.email):$},Z=L.map($=>{const G=Number($.fileSize||0),ae=(G/(1024*1024)).toFixed(2)+" MB";return{documentId:$.documentId||$.document_id,name:$.originalFileName||$.fileName,fileType:$.fileType||$.file_type||"",size:ae,sizeBytes:G,uploadedBy:de($.uploadedBy),uploadedAt:$.uploadedAt}}),je=Array.isArray(A.activities)?A.activities.filter($=>($.type||"").toLowerCase()!=="sla_warning"):[],ve={id:P.requestNumber||P.requestId,requestId:P.requestId,title:P.title,description:P.description,priority:D,status:h(P.status),summary:C,initiator:{name:((y=P.initiator)==null?void 0:y.displayName)||((w=P.initiator)==null?void 0:w.email),role:((N=P.initiator)==null?void 0:N.designation)||void 0,department:((S=P.initiator)==null?void 0:S.department)||void 0,email:((T=P.initiator)==null?void 0:T.email)||void 0,phone:((F=P.initiator)==null?void 0:F.phone)||void 0,avatar:u((R=P.initiator)==null?void 0:R.displayName,(M=P.initiator)==null?void 0:M.email)},createdAt:P.createdAt,updatedAt:P.updatedAt,totalSteps:P.totalLevels||1,currentStepRaw:(C==null?void 0:C.currentLevel)||P.currentLevel||1,currentStep:Math.min(Math.max(1,(C==null?void 0:C.currentLevel)||P.currentLevel||1),P.totalLevels||1),approvalFlow:K,approvals:B,documents:Z,spectators:Y,auditTrail:je,conclusionRemark:P.conclusionRemark||null,closureDate:P.closureDate||null};n(ve);const U=(b=a==null?void 0:a.email)==null?void 0:b.toLowerCase(),V=B.find($=>{const G=($.status||"").toString().toUpperCase(),ae=($.approverEmail||"").toLowerCase();return(G==="PENDING"||G==="IN_PROGRESS")&&ae===U});c(V||null);const te=a==null?void 0:a.userId;if(te){const $=E.some(G=>(G.participantType||"").toUpperCase()==="SPECTATOR"&&G.userId===te);d($)}else d(!1)}catch(A){console.error("[useRequestDetails] Error loading request details:",A),j&&n(null)}})(),()=>{j=!1}},[t,a]);const p=g.useMemo(()=>{if(r)return r;const j=dd[t];if(j)return j;const y=af[t];if(y)return y;const w=s.find(N=>N.id===t||N.requestNumber===t||N.request_number===t);return w||null},[t,s,r]),f=g.useMemo(()=>{var w,N,S;if(!p||!a)return!1;const j=(w=a==null?void 0:a.email)==null?void 0:w.toLowerCase(),y=(S=(N=p.initiator)==null?void 0:N.email)==null?void 0:S.toLowerCase();return j===y},[p,a]),v=g.useMemo(()=>{var y;if(!p)return[];const j=[];return(y=p.initiator)!=null&&y.email&&j.push({email:p.initiator.email.toLowerCase(),participantType:"INITIATOR",name:p.initiator.name}),p.approvalFlow&&Array.isArray(p.approvalFlow)&&p.approvalFlow.forEach(w=>{w.approverEmail&&j.push({email:w.approverEmail.toLowerCase(),participantType:"APPROVER",name:w.approver})}),p.spectators&&Array.isArray(p.spectators)&&p.spectators.forEach(w=>{w.email&&j.push({email:w.email.toLowerCase(),participantType:"SPECTATOR",name:w.name})}),p.participants&&Array.isArray(p.participants)&&p.participants.forEach(w=>{const N=(w.userEmail||w.email||"").toLowerCase(),S=(w.participantType||w.participant_type||"").toUpperCase(),T=w.userName||w.user_name||w.name;N&&S&&!j.find(F=>F.email===N)&&j.push({email:N,participantType:S,name:T})}),j},[p]);return{request:p,apiRequest:r,refreshing:i,refreshDetails:x,currentApprovalLevel:l,isSpectator:m,isInitiator:f,existingParticipants:v}}function nf(t,s,a,r){const[n,i]=g.useState([]),[o,l]=g.useState(0),[c,m]=g.useState([]);return g.useEffect(()=>{if(!t){console.warn("[useRequestSocket] No requestIdentifier, cannot join socket room");return}let d=!0,u=t;return(async()=>{var f;try{const v=await Gt.getWorkflowDetails(t);(f=v==null?void 0:v.workflow)!=null&&f.requestId&&d&&(u=v.workflow.requestId)}catch(v){console.error("[useRequestSocket] Failed to resolve UUID:",v)}if(!d)return;const h=hr();if(!h){console.error("[useRequestSocket] Socket not available");return}const x=r==null?void 0:r.userId,p=()=>{En(h,u,x)};return h.connected?p():h.on("connect",p),()=>{d&&(h.off("connect",p),td(h,u))}})(),()=>{d=!1}},[t,r]),g.useEffect(()=>{!t||!s||(async()=>{try{const d=await ua(t),u=s.auditTrail||[],h=[...d,...u];h.sort((x,p)=>{const f=new Date(x.createdAt||x.created_at||x.timestamp||0).getTime(),v=new Date(p.createdAt||p.created_at||p.timestamp||0).getTime();return f-v}),i(h)}catch(d){console.error("[useRequestSocket] Failed to fetch and merge messages:",d)}})()},[t,s]),g.useEffect(()=>{if(!t)return;const d=hr();if(!d)return;const u=x=>{a!=="worknotes"&&l(p=>p+1),(async()=>{try{const p=await ua(t),f=(s==null?void 0:s.auditTrail)||[],v=[...p,...f].sort((j,y)=>{const w=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime(),N=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime();return w-N});i(v)}catch(p){console.error("[useRequestSocket] Failed to refresh messages:",p)}})()},h=x=>{const p=x.type==="breach"?"⏰":x.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const f=await Gt.getWorkflowDetails(t);f&&(Array.isArray(f.tatAlerts)&&f.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${p} TAT Alert`,{body:x.message,icon:"/favicon.ico",tag:`tat-${x.requestId}-${x.type}`,requireInteraction:!1}))}catch(f){console.error("[useRequestSocket] Failed to refresh after TAT alert:",f)}})()};return d.on("noteHandler",u),d.on("worknote:new",u),d.on("tat:alert",h),()=>{d.off("noteHandler",u),d.off("worknote:new",u),d.off("tat:alert",h)}},[t,a,s]),g.useEffect(()=>{a==="worknotes"&&l(0)},[a]),{mergedMessages:n,unreadWorkNotes:o,workNoteAttachments:c,setWorkNoteAttachments:m}}async function of(t,s,a="SUPPORTING"){var o;const r=new FormData;r.append("file",t),r.append("requestId",s),r.append("category",a);const n=await oe.post("/documents",r,{headers:{"Content-Type":"multipart/form-data"}}),i=((o=n.data)==null?void 0:o.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 Qs=async t=>{const s=t?{category:t}:{};return(await oe.get("/users/configurations",{params:s})).data.data},Mr=async t=>{const s=t?{category:t}:{};return(await oe.get("/admin/configurations",{params:s})).data.data},dt=async(t,s)=>{await oe.put(`/admin/configurations/${t}`,{configValue:s})},lf=async t=>{await oe.post(`/admin/configurations/${t}/reset`)},cf=async t=>{const s=t?{year:t}:{};return(await oe.get("/admin/holidays",{params:s})).data.data},df=async t=>(await oe.post("/admin/holidays",t)).data.data,mf=async(t,s)=>(await oe.put(`/admin/holidays/${t}`,s)).data.data,uf=async t=>{await oe.delete(`/admin/holidays/${t}`)};function hf(t,s){const[a,r]=g.useState(!1),[n,i]=g.useState(null),[o,l]=g.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,m]=g.useState({show:!1,errors:[]});g.useEffect(()=>{(async()=>{try{const p=await Qs("DOCUMENT_POLICY"),f={};p.forEach(w=>{f[w.configKey]=w.configValue});const v=parseInt(f.MAX_FILE_SIZE_MB||"10"),y=(f.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(w=>w.trim().toLowerCase());l({maxFileSizeMB:v,allowedFileTypes:y})}catch(p){console.error("Failed to load document policy:",p)}})()},[]);const d=x=>{const p=o.maxFileSizeMB*1024*1024;if(x.size>p)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${o.maxFileSizeMB}MB. Current size: ${(x.size/(1024*1024)).toFixed(2)}MB`};const f=x.name.toLowerCase(),v=f.substring(f.lastIndexOf(".")+1);return o.allowedFileTypes.includes(v)?{valid:!0}:{valid:!1,reason:`File type "${v}" is not allowed. Allowed types: ${o.allowedFileTypes.join(", ")}`}},u=async x=>{var y,w;const p=x.target.files;if(!p||p.length===0)return;const f=Array.from(p),v=[],j=[];if(f.forEach(N=>{const S=d(N);S.valid?j.push(N):v.push({fileName:N.name,reason:S.reason||"Unknown validation error"})}),v.length>0&&m({show:!0,errors:v}),j.length===0){x.target&&(x.target.value="");return}r(!0);try{const N=j[0],S=t==null?void 0:t.requestId;if(!S){Me.error("Request ID not found");return}N&&await of(N,S,"SUPPORTING"),await s(),j.length<f.length?Me.warning(`${j.length} of ${f.length} file(s) were uploaded. ${v.length} file(s) were rejected.`):Me.success("Document uploaded successfully")}catch(N){console.error("[useDocumentUpload] Upload error:",N),Me.error(((w=(y=N==null?void 0:N.response)==null?void 0:y.data)==null?void 0:w.error)||"Failed to upload document")}finally{r(!1),x.target&&(x.target.value="")}};return{uploadingDocument:a,handleDocumentUpload:u,triggerFileInput:()=>{const x=document.createElement("input");x.type="file",x.accept=o.allowedFileTypes.map(p=>`.${p}`).join(","),x.onchange=u,x.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:o,documentError:c,setDocumentError:m}}const pf="modulepreload",xf=function(t){return"/"+t},Io={},Zr=function(s,a,r){let n=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));n=Promise.allSettled(a.map(c=>{if(c=xf(c),c in Io)return;Io[c]=!0;const m=c.endsWith(".css"),d=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${d}`))return;const u=document.createElement("link");if(u.rel=m?"stylesheet":pf,m||(u.as="script"),u.crossOrigin="",u.href=c,l&&u.setAttribute("nonce",l),document.head.appendChild(u),m)return new Promise((h,x)=>{u.addEventListener("load",h),u.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return n.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};function gf(t,s,a,r,n,i,o){const[l,c]=g.useState(""),[m,d]=g.useState(!1),[u,h]=g.useState(!1),[x,p]=g.useState(!1),f=async()=>{try{const{getConclusion:y}=await Zr(async()=>{const{getConclusion:N}=await import("./conclusionApi-LySNBiVn.js");return{getConclusion:N}},__vite__mapDeps([0,1,2,3,4,5,6])),w=await y(t.requestId||s);w&&w.aiGeneratedRemark&&(c(w.finalRemark||w.aiGeneratedRemark),p(!!w.aiGeneratedRemark))}catch{}},v=async()=>{try{d(!0);const{generateConclusion:y}=await Zr(async()=>{const{generateConclusion:N}=await import("./conclusionApi-LySNBiVn.js");return{generateConclusion:N}},__vite__mapDeps([0,1,2,3,4,5,6])),w=await y(t.requestId||s);c(w.aiGeneratedRemark),p(!0)}catch(y){console.error("[useConclusionRemark] AI generation failed:",y),c(""),p(!1)}finally{d(!1)}},j=async()=>{var y,w;if(!l.trim()){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),o==null||o(!0);return}try{h(!0);const{finalizeConclusion:N}=await Zr(async()=>{const{finalizeConclusion:S}=await import("./conclusionApi-LySNBiVn.js");return{finalizeConclusion:S}},__vite__mapDeps([0,1,2,3,4,5,6]));await N(t.requestId||s,l),i==null||i({success:!0,title:"Request Closed with Successful Completion",message:"The request has been finalized and moved to Closed Requests."}),o==null||o(!0),await r(),setTimeout(()=>{n?(n(),setTimeout(()=>{window.location.hash="#/closed-requests"},100)):window.location.hash="#/closed-requests"},2e3)}catch(N){i==null||i({success:!1,title:"Error",message:((w=(y=N.response)==null?void 0:y.data)==null?void 0:w.error)||"Failed to finalize conclusion"}),o==null||o(!0)}finally{h(!1)}};return g.useEffect(()=>{(t==null?void 0:t.status)==="approved"&&a&&!l&&f()},[t==null?void 0:t.status,a]),{conclusionRemark:l,setConclusionRemark:c,conclusionLoading:m,conclusionSubmitting:u,aiGenerated:x,handleGenerateConclusion:v,handleFinalizeConclusion:j}}function ff(t,s,a){const[r,n]=g.useState(!1),[i,o]=g.useState(!1),[l,c]=g.useState(!1),[m,d]=g.useState(!1),[u,h]=g.useState(!1),[x,p]=g.useState(!1),[f,v]=g.useState(null),[j,y]=g.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:o,showAddApproverModal:l,setShowAddApproverModal:c,showAddSpectatorModal:m,setShowAddSpectatorModal:d,showSkipApproverModal:u,setShowSkipApproverModal:h,showActionStatusModal:x,setShowActionStatusModal:p,skipApproverData:f,setSkipApproverData:v,actionStatus:j,setActionStatus:y,handleApproveConfirm:async R=>{var b,A;const M=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!M){alert("Approval level not found");return}await _g(t,M,R||""),await a(),(b=window==null?void 0:window.closeModal)==null||b.call(window),(A=window==null?void 0:window.toast)==null||A.call(window,"Approved successfully")},handleRejectConfirm:async R=>{var b,A;if(!(R!=null&&R.trim())){alert("Comments & remarks are required");return}const M=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!M){alert("Approval level not found");return}await Og(t,M,R.trim(),R.trim()),await a(),(b=window==null?void 0:window.closeModal)==null||b.call(window),(A=window==null?void 0:window.toast)==null||A.call(window,"Rejected successfully")},handleAddApprover:async(R,M,b)=>{var A,P;try{await nd(t,R,M,b),await a(),c(!1),y==null||y({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${b} with ${M}h TAT`}),p==null||p(!0)}catch(B){throw y==null||y({success:!1,title:"Failed to Add Approver",message:((P=(A=B==null?void 0:B.response)==null?void 0:A.data)==null?void 0:P.error)||"Failed to add approver. Please try again."}),p==null||p(!0),B}},handleSkipApprover:async R=>{var M,b;if(f)try{await Mg(t,f.levelId,R),await a(),h(!1),v(null),y==null||y({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),p==null||p(!0)}catch(A){throw y==null||y({success:!1,title:"Failed to Skip Approver",message:((b=(M=A==null?void 0:A.response)==null?void 0:M.data)==null?void 0:b.error)||"Failed to skip approver. Please try again."}),p==null||p(!0),A}},handleAddSpectator:async R=>{var M,b;try{await id(t,R),await a(),d(!1),y==null||y({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),p==null||p(!0)}catch(A){throw y==null||y({success:!1,title:"Failed to Add Spectator",message:((b=(M=A==null?void 0:A.response)==null?void 0:M.data)==null?void 0:b.error)||"Failed to add spectator. Please try again."}),p==null||p(!0),A}}}}const yf=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"}}},vf=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-300",label:"closed"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t}}},bf=t=>{switch(t){case"approval":case"approved":return e.jsx(xe,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(et,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(Ns,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Ot,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(Cr,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(we,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(Pe,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(wr,{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(Bt,{className:"w-5 h-5 text-gray-600"})}};function jf({sla:t,requestStatus:s,testId:a="sla-progress"}){return!t||s==="approved"||s==="rejected"||s==="closed"?e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${a}-status-only`,children:[s==="closed"?e.jsx(An,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(xe,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(et,{className:"h-4 w-4 text-red-600"}):e.jsx(Pe,{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"})]}):e.jsxs("div",{"data-testid":a,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(Pe,{className:"h-4 w-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:"SLA Progress"})]}),e.jsxs(J,{className:`text-xs ${t.status==="breached"?"bg-red-600 text-white animate-pulse":t.status==="critical"?"bg-orange-600 text-white":t.status==="approaching"?"bg-yellow-600 text-white":"bg-green-600 text-white"}`,"data-testid":`${a}-badge`,children:[t.percentageUsed||0,"% elapsed"]})]}),e.jsx(ds,{value:t.percentageUsed||0,className:`h-3 mb-2 ${t.status==="breached"?"[&>div]:bg-red-600":t.status==="critical"?"[&>div]:bg-orange-600":t.status==="approaching"?"[&>div]:bg-yellow-600":"[&>div]:bg-green-600"}`,"data-testid":`${a}-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("span",{className:"text-gray-600","data-testid":`${a}-elapsed`,children:[t.elapsedText||Je(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${t.status==="breached"?"text-red-600":t.status==="critical"?"text-orange-600":"text-gray-700"}`,"data-testid":`${a}-remaining`,children:[t.remainingText||Je(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${a}-deadline`,children:["Due: ",ms(t.deadline,!0)," • ",t.percentageUsed||0,"% elapsed"]}),t.status==="critical"&&e.jsxs("p",{className:"text-xs text-orange-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${a}-warning-critical`,children:[e.jsx(as,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),t.status==="breached"&&e.jsxs("p",{className:"text-xs text-red-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${a}-warning-breached`,children:[e.jsx(Tn,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function Nf({request:t,refreshing:s,onBack:a,onRefresh:r}){var o;const n=yf((t==null?void 0:t.priority)||"standard"),i=vf((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(I,{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(ra,{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(we,{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(J,{className:`${n.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:n.label}),e.jsx(J,{className:`${i.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:i.label})]})]})]})]}),e.jsxs(I,{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(Ot,{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})})]}),e.jsx("div",{className:"px-3 sm:px-4 md:px-6 py-3 sm:py-4 bg-gradient-to-r from-blue-50 to-indigo-50 border-b border-gray-200","data-testid":"sla-section",children:e.jsx(jf,{sla:((o=t.summary)==null?void 0:o.sla)||t.sla,requestStatus:t.status,testId:"request-sla"})})]})}function us({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:ce("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})}function wf({request:t,isInitiator:s,needsClosure:a,conclusionRemark:r,setConclusionRemark:n,conclusionLoading:i,conclusionSubmitting:o,aiGenerated:l,handleGenerateConclusion:c,handleFinalizeConclusion:m}){var d,u,h,x,p,f,v;return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[e.jsxs(W,{"data-testid":"initiator-card",children:[e.jsx(Q,{className:"pb-3 sm:pb-4",children:e.jsxs(ee,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(xt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(q,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(gt,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(ft,{className:"bg-gray-700 text-white font-semibold text-sm",children:((d=t.initiator)==null?void 0:d.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:((u=t.initiator)==null?void 0:u.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((h=t.initiator)==null?void 0:h.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((x=t.initiator)==null?void 0:x.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(Fc,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((p=t.initiator)==null?void 0:p.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(_c,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((f=t.initiator)==null?void 0:f.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(W,{"data-testid":"request-details-card",children:[e.jsx(Q,{className:"pb-3 sm:pb-4",children:e.jsxs(ee,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(we,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(q,{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("p",{className:"text-xs sm:text-sm text-gray-700 whitespace-pre-line leading-relaxed break-words",children:t.description})})]}),(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:qt(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:qt(t.updatedAt)})]})]})]})]}),t.claimDetails&&e.jsxs(W,{children:[e.jsx(Q,{className:"pb-4",children:e.jsxs(ee,{className:"flex items-center gap-2 text-base",children:[e.jsx(we,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(q,{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?cd(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("p",{className:"text-sm text-gray-700 mt-2 bg-gray-50 p-3 rounded-lg whitespace-pre-line",children:t.claimDetails.requestDescription})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(W,{children:[e.jsxs(Q,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(ee,{className:"flex items-center gap-2 text-base",children:[e.jsx(xe,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(le,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(q,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx("p",{className:"text-sm text-gray-700 whitespace-pre-line leading-relaxed",children:t.conclusionRemark})}),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 ",qt(t.closureDate)]}),e.jsxs("span",{children:["By ",((v=t.initiator)==null?void 0:v.name)||"Initiator"]})]})]})]}),a&&e.jsxs(W,{"data-testid":"conclusion-remark-card",children:[e.jsx(Q,{className:"bg-gradient-to-r from-green-50 to-emerald-50 border-b 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(ee,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(xe,{className:"w-5 h-5 text-green-600"}),"Conclusion Remark - Final Step"]}),e.jsx(le,{className:"mt-1 text-xs sm:text-sm",children:"All approvals are complete. Please review and finalize the conclusion to close this request."})]}),e.jsxs(I,{variant:"outline",size:"sm",onClick:c,disabled:i,className:"gap-2 shrink-0","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Ot,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),l?"Regenerate":"Generate with AI"]})]})}),e.jsx(q,{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($e,{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"}),l&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),e.jsx(us,{value:r,onChange:j=>n(j.target.value),placeholder:"Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals...",className:"text-sm resize-none",style:{height:"160px"},maxLength:2e3,"data-testid":"conclusion-remark-textarea"}),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.length," / 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(I,{onClick:m,disabled:o||!r.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function ir({delayDuration:t=0,...s}){return e.jsx(oh,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function Xr({...t}){return e.jsx(ir,{children:e.jsx(lh,{"data-slot":"tooltip",...t})})}function Jr({...t}){return e.jsx(ch,{"data-slot":"tooltip-trigger",...t})}function Qr({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(dh,{children:e.jsxs(mh,{"data-slot":"tooltip-content",sideOffset:s,className:ce("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(uh,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function ut({...t}){return e.jsx(xh,{"data-slot":"dialog",...t})}function Cf({...t}){return e.jsx(ph,{"data-slot":"dialog-portal",...t})}const md=g.forwardRef(({className:t,...s},a)=>e.jsx(yc,{ref:a,"data-slot":"dialog-overlay",className:ce("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}));md.displayName=yc.displayName;const it=g.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(Cf,{"data-slot":"dialog-portal",children:[e.jsx(md,{}),e.jsxs(vc,{ref:r,"data-slot":"dialog-content",className:ce("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(hh,{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(jt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));it.displayName=vc.displayName;const ht=g.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:ce("flex flex-col gap-2 text-center sm:text-left",t),...s}));ht.displayName="DialogHeader";const Et=g.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:ce("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));Et.displayName="DialogFooter";const ot=g.forwardRef(({className:t,...s},a)=>e.jsx(bc,{ref:a,"data-slot":"dialog-title",className:ce("text-lg leading-none font-semibold",t),...s}));ot.displayName=bc.displayName;const Xt=g.forwardRef(({className:t,...s},a)=>e.jsx(jc,{ref:a,"data-slot":"dialog-description",className:ce("text-muted-foreground text-sm",t),...s}));Xt.displayName=jc.displayName;const Lo=t=>{if(t<8)return Je(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${Je(r)}`:`${a}d`},Sf=(t,s)=>{if(s)return e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(xe,{className:"w-4 h-4 sm:w-5 sm:w-5 text-green-600"});case"rejected":return e.jsx(et,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"pending":case"in-review":return e.jsx(Pe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(Pe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(Pe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function Af({step:t,index:s,approval:a,isCurrentUser:r=!1,isInitiator:n=!1,onSkipApprover:i,onRefresh:o,testId:l="approval-step"}){const{user:c}=Zt(),[m,d]=g.useState(!1),[u,h]=g.useState(""),[x,p]=g.useState(!1),f=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";g.useEffect(()=>{m||h("")},[m]);const v=t.status==="pending"||t.status==="in-review",j=t.status==="approved",y=t.status==="rejected",w=t.status==="waiting",N=Number(t.tatHours||0),S=t.actualHours??0,T=j&&S?Math.max(0,N-S):0,F=N>0?S/N*100:0,R=F>=100,M=(c==null?void 0:c.role)==="ADMIN",b=Rr(c),A=t.approverId===(c==null?void 0:c.userId),P=M||b||A,B=async()=>{var E,L;if(!u.trim()){Me.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}p(!0);try{await $g(t.levelId,u.trim()),d(!1),h(""),Me.success("Breach Reason Updated",{description:"The breach reason has been saved and will appear in the TAT Breach Report.",duration:5e3}),o?await o():setTimeout(()=>{window.location.reload()},1e3)}catch(C){console.error("Error updating breach reason:",C);const k=((L=(E=C==null?void 0:C.response)==null?void 0:E.data)==null?void 0:L.error)||(C==null?void 0:C.message)||"Failed to update breach reason. Please try again.";Me.error("Failed to Update Breach Reason",{description:k,duration:5e3})}finally{p(!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":v?"border-blue-500 bg-blue-50 shadow-md":j?"border-green-500 bg-green-50":y?"border-red-500 bg-red-50":w?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${l}-${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":v?"bg-blue-100":j?"bg-green-100":y?"bg-red-100":w?"bg-gray-200":"bg-gray-100"}`,children:Sf(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":`${l}-approver-label`,children:["Approver ",s+1]}),e.jsx(J,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":v?"bg-yellow-100 text-yellow-800 border-yellow-200":j?"bg-green-100 text-green-800 border-green-200":y?"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":`${l}-status-badge`,children:t.isSkipped?"skipped":t.status}),t.isSkipped&&t.skipReason&&e.jsx(ir,{delayDuration:200,children:e.jsxs(Xr,{children:[e.jsx(Jr,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:E=>E.stopPropagation(),children:e.jsx(Re,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(Qr,{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(fo,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),j&&S&&e.jsx(J,{className:"bg-green-600 text-white text-xs","data-testid":`${l}-completion-time`,children:Lo(S)})]}),e.jsx("p",{className:"text-sm font-semibold text-gray-900","data-testid":`${l}-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":`${l}-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":`${l}-tat-hours`,children:[N," hours"]})]})]}),j&&S!==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?qt(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:Lo(S)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const E=Math.min(100,F);return e.jsxs(e.Fragment,{children:[e.jsx(ds,{value:E,className:`h-2 bg-gray-200 ${R?"[&>div]:bg-red-600":"[&>div]:bg-green-600"}`,"data-testid":`${l}-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 ${R?"text-red-600":"text-green-600"}`,children:[Math.round(E),"% of TAT used"]}),R&&P&&e.jsx(ir,{children:e.jsxs(Xr,{children:[e.jsx(Jr,{asChild:!0,children:e.jsx(I,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{h(f),d(!0)},children:e.jsx(er,{className:"w-3 h-3"})})}),e.jsx(Qr,{children:e.jsx("p",{children:f?"Edit breach reason":"Add breach reason"})})]})})]}),T>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",Je(T)]})]})]})})()}),R&&f&&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(er,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:f})]}),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(Ns,{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})]})]}),v&&(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?ms(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${a.sla.status==="critical"?"bg-orange-50 border-orange-200":a.sla.status==="breached"?"bg-red-50 border-red-200":"bg-yellow-50 border-yellow-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4"}),"Current Approver - Time Tracking"]}),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," / ",Je(N)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ds,{value:a.sla.percentageUsed,className:`h-3 ${a.sla.status==="breached"?"[&>div]:bg-red-600":a.sla.status==="critical"?"[&>div]:bg-orange-600":"[&>div]:bg-yellow-600"}`,"data-testid":`${l}-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.sla.status==="breached"?"text-red-600":a.sla.status==="critical"?"text-orange-600":"text-yellow-700"}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&P&&e.jsx(ir,{children:e.jsxs(Xr,{children:[e.jsx(Jr,{asChild:!0,children:e.jsx(I,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{h(f),d(!0)},children:e.jsx(er,{className:"w-3 h-3"})})}),e.jsx(Qr,{children:e.jsx("p",{children:f?"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(Tn,{className:"w-4 h-4"}),"Deadline Breached"]}),f&&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(er,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:f})]})]}),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(tp,{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 ",N," hours for approval"]})]})}),y&&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(et,{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(fo,{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 ",qt(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((E,L)=>{var C,k,D,z,K,Y;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${E.isBreached?"bg-red-50 border-red-200":(E.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${l}-tat-alert-${L}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(E.thresholdPercentage||0)===50&&e.jsx(sp,{className:"w-5 h-5 text-yellow-600"}),(E.thresholdPercentage||0)===75&&e.jsx(as,{className:"w-5 h-5 text-orange-600"}),(E.thresholdPercentage||0)===100&&e.jsx(Tn,{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 ",L+1," - ",E.thresholdPercentage||0,"% TAT"]}),e.jsx(J,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${E.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:E.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[E.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:Je(Number(E.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:[Je(Number(E.tatHoursElapsed||0)),((C=E.metadata)==null?void 0:C.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(E.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 ${(E.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[Je(Number(E.tatHoursRemaining||0)),((k=E.metadata)==null?void 0:k.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(E.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:E.expectedCompletionTime?ms(E.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"}),(((D=E.metadata)==null?void 0:D.testMode)||((z=E.metadata)==null?void 0:z.tatTestMode))&&e.jsx(J,{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: ",E.alertSentAt?qt(E.alertSentAt):"N/A"]}),(((K=E.metadata)==null?void 0:K.testMode)||((Y=E.metadata)==null?void 0:Y.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},L)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[j?"Approved":y?"Rejected":"Actioned"," on ",qt(t.timestamp)]}),n&&(v||t.status==="pending")&&!j&&!y&&t.levelId&&i&&e.jsxs("div",{className:"mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-200",children:[e.jsxs(I,{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:()=>i({levelId:t.levelId,approverName:t.approver,levelNumber:t.step}),"data-testid":`${l}-skip-button`,children:[e.jsx(Re,{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:"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(ut,{open:m,onOpenChange:d,children:e.jsxs(it,{className:"sm:max-w-[500px]",children:[e.jsxs(ht,{children:[e.jsx(ot,{children:f?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(Xt,{children:f?"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(us,{placeholder:"Enter the reason for the breach...",value:u,onChange:E=>h(E.target.value),className:"min-h-[100px]",maxLength:500}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[u.length,"/500 characters"]})]}),e.jsxs(Et,{children:[e.jsx(I,{variant:"outline",onClick:()=>{d(!1),h("")},disabled:x,children:"Cancel"}),e.jsx(I,{onClick:B,disabled:!u.trim()||x,className:"bg-red-600 hover:bg-red-700",children:x?"Saving...":"Save Reason"})]})]})})]})}function Tf({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(W,{children:[e.jsx(Q,{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(ee,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ms,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(le,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var x;const i=t.totalSteps||1,o=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,l=((x=t.approvalFlow)==null?void 0:x.filter(p=>{const f=(p.status||"").toLowerCase();return f==="approved"||f==="rejected"}).length)||0,c=l>=i,m=(t.status||"").toLowerCase(),d=m==="approved"||m==="rejected"||m==="closed",u=o>i,h=Math.min(Math.max(1,o),i);return u?e.jsxs(J,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0 bg-blue-50 text-blue-700 border-blue-200",children:["Closure Step - ",l," of ",i," steps completed"]}):d||c?e.jsxs(J,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0 bg-green-50 text-green-700 border-green-200",children:["Completed - ",l," of ",i," steps"]}):e.jsxs(J,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",h," of ",i," - ",l," completed"]})})()]})}),e.jsx(q,{children:t.approvalFlow&&t.approvalFlow.length>0?e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.approvalFlow.map((i,o)=>{var u,h,x;const l=(u=t.approvals)==null?void 0:u.find(p=>p.levelId===i.levelId),c=(h=s==null?void 0:s.email)==null?void 0:h.toLowerCase(),m=(x=i.approverEmail)==null?void 0:x.toLowerCase(),d=c&&m&&c===m;return e.jsx(Af,{step:i,index:o,approval:l,isCurrentUser:d,isInitiator:a,onSkipApprover:r,onRefresh:n,testId:"workflow-step"},o)})}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-workflow-steps",children:"No workflow steps defined"})})]})}const kf=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 Fo({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(we,{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," • Uploaded by ",t.uploadedBy," on ",qt(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&kf(t.fileType)&&s&&e.jsx(I,{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(Tt,{className:"w-4 h-4"})}),a&&e.jsx(I,{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(ts,{className:"w-4 h-4"})})]})]})}function Rf({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:o}){return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(W,{children:[e.jsx(Q,{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(ee,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(we,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx(le,{className:"text-xs sm:text-sm mt-1",children:"Documents attached while creating the request"})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsxs(I,{size:"sm",onClick:n,disabled:a||t.status==="closed",className:"gap-1 sm:gap-2 h-8 sm:h-9 text-xs sm:text-sm shrink-0","data-testid":"upload-document-btn",children:[e.jsx(pa,{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(q,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((l,c)=>e.jsx(Fo,{document:l,onPreview:m=>i(m),onDownload:o,testId:"request-document"},c))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),e.jsxs(W,{children:[e.jsxs(Q,{children:[e.jsxs(ee,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ns,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(le,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(q,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((l,c)=>e.jsx(Fo,{document:{documentId:l.attachmentId||"",name:l.name,fileType:l.type||"",size:l.size?`${(l.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:l.size,uploadedBy:l.uploadedBy,uploadedAt:l.uploadedAt},onPreview:m=>i(m),onDownload:async m=>{const{downloadWorkNoteAttachment:d}=require("@/services/workflowApi");await d(m)},testId:"worknote-attachment"},l.attachmentId||c))}):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"})})]})]})}function Pf({request:t}){return e.jsxs(W,{children:[e.jsxs(Q,{children:[e.jsxs(ee,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Bt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(le,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(q,{children:e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.auditTrail&&t.auditTrail.length>0?t.auditTrail.map((s,a)=>e.jsxs("div",{className:"flex items-start gap-4","data-testid":`activity-item-${a}`,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center",children:bf(s.type)})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-gray-900",children:s.action}),e.jsx("span",{className:"text-xs text-gray-500 whitespace-nowrap ml-4",children:qt(s.timestamp)})]}),e.jsx("div",{className:"text-sm text-gray-600 leading-relaxed",children:e.jsx("p",{className:"whitespace-pre-line break-words",children:s.details})})]})})]},a)):e.jsxs("div",{className:"text-center py-12","data-testid":"no-activity",children:[e.jsx(Bt,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No activity recorded yet"}),e.jsx("p",{className:"text-xs text-gray-400 mt-2",children:"Actions and updates will appear here"})]})})})]})}function vi({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:o,onClose:l}){const[c,m]=g.useState(100),[d,u]=g.useState(0),[h,x]=g.useState(null),[p,f]=g.useState(!1),[v,j]=g.useState(null),y=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),w=s.toLowerCase().includes("pdf"),N=y||w;g.useEffect(()=>{if(!o||!N||!a){x(null);return}return(async()=>{f(!0),j(null);try{const b=localStorage.getItem("accessToken"),A=await fetch(a,{headers:{Authorization:`Bearer ${b}`}});if(!A.ok)throw new Error("Failed to load file");const P=await A.blob(),B=window.URL.createObjectURL(P);x(B)}catch(b){console.error("Failed to load file for preview:",b),j("Failed to load file for preview")}finally{f(!1)}})(),()=>{h&&window.URL.revokeObjectURL(h)}},[o,a,N]);const S=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},T=()=>m(M=>Math.min(M+25,200)),F=()=>m(M=>Math.max(M-25,50)),R=()=>u(M=>(M+90)%360);return e.jsx(ut,{open:o,onOpenChange:l,children:e.jsx(it,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ht,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(Tt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ot,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[y&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(I,{variant:"ghost",size:"sm",onClick:F,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(ap,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[c,"%"]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:T,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(rp,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:R,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(np,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(I,{variant:"outline",size:"sm",onClick:S,className:"gap-2 h-9",children:[e.jsx(ts,{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:p?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx($e,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):v?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(jt,{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:v}),i&&n&&e.jsxs(I,{onClick:S,className:"gap-2",children:[e.jsx(ts,{className:"h-4 w-4"}),"Download ",t]})]}):N&&h?e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:h,alt:t,style:{transform:`scale(${c/100}) rotate(${d}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%"}})})]}):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(Tt,{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(I,{onClick:S,className:"gap-2",children:[e.jsx(ts,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}async function ys(t,s=10){return await oe.get("/users/search",{params:{q:t,limit:s}})}async function vs(t){var a;const s=await oe.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function Df(t,s,a){return await oe.post("/admin/users/assign-role",{email:t,role:s,userData:a?{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}:void 0})}async function Ef(t,s){return await oe.put(`/admin/users/${t}/role`,{role:s})}async function Mf(t,s=1,a=10){return await oe.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function If(){return await oe.get("/admin/users/role-statistics")}async function Lf(){var s,a;return((a=(s=(await oe.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const Wt={searchUsers:ys,ensureUserExists:vs,assignRole:Df,updateUserRole:Ef,getUsersByRole:Mf,getRoleStatistics:If,getAllUsers:Lf};function ud({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(ut,{open:t,onOpenChange:s,children:e.jsxs(it,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(ot,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following policy violations were detected:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:a.map((n,i)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:n.type}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:n.message}),n.currentValue!==void 0&&n.maxValue!==void 0&&e.jsxs("p",{className:"text-xs text-red-600 mt-1 font-semibold",children:["Current: ",n.currentValue," / Maximum: ",n.maxValue]})]},i))}),r&&e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"System Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[r.maxApprovalLevels!==void 0&&e.jsxs("li",{children:["Maximum approval levels: ",r.maxApprovalLevels]}),r.maxParticipants!==void 0&&e.jsxs("li",{children:["Maximum participants per request: ",r.maxParticipants]}),r.allowSpectators!==void 0&&e.jsxs("li",{children:["Allow adding spectators: ",r.allowSpectators?"Yes":"No"]}),r.maxSpectators!==void 0&&e.jsxs("li",{children:["Maximum spectators per request: ",r.maxSpectators]})]})]})]})})]}),e.jsx(Et,{children:e.jsx(I,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}function hd({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=g.useState(""),[o,l]=g.useState(!1),[c,m]=g.useState([]),[d,u]=g.useState(!1),[h,x]=g.useState(null),p=g.useRef(null),f=g.useRef(null),[v,j]=g.useState({open:!1,type:"error",email:"",message:""}),[y,w]=g.useState({open:!1,violations:[]}),[N,S]=g.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});g.useEffect(()=>{t&&(async()=>{var A;try{const P=await Qs("WORKFLOW_SHARING"),B=await Qs("TAT_SETTINGS"),E=[...P,...B],L={};E.forEach(C=>{L[C.configKey]=C.configValue}),S({maxApprovalLevels:parseInt(L.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(L.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((A=L.ALLOW_ADD_SPECTATOR)==null?void 0:A.toLowerCase())==="true",maxSpectators:parseInt(L.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(P){console.error("Failed to load system policy:",P)}})()},[t]);const T=async()=>{var k,D;const b=n.trim().toLowerCase();if(!b){j({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b)){j({open:!0,type:"error",email:b,message:"Please enter a valid email address"});return}const P=r.find(z=>(z.email||"").toLowerCase()===b);if(P){const z=((k=P.participantType)==null?void 0:k.toUpperCase())||"PARTICIPANT",K=P.name||b;if(z==="INITIATOR"){j({open:!0,type:"error",email:b,message:`${K} is the request initiator and cannot be added as a spectator.`});return}else if(z==="APPROVER"){j({open:!0,type:"error",email:b,message:`${K} is already an approver on this request and cannot be added as a spectator.`});return}else if(z==="SPECTATOR"){j({open:!0,type:"error",email:b,message:`${K} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:b,message:`${K} is already a participant on this request.`});return}}const B=[];N.allowSpectators||B.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const L=r.filter(z=>(z.participantType||"").toUpperCase()==="SPECTATOR").length;L>=N.maxSpectators&&B.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:L,maxValue:N.maxSpectators});const C=r.length+1;if(C>N.maxParticipants&&B.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:C,maxValue:N.maxParticipants}),B.length>0){w({open:!0,violations:B});return}if(!h||h.email.toLowerCase()!==b)try{const K=((D=(await ys(b,1)).data)==null?void 0:D.data)||[];if(K.length===0){j({open:!0,type:"not-found",email:b,message:""});return}const Y=K[0];await vs({userId:Y.userId,email:Y.email,displayName:Y.displayName,firstName:Y.firstName,lastName:Y.lastName,department:Y.department,phone:Y.phone,mobilePhone:Y.mobilePhone,designation:Y.designation,jobTitle:Y.jobTitle,manager:Y.manager,employeeId:Y.employeeId,employeeNumber:Y.employeeNumber,secondEmail:Y.secondEmail,location:Y.location})}catch(z){console.error("Failed to validate spectator:",z),j({open:!0,type:"error",email:b,message:"Failed to validate user. Please try again."});return}try{l(!0),await a(b),i(""),x(null),s()}catch(z){console.error("Failed to add spectator:",z)}finally{l(!1)}},F=()=>{o||(i(""),x(null),m([]),u(!1),s())};g.useEffect(()=>{c.length>0&&f.current&&f.current.scrollTo({top:f.current.scrollHeight,behavior:"smooth"})},[c.length]),g.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const R=b=>{if(i(b),h&&h.email.toLowerCase()!==b.toLowerCase()&&x(null),p.current&&clearTimeout(p.current),!b||!b.startsWith("@")||b.length<2){m([]),u(!1);return}u(!0),p.current=setTimeout(async()=>{var A;try{const P=b.slice(1),E=((A=(await ys(P,10)).data)==null?void 0:A.data)||[];m(E)}catch(P){console.error("Search failed:",P),m([])}finally{u(!1)}},300)},M=async b=>{try{await vs({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}),i(b.email),x(b),m([]),u(!1)}catch(A){console.error("Failed to ensure user exists:",A),j({open:!0,type:"error",email:b.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ut,{open:t,onOpenChange:F,children:[e.jsxs(it,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:F,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:o,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center",children:e.jsx(Tt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(ot,{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(mi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(me,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:b=>R(b.target.value),className:"pl-10 h-11 border-gray-300",disabled:o,autoFocus:!0}),(d||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:d?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(b=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>M(b),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(gt,{className:"h-8 w-8",children:e.jsx(ft,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(b.displayName||b.email).split(" ").map(A=>A[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:b.displayName||[b.firstName,b.lastName].filter(Boolean).join(" ")||b.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:b.email}),b.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:b.designation})]})]})},b.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(I,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:o,children:"Cancel"}),e.jsxs(I,{type:"button",onClick:T,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:o||!n.trim(),children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),o?"Adding...":"Add Spectator"]})]})]}),e.jsx(ut,{open:v.open,onOpenChange:b=>j(A=>({...A,open:b})),children:e.jsxs(it,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsx(ot,{className:"flex items-center gap-2",children:v.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[v.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:v.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(Sr,{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."]})})]}),v.type==="error"&&e.jsxs(e.Fragment,{children:[v.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:v.email}),"."]}),v.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:v.message})})]})]})})]}),e.jsx(Et,{children:e.jsx(I,{onClick:()=>j(b=>({...b,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(ud,{open:y.open,onClose:()=>w({open:!1,violations:[]}),violations:y.violations,policyDetails:{maxApprovalLevels:N.maxApprovalLevels,maxParticipants:N.maxParticipants,allowSpectators:N.allowSpectators,maxSpectators:N.maxSpectators}})]})}function pd({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[]}){const[i,o]=g.useState(""),[l,c]=g.useState(24),[m,d]=g.useState(null),[u,h]=g.useState(!1),[x,p]=g.useState([]),[f,v]=g.useState(!1),[j,y]=g.useState(null),w=g.useRef(null),N=g.useRef(null),[S,T]=g.useState({open:!1,type:"error",email:"",message:""}),F=n.filter(C=>C&&(C.status==="approved"||C.status==="rejected"||C.status==="skipped")),R=Math.max(1,F.length+1),M=Math.max(1,n.length+1),b=M>=R?Array.from({length:M-R+1},(C,k)=>R+k):[R];g.useEffect(()=>{b.length>0&&m===null&&d(b[0]||null)},[b.length,m]);const A=async()=>{var z,K;const C=i.trim().toLowerCase();if(!C){T({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(C)){T({open:!0,type:"error",email:C,message:"Please enter a valid email address"});return}if(!l||l<=0){T({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(l>720){T({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!m){T({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(m<R){T({open:!0,type:"error",email:"",message:`Cannot add approver at level ${m}. Minimum allowed level is ${R} (after completed levels)`});return}const D=r.find(Y=>(Y.email||"").toLowerCase()===C);if(D){const Y=((z=D.participantType)==null?void 0:z.toUpperCase())||"PARTICIPANT",de=D.name||C;if(Y==="INITIATOR"){T({open:!0,type:"error",email:C,message:`${de} is the request initiator and cannot be added as an approver.`});return}else if(Y==="APPROVER"){T({open:!0,type:"error",email:C,message:`${de} is already an approver on this request.`});return}else if(Y==="SPECTATOR"){T({open:!0,type:"error",email:C,message:`${de} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{T({open:!0,type:"error",email:C,message:`${de} is already a participant on this request.`});return}}if(!j||j.email.toLowerCase()!==C)try{const de=((K=(await ys(C,1)).data)==null?void 0:K.data)||[];if(de.length===0){T({open:!0,type:"not-found",email:C,message:""});return}const Z=de[0];await vs({userId:Z.userId,email:Z.email,displayName:Z.displayName,firstName:Z.firstName,lastName:Z.lastName,department:Z.department,phone:Z.phone,mobilePhone:Z.mobilePhone,designation:Z.designation,jobTitle:Z.jobTitle,manager:Z.manager,employeeId:Z.employeeId,employeeNumber:Z.employeeNumber,secondEmail:Z.secondEmail,location:Z.location})}catch(Y){console.error("Failed to validate approver:",Y),T({open:!0,type:"error",email:C,message:"Failed to validate user. Please try again."});return}try{h(!0),await a(C,l,m),o(""),c(24),d(null),y(null),s()}catch(Y){console.error("Failed to add approver:",Y)}finally{h(!1)}},P=()=>{u||(o(""),c(24),d(null),y(null),p([]),v(!1),s())},B=C=>{const k=C.toLowerCase();return k==="approved"?e.jsx(xe,{className:"w-4 h-4 text-green-600"}):k==="rejected"?e.jsx(et,{className:"w-4 h-4 text-red-600"}):k==="skipped"?e.jsx(Re,{className:"w-4 h-4 text-orange-600"}):k==="in-review"||k==="pending"?e.jsx(Pe,{className:"w-4 h-4 text-blue-600"}):e.jsx(Pe,{className:"w-4 h-4 text-gray-400"})};g.useEffect(()=>{x.length>0&&N.current&&N.current.scrollTo({top:N.current.scrollHeight,behavior:"smooth"})},[x.length]),g.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]);const E=C=>{if(o(C),j&&j.email.toLowerCase()!==C.toLowerCase()&&y(null),w.current&&clearTimeout(w.current),!C||!C.startsWith("@")||C.length<2){p([]),v(!1);return}v(!0),w.current=setTimeout(async()=>{var k;try{const D=C.slice(1),K=((k=(await ys(D,10)).data)==null?void 0:k.data)||[];p(K)}catch(D){console.error("Search failed:",D),p([])}finally{v(!1)}},300)},L=async C=>{try{await vs({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}),o(C.email),y(C),p([]),v(!1)}catch(k){console.error("Failed to ensure user exists:",k),T({open:!0,type:"error",email:C.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ut,{open:t,onOpenChange:P,children:[e.jsxs(it,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:P,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:u,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Xe,{className:"w-5 h-5 text-blue-600"})}),e.jsx(ot,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:N,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."}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(C=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${C.status==="approved"?"bg-green-100 border border-green-200":C.status==="rejected"?"bg-red-100 border border-red-200":C.status==="skipped"?"bg-orange-100 border border-orange-200":"bg-white border border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-blue-600 text-white text-xs font-semibold flex items-center justify-center",children:C.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:C.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[C.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[B(C.status),e.jsx(J,{variant:"outline",className:`text-xs ${C.status==="approved"?"bg-green-50 text-green-700 border-green-300":C.status==="rejected"?"bg-red-50 text-red-700 border-red-300":C.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:C.status})]})]},C.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:[" New approver can only be added at level ",R," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(Se,{value:(m==null?void 0:m.toString())||"",onValueChange:C=>d(Number(C)),disabled:u,children:[e.jsx(Te,{className:"h-11 border-gray-300",children:e.jsx(Ae,{placeholder:"Select level"})}),e.jsx(ke,{children:b.map(C=>e.jsx(H,{value:C.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",C]}),C<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",C,")"]})]})},C))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Choose where to insert the new approver. Existing levels will be automatically shifted."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{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(me,{type:"number",min:"1",max:"720",value:l,onChange:C=>c(Number(C.target.value)),className:"h-11 border-gray-300 flex-1",disabled:u,placeholder:"24"}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-600 bg-gray-100 px-3 h-11 rounded-md border border-gray-300",children:[e.jsx(Pe,{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(mi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(me,{type:"text",placeholder:"@username or user@example.com",value:i,onChange:C=>E(C.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(f||x.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..."}):x.length>0?e.jsx("ul",{className:"divide-y",children:x.map(C=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>L(C),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(gt,{className:"h-8 w-8",children:e.jsx(ft,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(C.displayName||C.email).split(" ").map(k=>k[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:C.displayName||[C.firstName,C.lastName].filter(Boolean).join(" ")||C.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:C.email}),C.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:C.designation})]})]})},C.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(I,{type:"button",variant:"outline",onClick:P,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(I,{type:"button",onClick:A,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!i.trim()||!m||!l,children:[e.jsx(Xe,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${m||"?"}`]})]})]}),e.jsx(ut,{open:S.open,onOpenChange:C=>T(k=>({...k,open:C})),children:e.jsxs(it,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsx(ot,{className:"flex items-center gap-2",children:S.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[S.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:S.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(Sr,{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."]})})]}),S.type==="error"&&e.jsxs(e.Fragment,{children:[S.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:S.email}),"."]}),S.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:S.message})})]})]})})]}),e.jsx(Et,{children:e.jsx(I,{onClick:()=>T(C=>({...C,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Ff=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"}},_f=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},Of=t=>t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(s,a,r,n)=>{const i=r+s.length,o=n[i];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">@'+a+"</span>":s}).replace(/\n/g,"<br />"),$f=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",_o=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(we,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(cp,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(we,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(we,{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(dp,{className:`${s} text-purple-600`}):e.jsx(wr,{className:`${s} text-gray-600`})};function xd({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:o=!1,isSpectator:l=!1,currentLevels:c=[],onAddApprover:m}){const d=kr(),u=t||d.requestId||"",[h,x]=g.useState(""),[p,f]=g.useState(""),[v,j]=g.useState(!1),[y,w]=g.useState([]),[N,S]=g.useState(!1),[T,F]=g.useState([]),[R,M]=g.useState(null),[b,A]=g.useState(null),[P,B]=g.useState(!1),[E,L]=g.useState(!1),C=g.useRef(null),k=g.useRef(null),D=g.useRef(null),z=g.useRef(!1),[K,Y]=g.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[de,Z]=g.useState({open:!1,errors:[]}),je=g.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[ve,U]=g.useState([]),V=ve.filter(O=>O.status==="online"),te=y.filter(O=>O.content.toLowerCase().includes(p.toLowerCase())||O.user.name.toLowerCase().includes(p.toLowerCase())),$=g.useMemo(()=>l!==void 0?l:!R||ve.length===0?!1:ve.some(O=>{const se=O.userId||O.user_id,_=(O.role||"").toString().toUpperCase(),ne=(O.participantType||O.participant_type||"").toString().toUpperCase();return se===R&&(_==="SPECTATOR"||ne==="SPECTATOR")}),[l,R,ve]);g.useEffect(()=>{},[ve]),g.useEffect(()=>{!u||!R||s||(async()=>{try{const O=await ua(u),se=Array.isArray(O)?O.map(_=>{const ne=_.userId||_.user_id;return{id:_.noteId||_.id||String(Math.random()),user:{name:_.userName||"User",avatar:(_.userName||"U").slice(0,2).toUpperCase(),role:_.userRole||"Participant"},content:_.message||"",timestamp:_.createdAt||new Date().toISOString(),isCurrentUser:ne===R,attachments:Array.isArray(_.attachments)?_.attachments.map(re=>({attachmentId:re.attachmentId||re.attachment_id,name:re.fileName||re.file_name||re.name,fileName:re.fileName||re.file_name||re.name,url:re.storageUrl||re.storage_url||re.url||"#",type:re.fileType||re.file_type||re.type||"file",fileType:re.fileType||re.file_type||re.type||"file",fileSize:re.fileSize||re.file_size})):void 0}}):[];w(se)}catch(O){console.error("[WorkNoteChat] Failed to load messages:",O)}})()},[u,R,s]);const G=g.useMemo(()=>{const O=[];return y.forEach(se=>{se.attachments&&se.attachments.length>0&&se.attachments.forEach(_=>{O.push({attachmentId:_.attachmentId||_.attachment_id,name:_.fileName||_.file_name||_.name||"Untitled",fileName:_.fileName||_.file_name||_.name||"Untitled",size:_.fileSize||_.file_size,type:_.fileType||_.file_type||_.type||"file",uploadedBy:se.user.name,uploadedAt:se.timestamp,url:_.storageUrl||_.storage_url||_.url||"#"})})}),O},[y]);g.useEffect(()=>{i&&G.length>=0&&i(G)},[G,i]);const ae=g.useMemo(()=>ve.map(O=>({email:(O.email||"").toLowerCase(),participantType:O.role==="Initiator"?"INITIATOR":O.role==="Approver"?"APPROVER":O.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:O.name})),[ve]),he=O=>{if(!O)return"Participant";switch(O.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return O.charAt(0).toUpperCase()+O.slice(1).toLowerCase()}},be=()=>{var O;(O=C.current)==null||O.scrollIntoView({behavior:"smooth"})};g.useEffect(()=>{be()},[y]);const _e=O=>{switch(O.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return O.charAt(0).toUpperCase()+O.slice(1).toLowerCase()}};g.useEffect(()=>{z.current||u&&(async()=>{try{const O=await Ks(u),se=Array.isArray(O==null?void 0:O.participants)?O.participants:[];if(se.length===0)return;const _=se.map(ie=>{const Ne=ie.participantType||ie.participant_type||"participant",ue=ie.userId||ie.user_id||"";return{name:ie.userName||ie.user_name||ie.user_email||ie.userEmail||"User",avatar:(ie.userName||ie.user_name||ie.user_email||"U").toString().split(" ").map(De=>De[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:_e(Ne.toString()),status:"offline",email:ie.userEmail||ie.user_email||"",permissions:["read","write","mention"],userId:ue}});z.current=!0,U(_);let ne=0;const re=3,pe=()=>{D.current&&D.current.connected?(D.current.emit("request:online-users",{requestId:u}),ne++,ne<re&&setTimeout(pe,500)):(ne++,ne<re&&setTimeout(pe,200))};setTimeout(pe,100)}catch(O){console.error("[WorkNoteChat] ❌ Failed to load participants:",O)}})()},[u]),g.useEffect(()=>()=>{u&&(z.current=!1)},[u]),g.useEffect(()=>{const O=localStorage.getItem("userData");if(O)try{const se=JSON.parse(O),_=(se==null?void 0:se.id)||(se==null?void 0:se.userId)||(se==null?void 0:se.user_id)||null;M(_)}catch(se){console.error("[WorkNoteChat] Failed to parse userData:",se)}},[]),g.useEffect(()=>{(async()=>{try{const se=await Qs("DOCUMENT_POLICY"),_={};se.forEach(ie=>{_[ie.configKey]=ie.configValue});const ne=parseInt(_.MAX_FILE_SIZE_MB||"10"),pe=(_.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(ie=>ie.trim().toLowerCase());Y({maxFileSizeMB:ne,allowedFileTypes:pe})}catch(se){console.error("Failed to load document policy:",se)}})()},[]),g.useEffect(()=>{if(!R)return;let O=u;return(async()=>{var se;try{const _=await Ks(u);(se=_==null?void 0:_.workflow)!=null&&se.requestId&&(O=_.workflow.requestId)}catch{}try{const _=hr();r?U(Ie=>Ie.map(ze=>ze.userId===R?{...ze,status:"online"}:ze)):(En(_,O,R),U(Ie=>Ie.map(ze=>ze.userId===R?{...ze,status:"online"}:ze)));const ne=Ie=>{const Ee=(Ie==null?void 0:Ie.note)||Ie;if(!Ee)return;const ze=Ee.noteId||Ee.id;w(Jt=>{if(Jt.some(Ge=>Ge.id===ze))return Jt;const vt=Ee.userName||Ee.user_name||"User",ho=Ee.userRole||Ee.user_role,Ur=he(ho),Nu=Ee.userId||Ee.user_id,wu={id:ze||String(Date.now()),user:{name:vt,avatar:vt.split(" ").map(Ge=>Ge[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ur},content:Ee.message||"",timestamp:Ee.createdAt||new Date().toISOString(),isCurrentUser:Nu===R,attachments:Array.isArray(Ee.attachments)?Ee.attachments.map(Ge=>({attachmentId:Ge.attachmentId||Ge.attachment_id,name:Ge.fileName||Ge.file_name||Ge.name,fileName:Ge.fileName||Ge.file_name||Ge.name,url:Ge.storageUrl||Ge.storage_url||Ge.url||"#",type:Ge.fileType||Ge.file_type||Ge.type||"file",fileType:Ge.fileType||Ge.file_type||Ge.type||"file",fileSize:Ge.fileSize||Ge.file_size})):void 0};return[...Jt,wu]})},re=Ie=>{U(Ee=>Ee.length===0||!Ee.find(vt=>vt.userId===Ie.userId)?Ee:Ee.map(vt=>vt.userId===Ie.userId?{...vt,status:"online"}:vt))},pe=Ie=>{Ie.userId!==R&&U(Ee=>Ee.length===0||!Ee.find(vt=>vt.userId===Ie.userId)?Ee:Ee.map(vt=>vt.userId===Ie.userId?{...vt,status:"offline"}:vt))},ie=Ie=>{U(Ee=>Ee.length===0?Ee:Ee.map(Jt=>{const vt=Jt.userId||"";if(vt===R)return{...Jt,status:"online"};const Ur=Ie.userIds.includes(vt);return{...Jt,status:Ur?"online":"offline"}}))},Ne=()=>{U(Ie=>Ie.map(ze=>ze.userId===R?{...ze,status:"online"}:ze)),r||En(_,O,R),z.current&&(_.emit("request:online-users",{requestId:O}),setTimeout(()=>_.emit("request:online-users",{requestId:O}),300),setTimeout(()=>_.emit("request:online-users",{requestId:O}),800))},ue=Ie=>{console.error("[WorkNoteChat] ❌ Socket error:",Ie)},De=Ie=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",Ie),U(Ee=>Ee.map(ze=>ze.userId===R?ze:{...ze,status:"offline"}))},hs=Ie=>{Ie.includes("presence")||Ie.includes("worknote")||Ie.includes("request")};_.on("connect",Ne),_.on("disconnect",De),_.on("error",ue),_.on("worknote:new",ne),_.on("presence:join",re),_.on("presence:leave",pe),_.on("presence:online",ie),_.onAny(hs),D.current=_,_.connected&&z.current&&(_.emit("request:online-users",{requestId:O}),setTimeout(()=>{_.emit("request:online-users",{requestId:O})},300),setTimeout(()=>{_.emit("request:online-users",{requestId:O})},800),setTimeout(()=>{_.emit("request:online-users",{requestId:O})},1500));const wt=()=>{_.off("connect",Ne),_.off("disconnect",De),_.off("error",ue),_.off("worknote:new",ne),_.off("presence:join",re),_.off("presence:leave",pe),_.off("presence:online",ie),_.offAny(hs),r||td(_,O),D.current=null};window.__wn_cleanup=wt}catch{}})(),()=>{var se;try{(se=window.__wn_cleanup)==null||se.call(window)}catch{}}},[u,R,r]);const Oe=async()=>{if(h.trim()||T.length>0){const O=Pt(h),se=O.map(re=>{const pe=ve.find(ie=>ie.name.toLowerCase().includes(re.toLowerCase()));return pe==null?void 0:pe.userId}).filter(Boolean),_=T.map(re=>({name:re.name,url:URL.createObjectURL(re),type:re.type.split("/")[1]||"file"})),ne={id:Date.now().toString(),user:{name:"You",avatar:"YO",role:"Current User"},content:h,timestamp:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),mentions:O,isHighPriority:h.includes("!important")||h.includes("urgent"),attachments:_.length>0?_:void 0,isCurrentUser:!0};if(a)try{await a(h,T)}catch{}else try{await rd(u,{message:h,mentions:se},T);const re=await ua(u),pe=Array.isArray(re)?re.map(ie=>{const Ne=ie.userId||ie.user_id;return{id:ie.noteId||ie.id||String(Math.random()),user:{name:ie.userName||"User",avatar:(ie.userName||"U").slice(0,2).toUpperCase(),role:ie.userRole||"Participant"},content:ie.message||"",timestamp:ie.createdAt||new Date().toISOString(),isCurrentUser:Ne===R,attachments:Array.isArray(ie.attachments)?ie.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}}):[];w(pe)}catch{w(re=>[...re,ne])}x(""),F([])}};g.useEffect(()=>{if(s&&Array.isArray(s))try{const se=s.filter(_=>(_.type||"").toLowerCase()!=="sla_warning").map(_=>{var re;if(_.type||_.activityType||_.isSystem)return{id:_.id||`activity-${_.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:_.details||_.action||_.content||"",timestamp:_.timestamp||_.createdAt||_.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const pe=_.userName||_.user_name||((re=_.user)==null?void 0:re.name)||"User",ie=_.userRole||_.user_role,Ne=he(ie),ue=_.userId||_.user_id;return{id:_.noteId||_.note_id||_.id||String(Math.random()),user:{name:pe,avatar:pe.split(" ").map(De=>De[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ne},content:_.message||_.content||"",timestamp:_.createdAt||_.created_at||_.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(_.attachments)?_.attachments.map(De=>({attachmentId:De.attachmentId||De.attachment_id,name:De.fileName||De.file_name||De.name,fileName:De.fileName||De.file_name||De.name,url:De.storageUrl||De.storage_url||De.url||"#",type:De.fileType||De.file_type||De.type||"file",fileType:De.fileType||De.file_type||De.type||"file",fileSize:De.fileSize||De.file_size})):void 0,isCurrentUser:ue===R}}}).sort((_,ne)=>new Date(_.timestamp).getTime()-new Date(ne.timestamp).getTime());w(se)}catch(O){console.error("[WorkNoteChat] Error mapping messages:",O)}else(async()=>{try{const O=await ua(u),se=Array.isArray(O)?O.map(_=>{const ne=_.userName||_.user_name||"User",re=_.userRole||_.user_role,pe=he(re),ie=_.userId||_.user_id;return{id:_.noteId||_.note_id||_.id||String(Math.random()),user:{name:ne,avatar:ne.split(" ").map(Ne=>Ne[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:pe},content:_.message||"",timestamp:_.createdAt||_.created_at||new Date().toISOString(),attachments:Array.isArray(_.attachments)?_.attachments.map(Ne=>({attachmentId:Ne.attachmentId||Ne.attachment_id,name:Ne.fileName||Ne.file_name||Ne.name,fileName:Ne.fileName||Ne.file_name||Ne.name,url:Ne.storageUrl||Ne.storage_url||Ne.url||"#",type:Ne.fileType||Ne.file_type||Ne.type||"file",fileType:Ne.fileType||Ne.file_type||Ne.type||"file",fileSize:Ne.fileSize||Ne.file_size})):void 0,isCurrentUser:ie===R}}):[];w(se)}catch(O){console.error("[WorkNoteChat] Error loading work notes:",O)}})()},[s,u,ve]);const Ue=O=>{const se=K.maxFileSizeMB*1024*1024;if(O.size>se)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${K.maxFileSizeMB}MB. Current size: ${(O.size/(1024*1024)).toFixed(2)}MB`};const _=O.name.toLowerCase(),ne=_.substring(_.lastIndexOf(".")+1);return K.allowedFileTypes.includes(ne)?{valid:!0}:{valid:!1,reason:`File type "${ne}" is not allowed. Allowed types: ${K.allowedFileTypes.join(", ")}`}},tt=O=>{if(!O.target.files||O.target.files.length===0)return;const se=Array.from(O.target.files),_=[],ne=[];se.forEach(re=>{const pe=Ue(re);pe.valid?ne.push(re):_.push({fileName:re.name,reason:pe.reason||"Unknown validation error"})}),_.length>0&&Z({open:!0,errors:_}),ne.length>0&&(F(re=>[...re,...ne]),ne.length<se.length?Me.warning(`${ne.length} of ${se.length} file(s) were added. ${_.length} file(s) were rejected.`):Me.success(`${ne.length} file(s) added successfully`)),O.target&&(O.target.value="")},Be=O=>{F(se=>se.filter((_,ne)=>ne!==O)),k.current&&(k.current.value="")},kt=O=>{x(se=>se+O),j(!1)},Le=()=>{var O;(O=k.current)==null||O.click()},Ca=async O=>{var se,_;try{await id(u,O);const ne=await Ks(u),re=Array.isArray(ne==null?void 0:ne.participants)?ne.participants:[];if(re.length){const pe=re.map(ie=>{const Ne=ie.participantType||ie.participant_type||"participant",ue=ie.userId||ie.user_id||"",De=ie.userName||ie.user_name||ie.userEmail||ie.user_email||"User",hs=ie.userEmail||ie.user_email||"",wt=De.split(" ").map(Ie=>Ie[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:De,avatar:wt,role:_e(Ne),status:"offline",email:hs,lastSeen:void 0,permissions:["read"],userId:ue}});U(pe),D.current&&D.current.connected&&D.current.emit("request:online-users",{requestId:u})}B(!1),alert("Spectator added successfully")}catch(ne){throw console.error("Failed to add spectator:",ne),alert(((_=(se=ne==null?void 0:ne.response)==null?void 0:se.data)==null?void 0:_.error)||"Failed to add spectator"),ne}},ws=async(O,se,_)=>{var ne,re;if(m)await m(O,se,_),L(!1);else try{await nd(u,O,se,_);const pe=await Ks(u),ie=Array.isArray(pe==null?void 0:pe.participants)?pe.participants:[];if(ie.length){const Ne=ie.map(ue=>{const De=ue.participantType||ue.participant_type||"participant",hs=ue.userId||ue.user_id||"",wt=ue.userName||ue.user_name||ue.userEmail||ue.user_email||"User",Ie=ue.userEmail||ue.user_email||"",Ee=wt.split(" ").map(ze=>ze[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:wt,avatar:Ee,role:_e(De),status:"offline",email:Ie,lastSeen:void 0,permissions:["read"],userId:hs}});U(Ne),D.current&&D.current.connected&&D.current.emit("request:online-users",{requestId:u})}L(!1),alert(`Approver added successfully at Level ${_} with ${se}h TAT`)}catch(pe){throw console.error("Failed to add approver:",pe),alert(((re=(ne=pe==null?void 0:pe.response)==null?void 0:ne.data)==null?void 0:re.error)||"Failed to add approver"),pe}},Rt=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","","","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],Pt=O=>{const se=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,_=[];let ne;for(;(ne=se.exec(O))!==null;)if(ne[1]){const re=ne.index+ne[0].length,pe=O.slice(re),ie=O[re];(pe.startsWith("@")||!ie||/\s|[.,!?;:]|@/.test(ie))&&_.push(ne[1].trim())}return _},Qa=O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),Oe())},ju=(O,se)=>{w(_=>_.map(ne=>{if(ne.id===O){const re=ne.reactions||[],pe=re.find(ie=>ie.emoji===se);if(pe)if(pe.users.includes("You")){if(pe.users=pe.users.filter(ie=>ie!=="You"),pe.users.length===0)return{...ne,reactions:re.filter(ie=>ie.emoji!==se)}}else pe.users.push("You");else re.push({emoji:se,users:["You"]});return{...ne,reactions:re}}return ne}))};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(Ns,{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:je.title}),e.jsx(J,{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:[V.slice(0,3).map((O,se)=>e.jsx(gt,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(ft,{className:"bg-blue-500 text-white text-xs font-semibold",children:O.avatar})},se)),V.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:["+",V.length-3]})]})}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>S(!N),className:"lg:hidden",children:e.jsx(Xe,{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(ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(me,{placeholder:"Search messages...",value:p,onChange:O=>f(O.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:[te.map(O=>{const se=O.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${O.isSystem?"justify-center":se?"justify-end":""}`,children:[!O.isSystem&&!se&&e.jsx(gt,{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(ft,{className:`text-white font-semibold text-xs sm:text-sm ${O.user.role==="Initiator"?"bg-green-600":O.user.role==="Current User"?"bg-blue-500":O.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:O.user.avatar})}),e.jsx("div",{className:`${se?"max-w-[70%]":"flex-1"} min-w-0 ${O.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:O.isSystem?e.jsxs("div",{className:"inline-flex items-center gap-2 sm:gap-3 px-3 sm:px-4 py-1.5 sm:py-2 bg-gray-100 rounded-full",children:[e.jsx(Bt,{className:"w-3 h-3 sm:w-4 sm:h-4 text-gray-500 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm text-gray-700",children:O.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:qt(O.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${se?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[O.user.name," ",se&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(J,{variant:"outline",className:"text-xs flex-shrink-0",children:O.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(Pe,{className:"w-3 h-3"}),qt(O.timestamp)]}),O.isHighPriority&&e.jsxs(J,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(ip,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${se?"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:Of(O.content)}}),O.attachments&&O.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:O.attachments.map((_,ne)=>{const re=_.fileSize||_.file_size,pe=_.fileName||_.file_name||_.name,ie=_.fileType||_.file_type||_.type||"",Ne=_.attachmentId||_.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(_o,{type:ie})}),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:pe}),re&&e.jsx("p",{className:"text-xs text-gray-500",children:$f(re)})]}),Ne&&(()=>{const ue=(ie||"").toLowerCase();return ue.includes("image")||ue.includes("pdf")||ue.includes("jpg")||ue.includes("jpeg")||ue.includes("png")||ue.includes("gif")})()&&e.jsx(I,{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:ue=>{ue.preventDefault(),ue.stopPropagation();const De=Ig(Ne);A({fileName:pe,fileType:ie,fileUrl:De,fileSize:re,attachmentId:Ne})},title:"Preview file",children:e.jsx(Tt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(I,{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 ue=>{if(ue.preventDefault(),ue.stopPropagation(),!Ne){alert("Cannot download: Attachment ID missing");return}try{await Mo(Ne)}catch{alert("Failed to download file")}},title:"Download file",children:e.jsx(ts,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},ne)})})}),O.reactions&&O.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:[O.reactions.map((_,ne)=>e.jsxs("button",{onClick:()=>ju(O.id,_.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${_.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:_.emoji}),e.jsx("span",{className:"text-xs font-medium",children:_.users.length})]},ne)),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>j(!v),children:e.jsx(Ps,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!O.isSystem&&se&&e.jsx(gt,{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(ft,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:O.user.avatar})})]},O.id)}),e.jsx("div",{ref:C})]})}),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:k,onChange:tt,className:"hidden",multiple:!0,accept:K.allowedFileTypes.map(O=>`.${O}`).join(",")}),T.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:T.map((O,se)=>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(_o,{type:O.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:O.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(O.size/1024).toFixed(1)," KB"]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>Be(se),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(jt,{className:"h-3 w-3 text-red-600"})})]},se))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const O=h.lastIndexOf("@"),se=O>=0;if(!se)return null;const _=h.slice(O+1),ne=_.trim(),re=_.endsWith(" "),pe=ne.length>0,ie=ne.includes(" ")&&!re,Ne=re&&pe;if(!(se&&_.length<=20&&!ie&&!Ne))return null;const De=ne.toLowerCase(),hs=ve.filter(wt=>wt.userId===R?!1:De?wt.name.toLowerCase().includes(De):!0);return e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border-2 border-blue-300 rounded-lg shadow-2xl p-3 z-[100] w-full sm:max-w-md",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 mb-2",children:"💬 Mention someone"}),e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-1",children:hs.length>0?hs.map((wt,Ie)=>e.jsxs("button",{type:"button",onClick:Ee=>{Ee.preventDefault(),Ee.stopPropagation();const ze=h.lastIndexOf("@"),Jt=h.slice(0,ze);x(Jt+"@"+wt.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(gt,{className:"h-10 w-10",children:e.jsx(ft,{className:`text-white text-sm font-semibold ${wt.role==="Initiator"?"bg-green-600":wt.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:wt.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:wt.name}),e.jsx("p",{className:"text-xs text-gray-600",children:wt.role})]})]},Ie)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:De?`No participants found matching "${De}"`:"No other participants available"})})]})})(),e.jsx(us,{placeholder:"Type your message... Use @username to mention someone",value:h,onChange:O=>x(O.target.value),onKeyPress:Qa,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}),v&&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(I,{variant:"ghost",size:"sm",onClick:()=>j(!1),className:"h-6 w-6 p-0",children:e.jsx(jt,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:Rt.map((O,se)=>e.jsx("button",{onClick:()=>kt(O),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:O,children:O},se))})]})]}),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(I,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:Le,title:"Attach file",children:e.jsx(wr,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>j(!v),title:"Add emoji",children:e.jsx(op,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>x(O=>O+"@"),title:"Mention someone",children:e.jsx(mi,{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:[h.length,"/2000"]}),e.jsxs(I,{onClick:Oe,disabled:!h.trim()&&T.length===0,className:"bg-blue-600 hover:bg-blue-700 h-8 sm:h-9 px-3 sm:px-4 disabled:opacity-50 disabled:cursor-not-allowed flex-shrink-0",size:"sm",children:[e.jsx(lp,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),N&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>S(!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
${N?"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(I,{variant:"ghost",size:"sm",onClick:()=>S(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(jt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:ve.map((O,se)=>{const _=O.userId===R;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gt,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(ft,{className:`text-white font-semibold text-sm ${O.role==="Initiator"?"bg-green-600":_?"bg-blue-500":"bg-slate-600"}`,children:O.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${Ff(O.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:[O.name," ",_&&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:O.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:_f(O.status)})]}),O.lastSeen&&O.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:O.lastSeen})]})]},se)})})]}),!$&&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:[o&&e.jsxs(I,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>L(!0),children:[e.jsx(Cr,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(I,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>B(!0),children:[e.jsx(Tt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),b&&e.jsx(vi,{fileName:b.fileName,fileType:b.fileType,fileUrl:b.fileUrl,fileSize:b.fileSize,attachmentId:b.attachmentId,onDownload:Mo,open:!!b,onClose:()=>A(null)}),!$&&e.jsx(hd,{open:P,onClose:()=>B(!1),onConfirm:Ca,requestIdDisplay:u,requestTitle:je.title,existingParticipants:ae}),!$&&o&&e.jsx(pd,{open:E,onClose:()=>L(!1),onConfirm:ws,requestIdDisplay:u,requestTitle:je.title,existingParticipants:ae,currentLevels:c}),e.jsx(ut,{open:de.open,onOpenChange:O=>Z(se=>({...se,open:O})),children:e.jsxs(it,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(ot,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Xt,{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:de.errors.map((O,se)=>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:O.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:O.reason})]},se))}),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: ",K.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",K.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Et,{children:e.jsx(I,{onClick:()=>Z({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}function Uf({requestId:t,requestTitle:s,mergedMessages:a,setWorkNoteAttachments:r,isInitiator:n,isSpectator:i,currentLevels:o,onAddApprover:l}){return e.jsx("div",{className:"h-[calc(100vh-300px)] min-h-[600px]",children:e.jsx(xd,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:o,onAddApprover:l})})}function Vf({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:o,onReject:l}){return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&e.jsxs(W,{"data-testid":"quick-actions-card",children:[e.jsx(Q,{className:"pb-2",children:e.jsx(ee,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(q,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(I,{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(Cr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(I,{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(Tt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),e.jsx("div",{className:"pt-3 sm:pt-4 space-y-2",children:r&&e.jsxs(e.Fragment,{children:[e.jsxs(I,{className:"w-full bg-green-600 hover:bg-green-700 text-white h-9 sm:h-10 text-xs sm:text-sm",onClick:o,"data-testid":"approve-request-button",children:[e.jsx(xe,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(I,{variant:"destructive",className:"w-full h-9 sm:h-10 text-xs sm:text-sm",onClick:l,"data-testid":"reject-request-button",children:[e.jsx(et,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]})})]})]}),t.spectators&&t.spectators.length>0&&e.jsxs(W,{"data-testid":"spectators-card",children:[e.jsx(Q,{className:"pb-2",children:e.jsx(ee,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(q,{className:"space-y-3",children:t.spectators.map((c,m)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${m}`,children:[e.jsx(gt,{className:"h-8 w-8",children:e.jsx(ft,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:c.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:c.role})]})]},m))})]})]})}function Bf({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:o}){const[l,c]=g.useState(r),[m,d]=g.useState(!1),u=(l==null?void 0:l.length)||0,h=g.useMemo(()=>l.slice(0,500),[l]),x=async()=>{try{d(!0),await a(h),s()}finally{d(!1)}};return e.jsx(ut,{open:t,onOpenChange:p=>!p&&s(),children:e.jsxs(it,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex items-center justify-center",children:e.jsx(xe,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(ot,{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:o||"—"})]}),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(J,{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(us,{value:h,onChange:p=>c(p.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(u,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(xe,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Approval Confirmation"}),e.jsx("div",{children:"This request will be forwarded to the next approver or completed if this is the final step."})]})]}),e.jsxs(Et,{className:"mt-4",children:[e.jsx(I,{variant:"outline",onClick:s,disabled:m,children:"Cancel"}),e.jsxs(I,{onClick:x,disabled:m,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(xe,{className:"w-4 h-4 mr-2"}),m?"Approving...":"Approve Request"]})]})]})})}function zf({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:o}){const[l,c]=g.useState(r),[m,d]=g.useState(!1),u=(l==null?void 0:l.length)||0,h=g.useMemo(()=>l.slice(0,500),[l]),x=async()=>{if(!h.trim()){alert("Comments & remarks are required");return}try{d(!0),await a(h),s()}finally{d(!1)}};return e.jsx(ut,{open:t,onOpenChange:p=>!p&&s(),children:e.jsxs(it,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx(et,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ot,{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:o||"—"})]}),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(J,{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(us,{value:h,onChange:p=>c(p.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(u,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(Re,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Rejection Guidelines"}),e.jsx("div",{children:"Please provide specific, actionable feedback to help the initiator improve their request."})]})]}),e.jsxs(Et,{className:"mt-4",children:[e.jsx(I,{variant:"outline",onClick:s,disabled:m,children:"Cancel"}),e.jsxs(I,{variant:"destructive",onClick:x,disabled:m,children:[e.jsx(et,{className:"w-4 h-4 mr-2"}),m?"Rejecting...":"Reject Request"]})]})]})})}function Hf({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:o}){const[l,c]=g.useState(""),[m,d]=g.useState(!1),u=async()=>{if(l.trim())try{d(!0),await a(l.trim()),c(""),s()}catch(x){console.error("Failed to skip approver:",x)}finally{d(!1)}},h=()=>{m||(c(""),s())};return e.jsx(ut,{open:t,onOpenChange:h,children:e.jsxs(it,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:h,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:m,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center",children:e.jsx(Re,{className:"w-5 h-5 text-orange-600"})}),e.jsx(ot,{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(Re,{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||o)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{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]}),o&&e.jsxs("p",{className:"text-sm text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Title:"})," ",o]})]})]}),(r||n)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{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(X,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(us,{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:l,onChange:x=>c(x.target.value),className:"min-h-[100px] border-2 border-gray-300 focus:border-orange-500",disabled:m,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(I,{type:"button",variant:"outline",onClick:h,className:"flex-1 h-11 border-gray-300",disabled:m,children:"Cancel"}),e.jsxs(I,{type:"button",onClick:u,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:m||!l.trim(),children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),m?"Skipping...":"Skip Approver"]})]})]})})}function Wf({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(ut,{open:t,onOpenChange:s,children:e.jsxs(it,{className:"sm:max-w-md",children:[e.jsx(ht,{children:e.jsxs(ot,{className:"flex items-center gap-2",children:[a?e.jsx(xe,{className:"w-5 h-5 text-green-600"}):e.jsx(Re,{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(xe,{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(et,{className:"w-8 h-8 text-red-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation failed. Please try again."})]})})}),e.jsx(Et,{children:e.jsx(I,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function qf({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:o,documentError:l,request:c,skipApproverData:m,actionStatus:d,existingParticipants:u,currentLevels:h,setShowApproveModal:x,setShowRejectModal:p,setShowAddApproverModal:f,setShowAddSpectatorModal:v,setShowSkipApproverModal:j,setShowActionStatusModal:y,setPreviewDocument:w,setDocumentError:N,setSkipApproverData:S,setActionStatus:T,handleApproveConfirm:F,handleRejectConfirm:R,handleAddApprover:M,handleAddSpectator:b,handleSkipApprover:A,downloadDocument:P,documentPolicy:B}){return e.jsxs(e.Fragment,{children:[e.jsx(Bf,{open:t,onClose:()=>x(!1),onConfirm:F,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(zf,{open:s,onClose:()=>p(!1),onConfirm:R,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(pd,{open:a,onClose:()=>f(!1),onConfirm:M,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u,currentLevels:h}),e.jsx(hd,{open:r,onClose:()=>v(!1),onConfirm:b,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u}),e.jsx(Hf,{open:n,onClose:()=>{j(!1),S(null)},onConfirm:A,approverName:m==null?void 0:m.approverName,levelNumber:m==null?void 0:m.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),o&&e.jsx(vi,{fileName:o.fileName,fileType:o.fileType,fileUrl:od(o.documentId),fileSize:o.fileSize,attachmentId:o.documentId,onDownload:P,open:!!o,onClose:()=>w(null)}),d&&e.jsx(Wf,{open:i,onClose:()=>{y(!1),T(null)},success:d.success,title:d.title,message:d.message}),e.jsx(ut,{open:l.show,onOpenChange:E=>N(L=>({...L,show:E})),children:e.jsxs(it,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(ot,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Xt,{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:l.errors.map((E,L)=>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:E.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:E.reason})]},L))}),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: ",B.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",B.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Et,{children:e.jsx(I,{onClick:()=>N({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}class Kf extends g.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 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(I,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(I,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function Gf({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=kr().requestId||t||"",o=new URLSearchParams(window.location.search).get("tab")||"overview",[l,c]=g.useState(o),{user:m}=Zt(),{request:d,apiRequest:u,refreshing:h,refreshDetails:x,currentApprovalLevel:p,isSpectator:f,isInitiator:v,existingParticipants:j}=rf(n,a,m),{mergedMessages:y,unreadWorkNotes:w,workNoteAttachments:N,setWorkNoteAttachments:S}=nf(n,u,l,m),{uploadingDocument:T,triggerFileInput:F,previewDocument:R,setPreviewDocument:M,documentPolicy:b,documentError:A,setDocumentError:P}=hf(u,x),{showApproveModal:B,setShowApproveModal:E,showRejectModal:L,setShowRejectModal:C,showAddApproverModal:k,setShowAddApproverModal:D,showAddSpectatorModal:z,setShowAddSpectatorModal:K,showSkipApproverModal:Y,setShowSkipApproverModal:de,showActionStatusModal:Z,setShowActionStatusModal:je,skipApproverData:ve,setSkipApproverData:U,actionStatus:V,setActionStatus:te,handleApproveConfirm:$,handleRejectConfirm:G,handleAddApprover:ae,handleSkipApprover:he,handleAddSpectator:be}=ff(n,p,x),{conclusionRemark:_e,setConclusionRemark:Oe,conclusionLoading:Ue,conclusionSubmitting:tt,aiGenerated:Be,handleGenerateConclusion:kt,handleFinalizeConclusion:Le}=gf(d,n,v,x,s,te,je);g.useEffect(()=>{const Qa=new URLSearchParams(window.location.search).get("tab");Qa&&c(Qa)},[n]);const Ca=()=>{x()},ws=(d==null?void 0:d.status)==="approved"&&v,Rt=((d==null?void 0:d.approvalFlow)||[]).filter(Pt=>Pt&&typeof Pt.step=="number").map(Pt=>({levelNumber:Pt.step||0,approverName:Pt.approver||"Unknown",status:Pt.status||"pending",tatHours:Pt.tatHours||24}));return!d&&!u?e.jsx("div",{className:"flex items-center justify-center h-screen","data-testid":"loading-state",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 request details..."})]})}):d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(Nf,{request:d,refreshing:h,onBack:s||(()=>window.history.back()),onRefresh:Ca}),e.jsxs(Dr,{value:l,onValueChange:c,className:"w-full","data-testid":"request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(Er,{className:"grid grid-cols-3 sm:grid-cols-5 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(lt,{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(mp,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),e.jsxs(lt,{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(Ms,{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(lt,{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(we,{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(lt,{value:"activity",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 col-span-1 sm:col-span-1","data-testid":"tab-activity",children:[e.jsx(Bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Activity"})]}),e.jsxs(lt,{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(Ns,{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(J,{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:l==="worknotes"?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:l==="worknotes"?"":"lg:col-span-2",children:[e.jsx(ct,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(wf,{request:d,isInitiator:v,needsClosure:ws,conclusionRemark:_e,setConclusionRemark:Oe,conclusionLoading:Ue,conclusionSubmitting:tt,aiGenerated:Be,handleGenerateConclusion:kt,handleFinalizeConclusion:Le})}),e.jsx(ct,{value:"workflow",className:"mt-0",children:e.jsx(Tf,{request:d,user:m,isInitiator:v,onSkipApprover:Pt=>{if(!Pt.levelId){alert("Level ID not available");return}U(Pt),de(!0)},onRefresh:x})}),e.jsx(ct,{value:"documents",className:"mt-0",children:e.jsx(Rf,{request:d,workNoteAttachments:N,uploadingDocument:T,documentPolicy:b,triggerFileInput:F,setPreviewDocument:M,downloadDocument:Mn})}),e.jsx(ct,{value:"activity",className:"mt-0",children:e.jsx(Pf,{request:d})}),e.jsx(ct,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:l!=="worknotes",children:e.jsx(Uf,{requestId:n,requestTitle:d.title,mergedMessages:y,setWorkNoteAttachments:S,isInitiator:v,isSpectator:f,currentLevels:Rt,onAddApprover:ae})})]}),l!=="worknotes"&&e.jsx(Vf,{request:d,isInitiator:v,isSpectator:f,currentApprovalLevel:p,onAddApprover:()=>D(!0),onAddSpectator:()=>K(!0),onApprove:()=>E(!0),onReject:()=>C(!0)})]})]})]})}),e.jsx(qf,{showApproveModal:B,showRejectModal:L,showAddApproverModal:k,showAddSpectatorModal:z,showSkipApproverModal:Y,showActionStatusModal:Z,previewDocument:R,documentError:A,request:d,skipApproverData:ve,actionStatus:V,existingParticipants:j,currentLevels:Rt,setShowApproveModal:E,setShowRejectModal:C,setShowAddApproverModal:D,setShowAddSpectatorModal:K,setShowSkipApproverModal:de,setShowActionStatusModal:je,setPreviewDocument:M,setDocumentError:P,setSkipApproverData:U,setActionStatus:te,handleApproveConfirm:$,handleRejectConfirm:G,handleAddApprover:ae,handleAddSpectator:be,handleSkipApprover:he,downloadDocument:Mn,documentPolicy:b})]}):e.jsx("div",{className:"flex items-center justify-center h-screen","data-testid":"not-found-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"The request you're looking for doesn't exist."}),e.jsx(I,{onClick:s,children:"Go Back"})]})})}function Yf(t){return e.jsx(Kf,{children:e.jsx(Gf,{...t})})}function Zf(){const{requestId:t}=kr(),s=ya(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(It,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(xd,{requestId:t||""})})})}const bi=g.createContext({});function ji(t){const s=g.useRef(null);return s.current===null&&(s.current=t()),s.current}const Ni=typeof window<"u",gd=Ni?g.useLayoutEffect:g.useEffect,Ir=g.createContext(null);function wi(t,s){t.indexOf(s)===-1&&t.push(s)}function Ci(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const bs=(t,s,a)=>a>s?s:a<t?t:a;let Si=()=>{};const js={},fd=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function yd(t){return typeof t=="object"&&t!==null}const vd=t=>/^0[^.\s]+$/u.test(t);function Ai(t){let s;return()=>(s===void 0&&(s=t()),s)}const Yt=t=>t,Xf=(t,s)=>a=>s(t(a)),qa=(...t)=>t.reduce(Xf),$a=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class Ti{constructor(){this.subscriptions=[]}add(s){return wi(this.subscriptions,s),()=>Ci(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 o=this.subscriptions[i];o&&o(s,a,r)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const os=t=>t*1e3,Kt=t=>t/1e3;function bd(t,s){return s?t*(1e3/s):0}const jd=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,Jf=1e-7,Qf=12;function e0(t,s,a,r,n){let i,o,l=0;do o=s+(a-s)/2,i=jd(o,r,n)-t,i>0?a=o:s=o;while(Math.abs(i)>Jf&&++l<Qf);return o}function Ka(t,s,a,r){if(t===s&&a===r)return Yt;const n=i=>e0(i,0,1,t,a);return i=>i===0||i===1?i:jd(n(i),s,r)}const Nd=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,wd=t=>s=>1-t(1-s),Cd=Ka(.33,1.53,.69,.99),ki=wd(Cd),Sd=Nd(ki),Ad=t=>(t*=2)<1?.5*ki(t):.5*(2-Math.pow(2,-10*(t-1))),Ri=t=>1-Math.sin(Math.acos(t)),Td=wd(Ri),kd=Nd(Ri),t0=Ka(.42,0,1,1),s0=Ka(0,0,.58,1),Rd=Ka(.42,0,.58,1),a0=t=>Array.isArray(t)&&typeof t[0]!="number",Pd=t=>Array.isArray(t)&&typeof t[0]=="number",r0={linear:Yt,easeIn:t0,easeInOut:Rd,easeOut:s0,circIn:Ri,circInOut:kd,circOut:Td,backIn:ki,backInOut:Sd,backOut:Cd,anticipate:Ad},n0=t=>typeof t=="string",Oo=t=>{if(Pd(t)){Si(t.length===4);const[s,a,r,n]=t;return Ka(s,a,r,n)}else if(n0(t))return r0[t];return t},sr=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function i0(t,s){let a=new Set,r=new Set,n=!1,i=!1;const o=new WeakSet;let l={delta:0,timestamp:0,isProcessing:!1};function c(d){o.has(d)&&(m.schedule(d),t()),d(l)}const m={schedule:(d,u=!1,h=!1)=>{const p=h&&n?a:r;return u&&o.add(d),p.has(d)||p.add(d),d},cancel:d=>{r.delete(d),o.delete(d)},process:d=>{if(l=d,n){i=!0;return}n=!0,[a,r]=[r,a],a.forEach(c),a.clear(),n=!1,i&&(i=!1,m.process(d))}};return m}const o0=40;function Dd(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,o=sr.reduce((w,N)=>(w[N]=i0(i),w),{}),{setup:l,read:c,resolveKeyframes:m,preUpdate:d,update:u,preRender:h,render:x,postRender:p}=o,f=()=>{const w=js.useManualTiming?n.timestamp:performance.now();a=!1,js.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(w-n.timestamp,o0),1)),n.timestamp=w,n.isProcessing=!0,l.process(n),c.process(n),m.process(n),d.process(n),u.process(n),h.process(n),x.process(n),p.process(n),n.isProcessing=!1,a&&s&&(r=!1,t(f))},v=()=>{a=!0,r=!0,n.isProcessing||t(f)};return{schedule:sr.reduce((w,N)=>{const S=o[N];return w[N]=(T,F=!1,R=!1)=>(a||v(),S.schedule(T,F,R)),w},{}),cancel:w=>{for(let N=0;N<sr.length;N++)o[sr[N]].cancel(w)},state:n,steps:o}}const{schedule:Ke,cancel:Ds,state:bt,steps:en}=Dd(typeof requestAnimationFrame<"u"?requestAnimationFrame:Yt,!0);let or;function l0(){or=void 0}const _t={now:()=>(or===void 0&&_t.set(bt.isProcessing||js.useManualTiming?bt.timestamp:performance.now()),or),set:t=>{or=t,queueMicrotask(l0)}},Ed=t=>s=>typeof s=="string"&&s.startsWith(t),Pi=Ed("--"),c0=Ed("var(--"),Di=t=>c0(t)?d0.test(t.split("/*")[0].trim()):!1,d0=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,ja={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Ua={...ja,transform:t=>bs(0,1,t)},ar={...ja,default:1},Ea=t=>Math.round(t*1e5)/1e5,Ei=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function m0(t){return t==null}const u0=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Mi=(t,s)=>a=>!!(typeof a=="string"&&u0.test(a)&&a.startsWith(t)||s&&!m0(a)&&Object.prototype.hasOwnProperty.call(a,s)),Md=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,o,l]=r.match(Ei);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(o),alpha:l!==void 0?parseFloat(l):1}},h0=t=>bs(0,255,t),tn={...ja,transform:t=>Math.round(h0(t))},Gs={test:Mi("rgb","red"),parse:Md("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+tn.transform(t)+", "+tn.transform(s)+", "+tn.transform(a)+", "+Ea(Ua.transform(r))+")"};function p0(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 In={test:Mi("#"),parse:p0,transform:Gs.transform},Ga=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),Rs=Ga("deg"),ls=Ga("%"),ge=Ga("px"),x0=Ga("vh"),g0=Ga("vw"),$o={...ls,parse:t=>ls.parse(t)/100,transform:t=>ls.transform(t*100)},ia={test:Mi("hsl","hue"),parse:Md("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+ls.transform(Ea(s))+", "+ls.transform(Ea(a))+", "+Ea(Ua.transform(r))+")"},rt={test:t=>Gs.test(t)||In.test(t)||ia.test(t),parse:t=>Gs.test(t)?Gs.parse(t):ia.test(t)?ia.parse(t):In.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Gs.transform(t):ia.transform(t),getAnimatableNone:t=>{const s=rt.parse(t);return s.alpha=0,rt.transform(s)}},f0=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function y0(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(Ei))==null?void 0:s.length)||0)+(((a=t.match(f0))==null?void 0:a.length)||0)>0}const Id="number",Ld="color",v0="var",b0="var(",Uo="${}",j0=/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 Va(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const l=s.replace(j0,c=>(rt.test(c)?(r.color.push(i),n.push(Ld),a.push(rt.parse(c))):c.startsWith(b0)?(r.var.push(i),n.push(v0),a.push(c)):(r.number.push(i),n.push(Id),a.push(parseFloat(c))),++i,Uo)).split(Uo);return{values:a,split:l,indexes:r,types:n}}function Fd(t){return Va(t).values}function _d(t){const{split:s,types:a}=Va(t),r=s.length;return n=>{let i="";for(let o=0;o<r;o++)if(i+=s[o],n[o]!==void 0){const l=a[o];l===Id?i+=Ea(n[o]):l===Ld?i+=rt.transform(n[o]):i+=n[o]}return i}}const N0=t=>typeof t=="number"?0:rt.test(t)?rt.getAnimatableNone(t):t;function w0(t){const s=Fd(t);return _d(t)(s.map(N0))}const Es={test:y0,parse:Fd,createTransformer:_d,getAnimatableNone:w0};function sn(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 C0({hue:t,saturation:s,lightness:a,alpha:r}){t/=360,s/=100,a/=100;let n=0,i=0,o=0;if(!s)n=i=o=a;else{const l=a<.5?a*(1+s):a+s-a*s,c=2*a-l;n=sn(c,l,t+1/3),i=sn(c,l,t),o=sn(c,l,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(o*255),alpha:r}}function pr(t,s){return a=>a>0?s:t}const Ye=(t,s,a)=>t+(s-t)*a,an=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},S0=[In,Gs,ia],A0=t=>S0.find(s=>s.test(t));function Vo(t){const s=A0(t);if(!s)return!1;let a=s.parse(t);return s===ia&&(a=C0(a)),a}const Bo=(t,s)=>{const a=Vo(t),r=Vo(s);if(!a||!r)return pr(t,s);const n={...a};return i=>(n.red=an(a.red,r.red,i),n.green=an(a.green,r.green,i),n.blue=an(a.blue,r.blue,i),n.alpha=Ye(a.alpha,r.alpha,i),Gs.transform(n))},Ln=new Set(["none","hidden"]);function T0(t,s){return Ln.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function k0(t,s){return a=>Ye(t,s,a)}function Ii(t){return typeof t=="number"?k0:typeof t=="string"?Di(t)?pr:rt.test(t)?Bo:D0:Array.isArray(t)?Od:typeof t=="object"?rt.test(t)?Bo:R0:pr}function Od(t,s){const a=[...t],r=a.length,n=t.map((i,o)=>Ii(i)(i,s[o]));return i=>{for(let o=0;o<r;o++)a[o]=n[o](i);return a}}function R0(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=Ii(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function P0(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],o=t.indexes[i][r[i]],l=t.values[o]??0;a[n]=l,r[i]++}return a}const D0=(t,s)=>{const a=Es.createTransformer(s),r=Va(t),n=Va(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?Ln.has(t)&&!n.values.length||Ln.has(s)&&!r.values.length?T0(t,s):qa(Od(P0(r,n),n.values),a):pr(t,s)};function $d(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?Ye(t,s,a):Ii(t)(t,s)}const E0=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>Ke.update(s,a),stop:()=>Ds(s),now:()=>bt.isProcessing?bt.timestamp:_t.now()}},Ud=(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)})`},xr=2e4;function Li(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<xr;)s+=a,r=t.next(s);return s>=xr?1/0:s}function M0(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(Li(r),xr);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:Kt(n)}}const I0=5;function Vd(t,s,a){const r=Math.max(s-I0,0);return bd(a-t(r),s-r)}const Ze={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},rn=.001;function L0({duration:t=Ze.duration,bounce:s=Ze.bounce,velocity:a=Ze.velocity,mass:r=Ze.mass}){let n,i,o=1-s;o=bs(Ze.minDamping,Ze.maxDamping,o),t=bs(Ze.minDuration,Ze.maxDuration,Kt(t)),o<1?(n=m=>{const d=m*o,u=d*t,h=d-a,x=Fn(m,o),p=Math.exp(-u);return rn-h/x*p},i=m=>{const u=m*o*t,h=u*a+a,x=Math.pow(o,2)*Math.pow(m,2)*t,p=Math.exp(-u),f=Fn(Math.pow(m,2),o);return(-n(m)+rn>0?-1:1)*((h-x)*p)/f}):(n=m=>{const d=Math.exp(-m*t),u=(m-a)*t+1;return-rn+d*u},i=m=>{const d=Math.exp(-m*t),u=(a-m)*(t*t);return d*u});const l=5/t,c=_0(n,i,l);if(t=os(t),isNaN(c))return{stiffness:Ze.stiffness,damping:Ze.damping,duration:t};{const m=Math.pow(c,2)*r;return{stiffness:m,damping:o*2*Math.sqrt(r*m),duration:t}}}const F0=12;function _0(t,s,a){let r=a;for(let n=1;n<F0;n++)r=r-t(r)/s(r);return r}function Fn(t,s){return t*Math.sqrt(1-s*s)}const O0=["duration","bounce"],$0=["stiffness","damping","mass"];function zo(t,s){return s.some(a=>t[a]!==void 0)}function U0(t){let s={velocity:Ze.velocity,stiffness:Ze.stiffness,damping:Ze.damping,mass:Ze.mass,isResolvedFromDuration:!1,...t};if(!zo(t,$0)&&zo(t,O0))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*bs(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:Ze.mass,stiffness:n,damping:i}}else{const a=L0(t);s={...s,...a,mass:Ze.mass},s.isResolvedFromDuration=!0}return s}function gr(t=Ze.visualDuration,s=Ze.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],o=a.keyframes[a.keyframes.length-1],l={done:!1,value:i},{stiffness:c,damping:m,mass:d,duration:u,velocity:h,isResolvedFromDuration:x}=U0({...a,velocity:-Kt(a.velocity||0)}),p=h||0,f=m/(2*Math.sqrt(c*d)),v=o-i,j=Kt(Math.sqrt(c/d)),y=Math.abs(v)<5;r||(r=y?Ze.restSpeed.granular:Ze.restSpeed.default),n||(n=y?Ze.restDelta.granular:Ze.restDelta.default);let w;if(f<1){const S=Fn(j,f);w=T=>{const F=Math.exp(-f*j*T);return o-F*((p+f*j*v)/S*Math.sin(S*T)+v*Math.cos(S*T))}}else if(f===1)w=S=>o-Math.exp(-j*S)*(v+(p+j*v)*S);else{const S=j*Math.sqrt(f*f-1);w=T=>{const F=Math.exp(-f*j*T),R=Math.min(S*T,300);return o-F*((p+f*j*v)*Math.sinh(R)+S*v*Math.cosh(R))/S}}const N={calculatedDuration:x&&u||null,next:S=>{const T=w(S);if(x)l.done=S>=u;else{let F=S===0?p:0;f<1&&(F=S===0?os(p):Vd(w,S,T));const R=Math.abs(F)<=r,M=Math.abs(o-T)<=n;l.done=R&&M}return l.value=l.done?o:T,l},toString:()=>{const S=Math.min(Li(N),xr),T=Ud(F=>N.next(S*F).value,S,30);return S+"ms "+T},toTransition:()=>{}};return N}gr.applyToOptions=t=>{const s=M0(t,100,gr);return t.ease=s.ease,t.duration=os(s.duration),t.type="keyframes",t};function _n({keyframes:t,velocity:s=0,power:a=.8,timeConstant:r=325,bounceDamping:n=10,bounceStiffness:i=500,modifyTarget:o,min:l,max:c,restDelta:m=.5,restSpeed:d}){const u=t[0],h={done:!1,value:u},x=R=>l!==void 0&&R<l||c!==void 0&&R>c,p=R=>l===void 0?c:c===void 0||Math.abs(l-R)<Math.abs(c-R)?l:c;let f=a*s;const v=u+f,j=o===void 0?v:o(v);j!==v&&(f=j-u);const y=R=>-f*Math.exp(-R/r),w=R=>j+y(R),N=R=>{const M=y(R),b=w(R);h.done=Math.abs(M)<=m,h.value=h.done?j:b};let S,T;const F=R=>{x(h.value)&&(S=R,T=gr({keyframes:[h.value,p(h.value)],velocity:Vd(w,R,h.value),damping:n,stiffness:i,restDelta:m,restSpeed:d}))};return F(0),{calculatedDuration:null,next:R=>{let M=!1;return!T&&S===void 0&&(M=!0,N(R),F(R)),S!==void 0&&R>=S?T.next(R-S):(!M&&N(R),h)}}}function V0(t,s,a){const r=[],n=a||js.mix||$d,i=t.length-1;for(let o=0;o<i;o++){let l=n(t[o],t[o+1]);if(s){const c=Array.isArray(s)?s[o]||Yt:s;l=qa(c,l)}r.push(l)}return r}function B0(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(Si(i===s.length),i===1)return()=>s[0];if(i===2&&s[0]===s[1])return()=>s[1];const o=t[0]===t[1];t[0]>t[i-1]&&(t=[...t].reverse(),s=[...s].reverse());const l=V0(s,r,n),c=l.length,m=d=>{if(o&&d<t[0])return s[0];let u=0;if(c>1)for(;u<t.length-2&&!(d<t[u+1]);u++);const h=$a(t[u],t[u+1],d);return l[u](h)};return a?d=>m(bs(t[0],t[i-1],d)):m}function z0(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=$a(0,s,r);t.push(Ye(a,1,n))}}function H0(t){const s=[0];return z0(s,t.length-1),s}function W0(t,s){return t.map(a=>a*s)}function q0(t,s){return t.map(()=>s||Rd).splice(0,t.length-1)}function Ma({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=a0(r)?r.map(Oo):Oo(r),i={done:!1,value:s[0]},o=W0(a&&a.length===s.length?a:H0(s),t),l=B0(o,s,{ease:Array.isArray(n)?n:q0(s,n)});return{calculatedDuration:t,next:c=>(i.value=l(c),i.done=c>=t,i)}}const K0=t=>t!==null;function Fi(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(K0),l=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!l||r===void 0?i[l]:r}const G0={decay:_n,inertia:_n,tween:Ma,keyframes:Ma,spring:gr};function Bd(t){typeof t.type=="string"&&(t.type=G0[t.type])}class _i{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 Y0=t=>t/100;class Oi extends _i{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!==_t.now()&&this.tick(_t.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;Bd(s);const{type:a=Ma,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:o=0}=s;let{keyframes:l}=s;const c=a||Ma;c!==Ma&&typeof l[0]!="number"&&(this.mixKeyframes=qa(Y0,$d(l[0],l[1])),l=[0,100]);const m=c({...s,keyframes:l});i==="mirror"&&(this.mirroredGenerator=c({...s,keyframes:[...l].reverse(),velocity:-o})),m.calculatedDuration===null&&(m.calculatedDuration=Li(m));const{calculatedDuration:d}=m;this.calculatedDuration=d,this.resolvedDuration=d+n,this.totalDuration=this.resolvedDuration*(r+1)-n,this.generator=m}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:o,resolvedDuration:l,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:m=0,keyframes:d,repeat:u,repeatType:h,repeatDelay:x,type:p,onUpdate:f,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,s):this.speed<0&&(this.startTime=Math.min(s-n/this.speed,this.startTime)),a?this.currentTime=s:this.updateTime(s);const j=this.currentTime-m*(this.playbackSpeed>=0?1:-1),y=this.playbackSpeed>=0?j<0:j>n;this.currentTime=Math.max(j,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let w=this.currentTime,N=r;if(u){const R=Math.min(this.currentTime,n)/l;let M=Math.floor(R),b=R%1;!b&&R>=1&&(b=1),b===1&&M--,M=Math.min(M,u+1),!!(M%2)&&(h==="reverse"?(b=1-b,x&&(b-=x/l)):h==="mirror"&&(N=o)),w=bs(0,1,b)*l}const S=y?{done:!1,value:d[0]}:N.next(w);i&&(S.value=i(S.value));let{done:T}=S;!y&&c!==null&&(T=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const F=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&T);return F&&p!==_n&&(S.value=Fi(d,this.options,v,this.speed)),f&&f(S.value),F&&this.finish(),S}then(s,a){return this.finished.then(s,a)}get duration(){return Kt(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+Kt(s)}get time(){return Kt(this.currentTime)}set time(s){var a;s=os(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(_t.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=Kt(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=E0,startTime:a}=this.options;this.driver||(this.driver=s(o=>this.tick(o))),(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(_t.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 Z0(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const Ys=t=>t*180/Math.PI,On=t=>{const s=Ys(Math.atan2(t[1],t[0]));return $n(s)},X0={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:On,rotateZ:On,skewX:t=>Ys(Math.atan(t[1])),skewY:t=>Ys(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},$n=t=>(t=t%360,t<0&&(t+=360),t),Ho=On,Wo=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),qo=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),J0={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Wo,scaleY:qo,scale:t=>(Wo(t)+qo(t))/2,rotateX:t=>$n(Ys(Math.atan2(t[6],t[5]))),rotateY:t=>$n(Ys(Math.atan2(-t[2],t[0]))),rotateZ:Ho,rotate:Ho,skewX:t=>Ys(Math.atan(t[4])),skewY:t=>Ys(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Un(t){return t.includes("scale")?1:0}function Vn(t,s){if(!t||t==="none")return Un(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=J0,n=a;else{const l=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=X0,n=l}if(!n)return Un(s);const i=r[s],o=n[1].split(",").map(ey);return typeof i=="function"?i(o):o[i]}const Q0=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return Vn(a,s)};function ey(t){return parseFloat(t.trim())}const Na=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],wa=new Set(Na),Ko=t=>t===ja||t===ge,ty=new Set(["x","y","z"]),sy=Na.filter(t=>!ty.has(t));function ay(t){const s=[];return sy.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const ea={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})=>Vn(s,"x"),y:(t,{transform:s})=>Vn(s,"y")};ea.translateX=ea.x;ea.translateY=ea.y;const ta=new Set;let Bn=!1,zn=!1,Hn=!1;function zd(){if(zn){const t=Array.from(ta).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=ay(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,o])=>{var l;(l=r.getValue(i))==null||l.set(o)})}),t.forEach(r=>r.measureEndState()),t.forEach(r=>{r.suspendedScrollY!==void 0&&window.scrollTo(0,r.suspendedScrollY)})}zn=!1,Bn=!1,ta.forEach(t=>t.complete(Hn)),ta.clear()}function Hd(){ta.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(zn=!0)})}function ry(){Hn=!0,Hd(),zd(),Hn=!1}class $i{constructor(s,a,r,n,i,o=!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=o}scheduleResolve(){this.state="scheduled",this.isAsync?(ta.add(this),Bn||(Bn=!0,Ke.read(Hd),Ke.resolveKeyframes(zd))):(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(),o=s[s.length-1];if(i!==void 0)s[0]=i;else if(r&&a){const l=r.readValue(a,o);l!=null&&(s[0]=l)}s[0]===void 0&&(s[0]=o),n&&i===void 0&&n.set(s[0])}Z0(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),ta.delete(this)}cancel(){this.state==="scheduled"&&(ta.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const ny=t=>t.startsWith("--");function iy(t,s,a){ny(s)?t.style.setProperty(s,a):t.style[s]=a}const oy=Ai(()=>window.ScrollTimeline!==void 0),ly={};function cy(t,s){const a=Ai(t);return()=>ly[s]??a()}const Wd=cy(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Da=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,Go={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Da([0,.65,.55,1]),circOut:Da([.55,0,1,.45]),backIn:Da([.31,.01,.66,-.59]),backOut:Da([.33,1.53,.69,.99])};function qd(t,s){if(t)return typeof t=="function"?Wd()?Ud(t,s):"ease-out":Pd(t)?Da(t):Array.isArray(t)?t.map(a=>qd(a,s)||Go.easeOut):Go[t]}function dy(t,s,a,{delay:r=0,duration:n=300,repeat:i=0,repeatType:o="loop",ease:l="easeOut",times:c}={},m=void 0){const d={[s]:a};c&&(d.offset=c);const u=qd(l,n);Array.isArray(u)&&(d.easing=u);const h={delay:r,duration:n,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:i+1,direction:o==="reverse"?"alternate":"normal"};return m&&(h.pseudoElement=m),t.animate(d,h)}function Kd(t){return typeof t=="function"&&"applyToOptions"in t}function my({type:t,...s}){return Kd(t)&&Wd()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class uy extends _i{constructor(s){if(super(),this.finishedTime=null,this.isStopped=!1,!s)return;const{element:a,name:r,keyframes:n,pseudoElement:i,allowFlatten:o=!1,finalKeyframe:l,onComplete:c}=s;this.isPseudoElement=!!i,this.allowFlatten=o,this.options=s,Si(typeof s.type!="string");const m=my(s);this.animation=dy(a,r,n,m,i),m.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const d=Fi(n,this.options,l,this.speed);this.updateMotionValue?this.updateMotionValue(d):iy(a,r,d),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 Kt(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+Kt(s)}get time(){return Kt(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=os(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&&oy()?(this.animation.timeline=s,Yt):a(this)}}const Gd={anticipate:Ad,backInOut:Sd,circInOut:kd};function hy(t){return t in Gd}function py(t){typeof t.ease=="string"&&hy(t.ease)&&(t.ease=Gd[t.ease])}const Yo=10;class xy extends uy{constructor(s){py(s),Bd(s),super(s),s.startTime&&(this.startTime=s.startTime),this.options=s}updateMotionValue(s){const{motionValue:a,onUpdate:r,onComplete:n,element:i,...o}=this.options;if(!a)return;if(s!==void 0){a.set(s);return}const l=new Oi({...o,autoplay:!1}),c=os(this.finishedTime??this.time);a.setWithVelocity(l.sample(c-Yo).value,l.sample(c).value,Yo),l.stop()}}const Zo=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Es.test(t)||t==="0")&&!t.startsWith("url("));function gy(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 fy(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],o=Zo(n,s),l=Zo(i,s);return!o||!l?!1:gy(t)||(a==="spring"||Kd(a))&&r}function Wn(t){t.duration=0,t.type="keyframes"}const yy=new Set(["opacity","clipPath","filter","transform"]),vy=Ai(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function by(t){var d;const{motionValue:s,name:a,repeatDelay:r,repeatType:n,damping:i,type:o}=t;if(!(((d=s==null?void 0:s.owner)==null?void 0:d.current)instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:m}=s.owner.getProps();return vy()&&a&&yy.has(a)&&(a!=="transform"||!m)&&!c&&!r&&n!=="mirror"&&i!==0&&o!=="inertia"}const jy=40;class Ny extends _i{constructor({autoplay:s=!0,delay:a=0,type:r="keyframes",repeat:n=0,repeatDelay:i=0,repeatType:o="loop",keyframes:l,name:c,motionValue:m,element:d,...u}){var p;super(),this.stop=()=>{var f,v;this._animation&&(this._animation.stop(),(f=this.stopTimeline)==null||f.call(this)),(v=this.keyframeResolver)==null||v.cancel()},this.createdAt=_t.now();const h={autoplay:s,delay:a,type:r,repeat:n,repeatDelay:i,repeatType:o,name:c,motionValue:m,element:d,...u},x=(d==null?void 0:d.KeyframeResolver)||$i;this.keyframeResolver=new x(l,(f,v,j)=>this.onKeyframesResolved(f,v,h,!j),c,m,d),(p=this.keyframeResolver)==null||p.scheduleResolve()}onKeyframesResolved(s,a,r,n){this.keyframeResolver=void 0;const{name:i,type:o,velocity:l,delay:c,isHandoff:m,onUpdate:d}=r;this.resolvedAt=_t.now(),fy(s,i,o,l)||((js.instantAnimations||!c)&&(d==null||d(Fi(s,r,a))),s[0]=s[s.length-1],Wn(r),r.repeat=0);const h={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>jy?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},x=!m&&by(h)?new xy({...h,element:h.motionValue.owner.current}):new Oi(h);x.finished.then(()=>this.notifyFinished()).catch(Yt),this.pendingTimeline&&(this.stopTimeline=x.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=x}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(),ry()),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 wy=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Cy(t){const s=wy.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Yd(t,s,a=1){const[r,n]=Cy(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const o=i.trim();return fd(o)?parseFloat(o):o}return Di(n)?Yd(n,s,a+1):n}function Ui(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const Zd=new Set(["width","height","top","left","right","bottom",...Na]),Sy={test:t=>t==="auto",parse:t=>t},Xd=t=>s=>s.test(t),Jd=[ja,ge,ls,Rs,g0,x0,Sy],Xo=t=>Jd.find(Xd(t));function Ay(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||vd(t):!0}const Ty=new Set(["brightness","contrast","saturate","opacity"]);function ky(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(Ei)||[];if(!r)return t;const n=a.replace(r,"");let i=Ty.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const Ry=/\b([a-z-]*)\(.*?\)/gu,qn={...Es,getAnimatableNone:t=>{const s=t.match(Ry);return s?s.map(ky).join(" "):t}},Jo={...ja,transform:Math.round},Py={rotate:Rs,rotateX:Rs,rotateY:Rs,rotateZ:Rs,scale:ar,scaleX:ar,scaleY:ar,scaleZ:ar,skew:Rs,skewX:Rs,skewY:Rs,distance:ge,translateX:ge,translateY:ge,translateZ:ge,x:ge,y:ge,z:ge,perspective:ge,transformPerspective:ge,opacity:Ua,originX:$o,originY:$o,originZ:ge},Vi={borderWidth:ge,borderTopWidth:ge,borderRightWidth:ge,borderBottomWidth:ge,borderLeftWidth:ge,borderRadius:ge,radius:ge,borderTopLeftRadius:ge,borderTopRightRadius:ge,borderBottomRightRadius:ge,borderBottomLeftRadius:ge,width:ge,maxWidth:ge,height:ge,maxHeight:ge,top:ge,right:ge,bottom:ge,left:ge,padding:ge,paddingTop:ge,paddingRight:ge,paddingBottom:ge,paddingLeft:ge,margin:ge,marginTop:ge,marginRight:ge,marginBottom:ge,marginLeft:ge,backgroundPositionX:ge,backgroundPositionY:ge,...Py,zIndex:Jo,fillOpacity:Ua,strokeOpacity:Ua,numOctaves:Jo},Dy={...Vi,color:rt,backgroundColor:rt,outlineColor:rt,fill:rt,stroke:rt,borderColor:rt,borderTopColor:rt,borderRightColor:rt,borderBottomColor:rt,borderLeftColor:rt,filter:qn,WebkitFilter:qn},Qd=t=>Dy[t];function em(t,s){let a=Qd(t);return a!==qn&&(a=Es),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const Ey=new Set(["auto","none","0"]);function My(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!Ey.has(i)&&Va(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=em(a,n)}class Iy extends $i{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 m=s[c];if(typeof m=="string"&&(m=m.trim(),Di(m))){const d=Yd(m,a.current);d!==void 0&&(s[c]=d),c===s.length-1&&(this.finalKeyframe=m)}}if(this.resolveNoneKeyframes(),!Zd.has(r)||s.length!==2)return;const[n,i]=s,o=Xo(n),l=Xo(i);if(o!==l)if(Ko(o)&&Ko(l))for(let c=0;c<s.length;c++){const m=s[c];typeof m=="string"&&(s[c]=parseFloat(m))}else ea[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||Ay(s[n]))&&r.push(n);r.length&&My(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=ea[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 l;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,o=r[i];r[i]=ea[a](s.measureViewportBox(),window.getComputedStyle(s.current)),o!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=o),(l=this.removedTransforms)!=null&&l.length&&this.removedTransforms.forEach(([c,m])=>{s.getValue(c).set(m)}),this.resolveNoneKeyframes()}}function Ly(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 tm=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function sm(t){return yd(t)&&"offsetHeight"in t}const Qo=30,Fy=t=>!isNaN(parseFloat(t));class _y{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=_t.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 o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(s),this.owner=a.owner}setCurrent(s){this.current=s,this.updatedAt=_t.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=Fy(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 Ti);const r=this.events[s].add(a);return s==="change"?()=>{r(),Ke.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=_t.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>Qo)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,Qo);return bd(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 xa(t,s){return new _y(t,s)}const{schedule:Bi}=Dd(queueMicrotask,!1),Qt={x:!1,y:!1};function am(){return Qt.x||Qt.y}function Oy(t){return t==="x"||t==="y"?Qt[t]?null:(Qt[t]=!0,()=>{Qt[t]=!1}):Qt.x||Qt.y?null:(Qt.x=Qt.y=!0,()=>{Qt.x=Qt.y=!1})}function rm(t,s){const a=Ly(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function el(t){return!(t.pointerType==="touch"||am())}function $y(t,s,a={}){const[r,n,i]=rm(t,a),o=l=>{if(!el(l))return;const{target:c}=l,m=s(c,l);if(typeof m!="function"||!c)return;const d=u=>{el(u)&&(m(u),c.removeEventListener("pointerleave",d))};c.addEventListener("pointerleave",d,n)};return r.forEach(l=>{l.addEventListener("pointerenter",o,n)}),i}const nm=(t,s)=>s?t===s?!0:nm(t,s.parentElement):!1,zi=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Uy=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Vy(t){return Uy.has(t.tagName)||t.tabIndex!==-1}const lr=new WeakSet;function tl(t){return s=>{s.key==="Enter"&&t(s)}}function nn(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const By=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=tl(()=>{if(lr.has(a))return;nn(a,"down");const n=tl(()=>{nn(a,"up")}),i=()=>nn(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 sl(t){return zi(t)&&!am()}function zy(t,s,a={}){const[r,n,i]=rm(t,a),o=l=>{const c=l.currentTarget;if(!sl(l))return;lr.add(c);const m=s(c,l),d=(x,p)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",h),lr.has(c)&&lr.delete(c),sl(x)&&typeof m=="function"&&m(x,{success:p})},u=x=>{d(x,c===window||c===document||a.useGlobalTarget||nm(c,x.target))},h=x=>{d(x,!1)};window.addEventListener("pointerup",u,n),window.addEventListener("pointercancel",h,n)};return r.forEach(l=>{(a.useGlobalTarget?window:l).addEventListener("pointerdown",o,n),sm(l)&&(l.addEventListener("focus",m=>By(m,n)),!Vy(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),i}function im(t){return yd(t)&&"ownerSVGElement"in t}function Hy(t){return im(t)&&t.tagName==="svg"}const St=t=>!!(t&&t.getVelocity),Wy=[...Jd,rt,Es],qy=t=>Wy.find(Xd(t)),Hi=g.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function al(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function Ky(...t){return s=>{let a=!1;const r=t.map(n=>{const i=al(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():al(t[n],null)}}}}function Gy(...t){return g.useCallback(Ky(...t),t)}class Yy extends g.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=sm(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 Zy({children:t,isPresent:s,anchorX:a,root:r}){const n=g.useId(),i=g.useRef(null),o=g.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:l}=g.useContext(Hi),c=Gy(i,t==null?void 0:t.ref);return g.useInsertionEffect(()=>{const{width:m,height:d,top:u,left:h,right:x}=o.current;if(s||!i.current||!m||!d)return;const p=a==="left"?`left: ${h}`:`right: ${x}`;i.current.dataset.motionPopId=n;const f=document.createElement("style");l&&(f.nonce=l);const v=r??document.head;return v.appendChild(f),f.sheet&&f.sheet.insertRule(`
[data-motion-pop-id="${n}"] {
position: absolute !important;
width: ${m}px !important;
height: ${d}px !important;
${p}px !important;
top: ${u}px !important;
}
`),()=>{v.contains(f)&&v.removeChild(f)}},[s]),e.jsx(Yy,{isPresent:s,childRef:i,sizeRef:o,children:g.cloneElement(t,{ref:c})})}const Xy=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:o,anchorX:l,root:c})=>{const m=ji(Jy),d=g.useId();let u=!0,h=g.useMemo(()=>(u=!1,{id:d,initial:s,isPresent:a,custom:n,onExitComplete:x=>{m.set(x,!0);for(const p of m.values())if(!p)return;r&&r()},register:x=>(m.set(x,!1),()=>m.delete(x))}),[a,m,r]);return i&&u&&(h={...h}),g.useMemo(()=>{m.forEach((x,p)=>m.set(p,!1))},[a]),g.useEffect(()=>{!a&&!m.size&&r&&r()},[a]),o==="popLayout"&&(t=e.jsx(Zy,{isPresent:a,anchorX:l,root:c,children:t})),e.jsx(Ir.Provider,{value:h,children:t})};function Jy(){return new Map}function om(t=!0){const s=g.useContext(Ir);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=g.useId();g.useEffect(()=>{if(t)return n(i)},[t]);const o=g.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,o]:[!0]}const rr=t=>t.key||"";function rl(t){const s=[];return g.Children.forEach(t,a=>{g.isValidElement(a)&&s.push(a)}),s}const Lr=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:o=!1,anchorX:l="left",root:c})=>{const[m,d]=om(o),u=g.useMemo(()=>rl(t),[t]),h=o&&!m?[]:u.map(rr),x=g.useRef(!0),p=g.useRef(u),f=ji(()=>new Map),[v,j]=g.useState(u),[y,w]=g.useState(u);gd(()=>{x.current=!1,p.current=u;for(let T=0;T<y.length;T++){const F=rr(y[T]);h.includes(F)?f.delete(F):f.get(F)!==!0&&f.set(F,!1)}},[y,h.length,h.join("-")]);const N=[];if(u!==v){let T=[...u];for(let F=0;F<y.length;F++){const R=y[F],M=rr(R);h.includes(M)||(T.splice(F,0,R),N.push(R))}return i==="wait"&&N.length&&(T=N),w(rl(T)),j(u),null}const{forceRender:S}=g.useContext(bi);return e.jsx(e.Fragment,{children:y.map(T=>{const F=rr(T),R=o&&!m?!1:u===y||h.includes(F),M=()=>{if(f.has(F))f.set(F,!0);else return;let b=!0;f.forEach(A=>{A||(b=!1)}),b&&(S==null||S(),w(p.current),o&&(d==null||d()),r&&r())};return e.jsx(Xy,{isPresent:R,initial:!x.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:R?void 0:M,anchorX:l,children:T},F)})})},lm=g.createContext({strict:!1}),nl={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"]},ga={};for(const t in nl)ga[t]={isEnabled:s=>nl[t].some(a=>!!s[a])};function Qy(t){for(const s in t)ga[s]={...ga[s],...t[s]}}const ev=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 fr(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||ev.has(t)}let cm=t=>!fr(t);function tv(t){typeof t=="function"&&(cm=s=>s.startsWith("on")?!fr(s):t(s))}try{tv(require("@emotion/is-prop-valid").default)}catch{}function sv(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(cm(n)||a===!0&&fr(n)||!s&&!fr(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Fr=g.createContext({});function _r(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Ba(t){return typeof t=="string"||Array.isArray(t)}const Wi=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],qi=["initial",...Wi];function Or(t){return _r(t.animate)||qi.some(s=>Ba(t[s]))}function dm(t){return!!(Or(t)||t.variants)}function av(t,s){if(Or(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Ba(a)?a:void 0,animate:Ba(r)?r:void 0}}return t.inherit!==!1?s:{}}function rv(t){const{initial:s,animate:a}=av(t,g.useContext(Fr));return g.useMemo(()=>({initial:s,animate:a}),[il(s),il(a)])}function il(t){return Array.isArray(t)?t.join(" "):t}const za={};function nv(t){for(const s in t)za[s]=t[s],Pi(s)&&(za[s].isCSSVariable=!0)}function mm(t,{layout:s,layoutId:a}){return wa.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!za[t]||t==="opacity")}const iv={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},ov=Na.length;function lv(t,s,a){let r="",n=!0;for(let i=0;i<ov;i++){const o=Na[i],l=t[o];if(l===void 0)continue;let c=!0;if(typeof l=="number"?c=l===(o.startsWith("scale")?1:0):c=parseFloat(l)===0,!c||a){const m=tm(l,Vi[o]);if(!c){n=!1;const d=iv[o]||o;r+=`${d}(${m}) `}a&&(s[o]=m)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function Ki(t,s,a){const{style:r,vars:n,transformOrigin:i}=t;let o=!1,l=!1;for(const c in s){const m=s[c];if(wa.has(c)){o=!0;continue}else if(Pi(c)){n[c]=m;continue}else{const d=tm(m,Vi[c]);c.startsWith("origin")?(l=!0,i[c]=d):r[c]=d}}if(s.transform||(o||a?r.transform=lv(s,t.transform,a):r.transform&&(r.transform="none")),l){const{originX:c="50%",originY:m="50%",originZ:d=0}=i;r.transformOrigin=`${c} ${m} ${d}`}}const Gi=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function um(t,s,a){for(const r in s)!St(s[r])&&!mm(r,a)&&(t[r]=s[r])}function cv({transformTemplate:t},s){return g.useMemo(()=>{const a=Gi();return Ki(a,s,t),Object.assign({},a.vars,a.style)},[s])}function dv(t,s){const a=t.style||{},r={};return um(r,a,t),Object.assign(r,cv(t,s)),r}function mv(t,s){const a={},r=dv(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 uv={offset:"stroke-dashoffset",array:"stroke-dasharray"},hv={offset:"strokeDashoffset",array:"strokeDasharray"};function pv(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?uv:hv;t[i.offset]=ge.transform(-r);const o=ge.transform(s),l=ge.transform(a);t[i.array]=`${o} ${l}`}function hm(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:o=0,...l},c,m,d){if(Ki(t,l,m),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:u,style:h}=t;u.transform&&(h.transform=u.transform,delete u.transform),(h.transform||u.transformOrigin)&&(h.transformOrigin=u.transformOrigin??"50% 50%",delete u.transformOrigin),h.transform&&(h.transformBox=(d==null?void 0:d.transformBox)??"fill-box",delete u.transformBox),s!==void 0&&(u.x=s),a!==void 0&&(u.y=a),r!==void 0&&(u.scale=r),n!==void 0&&pv(u,n,i,o,!1)}const pm=()=>({...Gi(),attrs:{}}),xm=t=>typeof t=="string"&&t.toLowerCase()==="svg";function xv(t,s,a,r){const n=g.useMemo(()=>{const i=pm();return hm(i,s,xm(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};um(i,t.style,t),n.style={...i,...n.style}}return n}const gv=["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 Yi(t){return typeof t!="string"||t.includes("-")?!1:!!(gv.indexOf(t)>-1||/[A-Z]/u.test(t))}function fv(t,s,a,{latestValues:r},n,i=!1){const l=(Yi(t)?xv:mv)(s,r,n,t),c=sv(s,typeof t=="string",i),m=t!==g.Fragment?{...c,...l,ref:a}:{},{children:d}=s,u=g.useMemo(()=>St(d)?d.get():d,[d]);return g.createElement(t,{...m,children:u})}function ol(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function Zi(t,s,a,r){if(typeof s=="function"){const[n,i]=ol(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]=ol(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function cr(t){return St(t)?t.get():t}function yv({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:vv(a,r,n,t),renderState:s()}}function vv(t,s,a,r){const n={},i=r(t,{});for(const h in i)n[h]=cr(i[h]);let{initial:o,animate:l}=t;const c=Or(t),m=dm(t);s&&m&&!c&&t.inherit!==!1&&(o===void 0&&(o=s.initial),l===void 0&&(l=s.animate));let d=a?a.initial===!1:!1;d=d||o===!1;const u=d?l:o;if(u&&typeof u!="boolean"&&!_r(u)){const h=Array.isArray(u)?u:[u];for(let x=0;x<h.length;x++){const p=Zi(t,h[x]);if(p){const{transitionEnd:f,transition:v,...j}=p;for(const y in j){let w=j[y];if(Array.isArray(w)){const N=d?w.length-1:0;w=w[N]}w!==null&&(n[y]=w)}for(const y in f)n[y]=f[y]}}}return n}const gm=t=>(s,a)=>{const r=g.useContext(Fr),n=g.useContext(Ir),i=()=>yv(t,s,r,n);return a?i():ji(i)};function Xi(t,s,a){var i;const{style:r}=t,n={};for(const o in r)(St(r[o])||s.style&&St(s.style[o])||mm(o,t)||((i=a==null?void 0:a.getValue(o))==null?void 0:i.liveStyle)!==void 0)&&(n[o]=r[o]);return n}const bv=gm({scrapeMotionValuesFromProps:Xi,createRenderState:Gi});function fm(t,s,a){const r=Xi(t,s,a);for(const n in t)if(St(t[n])||St(s[n])){const i=Na.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const jv=gm({scrapeMotionValuesFromProps:fm,createRenderState:pm}),Nv=Symbol.for("motionComponentSymbol");function oa(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function wv(t,s,a){return g.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):oa(a)&&(a.current=r))},[s])}const Ji=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Cv="framerAppearId",ym="data-"+Ji(Cv),vm=g.createContext({});function Sv(t,s,a,r,n){var f,v;const{visualElement:i}=g.useContext(Fr),o=g.useContext(lm),l=g.useContext(Ir),c=g.useContext(Hi).reducedMotion,m=g.useRef(null);r=r||o.renderer,!m.current&&r&&(m.current=r(t,{visualState:s,parent:i,props:a,presenceContext:l,blockInitialAnimation:l?l.initial===!1:!1,reducedMotionConfig:c}));const d=m.current,u=g.useContext(vm);d&&!d.projection&&n&&(d.type==="html"||d.type==="svg")&&Av(m.current,a,n,u);const h=g.useRef(!1);g.useInsertionEffect(()=>{d&&h.current&&d.update(a,l)});const x=a[ym],p=g.useRef(!!x&&!((f=window.MotionHandoffIsComplete)!=null&&f.call(window,x))&&((v=window.MotionHasOptimisedAnimation)==null?void 0:v.call(window,x)));return gd(()=>{d&&(h.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),p.current&&d.animationState&&d.animationState.animateChanges())}),g.useEffect(()=>{d&&(!p.current&&d.animationState&&d.animationState.animateChanges(),p.current&&(queueMicrotask(()=>{var j;(j=window.MotionHandoffMarkAsComplete)==null||j.call(window,x)}),p.current=!1),d.enteringChildren=void 0)}),d}function Av(t,s,a,r){const{layoutId:n,layout:i,drag:o,dragConstraints:l,layoutScroll:c,layoutRoot:m,layoutCrossfade:d}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:bm(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!o||l&&oa(l),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:m})}function bm(t){if(t)return t.options.allowProjection!==!1?t.projection:bm(t.parent)}function on(t,{forwardMotionProps:s=!1}={},a,r){a&&Qy(a);const n=Yi(t)?jv:bv;function i(l,c){let m;const d={...g.useContext(Hi),...l,layoutId:Tv(l)},{isStatic:u}=d,h=rv(l),x=n(l,u);if(!u&&Ni){kv();const p=Rv(d);m=p.MeasureLayout,h.visualElement=Sv(t,x,d,r,p.ProjectionNode)}return e.jsxs(Fr.Provider,{value:h,children:[m&&h.visualElement?e.jsx(m,{visualElement:h.visualElement,...d}):null,fv(t,l,wv(x,h.visualElement,c),x,u,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const o=g.forwardRef(i);return o[Nv]=t,o}function Tv({layoutId:t}){const s=g.useContext(bi).id;return s&&t!==void 0?s+"-"+t:t}function kv(t,s){g.useContext(lm).strict}function Rv(t){const{drag:s,layout:a}=ga;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 Pv(t,s){if(typeof Proxy>"u")return on;const a=new Map,r=(i,o)=>on(i,o,t,s),n=(i,o)=>r(i,o);return new Proxy(n,{get:(i,o)=>o==="create"?r:(a.has(o)||a.set(o,on(o,void 0,t,s)),a.get(o))})}function jm({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function Dv({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function Ev(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 ln(t){return t===void 0||t===1}function Kn({scale:t,scaleX:s,scaleY:a}){return!ln(t)||!ln(s)||!ln(a)}function Vs(t){return Kn(t)||Nm(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Nm(t){return ll(t.x)||ll(t.y)}function ll(t){return t&&t!=="0%"}function yr(t,s,a){const r=t-a,n=s*r;return a+n}function cl(t,s,a,r,n){return n!==void 0&&(t=yr(t,n,r)),yr(t,a,r)+s}function Gn(t,s=0,a=1,r,n){t.min=cl(t.min,s,a,r,n),t.max=cl(t.max,s,a,r,n)}function wm(t,{x:s,y:a}){Gn(t.x,s.translate,s.scale,s.originPoint),Gn(t.y,a.translate,a.scale,a.originPoint)}const dl=.999999999999,ml=1.0000000000001;function Mv(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,o;for(let l=0;l<n;l++){i=a[l],o=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&&ca(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),o&&(s.x*=o.x.scale,s.y*=o.y.scale,wm(t,o)),r&&Vs(i.latestValues)&&ca(t,i.latestValues))}s.x<ml&&s.x>dl&&(s.x=1),s.y<ml&&s.y>dl&&(s.y=1)}function la(t,s){t.min=t.min+s,t.max=t.max+s}function ul(t,s,a,r,n=.5){const i=Ye(t.min,t.max,n);Gn(t,s,a,i,r)}function ca(t,s){ul(t.x,s.x,s.scaleX,s.scale,s.originX),ul(t.y,s.y,s.scaleY,s.scale,s.originY)}function Cm(t,s){return jm(Ev(t.getBoundingClientRect(),s))}function Iv(t,s,a){const r=Cm(t,a),{scroll:n}=s;return n&&(la(r.x,n.offset.x),la(r.y,n.offset.y)),r}const hl=()=>({translate:0,scale:1,origin:0,originPoint:0}),da=()=>({x:hl(),y:hl()}),pl=()=>({min:0,max:0}),st=()=>({x:pl(),y:pl()}),Yn={current:null},Sm={current:!1};function Lv(){if(Sm.current=!0,!!Ni)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>Yn.current=t.matches;t.addEventListener("change",s),s()}else Yn.current=!1}const Fv=new WeakMap;function _v(t,s,a){for(const r in s){const n=s[r],i=a[r];if(St(n))t.addValue(r,n);else if(St(i))t.addValue(r,xa(n,{owner:t}));else if(i!==n)if(t.hasValue(r)){const o=t.getValue(r);o.liveStyle===!0?o.jump(n):o.hasAnimated||o.set(n)}else{const o=t.getStaticValue(r);t.addValue(r,xa(o!==void 0?o:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const xl=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Ov{scrapeMotionValuesFromProps(s,a,r){return{}}constructor({parent:s,props:a,presenceContext:r,reducedMotionConfig:n,blockInitialAnimation:i,visualState:o},l={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=$i,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 h=_t.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,Ke.render(this.render,!1,!0))};const{latestValues:c,renderState:m}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=a.initial?{...c}:{},this.renderState=m,this.parent=s,this.props=a,this.presenceContext=r,this.depth=s?s.depth+1:0,this.reducedMotionConfig=n,this.options=l,this.blockInitialAnimation=!!i,this.isControllingVariants=Or(a),this.isVariantNode=dm(a),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(s&&s.current);const{willChange:d,...u}=this.scrapeMotionValuesFromProps(a,{},this);for(const h in u){const x=u[h];c[h]!==void 0&&St(x)&&x.set(c[h])}}mount(s){var a;this.current=s,Fv.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)),Sm.current||Lv(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Yn.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Ds(this.notifyUpdate),Ds(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=wa.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",o=>{this.latestValues[s]=o,this.props.onUpdate&&Ke.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 ga){const a=ga[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):st()}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<xl.length;r++){const n=xl[r];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);const i="on"+n,o=s[i];o&&(this.propEventSubscriptions[n]=this.on(n,o))}this.prevMotionValues=_v(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=xa(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"&&(fd(r)||vd(r))?r=parseFloat(r):!qy(r)&&Es.test(a)&&(r=em(s,a)),this.setBaseTarget(s,St(r)?r.get():r)),St(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 o=Zi(this.props,a,(i=this.presenceContext)==null?void 0:i.custom);o&&(r=o[s])}if(a&&r!==void 0)return r;const n=this.getBaseTargetFromProps(this.props,s);return n!==void 0&&!St(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 Ti),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){Bi.render(this.render)}}class Am extends Ov{constructor(){super(...arguments),this.KeyframeResolver=Iy}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;St(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Tm(t,{style:s,vars:a},r,n){const i=t.style;let o;for(o in s)i[o]=s[o];n==null||n.applyProjectionStyles(i,r);for(o in a)i.setProperty(o,a[o])}function $v(t){return window.getComputedStyle(t)}class Uv extends Am{constructor(){super(...arguments),this.type="html",this.renderInstance=Tm}readValueFromInstance(s,a){var r;if(wa.has(a))return(r=this.projection)!=null&&r.isProjecting?Un(a):Q0(s,a);{const n=$v(s),i=(Pi(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return Cm(s,a)}build(s,a,r){Ki(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return Xi(s,a,r)}}const km=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 Vv(t,s,a,r){Tm(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(km.has(n)?n:Ji(n),s.attrs[n])}class Bv extends Am{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=st}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(wa.has(a)){const r=Qd(a);return r&&r.default||0}return a=km.has(a)?a:Ji(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return fm(s,a,r)}build(s,a,r){hm(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){Vv(s,a,r,n)}mount(s){this.isSVGTag=xm(s.tagName),super.mount(s)}}const zv=(t,s)=>Yi(t)?new Bv(s):new Uv(s,{allowProjection:t!==g.Fragment});function ha(t,s,a){const r=t.getProps();return Zi(r,s,a!==void 0?a:r.custom,t)}const Zn=t=>Array.isArray(t);function Hv(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,xa(a))}function Wv(t){return Zn(t)?t[t.length-1]||0:t}function qv(t,s){const a=ha(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const o in i){const l=Wv(i[o]);Hv(t,o,l)}}function Kv(t){return!!(St(t)&&t.add)}function Xn(t,s){const a=t.getValue("willChange");if(Kv(a))return a.add(s);if(!a&&js.WillChange){const r=new js.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function Rm(t){return t.props[ym]}const Gv=t=>t!==null;function Yv(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(Gv),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const Zv={type:"spring",stiffness:500,damping:25,restSpeed:10},Xv=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Jv={type:"keyframes",duration:.8},Qv={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},eb=(t,{keyframes:s})=>s.length>2?Jv:wa.has(t)?t.startsWith("scale")?Xv(s[1]):Zv:Qv;function tb({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:o,repeatDelay:l,from:c,elapsed:m,...d}){return!!Object.keys(d).length}const Qi=(t,s,a,r={},n,i)=>o=>{const l=Ui(r,t)||{},c=l.delay||r.delay||0;let{elapsed:m=0}=r;m=m-os(c);const d={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...l,delay:-m,onUpdate:h=>{s.set(h),l.onUpdate&&l.onUpdate(h)},onComplete:()=>{o(),l.onComplete&&l.onComplete()},name:t,motionValue:s,element:i?void 0:n};tb(l)||Object.assign(d,eb(t,d)),d.duration&&(d.duration=os(d.duration)),d.repeatDelay&&(d.repeatDelay=os(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let u=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(Wn(d),d.delay===0&&(u=!0)),(js.instantAnimations||js.skipAnimations)&&(u=!0,Wn(d),d.delay=0),d.allowFlatten=!l.type&&!l.ease,u&&!i&&s.get()!==void 0){const h=Yv(d.keyframes,l);if(h!==void 0){Ke.update(()=>{d.onUpdate(h),d.onComplete()});return}}return l.isSync?new Oi(d):new Ny(d)};function sb({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Pm(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:o,...l}=s;r&&(i=r);const c=[],m=n&&t.animationState&&t.animationState.getState()[n];for(const d in l){const u=t.getValue(d,t.latestValues[d]??null),h=l[d];if(h===void 0||m&&sb(m,d))continue;const x={delay:a,...Ui(i||{},d)},p=u.get();if(p!==void 0&&!u.isAnimating&&!Array.isArray(h)&&h===p&&!x.velocity)continue;let f=!1;if(window.MotionHandoffAnimation){const j=Rm(t);if(j){const y=window.MotionHandoffAnimation(j,d,Ke);y!==null&&(x.startTime=y,f=!0)}}Xn(t,d),u.start(Qi(d,u,h,t.shouldReduceMotion&&Zd.has(d)?{type:!1}:x,t,f));const v=u.animation;v&&c.push(v)}return o&&Promise.all(c).then(()=>{Ke.update(()=>{o&&qv(t,o)})}),c}function Dm(t,s,a,r=0,n=1){const i=Array.from(t).sort((m,d)=>m.sortNodePosition(d)).indexOf(s),o=t.size,l=(o-1)*r;return typeof a=="function"?a(i,o):n===1?i*r:l-i*r}function Jn(t,s,a={}){var c;const r=ha(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(Pm(t,r,a)):()=>Promise.resolve(),o=t.variantChildren&&t.variantChildren.size?(m=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:h}=n;return ab(t,s,m,d,u,h,a)}:()=>Promise.resolve(),{when:l}=n;if(l){const[m,d]=l==="beforeChildren"?[i,o]:[o,i];return m().then(()=>d())}else return Promise.all([i(),o(a.delay)])}function ab(t,s,a=0,r=0,n=0,i=1,o){const l=[];for(const c of t.variantChildren)c.notify("AnimationStart",s),l.push(Jn(c,s,{...o,delay:a+(typeof r=="function"?0:r)+Dm(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(l)}function rb(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>Jn(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=Jn(t,s,a);else{const n=typeof s=="function"?ha(t,s,a.custom):s;r=Promise.all(Pm(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function Em(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 nb=qi.length;function Mm(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?Mm(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<nb;a++){const r=qi[a],n=t.props[r];(Ba(n)||n===!1)&&(s[r]=n)}return s}const ib=[...Wi].reverse(),ob=Wi.length;function lb(t){return s=>Promise.all(s.map(({animation:a,options:r})=>rb(t,a,r)))}function cb(t){let s=lb(t),a=gl(),r=!0;const n=c=>(m,d)=>{var h;const u=ha(t,d,c==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(u){const{transition:x,transitionEnd:p,...f}=u;m={...m,...f,...p}}return m};function i(c){s=c(t)}function o(c){const{props:m}=t,d=Mm(t.parent)||{},u=[],h=new Set;let x={},p=1/0;for(let v=0;v<ob;v++){const j=ib[v],y=a[j],w=m[j]!==void 0?m[j]:d[j],N=Ba(w),S=j===c?y.isActive:null;S===!1&&(p=v);let T=w===d[j]&&w!==m[j]&&N;if(T&&r&&t.manuallyAnimateOnMount&&(T=!1),y.protectedKeys={...x},!y.isActive&&S===null||!w&&!y.prevProp||_r(w)||typeof w=="boolean")continue;const F=db(y.prevProp,w);let R=F||j===c&&y.isActive&&!T&&N||v>p&&N,M=!1;const b=Array.isArray(w)?w:[w];let A=b.reduce(n(j),{});S===!1&&(A={});const{prevResolvedValues:P={}}=y,B={...P,...A},E=k=>{R=!0,h.has(k)&&(M=!0,h.delete(k)),y.needsAnimating[k]=!0;const D=t.getValue(k);D&&(D.liveStyle=!1)};for(const k in B){const D=A[k],z=P[k];if(x.hasOwnProperty(k))continue;let K=!1;Zn(D)&&Zn(z)?K=!Em(D,z):K=D!==z,K?D!=null?E(k):h.add(k):D!==void 0&&h.has(k)?E(k):y.protectedKeys[k]=!0}y.prevProp=w,y.prevResolvedValues=A,y.isActive&&(x={...x,...A}),r&&t.blockInitialAnimation&&(R=!1);const L=T&&F;R&&(!L||M)&&u.push(...b.map(k=>{const D={type:j};if(typeof k=="string"&&r&&!L&&t.manuallyAnimateOnMount&&t.parent){const{parent:z}=t,K=ha(z,k);if(z.enteringChildren&&K){const{delayChildren:Y}=K.transition||{};D.delay=Dm(z.enteringChildren,t,Y)}}return{animation:k,options:D}}))}if(h.size){const v={};if(typeof m.initial!="boolean"){const j=ha(t,Array.isArray(m.initial)?m.initial[0]:m.initial);j&&j.transition&&(v.transition=j.transition)}h.forEach(j=>{const y=t.getBaseTarget(j),w=t.getValue(j);w&&(w.liveStyle=!0),v[j]=y??null}),u.push({animation:v})}let f=!!u.length;return r&&(m.initial===!1||m.initial===m.animate)&&!t.manuallyAnimateOnMount&&(f=!1),r=!1,f?s(u):Promise.resolve()}function l(c,m){var u;if(a[c].isActive===m)return Promise.resolve();(u=t.variantChildren)==null||u.forEach(h=>{var x;return(x=h.animationState)==null?void 0:x.setActive(c,m)}),a[c].isActive=m;const d=o(c);for(const h in a)a[h].protectedKeys={};return d}return{animateChanges:o,setActive:l,setAnimateFunction:i,getState:()=>a,reset:()=>{a=gl()}}}function db(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!Em(s,t):!1}function _s(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function gl(){return{animate:_s(!0),whileInView:_s(),whileHover:_s(),whileTap:_s(),whileDrag:_s(),whileFocus:_s(),exit:_s()}}class Ls{constructor(s){this.isMounted=!1,this.node=s}update(){}}class mb extends Ls{constructor(s){super(s),s.animationState||(s.animationState=cb(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();_r(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 ub=0;class hb extends Ls{constructor(){super(...arguments),this.id=ub++}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 pb={animation:{Feature:mb},exit:{Feature:hb}};function Ha(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function Ya(t){return{point:{x:t.pageX,y:t.pageY}}}const xb=t=>s=>zi(s)&&t(s,Ya(s));function Ia(t,s,a,r){return Ha(t,s,xb(a),r)}const Im=1e-4,gb=1-Im,fb=1+Im,Lm=.01,yb=0-Lm,vb=0+Lm;function Dt(t){return t.max-t.min}function bb(t,s,a){return Math.abs(t-s)<=a}function fl(t,s,a,r=.5){t.origin=r,t.originPoint=Ye(s.min,s.max,t.origin),t.scale=Dt(a)/Dt(s),t.translate=Ye(a.min,a.max,t.origin)-t.originPoint,(t.scale>=gb&&t.scale<=fb||isNaN(t.scale))&&(t.scale=1),(t.translate>=yb&&t.translate<=vb||isNaN(t.translate))&&(t.translate=0)}function La(t,s,a,r){fl(t.x,s.x,a.x,r?r.originX:void 0),fl(t.y,s.y,a.y,r?r.originY:void 0)}function yl(t,s,a){t.min=a.min+s.min,t.max=t.min+Dt(s)}function jb(t,s,a){yl(t.x,s.x,a.x),yl(t.y,s.y,a.y)}function vl(t,s,a){t.min=s.min-a.min,t.max=t.min+Dt(s)}function Fa(t,s,a){vl(t.x,s.x,a.x),vl(t.y,s.y,a.y)}function Ht(t){return[t("x"),t("y")]}const Fm=({current:t})=>t?t.ownerDocument.defaultView:null,bl=(t,s)=>Math.abs(t-s);function Nb(t,s){const a=bl(t.x,s.x),r=bl(t.y,s.y);return Math.sqrt(a**2+r**2)}class _m{constructor(s,a,{transformPagePoint:r,contextWindow:n=window,dragSnapToOrigin:i=!1,distanceThreshold:o=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 h=dn(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,p=Nb(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!p)return;const{point:f}=h,{timestamp:v}=bt;this.history.push({...f,timestamp:v});const{onStart:j,onMove:y}=this.handlers;x||(j&&j(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),y&&y(this.lastMoveEvent,h)},this.handlePointerMove=(h,x)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=cn(x,this.transformPagePoint),Ke.update(this.updatePoint,!0)},this.handlePointerUp=(h,x)=>{this.end();const{onEnd:p,onSessionEnd:f,resumeAnimation:v}=this.handlers;if(this.dragSnapToOrigin&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=dn(h.type==="pointercancel"?this.lastMoveEventInfo:cn(x,this.transformPagePoint),this.history);this.startEvent&&p&&p(h,j),f&&f(h,j)},!zi(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=o,this.contextWindow=n||window;const l=Ya(s),c=cn(l,this.transformPagePoint),{point:m}=c,{timestamp:d}=bt;this.history=[{...m,timestamp:d}];const{onSessionStart:u}=a;u&&u(s,dn(c,this.history)),this.removeListeners=qa(Ia(this.contextWindow,"pointermove",this.handlePointerMove),Ia(this.contextWindow,"pointerup",this.handlePointerUp),Ia(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),Ds(this.updatePoint)}}function cn(t,s){return s?{point:s(t.point)}:t}function jl(t,s){return{x:t.x-s.x,y:t.y-s.y}}function dn({point:t},s){return{point:t,delta:jl(t,Om(s)),offset:jl(t,wb(s)),velocity:Cb(s,.1)}}function wb(t){return t[0]}function Om(t){return t[t.length-1]}function Cb(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Om(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>os(s)));)a--;if(!r)return{x:0,y:0};const i=Kt(n.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const o={x:(n.x-r.x)/i,y:(n.y-r.y)/i};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function Sb(t,{min:s,max:a},r){return s!==void 0&&t<s?t=r?Ye(s,t,r.min):Math.max(t,s):a!==void 0&&t>a&&(t=r?Ye(a,t,r.max):Math.min(t,a)),t}function Nl(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 Ab(t,{top:s,left:a,bottom:r,right:n}){return{x:Nl(t.x,a,n),y:Nl(t.y,s,r)}}function wl(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 Tb(t,s){return{x:wl(t.x,s.x),y:wl(t.y,s.y)}}function kb(t,s){let a=.5;const r=Dt(t),n=Dt(s);return n>r?a=$a(s.min,s.max-r,t.min):r>n&&(a=$a(t.min,t.max-n,s.min)),bs(0,1,a)}function Rb(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 Qn=.35;function Pb(t=Qn){return t===!1?t=0:t===!0&&(t=Qn),{x:Cl(t,"left","right"),y:Cl(t,"top","bottom")}}function Cl(t,s,a){return{min:Sl(t,s),max:Sl(t,a)}}function Sl(t,s){return typeof t=="number"?t:t[s]||0}const Db=new WeakMap;class Eb{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=st(),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=u=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(Ya(u).point)},o=(u,h)=>{const{drag:x,dragPropagation:p,onDragStart:f}=this.getProps();if(x&&!p&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Oy(x),!this.openDragLock))return;this.latestPointerEvent=u,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ht(j=>{let y=this.getAxisMotionValue(j).get()||0;if(ls.test(y)){const{projection:w}=this.visualElement;if(w&&w.layout){const N=w.layout.layoutBox[j];N&&(y=Dt(N)*(parseFloat(y)/100))}}this.originPoint[j]=y}),f&&Ke.postRender(()=>f(u,h)),Xn(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},l=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h;const{dragPropagation:x,dragDirectionLock:p,onDirectionLock:f,onDrag:v}=this.getProps();if(!x&&!this.openDragLock)return;const{offset:j}=h;if(p&&this.currentDirection===null){this.currentDirection=Mb(j),this.currentDirection!==null&&f&&f(this.currentDirection);return}this.updateAxis("x",h.point,j),this.updateAxis("y",h.point,j),this.visualElement.render(),v&&v(u,h)},c=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h,this.stop(u,h),this.latestPointerEvent=null,this.latestPanInfo=null},m=()=>Ht(u=>{var h;return this.getAnimationState(u)==="paused"&&((h=this.getAxisMotionValue(u).animation)==null?void 0:h.play())}),{dragSnapToOrigin:d}=this.getProps();this.panSession=new _m(s,{onSessionStart:i,onStart:o,onMove:l,onSessionEnd:c,resumeAnimation:m},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:r,contextWindow:Fm(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:o}=n;this.startAnimation(o);const{onDragEnd:l}=this.getProps();l&&Ke.postRender(()=>l(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||!nr(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let o=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(o=Sb(o,this.constraints[s],this.elastic[s])),i.set(o)}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&&oa(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=Ab(r.layoutBox,s):this.constraints=!1,this.elastic=Pb(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&Ht(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Rb(r.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!oa(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=Iv(r,n.root,this.visualElement.getTransformPagePoint());let o=Tb(n.layout.layoutBox,i);if(a){const l=a(Dv(o));this.hasMutatedConstraints=!!l,l&&(o=jm(l))}return o}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},m=Ht(d=>{if(!nr(d,a,this.currentDirection))return;let u=c&&c[d]||{};o&&(u={min:0,max:0});const h=n?200:1e6,x=n?40:1e7,p={type:"inertia",velocity:r?s[d]:0,bounceStiffness:h,bounceDamping:x,timeConstant:750,restDelta:1,restSpeed:10,...i,...u};return this.startAxisValueAnimation(d,p)});return Promise.all(m).then(l)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return Xn(this.visualElement,s),r.start(Qi(s,r,0,a,this.visualElement,!1))}stopAnimation(){Ht(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Ht(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){Ht(a=>{const{drag:r}=this.getProps();if(!nr(a,r,this.currentDirection))return;const{projection:n}=this.visualElement,i=this.getAxisMotionValue(a);if(n&&n.layout){const{min:o,max:l}=n.layout.layoutBox[a];i.set(s[a]-Ye(o,l,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!oa(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};Ht(o=>{const l=this.getAxisMotionValue(o);if(l&&this.constraints!==!1){const c=l.get();n[o]=kb({min:c,max:c},this.constraints[o])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),Ht(o=>{if(!nr(o,s,null))return;const l=this.getAxisMotionValue(o),{min:c,max:m}=this.constraints[o];l.set(Ye(c,m,n[o]))})}addListeners(){if(!this.visualElement.current)return;Db.set(this.visualElement,this);const s=this.visualElement.current,a=Ia(s,"pointerdown",c=>{const{drag:m,dragListener:d=!0}=this.getProps();m&&d&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();oa(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()),Ke.read(r);const o=Ha(window,"resize",()=>this.scalePositionWithinConstraints()),l=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:m})=>{this.isDragging&&m&&(Ht(d=>{const u=this.getAxisMotionValue(d);u&&(this.originPoint[d]+=c[d].translate,u.set(u.get()+c[d].translate))}),this.visualElement.render())});return()=>{o(),a(),i(),l&&l()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:o=Qn,dragMomentum:l=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:o,dragMomentum:l}}}function nr(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function Mb(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class Ib extends Ls{constructor(s){super(s),this.removeGroupControls=Yt,this.removeListeners=Yt,this.controls=new Eb(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Yt}unmount(){this.removeGroupControls(),this.removeListeners()}}const Al=t=>(s,a)=>{t&&Ke.postRender(()=>t(s,a))};class Lb extends Ls{constructor(){super(...arguments),this.removePointerDownListener=Yt}onPointerDown(s){this.session=new _m(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Fm(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Al(s),onStart:Al(a),onMove:r,onEnd:(i,o)=>{delete this.session,n&&Ke.postRender(()=>n(i,o))}}}mount(){this.removePointerDownListener=Ia(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 dr={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Tl(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const ka={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(ge.test(t))t=parseFloat(t);else return t;const a=Tl(t,s.target.x),r=Tl(t,s.target.y);return`${a}% ${r}%`}},Fb={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Es.parse(t);if(n.length>5)return r;const i=Es.createTransformer(t),o=typeof n[0]!="number"?1:0,l=a.x.scale*s.x,c=a.y.scale*s.y;n[0+o]/=l,n[1+o]/=c;const m=Ye(l,c,.5);return typeof n[2+o]=="number"&&(n[2+o]/=m),typeof n[3+o]=="number"&&(n[3+o]/=m),i(n)}};let mn=!1;class _b extends g.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;nv(Ob),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),mn&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),dr.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:o}=r;return o&&(o.isPresent=i,mn=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?o.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?o.promote():o.relegate()||Ke.postRender(()=>{const l=o.getStack();(!l||!l.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Bi.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;mn=!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 $m(t){const[s,a]=om(),r=g.useContext(bi);return e.jsx(_b,{...t,layoutGroup:r,switchLayoutGroup:g.useContext(vm),isPresent:s,safeToRemove:a})}const Ob={borderRadius:{...ka,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:ka,borderTopRightRadius:ka,borderBottomLeftRadius:ka,borderBottomRightRadius:ka,boxShadow:Fb};function $b(t,s,a){const r=St(t)?t:xa(t);return r.start(Qi("",r,s,a)),r.animation}const Ub=(t,s)=>t.depth-s.depth;class Vb{constructor(){this.children=[],this.isDirty=!1}add(s){wi(this.children,s),this.isDirty=!0}remove(s){Ci(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(Ub),this.isDirty=!1,this.children.forEach(s)}}function Bb(t,s){const a=_t.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Ds(r),t(i-s))};return Ke.setup(r,!0),()=>Ds(r)}const Um=["TopLeft","TopRight","BottomLeft","BottomRight"],zb=Um.length,kl=t=>typeof t=="string"?parseFloat(t):t,Rl=t=>typeof t=="number"||ge.test(t);function Hb(t,s,a,r,n,i){n?(t.opacity=Ye(0,a.opacity??1,Wb(r)),t.opacityExit=Ye(s.opacity??1,0,qb(r))):i&&(t.opacity=Ye(s.opacity??1,a.opacity??1,r));for(let o=0;o<zb;o++){const l=`border${Um[o]}Radius`;let c=Pl(s,l),m=Pl(a,l);if(c===void 0&&m===void 0)continue;c||(c=0),m||(m=0),c===0||m===0||Rl(c)===Rl(m)?(t[l]=Math.max(Ye(kl(c),kl(m),r),0),(ls.test(m)||ls.test(c))&&(t[l]+="%")):t[l]=m}(s.rotate||a.rotate)&&(t.rotate=Ye(s.rotate||0,a.rotate||0,r))}function Pl(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const Wb=Vm(0,.5,Td),qb=Vm(.5,.95,Yt);function Vm(t,s,a){return r=>r<t?0:r>s?1:a($a(t,s,r))}function Dl(t,s){t.min=s.min,t.max=s.max}function zt(t,s){Dl(t.x,s.x),Dl(t.y,s.y)}function El(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Ml(t,s,a,r,n){return t-=s,t=yr(t,1/a,r),n!==void 0&&(t=yr(t,1/n,r)),t}function Kb(t,s=0,a=1,r=.5,n,i=t,o=t){if(ls.test(s)&&(s=parseFloat(s),s=Ye(o.min,o.max,s/100)-o.min),typeof s!="number")return;let l=Ye(i.min,i.max,r);t===i&&(l-=s),t.min=Ml(t.min,s,a,l,n),t.max=Ml(t.max,s,a,l,n)}function Il(t,s,[a,r,n],i,o){Kb(t,s[a],s[r],s[n],s.scale,i,o)}const Gb=["x","scaleX","originX"],Yb=["y","scaleY","originY"];function Ll(t,s,a,r){Il(t.x,s,Gb,a?a.x:void 0,r?r.x:void 0),Il(t.y,s,Yb,a?a.y:void 0,r?r.y:void 0)}function Fl(t){return t.translate===0&&t.scale===1}function Bm(t){return Fl(t.x)&&Fl(t.y)}function _l(t,s){return t.min===s.min&&t.max===s.max}function Zb(t,s){return _l(t.x,s.x)&&_l(t.y,s.y)}function Ol(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function zm(t,s){return Ol(t.x,s.x)&&Ol(t.y,s.y)}function $l(t){return Dt(t.x)/Dt(t.y)}function Ul(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class Xb{constructor(){this.members=[]}add(s){wi(this.members,s),s.scheduleRender()}remove(s){if(Ci(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 Jb(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,o=(a==null?void 0:a.z)||0;if((n||i||o)&&(r=`translate3d(${n}px, ${i}px, ${o}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:m,rotate:d,rotateX:u,rotateY:h,skewX:x,skewY:p}=a;m&&(r=`perspective(${m}px) ${r}`),d&&(r+=`rotate(${d}deg) `),u&&(r+=`rotateX(${u}deg) `),h&&(r+=`rotateY(${h}deg) `),x&&(r+=`skewX(${x}deg) `),p&&(r+=`skewY(${p}deg) `)}const l=t.x.scale*s.x,c=t.y.scale*s.y;return(l!==1||c!==1)&&(r+=`scale(${l}, ${c})`),r||"none"}const un=["","X","Y","Z"],Qb=1e3;let ej=0;function hn(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Hm(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=Rm(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Ke,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Hm(r)}function Wm({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(o={},l=s==null?void 0:s()){this.id=ej++,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(aj),this.nodes.forEach(oj),this.nodes.forEach(lj),this.nodes.forEach(rj)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=o,this.root=l?l.root||l:this,this.path=l?[...l.path,l]:[],this.parent=l,this.depth=l?l.depth+1:0;for(let c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new Vb)}addEventListener(o,l){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new Ti),this.eventHandlers.get(o).add(l)}notifyListeners(o,...l){const c=this.eventHandlers.get(o);c&&c.notify(...l)}hasListeners(o){return this.eventHandlers.has(o)}mount(o){if(this.instance)return;this.isSVG=im(o)&&!Hy(o),this.instance=o;const{layoutId:l,layout:c,visualElement:m}=this.options;if(m&&!m.current&&m.mount(o),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||l)&&(this.isLayoutDirty=!0),t){let d,u=0;const h=()=>this.root.updateBlockedByResize=!1;Ke.read(()=>{u=window.innerWidth}),t(o,()=>{const x=window.innerWidth;x!==u&&(u=x,this.root.updateBlockedByResize=!0,d&&d(),d=Bb(h,250),dr.hasAnimatedSinceResize&&(dr.hasAnimatedSinceResize=!1,this.nodes.forEach(zl)))})}l&&this.root.registerSharedNode(l,this),this.options.animate!==!1&&m&&(l||c)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u,hasRelativeLayoutChanged:h,layout:x})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const p=this.options.transition||m.getDefaultTransition()||hj,{onLayoutAnimationStart:f,onLayoutAnimationComplete:v}=m.getProps(),j=!this.targetLayout||!zm(this.targetLayout,x),y=!u&&h;if(this.options.layoutRoot||this.resumeFrom||y||u&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...Ui(p,"layout"),onPlay:f,onComplete:v};(m.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(d,y)}else u||zl(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=x})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Ds(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(cj),this.animationId++)}getTransformTemplate(){const{visualElement:o}=this.options;return o&&o.getProps().transformTemplate}willUpdate(o=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Hm(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;d<this.path.length;d++){const u=this.path[d];u.shouldResetTransform=!0,u.updateScroll("snapshot"),u.options.layoutRoot&&u.willUpdate(!1)}const{layoutId:l,layout:c}=this.options;if(l===void 0&&!c)return;const m=this.getTransformTemplate();this.prevTransformTemplateValue=m?m(this.latestValues,""):void 0,this.updateSnapshot(),o&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Vl);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Bl);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(ij),this.nodes.forEach(tj),this.nodes.forEach(sj)):this.nodes.forEach(Bl),this.clearAllSnapshots();const l=_t.now();bt.delta=bs(0,1e3/60,l-bt.timestamp),bt.timestamp=l,bt.isProcessing=!0,en.update.process(bt),en.preRender.process(bt),en.render.process(bt),bt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Bi.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(nj),this.sharedNodes.forEach(dj)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Ke.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Ke.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Dt(this.snapshot.measuredBox.x)&&!Dt(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 o=this.layout;this.layout=this.measure(!1),this.layoutCorrected=st(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:l}=this.options;l&&l.notify("LayoutMeasure",this.layout.layoutBox,o?o.layoutBox:void 0)}updateScroll(o="measure"){let l=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===o&&(l=!1),l&&this.instance){const c=r(this.instance);this.scroll={animationId:this.root.animationId,phase:o,isRoot:c,offset:a(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!n)return;const o=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,l=this.projectionDelta&&!Bm(this.projectionDelta),c=this.getTransformTemplate(),m=c?c(this.latestValues,""):void 0,d=m!==this.prevTransformTemplateValue;o&&this.instance&&(l||Vs(this.latestValues)||d)&&(n(this.instance,m),this.shouldResetTransform=!1,this.scheduleRender())}measure(o=!0){const l=this.measurePageBox();let c=this.removeElementScroll(l);return o&&(c=this.removeTransform(c)),pj(c),{animationId:this.root.animationId,measuredBox:l,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var m;const{visualElement:o}=this.options;if(!o)return st();const l=o.measureViewportBox();if(!(((m=this.scroll)==null?void 0:m.wasRoot)||this.path.some(xj))){const{scroll:d}=this.root;d&&(la(l.x,d.offset.x),la(l.y,d.offset.y))}return l}removeElementScroll(o){var c;const l=st();if(zt(l,o),(c=this.scroll)!=null&&c.wasRoot)return l;for(let m=0;m<this.path.length;m++){const d=this.path[m],{scroll:u,options:h}=d;d!==this.root&&u&&h.layoutScroll&&(u.wasRoot&&zt(l,o),la(l.x,u.offset.x),la(l.y,u.offset.y))}return l}applyTransform(o,l=!1){const c=st();zt(c,o);for(let m=0;m<this.path.length;m++){const d=this.path[m];!l&&d.options.layoutScroll&&d.scroll&&d!==d.root&&ca(c,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Vs(d.latestValues)&&ca(c,d.latestValues)}return Vs(this.latestValues)&&ca(c,this.latestValues),c}removeTransform(o){const l=st();zt(l,o);for(let c=0;c<this.path.length;c++){const m=this.path[c];if(!m.instance||!Vs(m.latestValues))continue;Kn(m.latestValues)&&m.updateSnapshot();const d=st(),u=m.measurePageBox();zt(d,u),Ll(l,m.latestValues,m.snapshot?m.snapshot.layoutBox:void 0,d)}return Vs(this.latestValues)&&Ll(l,this.latestValues),l}setTargetDelta(o){this.targetDelta=o,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(o){this.options={...this.options,...o,crossfade:o.crossfade!==void 0?o.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!==bt.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(o=!1){var h;const l=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=l.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=l.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=l.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==l;if(!(o||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:d,layoutId:u}=this.options;if(!(!this.layout||!(d||u))){if(this.resolvedRelativeTargetAt=bt.timestamp,!this.targetDelta&&!this.relativeTarget){const x=this.getClosestProjectingParent();x&&x.layout&&this.animationProgress!==1?(this.relativeParent=x,this.forceRelativeParentToResolveTarget(),this.relativeTarget=st(),this.relativeTargetOrigin=st(),Fa(this.relativeTargetOrigin,this.layout.layoutBox,x.layout.layoutBox),zt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=st(),this.targetWithTransforms=st()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),jb(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):zt(this.target,this.layout.layoutBox),wm(this.target,this.targetDelta)):zt(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const x=this.getClosestProjectingParent();x&&!!x.resumingFrom==!!this.resumingFrom&&!x.options.layoutScroll&&x.target&&this.animationProgress!==1?(this.relativeParent=x,this.forceRelativeParentToResolveTarget(),this.relativeTarget=st(),this.relativeTargetOrigin=st(),Fa(this.relativeTargetOrigin,this.target,x.target),zt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Kn(this.parent.latestValues)||Nm(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 p;const o=this.getLead(),l=!!this.resumingFrom||this!==o;let c=!0;if((this.isProjectionDirty||(p=this.parent)!=null&&p.isProjectionDirty)&&(c=!1),l&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===bt.timestamp&&(c=!1),c)return;const{layout:m,layoutId:d}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(m||d))return;zt(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,h=this.treeScale.y;Mv(this.layoutCorrected,this.treeScale,this.path,l),o.layout&&!o.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(o.target=o.layout.layoutBox,o.targetWithTransforms=st());const{target:x}=o;if(!x){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(El(this.prevProjectionDelta.x,this.projectionDelta.x),El(this.prevProjectionDelta.y,this.projectionDelta.y)),La(this.projectionDelta,this.layoutCorrected,x,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==h||!Ul(this.projectionDelta.x,this.prevProjectionDelta.x)||!Ul(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",x))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(o=!0){var l;if((l=this.options.visualElement)==null||l.scheduleRender(),o){const c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=da(),this.projectionDelta=da(),this.projectionDeltaWithTransform=da()}setAnimationOrigin(o,l=!1){const c=this.snapshot,m=c?c.latestValues:{},d={...this.latestValues},u=da();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!l;const h=st(),x=c?c.source:void 0,p=this.layout?this.layout.source:void 0,f=x!==p,v=this.getStack(),j=!v||v.members.length<=1,y=!!(f&&!j&&this.options.crossfade===!0&&!this.path.some(uj));this.animationProgress=0;let w;this.mixTargetDelta=N=>{const S=N/1e3;Hl(u.x,o.x,S),Hl(u.y,o.y,S),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Fa(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),mj(this.relativeTarget,this.relativeTargetOrigin,h,S),w&&Zb(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=st()),zt(w,this.relativeTarget)),f&&(this.animationValues=d,Hb(d,m,this.latestValues,S,y,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){var l,c,m;this.notifyListeners("animationStart"),(l=this.currentAnimation)==null||l.stop(),(m=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||m.stop(),this.pendingAnimation&&(Ds(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Ke.update(()=>{dr.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=xa(0)),this.currentAnimation=$b(this.motionValue,[0,1e3],{...o,velocity:0,isSync:!0,onUpdate:d=>{this.mixTargetDelta(d),o.onUpdate&&o.onUpdate(d)},onStop:()=>{},onComplete:()=>{o.onComplete&&o.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 o=this.getStack();o&&o.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(Qb),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:l,target:c,layout:m,latestValues:d}=o;if(!(!l||!c||!m)){if(this!==o&&this.layout&&m&&qm(this.options.animationType,this.layout.layoutBox,m.layoutBox)){c=this.target||st();const u=Dt(this.layout.layoutBox.x);c.x.min=o.target.x.min,c.x.max=c.x.min+u;const h=Dt(this.layout.layoutBox.y);c.y.min=o.target.y.min,c.y.max=c.y.min+h}zt(l,c),ca(l,d),La(this.projectionDeltaWithTransform,this.layoutCorrected,l,d)}}registerSharedNode(o,l){this.sharedNodes.has(o)||this.sharedNodes.set(o,new Xb),this.sharedNodes.get(o).add(l);const m=l.options.initialPromotionConfig;l.promote({transition:m?m.transition:void 0,preserveFollowOpacity:m&&m.shouldPreserveFollowOpacity?m.shouldPreserveFollowOpacity(l):void 0})}isLead(){const o=this.getStack();return o?o.lead===this:!0}getLead(){var l;const{layoutId:o}=this.options;return o?((l=this.getStack())==null?void 0:l.lead)||this:this}getPrevLead(){var l;const{layoutId:o}=this.options;return o?(l=this.getStack())==null?void 0:l.prevLead:void 0}getStack(){const{layoutId:o}=this.options;if(o)return this.root.sharedNodes.get(o)}promote({needsReset:o,transition:l,preserveFollowOpacity:c}={}){const m=this.getStack();m&&m.promote(this,c),o&&(this.projectionDelta=void 0,this.needsReset=!0),l&&this.setOptions({transition:l})}relegate(){const o=this.getStack();return o?o.relegate(this):!1}resetSkewAndRotation(){const{visualElement:o}=this.options;if(!o)return;let l=!1;const{latestValues:c}=o;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(l=!0),!l)return;const m={};c.z&&hn("z",o,m,this.animationValues);for(let d=0;d<un.length;d++)hn(`rotate${un[d]}`,o,m,this.animationValues),hn(`skew${un[d]}`,o,m,this.animationValues);o.render();for(const d in m)o.setStaticValue(d,m[d]),this.animationValues&&(this.animationValues[d]=m[d]);o.scheduleRender()}applyProjectionStyles(o,l){if(!this.instance||this.isSVG)return;if(!this.isVisible){o.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,o.visibility="",o.opacity="",o.pointerEvents=cr(l==null?void 0:l.pointerEvents)||"",o.transform=c?c(this.latestValues,""):"none";return}const m=this.getLead();if(!this.projectionDelta||!this.layout||!m.target){this.options.layoutId&&(o.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,o.pointerEvents=cr(l==null?void 0:l.pointerEvents)||""),this.hasProjected&&!Vs(this.latestValues)&&(o.transform=c?c({},""):"none",this.hasProjected=!1);return}o.visibility="";const d=m.animationValues||m.latestValues;this.applyTransformsToTarget();let u=Jb(this.projectionDeltaWithTransform,this.treeScale,d);c&&(u=c(d,u)),o.transform=u;const{x:h,y:x}=this.projectionDelta;o.transformOrigin=`${h.origin*100}% ${x.origin*100}% 0`,m.animationValues?o.opacity=m===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:o.opacity=m===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const p in za){if(d[p]===void 0)continue;const{correct:f,applyTo:v,isCSSVariable:j}=za[p],y=u==="none"?d[p]:f(d[p],m);if(v){const w=v.length;for(let N=0;N<w;N++)o[v[N]]=y}else j?this.options.visualElement.renderState.vars[p]=y:o[p]=y}this.options.layoutId&&(o.pointerEvents=m===this?cr(l==null?void 0:l.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(o=>{var l;return(l=o.currentAnimation)==null?void 0:l.stop()}),this.root.nodes.forEach(Vl),this.root.sharedNodes.clear()}}}function tj(t){t.updateLayout()}function sj(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,o=s.source!==t.layout.source;i==="size"?Ht(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],x=Dt(h);h.min=r[u].min,h.max=h.min+x}):qm(i,s.layoutBox,r)&&Ht(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],x=Dt(r[u]);h.max=h.min+x,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+x)});const l=da();La(l,r,s.layoutBox);const c=da();o?La(c,t.applyTransform(n,!0),s.measuredBox):La(c,r,s.layoutBox);const m=!Bm(l);let d=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:h,layout:x}=u;if(h&&x){const p=st();Fa(p,s.layoutBox,h.layoutBox);const f=st();Fa(f,r,x.layoutBox),zm(p,f)||(d=!0),u.options.layoutRoot&&(t.relativeTarget=f,t.relativeTargetOrigin=p,t.relativeParent=u)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:l,hasLayoutChanged:m,hasRelativeLayoutChanged:d})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function aj(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 rj(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function nj(t){t.clearSnapshot()}function Vl(t){t.clearMeasurements()}function Bl(t){t.isLayoutDirty=!1}function ij(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function zl(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function oj(t){t.resolveTargetDelta()}function lj(t){t.calcProjection()}function cj(t){t.resetSkewAndRotation()}function dj(t){t.removeLeadSnapshot()}function Hl(t,s,a){t.translate=Ye(s.translate,0,a),t.scale=Ye(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function Wl(t,s,a,r){t.min=Ye(s.min,a.min,r),t.max=Ye(s.max,a.max,r)}function mj(t,s,a,r){Wl(t.x,s.x,a.x,r),Wl(t.y,s.y,a.y,r)}function uj(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const hj={duration:.45,ease:[.4,0,.1,1]},ql=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Kl=ql("applewebkit/")&&!ql("chrome/")?Math.round:Yt;function Gl(t){t.min=Kl(t.min),t.max=Kl(t.max)}function pj(t){Gl(t.x),Gl(t.y)}function qm(t,s,a){return t==="position"||t==="preserve-aspect"&&!bb($l(s),$l(a),.2)}function xj(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const gj=Wm({attachResizeListener:(t,s)=>Ha(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),pn={current:void 0},Km=Wm({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!pn.current){const t=new gj({});t.mount(window),t.setOptions({layoutScroll:!0}),pn.current=t}return pn.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),fj={pan:{Feature:Lb},drag:{Feature:Ib,ProjectionNode:Km,MeasureLayout:$m}};function Yl(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&&Ke.postRender(()=>i(s,Ya(s)))}class yj extends Ls{mount(){const{current:s}=this.node;s&&(this.unmount=$y(s,(a,r)=>(Yl(this.node,r,"Start"),n=>Yl(this.node,n,"End"))))}unmount(){}}class vj extends Ls{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=qa(Ha(this.node.current,"focus",()=>this.onFocus()),Ha(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Zl(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&&Ke.postRender(()=>i(s,Ya(s)))}class bj extends Ls{mount(){const{current:s}=this.node;s&&(this.unmount=zy(s,(a,r)=>(Zl(this.node,r,"Start"),(n,{success:i})=>Zl(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const ei=new WeakMap,xn=new WeakMap,jj=t=>{const s=ei.get(t.target);s&&s(t)},Nj=t=>{t.forEach(jj)};function wj({root:t,...s}){const a=t||document;xn.has(a)||xn.set(a,{});const r=xn.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(Nj,{root:t,...s})),r[n]}function Cj(t,s,a){const r=wj(s);return ei.set(t,a),r.observe(t),()=>{ei.delete(t),r.unobserve(t)}}const Sj={some:0,all:1};class Aj extends Ls{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,o={root:a?a.current:void 0,rootMargin:r,threshold:typeof n=="number"?n:Sj[n]},l=c=>{const{isIntersecting:m}=c;if(this.isInView===m||(this.isInView=m,i&&!m&&this.hasEnteredView))return;m&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",m);const{onViewportEnter:d,onViewportLeave:u}=this.node.getProps(),h=m?d:u;h&&h(c)};return Cj(this.node.current,o,l)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:s,prevProps:a}=this.node;["amount","margin","root"].some(Tj(s,a))&&this.startObserver()}unmount(){}}function Tj({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const kj={inView:{Feature:Aj},tap:{Feature:bj},focus:{Feature:vj},hover:{Feature:yj}},Rj={layout:{ProjectionNode:Km,MeasureLayout:$m}},Pj={...pb,...kj,...fj,...Rj},yt=Pv(Pj,zv),Xl=[{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:kn,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"]},{id:"vendor-payment",name:"Vendor Payment",description:"Streamlined vendor payment approval with PO validation and financial controls",category:"Finance",icon:up,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"]}];function Dj({open:t,onClose:s,onSelectTemplate:a}){var l;const[r,n]=g.useState(null),i=c=>{n(c)},o=()=>{r&&(a(r),s())};return e.jsx(ut,{open:t,onOpenChange:s,children:e.jsxs(it,{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(ot,{className:"sr-only",children:"Select a Template"}),e.jsx(Xt,{className:"sr-only",children:"Choose from pre-configured templates with predefined workflows and approval chains for faster processing."}),e.jsx("button",{onClick:s,className:"absolute top-6 right-6 z-50 w-10 h-10 rounded-full bg-white shadow-lg hover:shadow-xl border border-gray-200 flex items-center justify-center transition-all hover:scale-110",children:e.jsx(jt,{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(Ar,{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:Xl.map((c,m)=>{const d=c.icon,u=r===c.id;return e.jsx(yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:m*.1},whileHover:{scale:1.03},whileTap:{scale:.98},children:e.jsxs(W,{className:`cursor-pointer h-full transition-all duration-300 border-2 ${u?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>i(c.id),children:[e.jsxs(Q,{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 ${c.color} flex items-center justify-center shadow-md`,children:e.jsx(d,{className:"w-7 h-7 text-white"})}),u&&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(fa,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ee,{className:"text-xl mb-2",children:c.name}),e.jsx(le,{className:"text-sm leading-relaxed",children:c.description})]})]}),e.jsxs(q,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(J,{variant:"secondary",className:"text-xs",children:c.category})}),e.jsx(Nt,{}),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(Pe,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:c.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Qe,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[c.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:[c.features.slice(0,3).map((h,x)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(xe,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:h})]},x)),c.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",c.features.length-3," more features"]})]})]})]})]})},c.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(I,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(I,{onClick:o,disabled:!r,size:"lg",className:`gap-2 px-8 ${r?"bg-blue-600 hover:bg-blue-700":"bg-gray-400"}`,children:["Continue with Template",e.jsx(mt,{className:"w-4 h-4"})]})]}),e.jsx(Lr,{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:(l=Xl.find(c=>c.id===r))==null?void 0:l.name})]})})})]})})]})})}const Ej={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 Mj(t,s,a){const[r,n]=g.useState(Ej),[i,o]=g.useState(null),[l,c]=g.useState(t),[m,d]=g.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[u,h]=g.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[x,p]=g.useState([]);return g.useEffect(()=>{(async()=>{var j;try{const y=await Qs("DOCUMENT_POLICY"),w={};y.forEach(A=>{w[A.configKey]=A.configValue});const N=parseInt(w.MAX_FILE_SIZE_MB||"10"),T=(w.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(A=>A.trim().toLowerCase());h({maxFileSizeMB:N,allowedFileTypes:T});const F=await Qs("WORKFLOW_SHARING"),R=await Qs("TAT_SETTINGS"),M=[...F,...R],b={};M.forEach(A=>{b[A.configKey]=A.configValue}),d({maxApprovalLevels:parseInt(b.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(b.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((j=b.ALLOW_ADD_SPECTATOR)==null?void 0:j.toLowerCase())==="true",maxSpectators:parseInt(b.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(y){console.error("Failed to load policies:",y)}})()},[]),g.useEffect(()=>{if(!t||!s)return;let v=!0;return(async()=>{try{c(!0);const j=await Ks(s);if(!v||!j)return;const y=j.workflow||{},w=Array.isArray(j.approvals)?j.approvals:[],N=Array.isArray(j.participants)?j.participants:[],S=Array.isArray(j.documents)?j.documents.filter(P=>!P.isDeleted):[];p(S);const T=(y.priority||"").toString().toLowerCase(),F={standard:"standard",express:"express"},R=y.templateType==="TEMPLATE"?"existing-template":"custom",M=a.find(P=>P.id===R)||a[0]||null;o(M);const b=w.sort((P,B)=>(P.levelNumber||0)-(B.levelNumber||0)).map(P=>{const B=Number(P.tatHours||24),E=Math.floor(B/24),L=B%24;return{id:P.approverId||`temp-${P.levelNumber}`,name:P.approverName||P.approverEmail||"",email:P.approverEmail||"",role:P.levelName||`Level ${P.levelNumber}`,department:"",avatar:(P.approverName||P.approverEmail||"XX").substring(0,2).toUpperCase(),level:P.levelNumber||1,canClose:!1,tat:E>0?E:L,tatType:E>0?"days":"hours",userId:P.approverId}}),A=N.filter(P=>(P.participantType||P.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(P.userEmail||P.user_email||P.email):!1).map((P,B)=>{const E=P.userId||P.user_id||P.id,L=P.userName||P.user_name||P.name||"",C=P.userEmail||P.user_email||P.email||"",D=(L||C||"XX").split(" ").map(z=>z[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:E||`spectator-${s}-${B}-${Date.now()}`,userId:E,name:L||C||"Spectator",email:C,role:"Spectator",department:P.department||"",avatar:D,level:1,canClose:!1}});n(P=>({...P,template:R,title:y.title||"",description:y.description||"",priority:F[T]||"standard",approvers:b,approverCount:b.length||1,spectators:A,maxLevel:Math.max(...b.map(B=>B.level||1),1)}))}catch(j){console.error("Failed to load draft:",j)}finally{v&&c(!1)}})(),()=>{v=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(v,j)=>{n(y=>({...y,[v]:j}))},selectedTemplate:i,setSelectedTemplate:o,loadingDraft:l,systemPolicy:m,documentPolicy:u,existingDocuments:x,setExistingDocuments:p}}const Jl=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function Ij(t,s,a){const[r,n]=g.useState(t?2:1),i=Jl.length,o=u=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u),l=()=>{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(u=>{if(!u||!u.email||!o(u.email))return!1;if(!u.userId)return!0;const h=u.tatType||"hours";return h==="hours"?u.tat&&u.tat>0&&u.tat<=720:h==="days"?u.tat&&u.tat>0&&u.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:Jl,isStepValid:l,nextStep:()=>{l()&&(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:u=>{u>=1&&u<=i&&n(u)},validateEmail:o}}function Lj(){const[t,s]=g.useState({open:!1,type:"error",email:"",message:""}),[a,r]=g.useState({open:!1,violations:[]}),[n,i]=g.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(h,x,p="")=>{s({open:!0,type:h,email:x,message:p})},closeValidationModal:()=>{s(h=>({...h,open:!1}))},openPolicyViolationModal:h=>{r({open:!0,violations:h})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:h=>{i({open:!0,errors:h})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function Fj(t){const s=(t==null?void 0:t.userId)||"",a=(t==null?void 0:t.email)||"",r=(t==null?void 0:t.displayName)||(t==null?void 0:t.name)||a.split("@")[0]||"Initiator";return{userId:s,userEmail:a,userName:r,participantType:"INITIATOR",canComment:!0,canViewDocuments:!0,canDownloadDocuments:!0,notificationEnabled:!0,addedBy:s}}function _j(t,s){return t.filter(a=>a==null?void 0:a.email).map(a=>({userId:a.userId||void 0,userEmail:a.email,userName:a.name||a.email.split("@")[0]||"Approver",participantType:"APPROVER",canComment:!0,canViewDocuments:!0,canDownloadDocuments:!0,notificationEnabled:!0,addedBy:s}))}function Oj(t,s){return t.filter(a=>a==null?void 0:a.email).map(a=>({userId:a.id||a.userId||void 0,userEmail:a.email,userName:a.name||a.email.split("@")[0]||"Spectator",participantType:"SPECTATOR",canComment:!0,canViewDocuments:!0,canDownloadDocuments:!0,notificationEnabled:!0,addedBy:s}))}function Gm(t,s,a){const r=Fj(t),n=(t==null?void 0:t.userId)||"",i=_j(s,n),o=Oj(a,n);return[r,...i,...o]}function $j(t,s){const a=t.map(n=>n==null?void 0:n.userId).filter(Boolean),r=t.map(n=>{var i,o;return(o=(i=n==null?void 0:n.email)==null?void 0:i.toLowerCase)==null?void 0:o.call(i)}).filter(Boolean);return s.filter(n=>{const i=a.includes(n==null?void 0:n.id),o=r.includes(((n==null?void 0:n.email)||"").toLowerCase());return!i&&!o})}function Uj(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function Vj(t,s,a){var n;const r=Uj(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 Bj(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return Vj(a,n,n===s)})}function Ql(t,s,a){const r=Gm(a,t.approvers||[],t.spectators||[]),n=$j(t.approvers||[],t.spectators||[]);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(i=>({userId:(i==null?void 0:i.userId)||"",email:(i==null?void 0:i.email)||"",name:i==null?void 0:i.name,tat:(i==null?void 0:i.tat)||"",tatType:(i==null?void 0:i.tatType)||"hours"})),spectators:n.map(i=>{var o,l;return{userId:(i==null?void 0:i.id)||"",name:(i==null?void 0:i.name)||((l=(o=i==null?void 0:i.email)==null?void 0:o.split("@"))==null?void 0:l[0])||"Spectator",email:(i==null?void 0:i.email)||""}}),ccList:(t.ccList||[]).map(i=>{var o,l;return{id:i==null?void 0:i.id,name:(i==null?void 0:i.name)||((l=(o=i==null?void 0:i.email)==null?void 0:o.split("@"))==null?void 0:l[0])||"CC",email:(i==null?void 0:i.email)||""}}),participants:r}}function ec(t,s,a){const r=Bj(t.approvers||[],t.approverCount||1),n=Gm(s,(t.approvers||[]).filter(i=>(i==null?void 0:i.email)&&(i==null?void 0:i.userId)),(t.spectators||[]).filter(i=>i==null?void 0:i.email));return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:r,participants:n,deleteDocumentIds:a.length>0?a:void 0}}function zj(t,s){return t.slice(0,s).some(n=>!(n!=null&&n.userId)||!(n!=null&&n.email))?{valid:!1,message:"Please select approvers using @ search so we can capture their user IDs."}:{valid:!0}}async function Ym(t,s){return{id:(await ad(t,s||[],"SUPPORTING")).id}}async function Zm(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await Fg(t,s,a||[],r):await Lg(t,s)}async function Xm(t){await ld(t)}async function Hj(t,s){const a=await Ym(t,s);return await Xm(a.id),a}async function Wj(t,s,a,r){await Zm(t,s,a,r),await Xm(t)}function qj({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:o,onSubmit:l}){const[c,m]=g.useState(!1),[d,u]=g.useState(!1);return{submitting:c,savingDraft:d,handleSubmit:async()=>{if(c||d)return;const p=zj(t.approvers||[],t.approverCount||1);if(!p.valid){alert(p.message);return}m(!0);try{if(i&&o){const f=ec(t,n,r);await Wj(o,f,a,r),l==null||l({...t,backendId:o,template:s})}else{const f=Ql(t,s,n),v=await Hj(f,a);l==null||l({...t,backendId:v.id,template:s})}}catch(f){console.error("Failed to submit workflow:",f),m(!1)}},handleSaveDraft:async()=>{if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||d)){u(!0);try{if(i&&o){const p=ec(t,n,r);await Zm(o,p,a,r),l==null||l({...t,backendId:o,template:s})}else{const p=Ql(t,s,n),f=await Ym(p,a);l==null||l({...t,backendId:f.id,template:s})}}catch(p){console.error("Failed to save draft:",p),u(!1)}}}}}async function Kj(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 ys(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 vs({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 Gj(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 o=r[i];if(o.userId||!o.email)continue;const l=await Kj(o,s);if(!l.success)return{success:!1,error:l.error};try{const d=(((n=(await ys(o.email,1)).data)==null?void 0:n.data)||[])[0];if(d){const u=await vs({userId:d.userId,email:d.email,displayName:d.displayName,firstName:d.firstName,lastName:d.lastName,department:d.department,phone:d.phone,mobilePhone:d.mobilePhone,designation:d.designation,jobTitle:d.jobTitle,manager:d.manager,employeeId:d.employeeId,employeeNumber:d.employeeNumber,secondEmail:d.secondEmail,location:d.location});r[i]={...o,userId:u.userId,name:u.displayName||o.name,department:u.department||o.department,avatar:(u.displayName||u.email).substring(0,2).toUpperCase()}}}catch(c){console.error(`Failed to update approver ${o.email}:`,c)}}return{success:!0,validatedApprovers:r}}function Yj({selectedTemplate:t,setSelectedTemplate:s,updateFormData:a,formData:r,currentStep:n,isStepValid:i,wizardNextStep:o,wizardPrevStep:l,user:c,openValidationModal:m,onSubmit:d}){const[u,h]=g.useState(!1),[x,p]=g.useState(null);return{showTemplateModal:u,setShowTemplateModal:h,previewDocument:x,selectTemplate:S=>{s(S),a("template",S.id),a("category",S.category),a("priority",S.priority);const T=new Date;T.setDate(T.getDate()+S.suggestedSLA),a("slaEndDate",T),S.id==="existing-template"&&h(!0)},handleTemplateSelection:S=>{d&&d({templateType:S})},nextStep:async()=>{var S;if(i()){if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){const T=((S=c==null?void 0:c.email)==null?void 0:S.toLowerCase())||"",F=await Gj(r.approvers,T);if(!F.success&&F.error){m(F.error.type,F.error.email,F.error.message);return}F.validatedApprovers&&a("approvers",F.validatedApprovers)}o()}},prevStep:()=>{l(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(S,T)=>{if(T){const F=S.documentId||S.document_id||"";p({fileName:S.originalFileName||S.fileName||"Document",fileType:S.fileType||S.file_type||"application/octet-stream",fileUrl:od(F),fileSize:Number(S.fileSize||S.file_size||0),documentId:F})}else{const F=URL.createObjectURL(S);p({fileName:S.name,fileType:S.type||"application/octet-stream",fileUrl:F,fileSize:S.size,file:S})}},closePreview:()=>{x!=null&&x.fileUrl&&(x!=null&&x.file)&&URL.revokeObjectURL(x.fileUrl),p(null)}}}const tc=[{id:"custom",name:"Custom Request",description:"Create a custom request for unique business needs with full flexibility to define your own workflow and requirements",category:"General",icon:Sr,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:we,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];function Zj({currentStep:t,totalSteps:s,stepNames:a}){const r=Math.round(t/s*100);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:"max-w-6xl 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-between mb-2","data-testid":"wizard-stepper-desktop-steps",children:a.map((n,i)=>e.jsxs("div",{className:"flex items-center","data-testid":`wizard-stepper-desktop-step-${i+1}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold ${i+1<t?"bg-green-600 text-white":i+1===t?"bg-blue-600 text-white":"bg-gray-200 text-gray-600"}`,"data-testid":`wizard-stepper-desktop-step-${i+1}-indicator`,children:i+1<t?e.jsx(fa,{className:"w-4 h-4"}):i+1}),i<a.length-1&&e.jsx("div",{className:`w-8 md:w-12 lg:w-16 h-1 mx-1 md:mx-2 ${i+1<t?"bg-green-600":"bg-gray-200"}`,"data-testid":`wizard-stepper-desktop-step-${i+1}-connector`})]},i))}),e.jsx("div",{className:"hidden lg:flex justify-between text-xs text-gray-600 mt-2","data-testid":"wizard-stepper-desktop-labels",children:a.map((n,i)=>e.jsx("span",{className:`${i+1===t?"font-semibold text-blue-600":""}`,"data-testid":`wizard-stepper-desktop-label-${i+1}`,children:n},i))})]})]})})}function Xj({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:o,submitting:l,savingDraft:c,loadingDraft:m,isEditing:d}){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(I,{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(ra,{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(I,{variant:"outline",onClick:o,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:m||l||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),d?"Updating...":"Saving..."]}):d?"Update Draft":"Save Draft"}),t===s?e.jsx(I,{onClick:i,disabled:!a||m||l||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:l?e.jsxs(e.Fragment,{children:[e.jsx($e,{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(Oc,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(I,{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(mt,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const sc=t=>{switch(t){case"high":return e.jsx(is,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Qe,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ms,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Qe,{className:"w-4 h-4 text-gray-600"})}};function Jj({templates:t,selectedTemplate:s,onSelectTemplate:a}){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:"Choose Your Request Type"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs."})]}),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:t.map(r=>e.jsx(yt.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${r.id}`,children:e.jsxs(W,{className:`cursor-pointer h-full transition-all duration-300 border-2 ${(s==null?void 0:s.id)===r.id?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>a(r),"data-testid":`template-card-${r.id}-clickable`,children:[e.jsxs(Q,{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 ${(s==null?void 0:s.id)===r.id?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${r.id}-icon`,children:e.jsx(r.icon,{className:`w-7 h-7 ${(s==null?void 0:s.id)===r.id?"text-blue-600":"text-gray-600"}`})}),(s==null?void 0:s.id)===r.id&&e.jsx(yt.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},"data-testid":`template-card-${r.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(fa,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ee,{className:"text-xl mb-2","data-testid":`template-card-${r.id}-name`,children:r.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(J,{variant:"secondary",className:"text-xs","data-testid":`template-card-${r.id}-category`,children:r.category}),sc(r.priority)]})]})]}),e.jsxs(q,{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-${r.id}-description`,children:r.description}),e.jsx(Nt,{}),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-${r.id}-estimated-time`,children:[e.jsx(Pe,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:r.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${r.id}-approvers-count`,children:[e.jsx(Xe,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[r.commonApprovers.length," approvers"]})]})]})]})]})},r.id))}),e.jsx(Lr,{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(W,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(Q,{children:e.jsxs(ee,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Nr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(q,{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(X,{className:"text-blue-900 font-semibold",children:"Suggested SLA"}),e.jsxs("p",{className:"text-blue-700 mt-1",children:[s.suggestedSLA," days"]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-priority",children:[e.jsx(X,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[sc(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(X,{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(X,{className:"text-blue-900 font-semibold",children:"Common Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:s.commonApprovers.map((r,n)=>e.jsx(J,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${n}`,children:r},`${s.id}-approver-${n}-${r}`))})]})]})]})})})]})}function Qj({className:t,...s}){return e.jsx(gh,{"data-slot":"radio-group",className:ce("grid gap-3",t),...s})}function ac({className:t,...s}){return e.jsx(fh,{"data-slot":"radio-group-item",className:ce("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(yh,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(hp,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function eN({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(we,{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(X,{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(me,{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(X,{htmlFor:"description",className:"text-base font-semibold",children:"Detailed Description *"}),e.jsx("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(us,{id:"description",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:border-blue-500 bg-white shadow-sm resize-none",value:t.description,onChange:r=>a("description",r.target.value),"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(X,{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(Qj,{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(ac,{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(br,{className:"w-4 h-4 text-red-600"}),e.jsx(X,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(J,{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(ac,{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(Pe,{className:"w-4 h-4 text-blue-600"}),e.jsx(X,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(J,{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(X,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(me,{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(X,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(Se,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Te,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ae,{})}),e.jsxs(ke,{children:[e.jsx(H,{value:"USD",children:"USD ($)"}),e.jsx(H,{value:"EUR",children:"EUR (€)"}),e.jsx(H,{value:"GBP",children:"GBP (£)"}),e.jsx(H,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(X,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(me,{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(X,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(me,{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(X,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(me,{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 tN(){const[t,s]=g.useState([]),[a,r]=g.useState(!1),n=g.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(c,m=10)=>{if(n.current&&clearTimeout(n.current),!c||!c.startsWith("@")||c.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var d;try{const u=c.slice(1),x=((d=(await ys(u,m)).data)==null?void 0:d.data)||[];s(x)}catch(u){console.error("User search failed:",u),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await vs({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(m){throw console.error("Failed to ensure user exists:",m),m}}}}function sN(){const[t,s]=g.useState({}),[a,r]=g.useState({}),n=g.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(l,c,m=10)=>{if(n.current[l]&&clearTimeout(n.current[l]),!c||!c.startsWith("@")||c.length<2){s(d=>({...d,[l]:[]})),r(d=>({...d,[l]:!1}));return}r(d=>({...d,[l]:!0})),n.current[l]=setTimeout(async()=>{var d;try{const u=c.slice(1),x=((d=(await ys(u,m)).data)==null?void 0:d.data)||[];s(p=>({...p,[l]:x}))}catch(u){console.error(`User search failed for index ${l}:`,u),s(h=>({...h,[l]:[]}))}finally{r(u=>({...u,[l]:!1}))}},300)},clearSearchForIndex:l=>{n.current[l]&&clearTimeout(n.current[l]),s(c=>({...c,[l]:[]})),r(c=>({...c,[l]:!1}))}}}function aN({formData:t,updateFormData:s,onValidationError:a}){const{userSearchResults:r,userSearchLoading:n,searchUsersForIndex:i,clearSearchForIndex:o}=sN(),l=(m,d)=>{var p,f,v,j,y;const u=[...t.approvers],x=((p=u[m])==null?void 0:p.email)!==d;if(u[m]={...u[m],email:d,level:m+1,userId:x||(f=u[m])==null?void 0:f.userId,name:x||(v=u[m])==null?void 0:v.name,department:x||(j=u[m])==null?void 0:j.department,avatar:x||(y=u[m])==null?void 0:y.avatar},s("approvers",u),!d||!d.startsWith("@")||d.length<2){o(m);return}i(m,d,10)},c=async(m,d)=>{try{const u=await vs({userId:d.userId,email:d.email,displayName:d.displayName,firstName:d.firstName,lastName:d.lastName,department:d.department,phone:d.phone,mobilePhone:d.mobilePhone,designation:d.designation,jobTitle:d.jobTitle,manager:d.manager,employeeId:d.employeeId,employeeNumber:d.employeeNumber,secondEmail:d.secondEmail,location:d.location}),h=[...t.approvers];h[m]={...h[m],email:d.email,name:d.displayName||[d.firstName,d.lastName].filter(Boolean).join(" "),userId:u.userId,level:m+1},s("approvers",h),o(m)}catch(u){console.error("Failed to ensure user exists:",u),a({type:"error",email:d.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(Xe,{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(W,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(Q,{children:[e.jsxs(ee,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(aa,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(le,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(q,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(X,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:()=>{const m=t.approverCount||1,d=Math.max(1,m-1);s("approverCount",d),t.approvers.length>d&&s("approvers",t.approvers.slice(0,d))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(pp,{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(I,{type:"button",variant:"outline",size:"sm",onClick:()=>{const m=t.approverCount||1,d=Math.min(10,m+1);s("approverCount",d)},disabled:(t.approverCount||1)>=10,"data-testid":"approval-workflow-increase-count",children:e.jsx(Ps,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-sm text-gray-600 mt-2",children:"Maximum 10 approvers allowed. Each approver will review sequentially."})]})})]}),e.jsxs(W,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(Q,{children:[e.jsxs(ee,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(At,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(le,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(q,{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(xt,{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(J,{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},(m,d)=>{var x,p,f,v,j,y,w,N,S,T,F;const u=d+1,h=u===(t.approverCount||1);if(!t.approvers[d]){const R=[...t.approvers];R[d]={email:"",name:"",level:u,tat:""},s("approvers",R)}return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${u}`,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 ${(x=t.approvers[d])!=null&&x.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 ${(p=t.approvers[d])!=null&&p.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:u})}),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 ",u]}),h&&e.jsx(J,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${u}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(X,{htmlFor:`approver-${u}`,className:"text-sm font-medium",children:"Email Address *"}),((f=t.approvers[d])==null?void 0:f.email)&&((v=t.approvers[d])==null?void 0:v.userId)&&e.jsxs(J,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(xe,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(me,{id:`approver-${u}`,type:"email",placeholder:"approver@royalenfield.com",value:((j=t.approvers[d])==null?void 0:j.email)||"",onChange:R=>l(d,R.target.value),className:"h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full","data-testid":`approval-workflow-approver-${u}-email-input`}),(n[d]||(((y=r[d])==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:n[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:(w=r[d])==null?void 0:w.map(R=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>c(d,R),"data-testid":`approval-workflow-approver-${u}-search-result-${R.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:R.displayName||R.email}),e.jsx("div",{className:"text-xs text-gray-600",children:R.email})]},R.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${u}-tat-field`,children:[e.jsx(X,{htmlFor:`tat-${u}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(me,{id:`tat-${u}`,type:"number",placeholder:((N=t.approvers[d])==null?void 0:N.tatType)==="days"?"7":"24",min:"1",max:((S=t.approvers[d])==null?void 0:S.tatType)==="days"?"30":"720",value:((T=t.approvers[d])==null?void 0:T.tat)||"",onChange:R=>{var b;const M=[...t.approvers];M[d]={...M[d],tat:parseInt(R.target.value)||"",level:u,tatType:((b=t.approvers[d])==null?void 0:b.tatType)||"hours"},s("approvers",M)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${u}-tat-input`}),e.jsxs(Se,{value:((F=t.approvers[d])==null?void 0:F.tatType)||"hours",onValueChange:R=>{const M=[...t.approvers];M[d]={...M[d],tatType:R,level:u,tat:""},s("approvers",M)},"data-testid":`approval-workflow-approver-${u}-tat-type-select`,children:[e.jsx(Te,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ae,{})}),e.jsxs(ke,{children:[e.jsx(H,{value:"hours",children:"Hours"}),e.jsx(H,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},u)})]})]})]})]})}function rN({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=g.useState(""),{searchResults:o,searchLoading:l,searchUsersDebounced:c,clearSearch:m,ensureUser:d}=tN(),u=p=>{if(i(p),!p||!p.startsWith("@")||p.length<2){m();return}c(p,10)},h=async p=>{if(p){if(p.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:p.email,message:"You cannot add yourself as a spectator."});return}try{const f=await d(p),v={id:f.userId,userId:f.userId,name:f.displayName||p.email.split("@")[0],email:f.email,avatar:(f.displayName||f.email).substring(0,2).toUpperCase(),role:"Spectator",department:f.department||"",level:1,canClose:!1},j=[...t.spectators,v];s("spectators",j),i(""),m()}catch{a({type:"error",email:p.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}},x=p=>{const f=t.spectators.filter(v=>v.id!==p);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(Tt,{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(W,{"data-testid":"participants-spectators-card",children:[e.jsxs(Q,{children:[e.jsxs(ee,{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(Tt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(J,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(le,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(q,{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(me,{placeholder:"Use @ sign to add a user",value:n,onChange:p=>u(p.target.value),onKeyPress:async p=>{p.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(p.preventDefault(),await h())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(l||o.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:l?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:o.map(p=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>h(p),"data-testid":`participants-spectators-search-result-${p.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:p.displayName||p.email}),e.jsx("div",{className:"text-xs text-gray-600",children:p.email})]},p.userId))})})]}),e.jsx(I,{size:"sm",onClick:()=>h(),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(Nr,{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(p=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-teal-50 rounded-lg","data-testid":`participants-spectator-${p.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gt,{className:"h-6 w-6",children:e.jsx(ft,{className:"bg-teal-600 text-white text-xs",children:p.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:p.name})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>x(p.id),"data-testid":`participants-spectator-${p.id}-remove`,children:e.jsx(jt,{className:"h-3 w-3"})})]},p.id))})]})]})})})]})}function nN({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:o,onDocumentsToDeleteChange:l,onPreviewDocument:c,onDocumentErrors:m,fileInputRef:d}){const u=f=>{const v=Array.from(f.target.files||[]);if(v.length===0)return;const j=t.maxFileSizeMB*1024*1024,y=[],w=[];v.forEach(N=>{if(N.size>j){y.push({fileName:N.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(N.size/1048576).toFixed(2)}MB`});return}const S=N.name.toLowerCase(),T=S.substring(S.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(T)){y.push({fileName:N.name,reason:`File type "${T}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}w.push(N)}),w.length>0&&i([...a,...w]),y.length>0&&m&&m(y),f.target&&(f.target.value="")},h=f=>{const v=a.filter((j,y)=>y!==f);i(v)},x=f=>{l([...n,f])},p=(f,v=!1)=>{if(v){const j=(f.fileType||f.file_type||"").toLowerCase(),y=(f.originalFileName||f.fileName||"").toLowerCase();return j.includes("image")||j.includes("pdf")||y.endsWith(".jpg")||y.endsWith(".jpeg")||y.endsWith(".png")||y.endsWith(".gif")||y.endsWith(".pdf")}else{const j=(f.type||"").toLowerCase(),y=(f.name||"").toLowerCase();return j.includes("image")||j.includes("pdf")||y.endsWith(".jpg")||y.endsWith(".jpeg")||y.endsWith(".png")||y.endsWith(".gif")||y.endsWith(".pdf")}};return e.jsxs(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(pa,{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(W,{"data-testid":"documents-upload-card",children:[e.jsxs(Q,{children:[e.jsxs(ee,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(we,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(le,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(q,{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(pa,{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:"Drag and drop files here, or click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(f=>`.${f}`).join(","),onChange:u,className:"hidden",id:"file-upload",ref:d,"data-testid":"documents-file-input"}),e.jsxs(I,{variant:"outline",size:"lg",type:"button",onClick:()=>{var f;return(f=d.current)==null?void 0:f.click()},"data-testid":"documents-browse-button",children:[e.jsx(Ps,{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(W,{"data-testid":"documents-existing-card",children:[e.jsx(Q,{children:e.jsxs(ee,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(J,{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(q,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(f=>{const v=f.documentId||f.document_id||"";return n.includes(v)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${v}`,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(we,{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:[p(f,!0)&&e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>c(f,!0),"data-testid":`documents-existing-${v}-preview`,children:e.jsx(Tt,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>x(v),"data-testid":`documents-existing-${v}-delete`,children:e.jsx(jt,{className:"h-4 w-4 text-red-600"})})]})]},v)})})})]}),a.length>0&&e.jsxs(W,{"data-testid":"documents-new-card",children:[e.jsx(Q,{children:e.jsxs(ee,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(J,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(q,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((f,v)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${v}`,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(we,{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:[p(f,!1)&&e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>c(f,!1),"data-testid":`documents-new-${v}-preview`,children:e.jsx(Tt,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>h(v),"data-testid":`documents-new-${v}-remove`,children:e.jsx(jt,{className:"h-4 w-4"})})]})]},v))})})]})]})]})}const iN=t=>{switch(t){case"high":return e.jsx(is,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Qe,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ms,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Qe,{className:"w-4 h-4 text-gray-600"})}};function oN({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(xe,{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(W,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(Q,{children:e.jsxs(ee,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(Oc,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(q,{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(X,{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(J,{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(X,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[iN(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(X,{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(X,{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(W,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(Q,{children:e.jsxs(ee,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(we,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(X,{className:"font-semibold",children:"Description"}),e.jsx("p",{className:"text-sm text-gray-700 mt-1 p-3 bg-gray-50 rounded-lg border",children: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(xp,{className:"w-4 h-4 text-blue-600"}),e.jsx(X,{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(W,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(Q,{children:[e.jsxs(ee,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(Xe,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(le,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(q,{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),o=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 ${o!=null&&o.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(J,{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:(o==null?void 0:o.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:o!=null&&o.tat?`${o.tat} ${o.tatType==="days"?"day":"hour"}${o.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(W,{"data-testid":"review-submit-participants-card",children:[e.jsx(Q,{children:e.jsxs(ee,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(Tt,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(q,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(X,{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(J,{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(W,{"data-testid":"review-submit-documents-card",children:[e.jsxs(Q,{children:[e.jsxs(ee,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(pa,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(le,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(q,{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(we,{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(W,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(q,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(xe,{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 lN({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(I,{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(ra,{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 cN({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(Lr,{mode:"wait",children:t})})})}function dN({modal:t,onClose:s}){return e.jsx(ut,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(it,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsxs(ot,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Xt,{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(Sr,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use"," ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," ","sign to search and select users from the directory for guaranteed results."]})})]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:[t.email&&e.jsxs(e.Fragment,{children:["Failed to validate ",e.jsx("strong",{children:t.email}),"."]}),!t.email&&e.jsx(e.Fragment,{children:"An error occurred during validation."})]}),t.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:t.message})})]})]})})]}),e.jsx(Et,{children:e.jsx(I,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function mN({modal:t,documentPolicy:s,onClose:a}){return e.jsx(ut,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(it,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(ot,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:t.errors.map((r,n)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3","data-testid":`document-error-${n}`,children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:r.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:r.reason})]},n))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",s.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types:"," ",s.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Et,{children:e.jsx(I,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function rc({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=kr(),i=ya(),o=n.requestId||a||"",l=r&&!!o,{user:c}=Zt(),{formData:m,updateFormData:d,selectedTemplate:u,setSelectedTemplate:h,loadingDraft:x,systemPolicy:p,documentPolicy:f,existingDocuments:v,setExistingDocuments:j}=Mj(l,o,tc),{currentStep:y,totalSteps:w,stepNames:N,isStepValid:S,nextStep:T,prevStep:F}=Ij(l,u,m),[R,M]=g.useState([]),[b,A]=g.useState([]),P=g.useRef(null),{validationModal:B,policyViolationModal:E,documentErrorModal:L,openValidationModal:C,closeValidationModal:k,closePolicyViolationModal:D,openDocumentErrorModal:z,closeDocumentErrorModal:K}=Lj(),{submitting:Y,savingDraft:de,handleSubmit:Z,handleSaveDraft:je}=qj({formData:m,selectedTemplate:u,documents:R,documentsToDelete:b,user:c,isEditing:l,editRequestId:o,onSubmit:s}),{showTemplateModal:ve,setShowTemplateModal:U,previewDocument:V,selectTemplate:te,handleTemplateSelection:$,nextStep:G,prevStep:ae,handlePreviewDocument:he,closePreview:be}=Yj({selectedTemplate:u,setSelectedTemplate:h,updateFormData:d,formData:m,currentStep:y,isStepValid:S,wizardNextStep:T,wizardPrevStep:F,user:c,openValidationModal:C,onSubmit:s}),_e=g.useCallback(()=>{y===1||y===3||y===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):ae()},[y,t,i,ae]),Oe=g.useRef(!0),Ue=g.useRef(!1);g.useEffect(()=>{Oe.current&&m.documents&&m.documents.length>0&&!Ue.current&&(M(m.documents),Ue.current=!0),Oe.current=!1},[m.documents]);const tt=g.useRef(!1),Be=g.useRef(R);g.useEffect(()=>{if(tt.current){tt.current=!1,Be.current=R;return}Be.current!==R&&(d("documents",R),Be.current=R)},[R]);const kt=()=>{switch(y){case 1:return e.jsx(Jj,{templates:tc,selectedTemplate:u,onSelectTemplate:te});case 2:return e.jsx(eN,{formData:m,selectedTemplate:u,updateFormData:d});case 3:return e.jsx(aN,{formData:m,updateFormData:d,onValidationError:Le=>C(Le.type,Le.email,Le.message)});case 4:return e.jsx(rN,{formData:m,updateFormData:d,onValidationError:Le=>C(Le.type,Le.email,Le.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(nN,{documentPolicy:f,isEditing:l,documents:R,existingDocuments:v,documentsToDelete:b,onDocumentsChange:M,onExistingDocumentsChange:j,onDocumentsToDeleteChange:A,onPreviewDocument:he,onDocumentErrors:Le=>z(Le),fileInputRef:P});case 6:return e.jsx(oN,{formData:m,selectedTemplate:u});default:return null}};return x?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(lN,{isEditing:l,currentStep:y,totalSteps:w,stepNames:N,onBack:_e}),e.jsx(Zj,{currentStep:y,totalSteps:w,stepNames:N}),e.jsx(cN,{children:kt()}),e.jsx(Xj,{currentStep:y,totalSteps:w,isStepValid:S(),onPrev:ae,onNext:G,onSubmit:Z,onSaveDraft:je,submitting:Y,savingDraft:de,loadingDraft:x,isEditing:l}),e.jsx(Dj,{open:ve,onClose:()=>U(!1),onSelectTemplate:$}),V&&e.jsx(vi,{fileName:V.fileName,fileType:V.fileType,fileUrl:V.fileUrl,fileSize:V.fileSize,open:!!V,onClose:be,onDownload:async()=>{if(V.file){const Le=document.createElement("a");Le.href=V.fileUrl,Le.download=V.fileName,document.body.appendChild(Le),Le.click(),document.body.removeChild(Le)}else V.documentId&&await Mn(V.documentId)},attachmentId:V.documentId}),e.jsx(dN,{modal:B,onClose:k}),e.jsx(mN,{modal:L,documentPolicy:f,onClose:K}),e.jsx(ud,{open:E.open,onClose:D,violations:E.violations,policyDetails:{maxApprovalLevels:p.maxApprovalLevels,maxParticipants:p.maxParticipants,allowSpectators:p.allowSpectators,maxSpectators:p.maxSpectators}})]})}var fe=function(){return fe=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},fe.apply(this,arguments)};function uN(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 Jm(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 Za(t){return t.mode==="multiple"}function Xa(t){return t.mode==="range"}function $r(t){return t.mode==="single"}var hN={root:"rdp",multiple_months:"rdp-multiple_months",with_weeknumber:"rdp-with_weeknumber",vhidden:"rdp-vhidden",button_reset:"rdp-button_reset",button:"rdp-button",caption:"rdp-caption",caption_start:"rdp-caption_start",caption_end:"rdp-caption_end",caption_between:"rdp-caption_between",caption_label:"rdp-caption_label",caption_dropdowns:"rdp-caption_dropdowns",dropdown:"rdp-dropdown",dropdown_month:"rdp-dropdown_month",dropdown_year:"rdp-dropdown_year",dropdown_icon:"rdp-dropdown_icon",months:"rdp-months",month:"rdp-month",table:"rdp-table",tbody:"rdp-tbody",tfoot:"rdp-tfoot",head:"rdp-head",head_row:"rdp-head_row",head_cell:"rdp-head_cell",nav:"rdp-nav",nav_button:"rdp-nav_button",nav_button_previous:"rdp-nav_button_previous",nav_button_next:"rdp-nav_button_next",nav_icon:"rdp-nav_icon",row:"rdp-row",weeknumber:"rdp-weeknumber",cell:"rdp-cell",day:"rdp-day",day_today:"rdp-day_today",day_outside:"rdp-day_outside",day_selected:"rdp-day_selected",day_disabled:"rdp-day_disabled",day_hidden:"rdp-day_hidden",day_range_start:"rdp-day_range_start",day_range_end:"rdp-day_range_end",day_range_middle:"rdp-day_range_middle"};function pN(t,s){return ye(t,"LLLL y",s)}function xN(t,s){return ye(t,"d",s)}function gN(t,s){return ye(t,"LLLL",s)}function fN(t){return"".concat(t)}function yN(t,s){return ye(t,"cccccc",s)}function vN(t,s){return ye(t,"yyyy",s)}var bN=Object.freeze({__proto__:null,formatCaption:pN,formatDay:xN,formatMonthCaption:gN,formatWeekNumber:fN,formatWeekdayName:yN,formatYearCaption:vN}),jN=function(t,s,a){return ye(t,"do MMMM (EEEE)",a)},NN=function(){return"Month: "},wN=function(){return"Go to next month"},CN=function(){return"Go to previous month"},SN=function(t,s){return ye(t,"cccc",s)},AN=function(t){return"Week n. ".concat(t)},TN=function(){return"Year: "},kN=Object.freeze({__proto__:null,labelDay:jN,labelMonthDropdown:NN,labelNext:wN,labelPrevious:CN,labelWeekNumber:AN,labelWeekday:SN,labelYearDropdown:TN});function RN(){var t="buttons",s=hN,a=_h,r={},n={},i=1,o={},l=new Date;return{captionLayout:t,classNames:s,formatters:bN,labels:kN,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:o,today:l,mode:"default"}}function PN(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,o=t.toDate;return r?i=Vt(r):s&&(i=new Date(s,0,1)),n?o=oi(n):a&&(o=new Date(a,11,31)),{fromDate:i?xo(i):void 0,toDate:o?xo(o):void 0}}var Qm=g.createContext(void 0);function DN(t){var s,a=t.initialProps,r=RN(),n=PN(a),i=n.fromDate,o=n.toDate,l=(s=a.captionLayout)!==null&&s!==void 0?s:r.captionLayout;l!=="buttons"&&(!i||!o)&&(l="buttons");var c;($r(a)||Za(a)||Xa(a))&&(c=a.onSelect);var m=fe(fe(fe({},r),a),{captionLayout:l,classNames:fe(fe({},r.classNames),a.classNames),components:fe({},a.components),formatters:fe(fe({},r.formatters),a.formatters),fromDate:i,labels:fe(fe({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:fe(fe({},r.modifiers),a.modifiers),modifiersClassNames:fe(fe({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:fe(fe({},r.styles),a.styles),toDate:o});return e.jsx(Qm.Provider,{value:m,children:t.children})}function Ve(){var t=g.useContext(Qm);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function eu(t){var s=Ve(),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 EN(t){return e.jsx("svg",fe({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 tu(t){var s,a,r=t.onChange,n=t.value,i=t.children,o=t.caption,l=t.className,c=t.style,m=Ve(),d=(a=(s=m.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:EN;return e.jsxs("div",{className:l,style:c,children:[e.jsx("span",{className:m.classNames.vhidden,children:t["aria-label"]}),e.jsx("select",{name:t.name,"aria-label":t["aria-label"],className:m.classNames.dropdown,style:m.styles.dropdown,value:n,onChange:r,children:i}),e.jsxs("div",{className:m.classNames.caption_label,style:m.styles.caption_label,"aria-hidden":"true",children:[o,e.jsx(d,{className:m.classNames.dropdown_icon,style:m.styles.dropdown_icon})]})]})}function MN(t){var s,a=Ve(),r=a.fromDate,n=a.toDate,i=a.styles,o=a.locale,l=a.formatters.formatMonthCaption,c=a.classNames,m=a.components,d=a.labels.labelMonthDropdown;if(!r)return e.jsx(e.Fragment,{});if(!n)return e.jsx(e.Fragment,{});var u=[];if(zh(r,n))for(var h=Vt(r),x=r.getMonth();x<=n.getMonth();x++)u.push(Hr(h,x));else for(var h=Vt(new Date),x=0;x<=11;x++)u.push(Hr(h,x));var p=function(v){var j=Number(v.target.value),y=Hr(Vt(t.displayMonth),j);t.onChange(y)},f=(s=m==null?void 0:m.Dropdown)!==null&&s!==void 0?s:tu;return e.jsx(f,{name:"months","aria-label":d(),className:c.dropdown_month,style:i.dropdown_month,onChange:p,value:t.displayMonth.getMonth(),caption:l(t.displayMonth,{locale:o}),children:u.map(function(v){return e.jsx("option",{value:v.getMonth(),children:l(v,{locale:o})},v.getMonth())})})}function IN(t){var s,a=t.displayMonth,r=Ve(),n=r.fromDate,i=r.toDate,o=r.locale,l=r.styles,c=r.classNames,m=r.components,d=r.formatters.formatYearCaption,u=r.labels.labelYearDropdown,h=[];if(!n)return e.jsx(e.Fragment,{});if(!i)return e.jsx(e.Fragment,{});for(var x=n.getFullYear(),p=i.getFullYear(),f=x;f<=p;f++)h.push(go(Hh(new Date),f));var v=function(y){var w=go(Vt(a),Number(y.target.value));t.onChange(w)},j=(s=m==null?void 0:m.Dropdown)!==null&&s!==void 0?s:tu;return e.jsx(j,{name:"years","aria-label":u(),className:c.dropdown_year,style:l.dropdown_year,onChange:v,value:a.getFullYear(),caption:d(a,{locale:o}),children:h.map(function(y){return e.jsx("option",{value:y.getFullYear(),children:d(y,{locale:o})},y.getFullYear())})})}function LN(t,s){var a=g.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function FN(t){var s=t.month,a=t.defaultMonth,r=t.today,n=s||a||r||new Date,i=t.toDate,o=t.fromDate,l=t.numberOfMonths,c=l===void 0?1:l;if(i&&_a(i,n)<0){var m=-1*(c-1);n=cs(i,m)}return o&&_a(n,o)<0&&(n=o),Vt(n)}function _N(){var t=Ve(),s=FN(t),a=LN(s,t.month),r=a[0],n=a[1],i=function(o){var l;if(!t.disableNavigation){var c=Vt(o);n(c),(l=t.onMonthChange)===null||l===void 0||l.call(t,c)}};return[r,i]}function ON(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=Vt(t),i=Vt(cs(n,r)),o=_a(i,n),l=[],c=0;c<o;c++){var m=cs(n,c);l.push(m)}return a&&(l=l.reverse()),l}function $N(t,s){if(!s.disableNavigation){var a=s.toDate,r=s.pagedNavigation,n=s.numberOfMonths,i=n===void 0?1:n,o=r?i:1,l=Vt(t);if(!a)return cs(l,o);var c=_a(a,t);if(!(c<i))return cs(l,o)}}function UN(t,s){if(!s.disableNavigation){var a=s.fromDate,r=s.pagedNavigation,n=s.numberOfMonths,i=n===void 0?1:n,o=r?i:1,l=Vt(t);if(!a)return cs(l,-o);var c=_a(l,a);if(!(c<=0))return cs(l,-o)}}var su=g.createContext(void 0);function VN(t){var s=Ve(),a=_N(),r=a[0],n=a[1],i=ON(r,s),o=$N(r,s),l=UN(r,s),c=function(u){return i.some(function(h){return li(u,h)})},m=function(u,h){c(u)||(h&&Rc(u,h)?n(cs(u,1+s.numberOfMonths*-1)):n(u))},d={currentMonth:r,displayMonths:i,goToMonth:n,goToDate:m,previousMonth:l,nextMonth:o,isDateDisplayed:c};return e.jsx(su.Provider,{value:d,children:t.children})}function Ja(){var t=g.useContext(su);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function nc(t){var s,a=Ve(),r=a.classNames,n=a.styles,i=a.components,o=Ja().goToMonth,l=function(d){o(cs(d,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:eu,m=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:m}),e.jsx(MN,{onChange:l,displayMonth:t.displayMonth}),e.jsx(IN,{onChange:l,displayMonth:t.displayMonth})]})}function BN(t){return e.jsx("svg",fe({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 zN(t){return e.jsx("svg",fe({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 vr=g.forwardRef(function(t,s){var a=Ve(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var o=i.join(" "),l=fe(fe({},n.button_reset),n.button);return t.style&&Object.assign(l,t.style),e.jsx("button",fe({},t,{ref:s,type:"button",className:o,style:l}))});function HN(t){var s,a,r=Ve(),n=r.dir,i=r.locale,o=r.classNames,l=r.styles,c=r.labels,m=c.labelPrevious,d=c.labelNext,u=r.components;if(!t.nextMonth&&!t.previousMonth)return e.jsx(e.Fragment,{});var h=m(t.previousMonth,{locale:i}),x=[o.nav_button,o.nav_button_previous].join(" "),p=d(t.nextMonth,{locale:i}),f=[o.nav_button,o.nav_button_next].join(" "),v=(s=u==null?void 0:u.IconRight)!==null&&s!==void 0?s:zN,j=(a=u==null?void 0:u.IconLeft)!==null&&a!==void 0?a:BN;return e.jsxs("div",{className:o.nav,style:l.nav,children:[!t.hidePrevious&&e.jsx(vr,{name:"previous-month","aria-label":h,className:x,style:l.nav_button_previous,disabled:!t.previousMonth,onClick:t.onPreviousClick,children:n==="rtl"?e.jsx(v,{className:o.nav_icon,style:l.nav_icon}):e.jsx(j,{className:o.nav_icon,style:l.nav_icon})}),!t.hideNext&&e.jsx(vr,{name:"next-month","aria-label":p,className:f,style:l.nav_button_next,disabled:!t.nextMonth,onClick:t.onNextClick,children:n==="rtl"?e.jsx(j,{className:o.nav_icon,style:l.nav_icon}):e.jsx(v,{className:o.nav_icon,style:l.nav_icon})})]})}function ic(t){var s=Ve().numberOfMonths,a=Ja(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,o=a.displayMonths,l=o.findIndex(function(p){return li(t.displayMonth,p)}),c=l===0,m=l===o.length-1,d=s>1&&(c||!m),u=s>1&&(m||!c),h=function(){r&&i(r)},x=function(){n&&i(n)};return e.jsx(HN,{displayMonth:t.displayMonth,hideNext:d,hidePrevious:u,nextMonth:n,previousMonth:r,onPreviousClick:h,onNextClick:x})}function WN(t){var s,a=Ve(),r=a.classNames,n=a.disableNavigation,i=a.styles,o=a.captionLayout,l=a.components,c=(s=l==null?void 0:l.CaptionLabel)!==null&&s!==void 0?s:eu,m;return n?m=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):o==="dropdown"?m=e.jsx(nc,{displayMonth:t.displayMonth,id:t.id}):o==="dropdown-buttons"?m=e.jsxs(e.Fragment,{children:[e.jsx(nc,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(ic,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id})]}):m=e.jsxs(e.Fragment,{children:[e.jsx(c,{id:t.id,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(ic,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:m})}function qN(t){var s=Ve(),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 KN(t,s,a){for(var r=a?ci(new Date):di(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var o=Ut(r,i);n.push(o)}return n}function GN(){var t=Ve(),s=t.classNames,a=t.styles,r=t.showWeekNumber,n=t.locale,i=t.weekStartsOn,o=t.ISOWeek,l=t.formatters.formatWeekdayName,c=t.labels.labelWeekday,m=KN(n,i,o);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}),m.map(function(d,u){return e.jsx("th",{scope:"col",className:s.head_cell,style:a.head_cell,"aria-label":c(d,{locale:n}),children:l(d,{locale:n})},u)})]})}function YN(){var t,s=Ve(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:GN;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function ZN(t){var s=Ve(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var eo=g.createContext(void 0);function XN(t){if(!Za(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(eo.Provider,{value:s,children:t.children})}return e.jsx(JN,{initialProps:t.initialProps,children:t.children})}function JN(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,o=function(m,d,u){var h,x;(h=s.onDayClick)===null||h===void 0||h.call(s,m,d,u);var p=!!(d.selected&&n&&(r==null?void 0:r.length)===n);if(!p){var f=!!(!d.selected&&i&&(r==null?void 0:r.length)===i);if(!f){var v=r?Jm([],r):[];if(d.selected){var j=v.findIndex(function(y){return Lt(m,y)});v.splice(j,1)}else v.push(m);(x=s.onSelect)===null||x===void 0||x.call(s,v,m,d,u)}}},l={disabled:[]};r&&l.disabled.push(function(m){var d=i&&r.length>i-1,u=r.some(function(h){return Lt(h,m)});return!!(d&&!u)});var c={selected:r,onDayClick:o,modifiers:l};return e.jsx(eo.Provider,{value:c,children:a})}function to(){var t=g.useContext(eo);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function QN(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?Lt(n,t)&&Lt(r,t)?void 0:Lt(n,t)?{from:n,to:void 0}:Lt(r,t)?void 0:Cn(r,t)?{from:t,to:n}:{from:r,to:t}:n?Cn(t,n)?{from:n,to:t}:{from:t,to:n}:r?Rc(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var so=g.createContext(void 0);function ew(t){if(!Xa(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(so.Provider,{value:s,children:t.children})}return e.jsx(tw,{initialProps:t.initialProps,children:t.children})}function tw(t){var s=t.initialProps,a=t.children,r=s.selected,n=r||{},i=n.from,o=n.to,l=s.min,c=s.max,m=function(x,p,f){var v,j;(v=s.onDayClick)===null||v===void 0||v.call(s,x,p,f);var y=QN(x,r);(j=s.onSelect)===null||j===void 0||j.call(s,y,x,p,f)},d={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(d.range_start=[i],o?(d.range_end=[o],Lt(i,o)||(d.range_middle=[{after:i,before:o}])):d.range_end=[i]):o&&(d.range_start=[o],d.range_end=[o]),l&&(i&&!o&&d.disabled.push({after:zr(i,l-1),before:Ut(i,l-1)}),i&&o&&d.disabled.push({after:i,before:Ut(i,l-1)}),!i&&o&&d.disabled.push({after:zr(o,l-1),before:Ut(o,l-1)})),c){if(i&&!o&&(d.disabled.push({before:Ut(i,-c+1)}),d.disabled.push({after:Ut(i,c-1)})),i&&o){var u=fs(o,i)+1,h=c-u;d.disabled.push({before:zr(i,h)}),d.disabled.push({after:Ut(o,h)})}!i&&o&&(d.disabled.push({before:Ut(o,-c+1)}),d.disabled.push({after:Ut(o,c-1)}))}return e.jsx(so.Provider,{value:{selected:r,onDayClick:m,modifiers:d},children:a})}function ao(){var t=g.useContext(so);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function mr(t){return Array.isArray(t)?Jm([],t):t!==void 0?[t]:[]}function sw(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=mr(n)}),s}var rs;(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"})(rs||(rs={}));var aw=rs.Selected,gs=rs.Disabled,rw=rs.Hidden,nw=rs.Today,gn=rs.RangeEnd,fn=rs.RangeMiddle,yn=rs.RangeStart,iw=rs.Outside;function ow(t,s,a){var r,n=(r={},r[aw]=mr(t.selected),r[gs]=mr(t.disabled),r[rw]=mr(t.hidden),r[nw]=[t.today],r[gn]=[],r[fn]=[],r[yn]=[],r[iw]=[],r);return t.fromDate&&n[gs].push({before:t.fromDate}),t.toDate&&n[gs].push({after:t.toDate}),Za(t)?n[gs]=n[gs].concat(s.modifiers[gs]):Xa(t)&&(n[gs]=n[gs].concat(a.modifiers[gs]),n[yn]=a.modifiers[yn],n[fn]=a.modifiers[fn],n[gn]=a.modifiers[gn]),n}var au=g.createContext(void 0);function lw(t){var s=Ve(),a=to(),r=ao(),n=ow(s,a,r),i=sw(s.modifiers),o=fe(fe({},n),i);return e.jsx(au.Provider,{value:o,children:t.children})}function ru(){var t=g.useContext(au);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function cw(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function dw(t){return!!(t&&typeof t=="object"&&"from"in t)}function mw(t){return!!(t&&typeof t=="object"&&"after"in t)}function uw(t){return!!(t&&typeof t=="object"&&"before"in t)}function hw(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function pw(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=fs(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var o=fs(t,r)>=0&&fs(n,t)>=0;return o}return n?Lt(n,t):r?Lt(r,t):!1}function xw(t){return Ec(t)}function gw(t){return Array.isArray(t)&&t.every(Ec)}function fw(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(xw(a))return Lt(t,a);if(gw(a))return a.includes(t);if(dw(a))return pw(t,a);if(hw(a))return a.dayOfWeek.includes(t.getDay());if(cw(a)){var r=fs(a.before,t),n=fs(a.after,t),i=r>0,o=n<0,l=Cn(a.before,a.after);return l?o&&i:i||o}return mw(a)?fs(t,a.after)>0:uw(a)?fs(a.before,t)>0:typeof a=="function"?a(t):!1})}function ro(t,s,a){var r=Object.keys(s).reduce(function(i,o){var l=s[o];return fw(t,l)&&i.push(o),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!li(t,a)&&(n.outside=!0),n}function yw(t,s){for(var a=Vt(t[0]),r=oi(t[t.length-1]),n,i,o=a;o<=r;){var l=ro(o,s),c=!l.disabled&&!l.hidden;if(!c){o=Ut(o,1);continue}if(l.selected)return o;l.today&&!i&&(i=o),n||(n=o),o=Ut(o,1)}return i||n}var vw=365;function nu(t,s){var a=s.moveBy,r=s.direction,n=s.context,i=s.modifiers,o=s.retry,l=o===void 0?{count:0,lastFocused:t}:o,c=n.weekStartsOn,m=n.fromDate,d=n.toDate,u=n.locale,h={day:Ut,week:wn,month:cs,year:Uh,startOfWeek:function(v){return n.ISOWeek?ci(v):di(v,{locale:u,weekStartsOn:c})},endOfWeek:function(v){return n.ISOWeek?Pc(v):Dc(v,{locale:u,weekStartsOn:c})}},x=h[a](t,r==="after"?1:-1);r==="before"&&m?x=Vh([m,x]):r==="after"&&d&&(x=Bh([d,x]));var p=!0;if(i){var f=ro(x,i);p=!f.disabled&&!f.hidden}return p?x:l.count>vw?l.lastFocused:nu(x,{moveBy:a,direction:r,context:n,modifiers:i,retry:fe(fe({},l),{count:l.count+1})})}var iu=g.createContext(void 0);function bw(t){var s=Ja(),a=ru(),r=g.useState(),n=r[0],i=r[1],o=g.useState(),l=o[0],c=o[1],m=yw(s.displayMonths,a),d=n??(l&&s.isDateDisplayed(l))?l:m,u=function(){c(n),i(void 0)},h=function(v){i(v)},x=Ve(),p=function(v,j){if(n){var y=nu(n,{moveBy:v,direction:j,context:x,modifiers:a});Lt(n,y)||(s.goToDate(y,n),h(y))}},f={focusedDay:n,focusTarget:d,blur:u,focus:h,focusDayAfter:function(){return p("day","after")},focusDayBefore:function(){return p("day","before")},focusWeekAfter:function(){return p("week","after")},focusWeekBefore:function(){return p("week","before")},focusMonthBefore:function(){return p("month","before")},focusMonthAfter:function(){return p("month","after")},focusYearBefore:function(){return p("year","before")},focusYearAfter:function(){return p("year","after")},focusStartOfWeek:function(){return p("startOfWeek","before")},focusEndOfWeek:function(){return p("endOfWeek","after")}};return e.jsx(iu.Provider,{value:f,children:t.children})}function no(){var t=g.useContext(iu);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function jw(t,s){var a=ru(),r=ro(t,a,s);return r}var io=g.createContext(void 0);function Nw(t){if(!$r(t.initialProps)){var s={selected:void 0};return e.jsx(io.Provider,{value:s,children:t.children})}return e.jsx(ww,{initialProps:t.initialProps,children:t.children})}function ww(t){var s=t.initialProps,a=t.children,r=function(i,o,l){var c,m,d;if((c=s.onDayClick)===null||c===void 0||c.call(s,i,o,l),o.selected&&!s.required){(m=s.onSelect)===null||m===void 0||m.call(s,void 0,i,o,l);return}(d=s.onSelect)===null||d===void 0||d.call(s,i,i,o,l)},n={selected:s.selected,onDayClick:r};return e.jsx(io.Provider,{value:n,children:a})}function ou(){var t=g.useContext(io);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function Cw(t,s){var a=Ve(),r=ou(),n=to(),i=ao(),o=no(),l=o.focusDayAfter,c=o.focusDayBefore,m=o.focusWeekAfter,d=o.focusWeekBefore,u=o.blur,h=o.focus,x=o.focusMonthBefore,p=o.focusMonthAfter,f=o.focusYearBefore,v=o.focusYearAfter,j=o.focusStartOfWeek,y=o.focusEndOfWeek,w=function(k){var D,z,K,Y;$r(a)?(D=r.onDayClick)===null||D===void 0||D.call(r,t,s,k):Za(a)?(z=n.onDayClick)===null||z===void 0||z.call(n,t,s,k):Xa(a)?(K=i.onDayClick)===null||K===void 0||K.call(i,t,s,k):(Y=a.onDayClick)===null||Y===void 0||Y.call(a,t,s,k)},N=function(k){var D;h(t),(D=a.onDayFocus)===null||D===void 0||D.call(a,t,s,k)},S=function(k){var D;u(),(D=a.onDayBlur)===null||D===void 0||D.call(a,t,s,k)},T=function(k){var D;(D=a.onDayMouseEnter)===null||D===void 0||D.call(a,t,s,k)},F=function(k){var D;(D=a.onDayMouseLeave)===null||D===void 0||D.call(a,t,s,k)},R=function(k){var D;(D=a.onDayPointerEnter)===null||D===void 0||D.call(a,t,s,k)},M=function(k){var D;(D=a.onDayPointerLeave)===null||D===void 0||D.call(a,t,s,k)},b=function(k){var D;(D=a.onDayTouchCancel)===null||D===void 0||D.call(a,t,s,k)},A=function(k){var D;(D=a.onDayTouchEnd)===null||D===void 0||D.call(a,t,s,k)},P=function(k){var D;(D=a.onDayTouchMove)===null||D===void 0||D.call(a,t,s,k)},B=function(k){var D;(D=a.onDayTouchStart)===null||D===void 0||D.call(a,t,s,k)},E=function(k){var D;(D=a.onDayKeyUp)===null||D===void 0||D.call(a,t,s,k)},L=function(k){var D;switch(k.key){case"ArrowLeft":k.preventDefault(),k.stopPropagation(),a.dir==="rtl"?l():c();break;case"ArrowRight":k.preventDefault(),k.stopPropagation(),a.dir==="rtl"?c():l();break;case"ArrowDown":k.preventDefault(),k.stopPropagation(),m();break;case"ArrowUp":k.preventDefault(),k.stopPropagation(),d();break;case"PageUp":k.preventDefault(),k.stopPropagation(),k.shiftKey?f():x();break;case"PageDown":k.preventDefault(),k.stopPropagation(),k.shiftKey?v():p();break;case"Home":k.preventDefault(),k.stopPropagation(),j();break;case"End":k.preventDefault(),k.stopPropagation(),y();break}(D=a.onDayKeyDown)===null||D===void 0||D.call(a,t,s,k)},C={onClick:w,onFocus:N,onBlur:S,onKeyDown:L,onKeyUp:E,onMouseEnter:T,onMouseLeave:F,onPointerEnter:R,onPointerLeave:M,onTouchCancel:b,onTouchEnd:A,onTouchMove:P,onTouchStart:B};return C}function Sw(){var t=Ve(),s=ou(),a=to(),r=ao(),n=$r(t)?s.selected:Za(t)?a.selected:Xa(t)?r.selected:void 0;return n}function Aw(t){return Object.values(rs).includes(t)}function Tw(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(Aw(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function kw(t,s){var a=fe({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=fe(fe({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function Rw(t,s,a){var r,n,i,o=Ve(),l=no(),c=jw(t,s),m=Cw(t,c),d=Sw(),u=!!(o.onDayClick||o.mode!=="default");g.useEffect(function(){var T;c.outside||l.focusedDay&&u&&Lt(l.focusedDay,t)&&((T=a.current)===null||T===void 0||T.focus())},[l.focusedDay,t,a,u,c.outside]);var h=Tw(o,c).join(" "),x=kw(o,c),p=!!(c.outside&&!o.showOutsideDays||c.hidden),f=(i=(n=o.components)===null||n===void 0?void 0:n.DayContent)!==null&&i!==void 0?i:ZN,v=e.jsx(f,{date:t,displayMonth:s,activeModifiers:c}),j={style:x,className:h,children:v,role:"gridcell"},y=l.focusTarget&&Lt(l.focusTarget,t)&&!c.outside,w=l.focusedDay&&Lt(l.focusedDay,t),N=fe(fe(fe({},j),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=w||y?0:-1,r)),m),S={isButton:u,isHidden:p,activeModifiers:c,selectedDays:d,buttonProps:N,divProps:j};return S}function Pw(t){var s=g.useRef(null),a=Rw(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(vr,fe({name:"day",ref:s},a.buttonProps)):e.jsx("div",fe({},a.divProps))}function Dw(t){var s=t.number,a=t.dates,r=Ve(),n=r.onWeekNumberClick,i=r.styles,o=r.classNames,l=r.locale,c=r.labels.labelWeekNumber,m=r.formatters.formatWeekNumber,d=m(Number(s),{locale:l});if(!n)return e.jsx("span",{className:o.weeknumber,style:i.weeknumber,children:d});var u=c(Number(s),{locale:l}),h=function(x){n(s,a,x)};return e.jsx(vr,{name:"week-number","aria-label":u,className:o.weeknumber,style:i.weeknumber,onClick:h,children:d})}function Ew(t){var s,a,r=Ve(),n=r.styles,i=r.classNames,o=r.showWeekNumber,l=r.components,c=(s=l==null?void 0:l.Day)!==null&&s!==void 0?s:Pw,m=(a=l==null?void 0:l.WeekNumber)!==null&&a!==void 0?a:Dw,d;return o&&(d=e.jsx("td",{className:i.cell,style:n.cell,children:e.jsx(m,{number:t.weekNumber,dates:t.dates})})),e.jsxs("tr",{className:i.row,style:n.row,children:[d,t.dates.map(function(u){return e.jsx("td",{className:i.cell,style:n.cell,role:"presentation",children:e.jsx(c,{displayMonth:t.displayMonth,date:u})},$h(u))})]})}function oc(t,s,a){for(var r=a!=null&&a.ISOWeek?Pc(s):Dc(s,a),n=a!=null&&a.ISOWeek?ci(t):di(t,a),i=fs(r,n),o=[],l=0;l<=i;l++)o.push(Ut(n,l));var c=o.reduce(function(m,d){var u=a!=null&&a.ISOWeek?Wh(d):qh(d,a),h=m.find(function(x){return x.weekNumber===u});return h?(h.dates.push(d),m):(m.push({weekNumber:u,dates:[d]}),m)},[]);return c}function Mw(t,s){var a=oc(Vt(t),oi(t),s);if(s!=null&&s.useFixedWeeks){var r=Oh(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],o=wn(i,6-r),l=oc(wn(i,1),o,s);a.push.apply(a,l)}}return a}function Iw(t){var s,a,r,n=Ve(),i=n.locale,o=n.classNames,l=n.styles,c=n.hideHead,m=n.fixedWeeks,d=n.components,u=n.weekStartsOn,h=n.firstWeekContainsDate,x=n.ISOWeek,p=Mw(t.displayMonth,{useFixedWeeks:!!m,ISOWeek:x,locale:i,weekStartsOn:u,firstWeekContainsDate:h}),f=(s=d==null?void 0:d.Head)!==null&&s!==void 0?s:YN,v=(a=d==null?void 0:d.Row)!==null&&a!==void 0?a:Ew,j=(r=d==null?void 0:d.Footer)!==null&&r!==void 0?r:qN;return e.jsxs("table",{id:t.id,className:o.table,style:l.table,role:"grid","aria-labelledby":t["aria-labelledby"],children:[!c&&e.jsx(f,{}),e.jsx("tbody",{className:o.tbody,style:l.tbody,children:p.map(function(y){return e.jsx(v,{displayMonth:t.displayMonth,dates:y.dates,weekNumber:y.weekNumber},y.weekNumber)})}),e.jsx(j,{displayMonth:t.displayMonth})]})}function Lw(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Fw=Lw()?g.useLayoutEffect:g.useEffect,vn=!1,_w=0;function lc(){return"react-day-picker-".concat(++_w)}function Ow(t){var s,a=t??(vn?lc():null),r=g.useState(a),n=r[0],i=r[1];return Fw(function(){n===null&&i(lc())},[]),g.useEffect(function(){vn===!1&&(vn=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function $w(t){var s,a,r=Ve(),n=r.dir,i=r.classNames,o=r.styles,l=r.components,c=Ja().displayMonths,m=Ow(r.id?"".concat(r.id,"-").concat(t.displayIndex):void 0),d=r.id?"".concat(r.id,"-grid-").concat(t.displayIndex):void 0,u=[i.month],h=o.month,x=t.displayIndex===0,p=t.displayIndex===c.length-1,f=!x&&!p;n==="rtl"&&(s=[x,p],p=s[0],x=s[1]),x&&(u.push(i.caption_start),h=fe(fe({},h),o.caption_start)),p&&(u.push(i.caption_end),h=fe(fe({},h),o.caption_end)),f&&(u.push(i.caption_between),h=fe(fe({},h),o.caption_between));var v=(a=l==null?void 0:l.Caption)!==null&&a!==void 0?a:WN;return e.jsxs("div",{className:u.join(" "),style:h,children:[e.jsx(v,{id:m,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(Iw,{id:d,"aria-labelledby":m,displayMonth:t.displayMonth})]},t.displayIndex)}function Uw(t){var s=Ve(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function Vw(t){var s,a,r=t.initialProps,n=Ve(),i=no(),o=Ja(),l=g.useState(!1),c=l[0],m=l[1];g.useEffect(function(){n.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),m(!0)))},[n.initialFocus,c,i.focus,i.focusTarget,i]);var d=[n.classNames.root,n.className];n.numberOfMonths>1&&d.push(n.classNames.multiple_months),n.showWeekNumber&&d.push(n.classNames.with_weeknumber);var u=fe(fe({},n.styles.root),n.style),h=Object.keys(r).filter(function(p){return p.startsWith("data-")}).reduce(function(p,f){var v;return fe(fe({},p),(v={},v[f]=r[f],v))},{}),x=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:Uw;return e.jsx("div",fe({className:d.join(" "),style:u,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},h,{children:e.jsx(x,{children:o.displayMonths.map(function(p,f){return e.jsx($w,{displayIndex:f,displayMonth:p},f)})})}))}function Bw(t){var s=t.children,a=uN(t,["children"]);return e.jsx(DN,{initialProps:a,children:e.jsx(VN,{children:e.jsx(Nw,{initialProps:a,children:e.jsx(XN,{initialProps:a,children:e.jsx(ew,{initialProps:a,children:e.jsx(lw,{children:e.jsx(bw,{children:s})})})})})})})}function zw(t){return e.jsx(Bw,fe({},t,{children:e.jsx(Vw,{initialProps:t})}))}function bn({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(zw,{showOutsideDays:a,className:ce("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:ce(Oa({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:ce("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:ce(Oa({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($c,{className:ce("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(ui,{className:ce("size-4",n),...i})},...r})}const lu={"RE-MH-001":{code:"RE-MH-001",name:"Royal Motors Mumbai",email:"dealer@royalmotorsmumbai.com",phone:"+91 98765 12345",address:"Shop No. 12-15, Central Avenue, Andheri West",city:"Mumbai",state:"Maharashtra",region:"West",managerName:"Rahul Deshmukh"},"RE-DL-002":{code:"RE-DL-002",name:"Delhi Enfield Center",email:"contact@delhienfield.com",phone:"+91 98765 23456",address:"45-48, Rajouri Garden, Main Market",city:"New Delhi",state:"Delhi",region:"North",managerName:"Vikram Singh"},"RE-BLR-003":{code:"RE-BLR-003",name:"Bangalore Royal Bikes",email:"info@bangaloreroyalbikes.com",phone:"+91 98765 34567",address:"123, MG Road, Near Trinity Metro",city:"Bangalore",state:"Karnataka",region:"South",managerName:"Suresh Kumar"},"RE-CHN-004":{code:"RE-CHN-004",name:"Chennai Enfield Hub",email:"chennai@enfieldhub.com",phone:"+91 98765 45678",address:"78-80, Anna Salai, T Nagar",city:"Chennai",state:"Tamil Nadu",region:"South",managerName:"Venkat Ramanan"},"RE-HYD-005":{code:"RE-HYD-005",name:"Hyderabad Royal Motorcycles",email:"hyderabad@royalmotorcycles.com",phone:"+91 98765 56789",address:"234, Banjara Hills, Road No. 12",city:"Hyderabad",state:"Telangana",region:"South",managerName:"Anil Reddy"},"RE-KOL-006":{code:"RE-KOL-006",name:"Kolkata Enfield Motors",email:"kolkata@enfieldmotors.com",phone:"+91 98765 67890",address:"56-58, Park Street, Near Park Hotel",city:"Kolkata",state:"West Bengal",region:"East",managerName:"Amit Chatterjee"},"RE-PUN-007":{code:"RE-PUN-007",name:"Pune Royal Dealership",email:"pune@royaldealership.com",phone:"+91 98765 78901",address:"345, FC Road, Deccan Gymkhana",city:"Pune",state:"Maharashtra",region:"West",managerName:"Sandeep Patil"},"RE-AHM-008":{code:"RE-AHM-008",name:"Ahmedabad Enfield Plaza",email:"ahmedabad@enfieldplaza.com",phone:"+91 98765 89012",address:"123, CG Road, Navrangpura",city:"Ahmedabad",state:"Gujarat",region:"West",managerName:"Kiran Patel"},"RE-JP-009":{code:"RE-JP-009",name:"Jaipur Royal Enfield",email:"jaipur@royalenfield.com",phone:"+91 98765 90123",address:"67, MI Road, C-Scheme",city:"Jaipur",state:"Rajasthan",region:"North",managerName:"Rajesh Sharma"},"RE-LKO-010":{code:"RE-LKO-010",name:"Lucknow Enfield Showroom",email:"lucknow@enfieldshowroom.com",phone:"+91 98765 01234",address:"89, Hazratganj, Near Halwasiya Crossing",city:"Lucknow",state:"Uttar Pradesh",region:"North",managerName:"Ankit Verma"}};function Hw(t){return lu[t]||null}function Ww(){return Object.values(lu)}function qw(t){return`${t.address}, ${t.city}, ${t.state}`}const Kw=["Marketing Activity","Promotional Event","Dealer Training","Infrastructure Development","Customer Experience Initiative","Service Campaign"],Gw=Ww(),jn=["Claim Details","Review & Submit"];function Yw({onBack:t,onSubmit:s}){const[a,r]=g.useState(1),[n,i]=g.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:""}),o=jn.length,l=(p,f)=>{i(v=>({...v,[p]:f}))},c=()=>{switch(a){case 1:return n.activityName&&n.activityType&&n.dealerCode&&n.dealerName&&n.activityDate&&n.location&&n.requestDescription;case 2:return!0;default:return!1}},m=()=>{a<o&&c()&&r(a+1)},d=()=>{a>1&&r(a-1)},u=p=>{const f=Hw(p);f&&(l("dealerCode",f.code),l("dealerName",f.name),l("dealerEmail",f.email),l("dealerPhone",f.phone),l("dealerAddress",qw(f)))},h=()=>{const p={...n,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",workflowSteps:[{step:1,name:"Initiator Evaluation",status:"pending",approver:"Current User (Initiator)",description:"Review and confirm all claim details and documents"},{step:2,name:"IO Confirmation",status:"waiting",approver:"System",description:"Automatic IO generation upon initiator approval"},{step:3,name:"Department Lead Approval",status:"waiting",approver:"Department Lead",description:"Budget blocking and final approval"},{step:4,name:"Document Submission",status:"waiting",approver:"Dealer",description:"Dealer submits completion documents"},{step:5,name:"Document Verification",status:"waiting",approver:"Initiator",description:"Verify completion documents"},{step:6,name:"E-Invoice Generation",status:"waiting",approver:"System",description:"Auto-generate e-invoice based on approved amount"},{step:7,name:"Credit Note Issuance",status:"waiting",approver:"Finance",description:"Issue credit note to dealer"}]};Me.success("Claim Request Created",{description:"Your claim management request has been submitted successfully."}),s&&s(p)},x=()=>{switch(a){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(kn,{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(X,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(me,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:n.activityName,onChange:p=>l("activityName",p.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(X,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(Se,{value:n.activityType,onValueChange:p=>l("activityType",p),children:[e.jsx(Te,{className:"mt-2 h-12",children:e.jsx(Ae,{placeholder:"Select activity type"})}),e.jsx(ke,{children:Kw.map(p=>e.jsx(H,{value:p,children:p},p))})]})]})]}),e.jsxs("div",{children:[e.jsx(X,{htmlFor:"dealer",className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsxs(Se,{value:n.dealerCode,onValueChange:u,children:[e.jsx(Te,{className:"mt-2 h-12",children:e.jsx(Ae,{placeholder:"Select dealer",children:n.dealerCode&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:n.dealerCode}),e.jsx("span",{className:"text-gray-400",children:"•"}),e.jsx("span",{children:n.dealerName})]})})}),e.jsx(ke,{children:Gw.map(p=>e.jsx(H,{value:p.code,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-semibold",children:p.code}),e.jsx("span",{className:"text-gray-400",children:"•"}),e.jsx("span",{children:p.name})]})},p.code))})]}),n.dealerCode&&e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:n.dealerName})," (",n.dealerCode,")"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(Zs,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),n.activityDate?ye(n.activityDate,"PPP"):"Select date"]})}),e.jsx(Js,{className:"w-auto p-0",align:"start",children:e.jsx(bn,{mode:"single",selected:n.activityDate,onSelect:p=>l("activityDate",p),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(X,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(me,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:n.location,onChange:p=>l("location",p.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(X,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),e.jsx(us,{id:"requestDescription",placeholder:"Provide a detailed description of your claim requirement...",value:n.requestDescription,onChange:p=>l("requestDescription",p.target.value),className:"mt-2 min-h-[120px]"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Include key details about the claim, objectives, and expected outcomes"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(X,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(J,{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(X,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(Zs,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),n.periodStartDate?ye(n.periodStartDate,"PPP"):"Start date"]})}),e.jsx(Js,{className:"w-auto p-0",align:"start",children:e.jsx(bn,{mode:"single",selected:n.periodStartDate,onSelect:p=>l("periodStartDate",p),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(Zs,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),n.periodEndDate?ye(n.periodEndDate,"PPP"):"End date"]})}),e.jsx(Js,{className:"w-auto p-0",align:"start",children:e.jsx(bn,{mode:"single",selected:n.periodEndDate,onSelect:p=>l("periodEndDate",p),initialFocus:!0})})]})]})]}),(n.periodStartDate||n.periodEndDate)&&e.jsx("p",{className:"text-xs text-gray-600 mt-2",children:n.periodStartDate&&n.periodEndDate?`Period: ${ye(n.periodStartDate,"MMM dd, yyyy")} - ${ye(n.periodEndDate,"MMM dd, yyyy")}`:"Please select both start and end dates for the period"})]})]})]});case 2: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(xe,{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(W,{className:"border-2",children:[e.jsx(Q,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(q,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:n.activityName})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(J,{variant:"secondary",className:"mt-1",children:n.activityType})]})]})})]}),e.jsxs(W,{className:"border-2",children:[e.jsx(Q,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(gp,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(q,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{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:n.dealerCode})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:n.dealerName})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:n.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:n.dealerPhone})]}),n.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:n.dealerAddress})]})]})})]}),e.jsxs(W,{className:"border-2",children:[e.jsx(Q,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(q,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:n.activityDate?ye(n.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(X,{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(fp,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:n.location})]})]}),n.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(X,{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:n.estimatedBudget})]})]})})]}),e.jsxs(W,{className:"border-2",children:[e.jsx(Q,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(we,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(q,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(X,{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("p",{className:"text-gray-900 whitespace-pre-wrap",children:n.requestDescription})})]})})]}),(n.periodStartDate||n.periodEndDate)&&e.jsxs(W,{className:"border-2",children:[e.jsx(Q,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(q,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:n.periodStartDate?ye(n.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:n.periodEndDate?ye(n.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(Nr,{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.jsx("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(I,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(ra,{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(J,{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 ",a," of ",o,": ",e.jsx("span",{className:"hidden sm:inline",children:jn[a-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(ds,{value:a/o*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:jn.map((p,f)=>e.jsx("span",{className:`text-xs sm:text-sm ${f+1<=a?"text-blue-600 font-medium":"text-gray-400"}`,children:f+1},f))})]})]}),e.jsx(W,{className:"mb-6 sm:mb-8",children:e.jsx(q,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(Lr,{mode:"wait",children:x()})})}),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(I,{variant:"outline",onClick:d,disabled:a===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(ra,{className:"w-4 h-4"}),"Previous"]}),a<o?e.jsxs(I,{onClick:m,disabled:!c(),className:"gap-2 w-full sm:w-auto order-1 sm:order-2",children:["Next",e.jsx(mt,{className:"w-4 h-4"})]}):e.jsxs(I,{onClick:h,disabled:!c(),className:"gap-2 bg-green-600 hover:bg-green-700 w-full sm:w-auto order-1 sm:order-2",children:[e.jsx(fa,{className:"w-4 h-4"}),"Submit Claim Request"]})]})]})})}function cu({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(J,{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 es({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:o,testId:l="stats-card"}){return e.jsx(W,{className:`${n} border transition-shadow hover:shadow-md`,"data-testid":l,children:e.jsx(q,{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":`${l}-label`,children:t}),e.jsx("p",{className:`text-xl sm:text-2xl font-bold ${o}`,"data-testid":`${l}-value`,children:s})]}),e.jsx(a,{className:`w-6 h-6 sm:w-8 sm:h-8 ${r}`,"data-testid":`${l}-icon`})]})})})}function Zw({stats:t}){return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3 sm:gap-4","data-testid":"my-requests-stats",children:[e.jsx(es,{label:"Total",value:t.total,icon:we,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"}),e.jsx(es,{label:"Pending",value:t.pending,icon:Pe,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"}),e.jsx(es,{label:"Approved",value:t.approved,icon:xe,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"}),e.jsx(es,{label:"Rejected",value:t.rejected,icon:et,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"}),e.jsx(es,{label:"Draft",value:t.draft,icon:Wa,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"})]})}function Xw({searchTerm:t,statusFilter:s,priorityFilter:a,onSearchChange:r,onStatusChange:n,onPriorityChange:i}){return e.jsx(W,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(q,{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(ns,{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(me,{placeholder:"Search requests by title, description, or ID...",value:t,onChange:o=>r(o.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(Se,{value:s,onValueChange:n,children:[e.jsx(Te,{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(Ae,{placeholder:"Status"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Status"}),e.jsx(H,{value:"draft",children:"Draft"}),e.jsx(H,{value:"pending",children:"Pending"}),e.jsx(H,{value:"approved",children:"Approved"}),e.jsx(H,{value:"rejected",children:"Rejected"}),e.jsx(H,{value:"closed",children:"Closed"})]})]}),e.jsxs(Se,{value:a,onValueChange:i,children:[e.jsx(Te,{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(Ae,{placeholder:"Priority"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Priority"}),e.jsx(H,{value:"express",children:"Express"}),e.jsx(H,{value:"standard",children:"Standard"})]})]})]})]})})})}function Jw(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:is,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Qe,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Qe,iconColor:"text-gray-600"}}}function Qw(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:xe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:et,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Pe,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:xe,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Wa,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600"}}}function e1({request:t,index:s,onViewRequest:a}){const r=Qw(t.status),n=Jw(t.priority),i=r.icon,o=n.icon;return e.jsx(yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(W,{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(q,{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(J,{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})]}),e.jsxs(J,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(o,{className:"w-3 h-3 mr-1"}),t.priority]}),t.templateType&&e.jsxs(J,{variant:"secondary",className:"bg-purple-100 text-purple-700 text-xs shrink-0 hidden sm:inline-flex","data-testid":"template-badge",children:[e.jsx(we,{className:"w-3 h-3 mr-1"}),"Template: ",t.templateName]})]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2","data-testid":"request-description",children:t.description}),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:"})," ",ms(t.submittedDate)]})]})]}),e.jsx(mt,{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.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(xt,{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(Ms,{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(Pe,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ms(t.submittedDate)]})]})]})]})})})})}function t1({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(W,{"data-testid":"loading-state",children:e.jsx(q,{className:"p-6 text-sm text-gray-600",children:"Loading your requests…"})});if(t.length===0){const o=a||r!=="all"||n!=="all";return e.jsx(W,{"data-testid":"empty-state",children:e.jsxs(q,{className:"p-12 text-center",children:[e.jsx(we,{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:o?"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((o,l)=>e.jsx(e1,{request:o,index:l,onViewRequest:i},o.id))})}function s1(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,templateName:t.templateName}}function du(t){return Array.isArray(t)?t.map(s1):[]}function a1({itemsPerPage:t=10,initialFilters:s}={}){const[a,r]=g.useState([]),[n,i]=g.useState(!1),[o,l]=g.useState(!1),[c,m]=g.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=g.useRef(!0),u=g.useCallback(async(h=1,x)=>{try{h===1&&(i(!0),r([]));const p=await Gt.listMyWorkflows({page:h,limit:t,search:x==null?void 0:x.search,status:x==null?void 0:x.status,priority:x==null?void 0:x.priority}),f=Array.isArray(p==null?void 0:p.data)?p.data:[],v=du(f);r(v),l(!0);const j=p==null?void 0:p.pagination;j&&m({currentPage:j.page||1,totalPages:j.totalPages||1,totalRecords:j.total||0,itemsPerPage:t})}catch(p){console.error("[MyRequests] Error fetching requests:",p),r([]),l(!0)}finally{i(!1)}},[t]);return g.useEffect(()=>{d.current&&(u(1,s),d.current=!1)},[]),{requests:a,loading:n,hasFetchedFromApi:o,pagination:c,fetchMyRequests:u}}function r1({onFiltersChange:t,debounceMs:s=500}={}){const[a,r]=g.useState(""),[n,i]=g.useState("all"),[o,l]=g.useState("all"),c=g.useRef(null),m=g.useCallback(()=>({search:a,status:n,priority:o}),[a,n,o]);g.useEffect(()=>{c.current&&clearTimeout(c.current);const u=setTimeout(()=>{t&&t(m())},a?s:0);return c.current=u,()=>{c.current&&clearTimeout(c.current)}},[a,n,o,t,m,s]);const d=g.useCallback(()=>{r(""),i("all"),l("all")},[]);return{searchTerm:a,statusFilter:n,priorityFilter:o,setSearchTerm:r,setStatusFilter:i,setPriorityFilter:l,getFilters:m,resetFilters:d}}function n1({requests:t,totalRecords:s}){return g.useMemo(()=>({total:s||t.length,pending:t.filter(r=>r.status==="pending").length,approved:t.filter(r=>r.status==="approved").length,rejected:t.filter(r=>r.status==="rejected").length,draft:t.filter(r=>r.status==="draft").length,closed:t.filter(r=>r.status==="closed").length}),[t,s])}function i1({onViewRequest:t,dynamicRequests:s=[]}){const a=a1({itemsPerPage:10}),r=g.useRef(a.fetchMyRequests);r.current=a.fetchMyRequests;const n=r1({onFiltersChange:g.useCallback(m=>{r.current(1,{search:m.search||void 0,status:m.status!=="all"?m.status:void 0,priority:m.priority!=="all"?m.priority:void 0})},[])}),i=du(s),o=a.hasFetchedFromApi?a.requests:i,l=n1({requests:o,totalRecords:a.pagination.totalRecords}),c=g.useCallback(m=>{m>=1&&m<=a.pagination.totalPages&&a.fetchMyRequests(m,{search:n.searchTerm||void 0,status:n.statusFilter!=="all"?n.statusFilter:void 0,priority:n.priorityFilter!=="all"?n.priorityFilter:void 0})},[a,n]);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(cu,{icon:we,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${a.pagination.totalRecords||o.length} total`,label:"requests",loading:a.loading},testId:"my-requests-header"}),e.jsx(Zw,{stats:l}),e.jsx(Xw,{searchTerm:n.searchTerm,statusFilter:n.statusFilter,priorityFilter:n.priorityFilter,onSearchChange:n.setSearchTerm,onStatusChange:n.setStatusFilter,onPriorityChange:n.setPriorityFilter}),e.jsx(t1,{requests:o,loading:a.loading,searchTerm:n.searchTerm,statusFilter:n.statusFilter,priorityFilter:n.priorityFilter,onViewRequest:t}),e.jsx(ba,{currentPage:a.pagination.currentPage,totalPages:a.pagination.totalPages,totalRecords:a.pagination.totalRecords,itemsPerPage:a.pagination.itemsPerPage,onPageChange:c,loading:a.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function o1({isOrgLevel:t,totalRequests:s,loading:a,loadingStats:r,exporting:n,onExport:i}){return e.jsxs("div",{className:"flex items-start justify-between gap-4","data-testid":"requests-header-container",children:[e.jsx(cu,{icon:we,title:t?"All Requests (Organization)":"My Requests",description:t?"View and filter all organization-wide workflow requests with advanced filtering options":"View and filter your workflow requests with advanced filtering options",badge:{value:`${s} total`,label:"requests",loading:a||r},testId:"requests-header"}),e.jsx(I,{onClick:i,disabled:n||a,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-button",children:n?e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function l1({stats:t}){return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-3 sm:gap-4","data-testid":"requests-stats",children:[e.jsx(es,{label:"Total",value:t.total,icon:we,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"}),e.jsx(es,{label:"Pending",value:t.pending,icon:Pe,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"}),e.jsx(es,{label:"Approved",value:t.approved,icon:xe,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"}),e.jsx(es,{label:"Rejected",value:t.rejected,icon:et,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"}),e.jsx(es,{label:"Closed",value:t.closed,icon:hi,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"}),e.jsx(es,{label:"Draft",value:t.draft,icon:Wa,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"})]})}const c1=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:is,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Qe,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Qe,iconColor:"text-gray-600"}}},d1=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:xe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:et,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Pe,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:xe,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Wa,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600"}}};function m1({request:t,index:s,onViewRequest:a}){const r=d1(t.status),n=c1(t.priority),i=r.icon,o=n.icon;return e.jsx(yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(W,{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(q,{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(J,{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})]}),e.jsxs(J,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(o,{className:"w-3 h-3 mr-1"}),t.priority]}),t.department&&e.jsx(J,{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","data-testid":"request-description",children:t.description}),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:"})," ",ms(t.submittedDate)]})]})]}),e.jsx(mt,{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.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(xt,{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(Ms,{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(Pe,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ms(t.submittedDate)]})]})]})]})})})})}function u1({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(W,{"data-testid":"loading-state",children:e.jsx(q,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(W,{"data-testid":"empty-state",children:e.jsxs(q,{className:"p-12 text-center",children:[e.jsx(we,{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(m1,{request:n,index:i,onViewRequest:r},n.id))})}function h1(){const[t,s]=Tr(),[a,r]=g.useState(t.get("search")||""),[n,i]=g.useState(t.get("status")||"all"),[o,l]=g.useState(t.get("priority")||"all"),[c,m]=g.useState(t.get("slaCompliance")||"all"),[d,u]=g.useState(t.get("department")||"all"),[h,x]=g.useState(t.get("initiator")||"all"),[p,f]=g.useState(t.get("approver")||"all"),[v,j]=g.useState(t.get("approverType")==="any"?"any":"current"),[y,w]=g.useState(t.get("dateRange")||"month"),[N,S]=g.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[T,F]=g.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[R,M]=g.useState(!1);g.useEffect(()=>{const L=new URLSearchParams;a&&L.set("search",a),n!=="all"&&L.set("status",n),o!=="all"&&L.set("priority",o),c!=="all"&&L.set("slaCompliance",c),d!=="all"&&L.set("department",d),h!=="all"&&L.set("initiator",h),p!=="all"&&(L.set("approver",p),L.set("approverType",v)),y&&L.set("dateRange",y),N&&L.set("startDate",N.toISOString()),T&&L.set("endDate",T.toISOString()),s(L,{replace:!0})},[a,n,o,c,d,h,p,v,y,N,T,s]);const b=g.useCallback(()=>({search:a||void 0,status:n!=="all"?n:void 0,priority:o!=="all"?o:void 0,slaCompliance:c!=="all"?c:void 0,department:d!=="all"?d:void 0,initiator:h!=="all"?h:void 0,approver:p!=="all"?p:void 0,approverType:p!=="all"?v:void 0,dateRange:y,startDate:N,endDate:T}),[a,n,o,c,d,h,p,v,y,N,T]),A=g.useCallback(()=>{r(""),i("all"),l("all"),m("all"),u("all"),x("all"),f("all"),j("current"),w("month"),S(void 0),F(void 0),M(!1)},[]),P=g.useCallback(L=>{const C=L;w(C),C!=="custom"?(S(void 0),F(void 0),M(!1)):M(!0)},[]),B=g.useCallback(()=>{if(N&&T){if(N>T){const L=N;S(T),F(L)}M(!1)}},[N,T]);return{searchTerm:a,statusFilter:n,priorityFilter:o,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:h,approverFilter:p,approverFilterType:v,dateRange:y,customStartDate:N,customEndDate:T,showCustomDatePicker:R,hasActiveFilters:!!(a||n!=="all"||o!=="all"||c!=="all"||d!=="all"||h!=="all"||p!=="all"||y!=="month"||N||T),setSearchTerm:r,setStatusFilter:i,setPriorityFilter:l,setSlaComplianceFilter:m,setDepartmentFilter:u,setInitiatorFilter:x,setApproverFilter:f,setApproverFilterType:j,setDateRange:w,setCustomStartDate:S,setCustomEndDate:F,setShowCustomDatePicker:M,getFilters:b,clearFilters:A,handleDateRangeChange:P,handleApplyCustomDate:B}}function cc({allUsers:t,filterValue:s,onFilterChange:a}){const[r,n]=g.useState(""),[i,o]=g.useState([]),[l,c]=g.useState(!1),[m,d]=g.useState(null),u=g.useRef(null);g.useEffect(()=>{if(s!=="all"&&t.length>0){const f=t.find(v=>v.userId===s);f&&(d(f),n(f.displayName||f.email))}},[s,t]),g.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const h=g.useCallback(f=>{if(n(f),u.current&&clearTimeout(u.current),!f||f.trim().length<2){o([]),c(!1);return}u.current=setTimeout(()=>{const v=f.toLowerCase().trim(),j=t.filter(y=>{const w=(y.email||"").toLowerCase(),N=(y.displayName||"").toLowerCase();return w.includes(v)||N.includes(v)});o(j.slice(0,10)),c(j.length>0)},300)},[t]),x=g.useCallback(f=>{d(f),a(f.userId),n(f.displayName||f.email),c(!1),o([])},[a]),p=g.useCallback(()=>{d(null),a("all"),n(""),c(!1),o([])},[a]);return{searchQuery:r,searchResults:i,showResults:l,selectedUser:m,handleSearch:h,handleSelect:x,handleClear:p,setShowResults:c}}function p1(t){var m,d,u,h,x,p,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 o=t.currentApprover||t.current_approver||t.currentApproverData;if(o)n=o.name||o.approverName||o.displayName||o.email||o.approverEmail||"—";else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const v=t.approvals.find(j=>{const y=(j.status||"").toString().toUpperCase();return y==="PENDING"||y==="IN_PROGRESS"});if(v)n=v.approverName||((m=v.approver)==null?void 0:m.name)||((d=v.approver)==null?void 0:d.displayName)||v.approverEmail||((u=v.approver)==null?void 0:u.email)||"—";else{const y=[...t.approvals].sort((w,N)=>{const S=w.levelNumber||w.level_number||0;return(N.levelNumber||N.level_number||0)-S})[0];y&&(n=y.approverName||((h=y.approver)==null?void 0:h.name)||((x=y.approver)==null?void 0:x.displayName)||y.approverEmail||((p=y.approver)==null?void 0:p.email)||"—")}}const l=t.currentLevel||t.current_level||t.currentLevelNumber||t.current_level_number,c=t.totalLevels||t.total_levels||t.totalLevelsCount||t.total_levels_count;if(l&&c)i=`${l} of ${c}`;else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const v=t.approvals.find(j=>{const y=(j.status||"").toString().toUpperCase();return y==="PENDING"||y==="IN_PROGRESS"});if(v){const j=v.levelNumber||v.level_number||0,y=c||t.approvals.length;i=`${j} of ${y}`}else c&&(i=`${c} of ${c}`)}else t.currentStep&&t.totalSteps&&(i=`${t.currentStep} of ${t.totalSteps}`);return{id:t.requestNumber||t.request_number||t.requestId||t.id||t.request_id,requestId:t.requestId||t.id||t.request_id,displayId:t.requestNumber||t.request_number||t.id,title:t.title,description:t.description,status:r.toLowerCase().replace("_","-"),priority:a,department:t.department||((f=t.initiator)==null?void 0:f.department),submittedDate:t.submittedAt||(t.createdAt?new Date(t.createdAt).toISOString().split("T")[0]:void 0),createdAt:s,currentApprover:n,approverLevel:i,templateType:t.templateType,templateName:t.templateName}}function x1(t){return Array.isArray(t)?t.map(p1):[]}function g1(t,s,a,r,n,i){const o=r;if(t.length>0){const l=t.length,c=t.filter(x=>{const p=(x.status||"").toString().toUpperCase();return p==="PENDING"||p==="IN_PROGRESS"}).length,m=t.filter(x=>(x.status||"").toString().toUpperCase()==="APPROVED").length,d=t.filter(x=>(x.status||"").toString().toUpperCase()==="REJECTED").length,u=t.filter(x=>(x.status||"").toString().toUpperCase()==="DRAFT").length,h=t.filter(x=>(x.status||"").toString().toUpperCase()==="CLOSED").length;return{total:l,pending:c,approved:m,rejected:d,draft:u,closed:h}}else return s&&!o&&a?{total:a.total,pending:a.pending,approved:a.approved,rejected:a.rejected,draft:a.draft,closed:a.closed}:{total:n||i.length,pending:i.filter(l=>l.status==="pending"||l.status==="in-progress").length,approved:i.filter(l=>l.status==="approved").length,rejected:i.filter(l=>l.status==="rejected").length,draft:i.filter(l=>l.status==="draft").length,closed:i.filter(l=>l.status==="closed").length}}var mu={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(ni,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",o="second",l="minute",c="hour",m="day",d="week",u="month",h="quarter",x="year",p="date",f="Invalid Date",v=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,j=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,y={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(E){var L=["th","st","nd","rd"],C=E%100;return"["+E+(L[(C-20)%10]||L[C]||L[0])+"]"}},w=function(E,L,C){var k=String(E);return!k||k.length>=L?E:""+Array(L+1-k.length).join(C)+E},N={s:w,z:function(E){var L=-E.utcOffset(),C=Math.abs(L),k=Math.floor(C/60),D=C%60;return(L<=0?"+":"-")+w(k,2,"0")+":"+w(D,2,"0")},m:function E(L,C){if(L.date()<C.date())return-E(C,L);var k=12*(C.year()-L.year())+(C.month()-L.month()),D=L.clone().add(k,u),z=C-D<0,K=L.clone().add(k+(z?-1:1),u);return+(-(k+(C-D)/(z?D-K:K-D))||0)},a:function(E){return E<0?Math.ceil(E)||0:Math.floor(E)},p:function(E){return{M:u,y:x,w:d,d:m,D:p,h:c,m:l,s:o,ms:i,Q:h}[E]||String(E||"").toLowerCase().replace(/s$/,"")},u:function(E){return E===void 0}},S="en",T={};T[S]=y;var F="$isDayjsObject",R=function(E){return E instanceof P||!(!E||!E[F])},M=function E(L,C,k){var D;if(!L)return S;if(typeof L=="string"){var z=L.toLowerCase();T[z]&&(D=z),C&&(T[z]=C,D=z);var K=L.split("-");if(!D&&K.length>1)return E(K[0])}else{var Y=L.name;T[Y]=L,D=Y}return!k&&D&&(S=D),D||!k&&S},b=function(E,L){if(R(E))return E.clone();var C=typeof L=="object"?L:{};return C.date=E,C.args=arguments,new P(C)},A=N;A.l=M,A.i=R,A.w=function(E,L){return b(E,{locale:L.$L,utc:L.$u,x:L.$x,$offset:L.$offset})};var P=function(){function E(C){this.$L=M(C.locale,null,!0),this.parse(C),this.$x=this.$x||C.x||{},this[F]=!0}var L=E.prototype;return L.parse=function(C){this.$d=function(k){var D=k.date,z=k.utc;if(D===null)return new Date(NaN);if(A.u(D))return new Date;if(D instanceof Date)return new Date(D);if(typeof D=="string"&&!/Z$/i.test(D)){var K=D.match(v);if(K){var Y=K[2]-1||0,de=(K[7]||"0").substring(0,3);return z?new Date(Date.UTC(K[1],Y,K[3]||1,K[4]||0,K[5]||0,K[6]||0,de)):new Date(K[1],Y,K[3]||1,K[4]||0,K[5]||0,K[6]||0,de)}}return new Date(D)}(C),this.init()},L.init=function(){var C=this.$d;this.$y=C.getFullYear(),this.$M=C.getMonth(),this.$D=C.getDate(),this.$W=C.getDay(),this.$H=C.getHours(),this.$m=C.getMinutes(),this.$s=C.getSeconds(),this.$ms=C.getMilliseconds()},L.$utils=function(){return A},L.isValid=function(){return this.$d.toString()!==f},L.isSame=function(C,k){var D=b(C);return this.startOf(k)<=D&&D<=this.endOf(k)},L.isAfter=function(C,k){return b(C)<this.startOf(k)},L.isBefore=function(C,k){return this.endOf(k)<b(C)},L.$g=function(C,k,D){return A.u(C)?this[k]:this.set(D,C)},L.unix=function(){return Math.floor(this.valueOf()/1e3)},L.valueOf=function(){return this.$d.getTime()},L.startOf=function(C,k){var D=this,z=!!A.u(k)||k,K=A.p(C),Y=function($,G){var ae=A.w(D.$u?Date.UTC(D.$y,G,$):new Date(D.$y,G,$),D);return z?ae:ae.endOf(m)},de=function($,G){return A.w(D.toDate()[$].apply(D.toDate("s"),(z?[0,0,0,0]:[23,59,59,999]).slice(G)),D)},Z=this.$W,je=this.$M,ve=this.$D,U="set"+(this.$u?"UTC":"");switch(K){case x:return z?Y(1,0):Y(31,11);case u:return z?Y(1,je):Y(0,je+1);case d:var V=this.$locale().weekStart||0,te=(Z<V?Z+7:Z)-V;return Y(z?ve-te:ve+(6-te),je);case m:case p:return de(U+"Hours",0);case c:return de(U+"Minutes",1);case l:return de(U+"Seconds",2);case o:return de(U+"Milliseconds",3);default:return this.clone()}},L.endOf=function(C){return this.startOf(C,!1)},L.$set=function(C,k){var D,z=A.p(C),K="set"+(this.$u?"UTC":""),Y=(D={},D[m]=K+"Date",D[p]=K+"Date",D[u]=K+"Month",D[x]=K+"FullYear",D[c]=K+"Hours",D[l]=K+"Minutes",D[o]=K+"Seconds",D[i]=K+"Milliseconds",D)[z],de=z===m?this.$D+(k-this.$W):k;if(z===u||z===x){var Z=this.clone().set(p,1);Z.$d[Y](de),Z.init(),this.$d=Z.set(p,Math.min(this.$D,Z.daysInMonth())).$d}else Y&&this.$d[Y](de);return this.init(),this},L.set=function(C,k){return this.clone().$set(C,k)},L.get=function(C){return this[A.p(C)]()},L.add=function(C,k){var D,z=this;C=Number(C);var K=A.p(k),Y=function(je){var ve=b(z);return A.w(ve.date(ve.date()+Math.round(je*C)),z)};if(K===u)return this.set(u,this.$M+C);if(K===x)return this.set(x,this.$y+C);if(K===m)return Y(1);if(K===d)return Y(7);var de=(D={},D[l]=r,D[c]=n,D[o]=a,D)[K]||1,Z=this.$d.getTime()+C*de;return A.w(Z,this)},L.subtract=function(C,k){return this.add(-1*C,k)},L.format=function(C){var k=this,D=this.$locale();if(!this.isValid())return D.invalidDate||f;var z=C||"YYYY-MM-DDTHH:mm:ssZ",K=A.z(this),Y=this.$H,de=this.$m,Z=this.$M,je=D.weekdays,ve=D.months,U=D.meridiem,V=function(G,ae,he,be){return G&&(G[ae]||G(k,z))||he[ae].slice(0,be)},te=function(G){return A.s(Y%12||12,G,"0")},$=U||function(G,ae,he){var be=G<12?"AM":"PM";return he?be.toLowerCase():be};return z.replace(j,function(G,ae){return ae||function(he){switch(he){case"YY":return String(k.$y).slice(-2);case"YYYY":return A.s(k.$y,4,"0");case"M":return Z+1;case"MM":return A.s(Z+1,2,"0");case"MMM":return V(D.monthsShort,Z,ve,3);case"MMMM":return V(ve,Z);case"D":return k.$D;case"DD":return A.s(k.$D,2,"0");case"d":return String(k.$W);case"dd":return V(D.weekdaysMin,k.$W,je,2);case"ddd":return V(D.weekdaysShort,k.$W,je,3);case"dddd":return je[k.$W];case"H":return String(Y);case"HH":return A.s(Y,2,"0");case"h":return te(1);case"hh":return te(2);case"a":return $(Y,de,!0);case"A":return $(Y,de,!1);case"m":return String(de);case"mm":return A.s(de,2,"0");case"s":return String(k.$s);case"ss":return A.s(k.$s,2,"0");case"SSS":return A.s(k.$ms,3,"0");case"Z":return K}return null}(G)||K.replace(":","")})},L.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},L.diff=function(C,k,D){var z,K=this,Y=A.p(k),de=b(C),Z=(de.utcOffset()-this.utcOffset())*r,je=this-de,ve=function(){return A.m(K,de)};switch(Y){case x:z=ve()/12;break;case u:z=ve();break;case h:z=ve()/3;break;case d:z=(je-Z)/6048e5;break;case m:z=(je-Z)/864e5;break;case c:z=je/n;break;case l:z=je/r;break;case o:z=je/a;break;default:z=je}return D?z:A.a(z)},L.daysInMonth=function(){return this.endOf(u).$D},L.$locale=function(){return T[this.$L]},L.locale=function(C,k){if(!C)return this.$L;var D=this.clone(),z=M(C,k,!0);return z&&(D.$L=z),D},L.clone=function(){return A.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()},E}(),B=P.prototype;return b.prototype=B,[["$ms",i],["$s",o],["$m",l],["$H",c],["$W",m],["$M",u],["$y",x],["$D",p]].forEach(function(E){B[E[1]]=function(L){return this.$g(L,E[0],E[1])}}),b.extend=function(E,L){return E.$i||(E(L,P,b),E.$i=!0),b},b.locale=M,b.isDayjs=R,b.unix=function(E){return b(1e3*E)},b.en=T[S],b.Ls=T,b.p={},b})})(mu);var f1=mu.exports;const $t=ii(f1);var uu={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(ni,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(uu);var y1=uu.exports;const hu=ii(y1);var pu={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(ni,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(pu);var v1=pu.exports;const xu=ii(v1);$t.extend(xu);$t.extend(hu);function ti(t,s){let a=[...t];if(s.search){const r=s.search.toLowerCase();a=a.filter(n=>{var i,o,l,c;return((i=n.title)==null?void 0:i.toLowerCase().includes(r))||((o=n.description)==null?void 0:o.toLowerCase().includes(r))||((l=n.requestNumber)==null?void 0:l.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=>{const n=(r.status||"").toString().toUpperCase();return n==="PENDING"||n==="IN_PROGRESS"});else{const r=s.status.toUpperCase().replace("-","_");a=a.filter(n=>{const i=(n.status||"").toString().toUpperCase();return r==="IN_PROGRESS"||r==="IN-PROGRESS"?i==="IN_PROGRESS":i===r})}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,o;return(r.initiatorId||r.initiator_id||((i=r.initiator)==null?void 0:i.userId)||((o=r.initiator)==null?void 0:o.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 o,l,c,m,d,u;return(((o=n.currentApprover)==null?void 0:o.userId)||((l=n.currentApprover)==null?void 0:l.user_id)||((m=(c=n.approvals)==null?void 0:c.find(h=>{const x=(h.status||"").toString().toUpperCase();return x==="IN_PROGRESS"||x==="PENDING"}))==null?void 0:m.approverId)||((u=(d=n.approvals)==null?void 0:d.find(h=>{const x=(h.status||"").toString().toUpperCase();return x==="IN_PROGRESS"||x==="PENDING"}))==null?void 0:u.approver_id)||n.currentApproverId||n.current_approver_id)===s.approver}):a=a.filter(n=>{var o,l;const i=[];return(o=n.currentApprover)!=null&&o.userId&&i.push(n.currentApprover.userId),(l=n.currentApprover)!=null&&l.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,m,d,u,h,x,p,f,v,j,y,w;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const N=(r.status||"").toString().toUpperCase();if(!(N==="APPROVED"||N==="REJECTED"||N==="CLOSED"))return!1;const T=((c=r.currentLevelSLA)==null?void 0:c.status)||((d=(m=r.currentApprover)==null?void 0:m.sla)==null?void 0:d.status)||((u=r.sla)==null?void 0:u.status)||((x=(h=r.summary)==null?void 0:h.sla)==null?void 0:x.status);return T?T!=="breached"&&T.toLowerCase()!=="breached":!0}const i=((p=r.currentLevelSLA)==null?void 0:p.status)||((v=(f=r.currentApprover)==null?void 0:f.sla)==null?void 0:v.status)||((j=r.sla)==null?void 0:j.status)||((w=(y=r.summary)==null?void 0:y.sla)==null?void 0:w.status);if(!i)return n==="on-track"||n==="on_track";const l={"on-track":"on_track",on_track:"on_track",approaching:"approaching",critical:"critical",breached:"breached"}[n.toLowerCase()]||n.toLowerCase();return i===l||i.toLowerCase()===l})),s.dateRange){let r=null,n=null;if(s.dateRange==="custom"&&s.startDate&&s.endDate)r=$t(s.startDate).startOf("day").toDate(),n=$t(s.endDate).endOf("day").toDate();else{const i=$t();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 o=i.submittedAt||i.submission_date||i.submitted_at;if(!o){const d=i.createdAt||i.created_at||i.created_date;if(!d)return!1;const u=$t(d).startOf("day").toDate(),h=$t(r).startOf("day").toDate(),x=$t(n).endOf("day").toDate();return u>=h&&u<=x}const l=$t(o).startOf("day").toDate(),c=$t(r).startOf("day").toDate(),m=$t(n).endOf("day").toDate();return l>=c&&l<=m}))}return a}$t.extend(hu);$t.extend(xu);function b1(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return ye(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function j1(t,s){const a=ti(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var y,w,N,S,T;const m=(c.status||"").toString().toLowerCase().replace("_","-"),d=(c.priority||"").toString().toLowerCase(),u=((y=c.initiator)==null?void 0:y.displayName)||((w=c.initiator)==null?void 0:w.email)||c.initiatorName||"N/A",h=c.department||((N=c.initiator)==null?void 0:N.department)||"N/A",x=((S=c.currentApprover)==null?void 0:S.displayName)||((T=c.currentApprover)==null?void 0:T.email)||c.currentApproverName||"N/A",p=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",f=b1(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),v=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),j=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,m,d,`"${u.replace(/"/g,'""')}"`,`"${h.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,p,f,`"${v}"`];r.push(j.join(","))});const n=r.join(`
`),i=new Blob([n],{type:"text/csv;charset=utf-8;"}),o=document.createElement("a"),l=URL.createObjectURL(i);o.setAttribute("href",l),o.setAttribute("download",`requests-export-${new Date().toISOString().split("T")[0]}.csv`),o.style.visibility="hidden",document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(l)}async function N1({page:t,itemsPerPage:s,filters:a,isOrgLevel:r}){if(r){const n=[];let i=1,o=!0;const l=50;for(;o&&i<=l;){const h=await Gt.listWorkflows({page:i,limit:100});let x=[];Array.isArray(h==null?void 0:h.data)?x=h.data:Array.isArray(h)&&(x=h),x.length>0?(n.push(...x),i++,h!=null&&h.pagination?o=i<=h.pagination.totalPages:o=x.length===100):o=!1}const c=a?ti(n,a):n,m=(t-1)*s,d=m+s;return{data:c.slice(m,d),allData:n,filteredData:c,pagination:{page:t,limit:s,total:c.length,totalPages:Math.ceil(c.length/s)||1}}}else{const n=(a==null?void 0:a.dateRange)&&a.dateRange!=="month";let i=[];if(n||(a==null?void 0:a.dateRange)==="custom"){const d=[];let u=1,h=!0;const x=50;for(;h&&u<=x;){const p=await Gt.listMyWorkflows({page:u,limit:100,search:a==null?void 0:a.search,status:(a==null?void 0:a.status)!=="all"?a==null?void 0:a.status:void 0,priority:(a==null?void 0:a.priority)!=="all"?a==null?void 0:a.priority:void 0}),f=Array.isArray(p==null?void 0:p.data)?p.data:[];f.length>0?(d.push(...f),u++,p!=null&&p.pagination?h=u<=p.pagination.totalPages:h=f.length===100):h=!1}i=d}else{const d=await Gt.listMyWorkflows({page:t,limit:s,search:a==null?void 0:a.search,status:(a==null?void 0:a.status)!=="all"?a==null?void 0:a.status:void 0,priority:(a==null?void 0:a.priority)!=="all"?a==null?void 0:a.priority:void 0});i=Array.isArray(d==null?void 0:d.data)?d.data:[]}let o=a?ti(i,a):i;const l=(t-1)*s,c=l+s;return{data:o.slice(l,c),allData:i,filteredData:o,pagination:{page:t,limit:s,total:o.length,totalPages:Math.ceil(o.length/s)||1}}}}async function w1(t){const s=[];let a=1,r=!0;const n=100;for(;r&&a<=n;){const i=t?await Gt.listWorkflows({page:a,limit:100}):await Gt.listMyWorkflows({page:a,limit:100});let o=[];Array.isArray(i==null?void 0:i.data)?o=i.data:Array.isArray(i)&&(o=i),o.length>0?(s.push(...o),a++,i!=null&&i.pagination?r=a<=i.pagination.totalPages:r=o.length===100):r=!1}return s}function C1({onViewRequest:t}){const{user:s}=Zt(),a=g.useMemo(()=>Rr(s),[s]),r=h1(),[n,i]=g.useState([]),[o,l]=g.useState(!1),[c,m]=g.useState(!1),[d,u]=g.useState([]),[h,x]=g.useState(null),[p,f]=g.useState(!1),[v,j]=g.useState([]),[y,w]=g.useState(!1),[N,S]=g.useState([]),[T,F]=g.useState(1),[R,M]=g.useState(1),[b,A]=g.useState(0),[P]=g.useState(10),B=cc({allUsers:N,filterValue:r.initiatorFilter,onFilterChange:r.setInitiatorFilter}),E=cc({allUsers:N,filterValue:r.approverFilter,onFilterChange:r.setApproverFilter}),L=g.useCallback(async(U,V,te)=>{if(a)try{f(!0);const $=await We.getRequestStats(U,V?V.toISOString():void 0,te?te.toISOString():void 0);x({total:$.totalRequests||0,pending:$.openRequests||0,approved:$.approvedRequests||0,rejected:$.rejectedRequests||0,draft:$.draftRequests||0,closed:0})}catch{}finally{f(!1)}},[a]),C=g.useCallback(async()=>{try{w(!0);const U=await We.getDepartments();j(U)}catch{}finally{w(!1)}},[]),k=g.useCallback(async()=>{try{const V=(await Wt.getAllUsers()).map(te=>({userId:te.userId,email:te.email,displayName:te.displayName||te.email}));S(V)}catch(U){console.error("Failed to fetch users:",U)}},[]),D=g.useRef(r),z=g.useRef(L);g.useEffect(()=>{D.current=r,z.current=L},[r,L]);const K=g.useCallback(async(U=1)=>{try{U===1&&(l(!0),i([]),u([]));const V=D.current.getFilters(),te=await N1({page:U,itemsPerPage:P,filters:V,isOrgLevel:a});if(i(te.data),u(te.filteredData),F(te.pagination.page),M(te.pagination.totalPages),A(te.pagination.total),a){const $=te.allData.filter(G=>(G.status||"").toString().toUpperCase()==="CLOSED").length;z.current(V.dateRange,V.startDate,V.endDate).then(()=>{x(G=>G?{...G,closed:$}:null)})}}catch{i([])}finally{l(!1)}},[P,a]),Y=g.useCallback(async()=>{try{m(!0);const U=await w1(a);await j1(U,r.getFilters())}catch(U){console.error("Failed to export requests:",U),alert("Failed to export requests. Please try again.")}finally{m(!1)}},[a,r]);g.useEffect(()=>{C(),k()},[C,k]),g.useEffect(()=>{a&&z.current(r.dateRange,r.customStartDate,r.customEndDate)},[a,r.dateRange,r.customStartDate,r.customEndDate]),g.useEffect(()=>{const U=setTimeout(()=>{F(1),K(1)},r.searchTerm?500:0);return()=>clearTimeout(U)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.slaComplianceFilter,r.departmentFilter,r.initiatorFilter,r.approverFilter,r.approverFilterType,r.dateRange,r.customStartDate,r.customEndDate]);const de=g.useCallback(U=>{U>=1&&U<=R&&(F(U),K(U))},[R,K]),Z=g.useMemo(()=>x1(n),[n]),je=g.useMemo(()=>g1(d,a,h,r.hasActiveFilters,b,Z),[d,a,h,r.hasActiveFilters,b,Z]),ve=a&&h?h.total:b||Z.length;return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(o1,{isOrgLevel:a,totalRequests:ve,loading:o,loadingStats:p,exporting:c,onExport:Y}),e.jsx(l1,{stats:je}),e.jsx(W,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(q,{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(jr,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),r.hasActiveFilters&&e.jsx(J,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),r.hasActiveFilters&&e.jsxs(I,{variant:"ghost",size:"sm",onClick:r.clearFilters,className:"gap-2",children:[e.jsx(Ot,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Nt,{}),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(ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(me,{placeholder:"Search requests...",value:r.searchTerm,onChange:U=>r.setSearchTerm(U.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Se,{value:r.statusFilter,onValueChange:r.setStatusFilter,children:[e.jsx(Te,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ae,{placeholder:"All Status"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Status"}),e.jsx(H,{value:"draft",children:"Draft"}),e.jsx(H,{value:"pending",children:"Pending"}),e.jsx(H,{value:"approved",children:"Approved"}),e.jsx(H,{value:"rejected",children:"Rejected"}),e.jsx(H,{value:"closed",children:"Closed"})]})]}),e.jsxs(Se,{value:r.priorityFilter,onValueChange:r.setPriorityFilter,children:[e.jsx(Te,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ae,{placeholder:"All Priority"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Priority"}),e.jsx(H,{value:"express",children:"Express"}),e.jsx(H,{value:"standard",children:"Standard"})]})]}),e.jsxs(Se,{value:r.departmentFilter,onValueChange:r.setDepartmentFilter,disabled:y||v.length===0,children:[e.jsx(Te,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ae,{placeholder:y?"Loading...":"All Departments"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Departments"}),v.map(U=>e.jsx(H,{value:U,children:U},U))]})]}),e.jsxs(Se,{value:r.slaComplianceFilter,onValueChange:r.setSlaComplianceFilter,children:[e.jsx(Te,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ae,{placeholder:"All SLA Status"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All SLA Status"}),e.jsx(H,{value:"compliant",children:"Compliant"}),e.jsx(H,{value:"on-track",children:"On Track"}),e.jsx(H,{value:"approaching",children:"Approaching"}),e.jsx(H,{value:"critical",children:"Critical"}),e.jsx(H,{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(X,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),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(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:B.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{placeholder:"Search initiator...",value:B.searchQuery,onChange:U=>B.handleSearch(U.target.value),onFocus:()=>{B.searchResults.length>0&&B.setShowResults(!0)},onBlur:()=>setTimeout(()=>B.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),B.showResults&&B.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:B.searchResults.map(U=>e.jsx("button",{type:"button",onClick:()=>B.handleSelect(U),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:U.displayName||U.email}),U.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:U.email})]})},U.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(X,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r.approverFilter!=="all"&&e.jsxs(Se,{value:r.approverFilterType,onValueChange:U=>r.setApproverFilterType(U),children:[e.jsx(Te,{className:"h-7 w-32 text-xs",children:e.jsx(Ae,{})}),e.jsxs(ke,{children:[e.jsx(H,{value:"current",children:"Current Only"}),e.jsx(H,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:E.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:E.selectedUser.displayName||E.selectedUser.email}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:E.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{placeholder:"Search approver...",value:E.searchQuery,onChange:U=>E.handleSearch(U.target.value),onFocus:()=>{E.searchResults.length>0&&E.setShowResults(!0)},onBlur:()=>setTimeout(()=>E.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),E.showResults&&E.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:E.searchResults.map(U=>e.jsx("button",{type:"button",onClick:()=>E.handleSelect(U),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:U.displayName||U.email}),U.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:U.email})]})},U.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Se,{value:r.dateRange,onValueChange:r.handleDateRangeChange,children:[e.jsx(Te,{className:"w-[160px] h-10",children:e.jsx(Ae,{placeholder:"Date Range"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"today",children:"Today"}),e.jsx(H,{value:"week",children:"This Week"}),e.jsx(H,{value:"month",children:"This Month"}),e.jsx(H,{value:"custom",children:"Custom Range"})]})]}),r.dateRange==="custom"&&e.jsxs(Zs,{open:r.showCustomDatePicker,onOpenChange:r.setShowCustomDatePicker,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(qe,{className:"w-4 h-4"}),r.customStartDate&&r.customEndDate?`${ye(r.customStartDate,"MMM d, yyyy")} - ${ye(r.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Js,{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(X,{htmlFor:"start-date",children:"Start Date"}),e.jsx(me,{id:"start-date",type:"date",value:r.customStartDate?ye(r.customStartDate,"yyyy-MM-dd"):"",onChange:U=>{const V=U.target.value?new Date(U.target.value):void 0;V?(r.setCustomStartDate(V),r.customEndDate&&V>r.customEndDate&&r.setCustomEndDate(V)):r.setCustomStartDate(void 0)},max:ye(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"end-date",children:"End Date"}),e.jsx(me,{id:"end-date",type:"date",value:r.customEndDate?ye(r.customEndDate,"yyyy-MM-dd"):"",onChange:U=>{const V=U.target.value?new Date(U.target.value):void 0;V?(r.setCustomEndDate(V),r.customStartDate&&V<r.customStartDate&&r.setCustomStartDate(V)):r.setCustomEndDate(void 0)},min:r.customStartDate?ye(r.customStartDate,"yyyy-MM-dd"):void 0,max:ye(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(I,{size:"sm",onClick:r.handleApplyCustomDate,disabled:!r.customStartDate||!r.customEndDate,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(I,{size:"sm",variant:"outline",onClick:()=>{r.setShowCustomDatePicker(!1),r.setCustomStartDate(void 0),r.setCustomEndDate(void 0),r.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(u1,{requests:Z,loading:o,hasActiveFilters:r.hasActiveFilters,onViewRequest:t}),e.jsx(ba,{currentPage:T,totalPages:R,totalRecords:b,itemsPerPage:P,onPageChange:de,loading:o,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function S1(){const t=ya();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(W,{children:e.jsxs(q,{className:"p-8 text-center",children:[e.jsx(Re,{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(I,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(ra,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function A1({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(Xe,{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(I,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx(Ot,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function T1({approverStats:t,calculatedStats:s}){if(!t)return null;const a=(t==null?void 0:t.tatCompliancePercent)??s.tatComplianceRate;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(W,{children:[e.jsx(Q,{className:"pb-3",children:e.jsx(ee,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(q,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[a,"%"]}),e.jsx("div",{className:`p-2 rounded-lg ${a>=95?"bg-green-100":a>=90?"bg-blue-100":a>=85?"bg-orange-100":"bg-red-100"}`,children:e.jsx(Qe,{className:`w-5 h-5 ${a>=95?"text-green-600":a>=90?"text-blue-600":a>=85?"text-orange-600":"text-red-600"}`})})]}),e.jsx(ds,{value:a,className:"mt-2 h-2"})]})]}),e.jsxs(W,{children:[e.jsx(Q,{className:"pb-3",children:e.jsx(ee,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(q,{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(xe,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(W,{children:[e.jsx(Q,{className:"pb-3",children:e.jsx(ee,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(q,{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(pi,{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(W,{children:[e.jsx(Q,{className:"pb-3",children:e.jsx(ee,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(q,{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(Pe,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function k1({approverName:t,approverStats:s,calculatedStats:a}){return e.jsxs(W,{"data-testid":"approver-actions-stats",children:[e.jsxs(Q,{children:[e.jsx(ee,{children:"Approver's Actions (Filtered)"}),e.jsxs(le,{children:["Statistics based on ",t,"'s actions with current filters applied"]})]}),e.jsxs(q,{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(Xe,{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(xe,{className:"w-5 h-5 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:a.completedActions>0?`${a.approvalRate}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:a.approvedByApprover}),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(et,{className:"w-5 h-5 text-red-600"}),e.jsx("span",{className:"text-xs text-red-600 font-medium",children:a.completedActions>0?`${a.rejectionRate}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:a.rejectedByApprover}),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(Pe,{className:"w-5 h-5 text-yellow-600"})}),e.jsx("div",{className:"text-2xl font-bold text-yellow-700",children:a.pendingByApprover}),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(hi,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"text-2xl font-bold text-gray-700",children:a.closedByApprover}),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(we,{className:"w-5 h-5 text-blue-600"})}),e.jsx("div",{className:"text-2xl font-bold text-blue-700",children:a.total}),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(Qe,{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(yp,{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}%`:a.completedActions>0?`${a.tatComplianceRate}%`:"N/A"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:a.compliant}),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(Re,{className:"w-5 h-5 text-red-600"})}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:a.breached}),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(Uc,{className:"w-5 h-5 text-purple-600"})}),e.jsx("div",{className:"text-2xl font-bold text-purple-700",children:a.completedActions}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Completed Actions"})]})]})]})]})]})}function R1({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:o,showCustomDatePicker:l,tempCustomStartDate:c,tempCustomEndDate:m,onSearchChange:d,onStatusChange:u,onPriorityChange:h,onSlaComplianceChange:x,onDateRangeChange:p,onShowCustomDatePickerChange:f,onTempStartDateChange:v,onTempEndDateChange:j,onApplyCustomDate:y,onClearFilters:w}){return e.jsxs(W,{"data-testid":"approver-performance-filters",children:[e.jsx(Q,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Filters"}),e.jsx(I,{variant:"ghost",size:"sm",onClick:w,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(q,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(me,{placeholder:"Search requests...",value:t,onChange:N=>d(N.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(Se,{value:s,onValueChange:u,children:[e.jsx(Te,{"data-testid":"status-filter",children:e.jsx(Ae,{placeholder:"Status"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Status"}),e.jsx(H,{value:"pending",children:"Pending"}),e.jsx(H,{value:"approved",children:"Approved"}),e.jsx(H,{value:"rejected",children:"Rejected"}),e.jsx(H,{value:"closed",children:"Closed"})]})]}),e.jsxs(Se,{value:a,onValueChange:h,children:[e.jsx(Te,{"data-testid":"priority-filter",children:e.jsx(Ae,{placeholder:"Priority"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Priority"}),e.jsx(H,{value:"express",children:"Express"}),e.jsx(H,{value:"standard",children:"Standard"})]})]}),e.jsxs(Se,{value:r,onValueChange:x,children:[e.jsx(Te,{"data-testid":"sla-compliance-filter",children:e.jsx(Ae,{placeholder:"SLA Compliance"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All SLA"}),e.jsx(H,{value:"compliant",children:"Compliant"}),e.jsx(H,{value:"on-track",children:"On Track"}),e.jsx(H,{value:"approaching",children:"Approaching"}),e.jsx(H,{value:"critical",children:"Critical"}),e.jsx(H,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Se,{value:n,onValueChange:p,children:[e.jsx(Te,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Ae,{placeholder:"Date Range"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"today",children:"Today"}),e.jsx(H,{value:"week",children:"This Week"}),e.jsx(H,{value:"month",children:"This Month"}),e.jsx(H,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(Zs,{open:l,onOpenChange:f,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(qe,{className:"w-4 h-4"}),c&&m?`${ye(c,"MMM d")} - ${ye(m,"MMM d")}`:"Select dates"]})}),e.jsx(Js,{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(X,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(me,{id:"start-date",type:"date",value:c?ye(c,"yyyy-MM-dd"):"",onChange:N=>{const S=N.target.value?new Date(N.target.value):void 0;S?(v(S),m&&S>m&&j(S)):v(void 0)},max:ye(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(me,{id:"end-date",type:"date",value:m?ye(m,"yyyy-MM-dd"):"",onChange:N=>{const S=N.target.value?new Date(N.target.value):void 0;S?(j(S),c&&S<c&&v(S)):j(void 0)},min:c?ye(c,"yyyy-MM-dd"):void 0,max:ye(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(I,{size:"sm",onClick:y,disabled:!c||!m,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-date-button",children:"Apply"}),e.jsx(I,{size:"sm",variant:"outline",onClick:()=>{f(!1),v(i),j(o),(!i||!o)&&p("month")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const P1=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ms,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Qe,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Qe,iconColor:"text-gray-600"}}},D1=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:xe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:et,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Pe,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Pe,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:xe,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:we,iconColor:"text-gray-600"}}},E1=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 M1(t){if(!t)return"N/A";try{return ye(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function I1(t){if(!t)return"N/A";try{return ye(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function L1({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l}){const c=ya();return e.jsxs(W,{"data-testid":"approver-performance-request-list",children:[e.jsxs(Q,{children:[e.jsx(ee,{children:"Request Details"}),e.jsxs(le,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(q,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(Ot,{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(we,{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(m=>{const d=P1(m.priority),u=D1(m.status),h=E1(m.slaStatus||""),x=d.icon,p=u.icon;return e.jsx(W,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>c(`/request/${m.requestId}`),"data-testid":`request-card-${m.requestId}`,children:e.jsx(q,{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:m.requestNumber}),e.jsxs(J,{className:d.color,"data-testid":"priority-badge",children:[e.jsx(x,{className:`w-3 h-3 mr-1 ${d.iconColor}`}),m.priority]}),e.jsxs(J,{className:u.color,"data-testid":"status-badge",children:[e.jsx(p,{className:`w-3 h-3 mr-1 ${u.iconColor}`}),m.status]}),m.approvalStatus&&e.jsx(J,{className:m.approvalStatus==="approved"||m.approvalStatus==="APPROVED"?"bg-green-100 text-green-800 border-green-200":m.approvalStatus==="rejected"||m.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:m.approvalStatus==="approved"||m.approvalStatus==="APPROVED"?e.jsxs(e.Fragment,{children:[e.jsx(xe,{className:"w-3 h-3 mr-1"}),"Approved"]}):m.approvalStatus==="rejected"||m.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(et,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-3 h-3 mr-1"}),"Pending"]})}),m.slaStatus&&e.jsx(J,{className:h.color,"data-testid":"sla-status-badge",children:h.label})]}),e.jsx("h3",{className:"font-medium text-gray-900 mb-1 truncate","data-testid":"request-title",children:m.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(xt,{className:"w-3 h-3"}),m.initiatorName,m.initiatorDepartment&&e.jsxs("span",{className:"ml-1",children:["(",m.initiatorDepartment,")"]})]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"submission-date",children:[e.jsx(Pe,{className:"w-3 h-3"}),"Submitted: ",M1(m.submissionDate)]}),m.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(xe,{className:"w-3 h-3"}),"Action: ",I1(m.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(Qe,{className:"w-3 h-3"}),"Level ",m.levelNumber," of ",m.totalLevels]}),m.levelElapsedHours&&m.levelElapsedHours>0&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"tat-info",children:[e.jsx(pi,{className:"w-3 h-3"}),Je(m.levelElapsedHours)," / ",Je(m.levelTatHours||0)," TAT"]})]})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:f=>{f.stopPropagation(),c(`/request/${m.requestId}`)},"data-testid":"view-request-button",children:e.jsx(mt,{className:"w-4 h-4"})})]})})},m.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(ba,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function F1(){const[t]=Tr(),[s,a]=g.useState(""),[r,n]=g.useState(t.get("status")||"all"),[i,o]=g.useState(t.get("priority")||"all"),[l,c]=g.useState(t.get("slaCompliance")||"all"),[m,d]=g.useState(t.get("dateRange")||"month"),[u,h]=g.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[x,p]=g.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[f,v]=g.useState(!1),[j,y]=g.useState(void 0),[w,N]=g.useState(void 0),S=g.useCallback(()=>{a(""),n("all"),o("all"),c("all"),d("month"),h(void 0),p(void 0),y(void 0),N(void 0),v(!1)},[]),T=g.useCallback(R=>{const M=R;d(M),M!=="custom"?(h(void 0),p(void 0),y(void 0),N(void 0),v(!1)):(y(u),N(x),v(!0))},[u,x]),F=g.useCallback(()=>{if(j&&w){if(j>w){const R=j;h(w),p(R),y(w),N(R)}else h(j),p(w);v(!1)}},[j,w]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:l,dateRange:m,customStartDate:u,customEndDate:x,showCustomDatePicker:f,tempCustomStartDate:j,tempCustomEndDate:w,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:o,setSlaComplianceFilter:c,setDateRange:d,setCustomStartDate:h,setCustomEndDate:p,setShowCustomDatePicker:v,setTempCustomStartDate:y,setTempCustomEndDate:N,clearFilters:S,handleDateRangeChange:T,handleApplyCustomDate:F}}function _1({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:o,searchTerm:l,itemsPerPage:c}){const[m,d]=g.useState([]),[u,h]=g.useState(null),[x,p]=g.useState([]),[f,v]=g.useState(!0),[j,y]=g.useState(!1),[w,N]=g.useState(1),[S,T]=g.useState(1),[F,R]=g.useState(0),M=g.useRef(!0),b=g.useCallback(async()=>{if(t)try{const L=(await We.getApproverPerformance(s,1,100,a,r)).performance.find(C=>C.approverId===t);L&&h(L)}catch(E){console.error("Failed to fetch approver stats:",E)}},[t,s,a,r]),A=g.useCallback(async(E=1)=>{if(!t){v(!1);return}try{v(!0);const L=await We.getRequestsByApprover(t,E,c,s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,o!=="all"?o:void 0,l||void 0);d(L.requests),R(L.pagination.totalRecords),T(L.pagination.totalPages),N(E);const C=await We.getRequestsByApprover(t,1,1e4,s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,o!=="all"?o:void 0,l||void 0);p(C.requests)}catch(L){console.error("Failed to fetch requests:",L)}finally{v(!1),y(!1)}},[t,s,a,r,n,i,o,l,c]);g.useEffect(()=>{M.current&&(M.current=!1,b(),A(1))},[]),g.useEffect(()=>{M.current||(b(),A(1))},[s,a,r,n,i,o,l]);const P=g.useCallback(()=>{y(!0),b(),A(1)},[b,A]),B=g.useCallback(E=>{N(E);const L=(E-1)*c,C=L+c,k=x.slice(L,C);d(k)},[x,c]);return g.useEffect(()=>{const E=(w-1)*c,L=E+c,C=x.slice(E,L);d(C),T(Math.ceil(x.length/c)),w>Math.ceil(x.length/c)&&x.length>0&&N(1)},[x,w,c]),{requests:m,approverStats:u,allFilteredRequests:x,loading:f,refreshing:j,currentPage:w,totalPages:S,totalRecords:F,handleRefresh:P,handlePageChange:B}}function O1(t){const s=t,a=s.filter(x=>(x.approvalStatus||"").toLowerCase()==="approved").length,r=s.filter(x=>(x.approvalStatus||"").toLowerCase()==="rejected").length,n=s.filter(x=>{const p=(x.approvalStatus||"").toLowerCase();return["pending","in_progress","in-progress"].includes(p)}).length,i=s.filter(x=>(x.status||"").toLowerCase()==="closed").length,o=s.filter(x=>{const p=x.isBreached===!0||x.isBreached===1,f=(x.slaStatus||"").toLowerCase()==="breached";return p||f}).length,l=s.filter(x=>{const p=(x.approvalStatus||"").toLowerCase(),f=p==="approved"||p==="rejected",v=["pending","in_progress","in-progress"].includes(p),j=!(x.isBreached===!0||x.isBreached===1)&&(x.slaStatus||"").toLowerCase()!=="breached";return f&&j||v&&j}).length,c=a+r,m=c>0?Math.round(a/c*100):0,d=c>0?Math.round(r/c*100):0,u=s.length,h=u>0?Math.floor(l/u*100):0;return{total:s.length,approvedByApprover:a,rejectedByApprover:r,pendingByApprover:n,closedByApprover:i,breached:o,compliant:l,approvalRate:m,rejectionRate:d,tatComplianceRate:h,completedActions:c}}const dc=10;function $1(){const[t]=Tr(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=F1(),n=_1({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:dc}),i=g.useMemo(()=>O1(n.allFilteredRequests),[n.allFilteredRequests]);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(A1,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(T1,{approverStats:n.approverStats,calculatedStats:i}),e.jsx(k1,{approverName:a,approverStats:n.approverStats,calculatedStats:i}),e.jsx(R1,{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(L1,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:dc,onPageChange:n.handlePageChange})]}):e.jsx(S1,{})}function U1(){const{user:t}=Zt(),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(W,{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(q,{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(gt,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Pr,{src:(t==null?void 0:t.picture)||""}),e.jsx(ft,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),Us(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(At,{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:[Us(t)&&e.jsxs(J,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(At,{className:"w-3 h-3 mr-1"}),"Administrator"]}),Sa(t)&&e.jsxs(J,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(Xe,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(J,{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(W,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(Q,{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(xt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(le,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(q,{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(Fc,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"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(xt,{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(xt,{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(xt,{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(_c,{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(W,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(Q,{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(yo,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(le,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(q,{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(xt,{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(vp,{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(yo,{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(At,{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(J,{variant:Us(t)||Sa(t)?"default":"secondary",className:Us(t)?"bg-yellow-400 text-slate-900":Sa(t)?"bg-blue-400 text-slate-900":"",children:Us(t)?"Administrator":Sa(t)?"Management":"User"}),(Us(t)||Sa(t))&&e.jsx(xe,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(Q,{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(qe,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(le,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(q,{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(xe,{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(J,{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 V1="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",B1="https://re-workflow-nt-api-dev.siplsolutions.com";function z1(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 H1(){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 W1(t){var n,i,o;let s;try{const l=await t.pushManager.getSubscription();l?s=l:s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:z1(V1)})}catch(l){throw new Error(`Failed to subscribe to push notifications: ${(l==null?void 0:l.message)||"Unknown error"}`)}const a=s.toJSON(),r=((i=(n=window==null?void 0:window.localStorage)==null?void 0:n.getItem)==null?void 0:i.call(n,"accessToken"))||((o=((document==null?void 0:document.cookie)||"").match(/accessToken=([^;]+)/))==null?void 0:o[1])||"";if(!r)throw new Error("Authentication token not found. Please log in again.");try{const l=await fetch(`${B1}/api/v1/workflows/notifications/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(a)});if(!l.ok){const m=await l.json().catch(()=>({error:"Unknown error"}));throw new Error((m==null?void 0:m.error)||(m==null?void 0:m.message)||`Server error: ${l.status}`)}const c=await l.json();if(!c.success)throw new Error(c.error||"Failed to save subscription")}catch(l){throw l instanceof Error&&l.message.includes("Failed")?l:new Error(`Failed to save subscription to server: ${(l==null?void 0:l.message)||"Network error"}`)}return s}async function q1(){if(!("Notification"in window))throw new Error("Notifications are not supported in this browser");let t=Notification.permission;if(t==="default"&&(t=await Notification.requestPermission()),t!=="granted")throw new Error("Notification permission was denied. Please enable notifications in your browser settings.");let s;try{s=await H1()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await W1(s)}catch(a){throw a}}function ss({className:t,...s}){return e.jsx(vh,{"data-slot":"switch",className:ce("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(bh,{"data-slot":"switch-thumb",className:ce("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 si({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const o=g.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(jh,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:ce("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(Nh,{"data-slot":"slider-track",className:ce("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(wh,{"data-slot":"slider-range",className:ce("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:o.length},(l,c)=>e.jsx(Ch,{"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 K1({onConfigUpdate:t}){const[s,a]=g.useState([]),[r,n]=g.useState(!0),[i,o]=g.useState(null),[l,c]=g.useState(null),[m,d]=g.useState({}),[u,h]=g.useState(null);g.useEffect(()=>{x()},[]);const x=async()=>{var b,A;try{n(!0),c(null);const P=await Mr();a(P)}catch(P){c(((A=(b=P.response)==null?void 0:b.data)==null?void 0:A.error)||"Failed to load configurations")}finally{n(!1)}},p=async b=>{var A,P;try{o(b.configKey),c(null);const B=m[b.configKey]??b.configValue;if(b.validationRules){const E=parseFloat(B);if(b.valueType==="NUMBER"){if(b.validationRules.min!==void 0&&E<b.validationRules.min)throw new Error(`Value must be at least ${b.validationRules.min}`);if(b.validationRules.max!==void 0&&E>b.validationRules.max)throw new Error(`Value must be at most ${b.validationRules.max}`)}}await dt(b.configKey,B),a(E=>E.map(L=>L.configKey===b.configKey?{...L,configValue:B}:L)),d(E=>{const L={...E};return delete L[b.configKey],L}),h(`${b.displayName} updated successfully`),setTimeout(()=>h(null),3e3),t&&t()}catch(B){c(B.message||((P=(A=B.response)==null?void 0:A.data)==null?void 0:P.error)||"Failed to save configuration")}finally{o(null)}},f=async b=>{var A,P;if(confirm(`Reset "${b.displayName}" to default value?`))try{o(b.configKey),c(null),await lf(b.configKey),a(B=>B.map(E=>E.configKey===b.configKey?{...E,configValue:E.defaultValue||""}:E)),d(B=>{const E={...B};return delete E[b.configKey],E}),h(`${b.displayName} reset to default`),setTimeout(()=>h(null),3e3)}catch(B){c(((P=(A=B.response)==null?void 0:A.data)==null?void 0:P.error)||"Failed to reset configuration")}finally{o(null)}},v=(b,A)=>{d(P=>({...P,[b]:A}))},j=b=>m[b.configKey]??b.configValue,y=b=>m[b.configKey]!==void 0&&m[b.configKey]!==b.configValue,w=b=>{var B,E,L,C;const A=j(b),P=i===b.configKey;if(!b.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:b.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Re,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(b.uiComponent||b.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 ${A==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${A==="true"?"text-green-700":"text-slate-600"}`,children:A==="true"?"Enabled":"Disabled"})]}),e.jsx(ss,{checked:A==="true",onCheckedChange:K=>v(b.configKey,K?"true":"false"),disabled:P})]});case"slider":const k=parseInt(A)||0,D=((B=b.validationRules)==null?void 0:B.min)||0,z=((E=b.validationRules)==null?void 0:E.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:[k,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",D,"-",z]})]}),e.jsx(si,{value:[k],min:D,max:z,step:1,onValueChange:([K])=>{K!==void 0&&v(b.configKey,K.toString())},disabled:P,className:"w-full"})]});case"number":return e.jsx(me,{type:"number",value:A,onChange:K=>v(b.configKey,K.target.value),disabled:P,min:(L=b.validationRules)==null?void 0:L.min,max:(C=b.validationRules)==null?void 0:C.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(me,{type:"text",value:A,onChange:K=>v(b.configKey,K.target.value),disabled:P,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},N=b=>{switch(b){case"TAT_SETTINGS":return e.jsx(Pe,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(we,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(Ft,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Ar,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(Vc,{className:"w-5 h-5"});default:return e.jsx(aa,{className:"w-5 h-5"})}},S=["NOTIFICATION_RULES","DASHBOARD_LAYOUT"],T=["ALLOW_EXTERNAL_SHARING"],F=s.filter(b=>!S.includes(b.configCategory)&&!T.includes(b.configKey)),R=F.reduce((b,A)=>(b[A.configCategory]||(b[A.configCategory]=[]),b[A.configCategory].push(A),b),{});if(Object.keys(R).forEach(b=>{const A=R[b];A&&A.sort((P,B)=>P.sortOrder-B.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx($e,{className:"w-8 h-8 animate-spin text-gray-400"})});if(F.length===0)return e.jsx(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(q,{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(aa,{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 M=Object.keys(R);return e.jsxs("div",{className:"space-y-6",children:[u&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(xe,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:u})]}),l&&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(Re,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:l}),e.jsx(I,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(Dr,{defaultValue:M[0],className:"w-full",children:[e.jsx(Er,{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:M.map(b=>e.jsx(lt,{value:b,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:b.replace(/_/g," ")})},b))}),M.map(b=>{var A,P,B;return e.jsx(ct,{value:b,className:"space-y-4 mt-6",children:e.jsxs(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(Q,{className:"pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx("div",{className:"text-white",children:N(b)})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold text-slate-900",children:b.replace(/_/g," ")}),e.jsxs(le,{className:"text-sm",children:[((A=R[b])==null?void 0:A.length)||0," setting",(((P=R[b])==null?void 0:P.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(q,{className:"space-y-6",children:(B=R[b])==null?void 0:B.map(E=>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(X,{className:"text-sm font-semibold text-slate-900",children:E.displayName}),y(E)&&e.jsx(J,{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"}),E.requiresRestart&&e.jsx(J,{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"})]}),E.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:E.description}),E.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:E.defaultValue})]})]})}),w(E),E.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(I,{size:"sm",onClick:()=>p(E),disabled:!y(E)||i===E.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===E.configKey?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"w-4 h-4"}),"Save Changes"]})}),E.defaultValue&&e.jsxs(I,{size:"sm",variant:"outline",onClick:()=>f(E),disabled:i===E.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(bp,{className:"w-4 h-4"}),"Reset to Default"]})]})]},E.configKey))})]})},b)})]})]})}function G1(){const[t,s]=g.useState([]),[a,r]=g.useState(!0),[n,i]=g.useState(new Date().getFullYear()),[o,l]=g.useState(!1),[c,m]=g.useState(null),[d,u]=g.useState(null),[h,x]=g.useState(null),[p,f]=g.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});g.useEffect(()=>{v()},[n]);const v=async()=>{var b,A;try{r(!0),u(null);const P=await cf(n);s(P)}catch(P){u(((A=(b=P.response)==null?void 0:b.data)==null?void 0:A.error)||"Failed to load holidays")}finally{r(!1)}},j=()=>{f({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),m(null),l(!0)},y=b=>{f({holidayDate:b.holidayDate,holidayName:b.holidayName,description:b.description||"",holidayType:b.holidayType,isRecurring:b.isRecurring}),m(b),l(!0)},w=()=>{if(c)return;const b=new Date;return b.setDate(b.getDate()+1),b.toISOString().split("T")[0]},N=async()=>{var b,A;try{if(u(null),!p.holidayDate||!p.holidayName){u("Holiday date and name are required");return}c?(await mf(c.holidayId,p),x("Holiday updated successfully")):(await df(p),x("Holiday created successfully")),await v(),l(!1),setTimeout(()=>x(null),3e3)}catch(P){u(((A=(b=P.response)==null?void 0:b.data)==null?void 0:A.error)||"Failed to save holiday")}},S=async b=>{var A,P;if(confirm(`Delete "${b.holidayName}"?`))try{u(null),await uf(b.holidayId),x("Holiday deleted successfully"),await v(),setTimeout(()=>x(null),3e3)}catch(B){u(((P=(A=B.response)==null?void 0:A.data)==null?void 0:P.error)||"Failed to delete holiday")}},T=b=>{switch(b){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"}},F=Array.from({length:5},(b,A)=>new Date().getFullYear()-1+A),R=t.reduce((b,A)=>{const P=new Date(A.holidayDate).toLocaleString("default",{month:"long"});return b[P]||(b[P]=[]),b[P].push(A),b},{}),M=Object.keys(R).sort((b,A)=>{const P=new Date(Date.parse(b+" 1, 2000")).getMonth(),B=new Date(Date.parse(A+" 1, 2000")).getMonth();return P-B});return e.jsxs("div",{className:"space-y-6",children:[h&&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(xe,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:h})]}),d&&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(Re,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:d}),e.jsx(I,{size:"sm",variant:"ghost",onClick:()=>u(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(W,{className:"shadow-lg border-0 rounded-md",children:e.jsx(Q,{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(qe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(le,{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(Se,{value:n.toString(),onValueChange:b=>i(parseInt(b)),children:[e.jsx(Te,{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(Ae,{})}),e.jsx(ke,{className:"rounded-md",children:F.map(b=>e.jsx(H,{value:b.toString(),children:b},b))})]}),e.jsxs(I,{onClick:j,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(Ps,{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($e,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(q,{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(qe,{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(I,{onClick:j,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Ps,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:M.map(b=>{var A,P,B;return e.jsxs(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(Q,{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(ee,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[b," ",n]}),e.jsxs(le,{className:"text-xs sm:text-sm",children:[((A=R[b])==null?void 0:A.length)||0," holiday",(((P=R[b])==null?void 0:P.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(qe,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(q,{className:"space-y-3 pt-4",children:(B=R[b])==null?void 0:B.map(E=>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:E.holidayName}),e.jsx(J,{variant:"outline",className:`${T(E.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:E.holidayType}),E.isRecurring&&e.jsx(J,{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:cd(E.holidayDate)}),E.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:E.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(I,{size:"sm",variant:"ghost",onClick:()=>y(E),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(jp,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(I,{size:"sm",variant:"ghost",onClick:()=>S(E),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(xi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},E.holidayId))})]},b)})}),e.jsx(ut,{open:o,onOpenChange:l,children:e.jsxs(it,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(ht,{className:"pb-4 border-b border-slate-100 px-6 pt-6 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg shadow-md",children:e.jsx(qe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ot,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(Xt,{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(X,{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(me,{id:"date",type:"date",value:p.holidayDate,onChange:b=>f({...p,holidayDate:b.target.value}),min:w(),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:c?"Select the holiday date":"Select the holiday date (minimum: tomorrow)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(X,{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(me,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:p.holidayName,onChange:b=>f({...p,holidayName:b.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(X,{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(me,{id:"description",placeholder:"Add additional details about this holiday...",value:p.description,onChange:b=>f({...p,description:b.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(X,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(Se,{value:p.holidayType,onValueChange:b=>f({...p,holidayType:b}),children:[e.jsx(Te,{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(Ae,{})}),e.jsxs(ke,{className:"rounded-lg",children:[e.jsx(H,{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(H,{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(H,{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(H,{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({...p,isRecurring:!p.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:p.isRecurring,onChange:b=>f({...p,isRecurring:b.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(X,{htmlFor:"recurring",className:"font-semibold cursor-pointer text-sm text-slate-900 block mb-1",children:"Recurring Holiday"}),e.jsx("p",{className:"text-xs text-slate-600",children:"This holiday will automatically repeat every year on the same date"})]})]})]}),e.jsxs(Et,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(I,{variant:"outline",onClick:()=>l(!1),className:"h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:"Cancel"}),e.jsxs(I,{onClick:N,disabled:!p.holidayDate||!p.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(qe,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function Y1(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function Z1(){const[t,s]=g.useState(""),[a,r]=g.useState([]),[n,i]=g.useState(!1),[o,l]=g.useState(null),[c,m]=g.useState("USER"),[d,u]=g.useState(!1),[h,x]=g.useState(null),[p,f]=g.useState([]),[v,j]=g.useState(!1),[y,w]=g.useState({admins:0,management:0,users:0}),[N,S]=g.useState("ELEVATED"),[T,F]=g.useState(1),[R,M]=g.useState(1),[b,A]=g.useState(0),P=10,B=g.useRef(null),E=g.useRef(null),L=g.useCallback(Y1(async U=>{var V,te,$;if(!U||U.length<2){r([]);return}i(!0);try{const ae=((V=(await Wt.searchUsers(U,20)).data)==null?void 0:V.data)||[];r(ae)}catch(G){console.error("Search failed:",G),x({type:"error",text:(($=(te=G.response)==null?void 0:te.data)==null?void 0:$.message)||"Failed to search users"})}finally{i(!1)}},300),[]),C=U=>{const V=U.target.value;s(V),L(V)},k=async U=>{l(U),s(U.email),r([]);const V=p.find(te=>te.email.toLowerCase()===U.email.toLowerCase()||te.userId===U.userId);if(V&&V.role)m(V.role);else try{const $=(await Wt.getAllUsers()).find(G=>G.email&&G.email.toLowerCase()===U.email.toLowerCase()||G.userId&&G.userId===U.userId);$&&$.role?m($.role):m("USER")}catch(te){console.error("Failed to check user role:",te),m("USER")}},D=async()=>{var U,V;if(!o||!c){x({type:"error",text:"Please select a user and role"});return}u(!0),x(null);try{await Wt.assignRole(o.email,c,o),x({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),m("USER"),await z(),await K()}catch(te){console.error("Role assignment failed:",te),x({type:"error",text:((V=(U=te.response)==null?void 0:U.data)==null?void 0:V.error)||"Failed to assign role"})}finally{u(!1)}},z=async(U=T)=>{var V,te,$,G,ae,he;j(!0);try{const be=await Wt.getUsersByRole(N,U,P),_e=((te=(V=be.data)==null?void 0:V.data)==null?void 0:te.users)||[],Oe=(G=($=be.data)==null?void 0:$.data)==null?void 0:G.pagination,Ue=(he=(ae=be.data)==null?void 0:ae.data)==null?void 0:he.summary;f(_e),Oe&&(F(Oe.currentPage),M(Oe.totalPages),A(Oe.totalUsers)),Ue&&w({admins:Ue.ADMIN||0,management:Ue.MANAGEMENT||0,users:Ue.USER||0})}catch(be){console.error("Failed to fetch users:",be)}finally{j(!1)}},K=async()=>{var U,V,te,$,G,ae;try{const he=await Wt.getRoleStatistics(),be=((V=(U=he.data)==null?void 0:U.data)==null?void 0:V.statistics)||((te=he.data)==null?void 0:te.statistics)||[];w({admins:parseInt((($=be.find(_e=>_e.role==="ADMIN"))==null?void 0:$.count)||"0"),management:parseInt(((G=be.find(_e=>_e.role==="MANAGEMENT"))==null?void 0:G.count)||"0"),users:parseInt(((ae=be.find(_e=>_e.role==="USER"))==null?void 0:ae.count)||"0")})}catch(he){console.error("Failed to fetch statistics:",he)}};g.useEffect(()=>{z(1),K()},[N]);const Y=U=>{S(U),F(1)},de=U=>{z(U)},Z=U=>{S(U),F(1),requestAnimationFrame(()=>{const V=E.current;V&&V.scrollIntoView({behavior:"smooth",block:"start"})})};g.useEffect(()=>{const U=V=>{B.current&&!B.current.contains(V.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",U),()=>{document.removeEventListener("mousedown",U)}},[a]);const je=U=>{switch(U){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"}},ve=U=>{switch(U){case"ADMIN":return e.jsx(na,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(Xe,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(xt,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs("div",{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(W,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${N==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>Z("ADMIN"),children:e.jsx(q,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Administrators"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"admin-count",children:y.admins}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1 font-semibold",children:N==="ADMIN"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-xl shadow-md",children:e.jsx(na,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(W,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${N==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>Z("MANAGEMENT"),children:e.jsx(q,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Management"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"management-count",children:y.management}),e.jsx("p",{className:"text-xs text-blue-700 mt-1 font-semibold",children:N==="MANAGEMENT"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-blue-400 to-blue-500 rounded-xl shadow-md",children:e.jsx(Xe,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(W,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${N==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>Z("USER"),children:e.jsx(q,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Regular Users"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"user-count",children:y.users}),e.jsx("p",{className:"text-xs text-gray-700 mt-1 font-semibold",children:N==="USER"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-gray-400 to-gray-500 rounded-xl shadow-md",children:e.jsx(xt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsxs(W,{className:"shadow-lg border",children:[e.jsx(Q,{className:"border-b 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-lg shadow-md",children:e.jsx(Np,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold",children:"Assign User Role"}),e.jsx(le,{className:"text-sm",children:"Search for a user in Okta and assign them a role"})]})]})}),e.jsxs(q,{className:"space-y-5 pt-6",children:[e.jsxs("div",{className:"space-y-2",ref:B,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(me,{type:"text",placeholder:"Type name or email address...",value:t,onChange:C,className:"pl-10 pr-10 h-12 border rounded-lg border-gray-300 focus:border-purple-500 focus:ring-2 focus:ring-purple-200 transition-all","data-testid":"user-search-input"}),n&&e.jsx($e,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-purple-500 animate-spin"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Start typing to search across all Okta users"}),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-3",children:a.map(U=>e.jsxs("button",{onClick:()=>k(U),className:"w-full text-left p-3 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${U.email}`,children:[e.jsx("p",{className:"font-medium text-gray-900",children:U.displayName||U.email}),e.jsx("p",{className:"text-sm text-gray-600",children:U.email}),U.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:[U.department,U.designation?`${U.designation}`:""]})]},U.userId))})]})]}),o&&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:(o.displayName||o.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-slate-900",children:o.displayName||o.email}),e.jsx("p",{className:"text-sm text-slate-600",children:o.email}),o.department&&e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[o.department,o.designation?`${o.designation}`:""]})]})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{l(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(Se,{value:c,onValueChange:U=>m(U),children:[e.jsx(Te,{className:"h-12 border border-gray-300 py-2 rounded-lg focus:border-purple-500 focus:ring-1 focus:ring-purple-200 transition-all","data-testid":"role-select",children:e.jsx(Ae,{placeholder:"Select role"})}),e.jsxs(ke,{className:"rounded-lg",children:[e.jsx(H,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(H,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(H,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(na,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(I,{onClick:D,disabled:!o||d,className:"w-full h-12 bg-re-green hover:bg-re-green/90 text-white font-medium shadow-md hover:shadow-lg transition-all disabled:opacity-50 rounded-lg","data-testid":"assign-role-button",children:d?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),"Assign Role"]})}),h&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${h.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:[h.type==="success"?e.jsx(xe,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Re,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${h.type==="success"?"text-green-800":"text-red-800"}`,children:h.text})]})})]})]}),e.jsx("div",{ref:E,children:e.jsxs(W,{className:"shadow-lg border",children:[e.jsx(Q,{className:"border-b pb-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-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-lg shadow-md",children:e.jsx(At,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold",children:"User Management"}),e.jsxs(le,{className:"text-sm",children:["View and manage user roles (",b," ",N!=="ALL"&&N!=="ELEVATED"?N.toLowerCase():""," users)"]})]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Se,{value:N,onValueChange:Y,children:[e.jsx(Te,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Ae,{placeholder:"Filter by role"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",y.admins+y.management,")"]})]})}),e.jsx(H,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(na,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",y.admins,")"]})]})}),e.jsx(H,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",y.management,")"]})]})}),e.jsx(H,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",y.users,")"]})]})}),e.jsx(H,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",y.admins+y.management+y.users,")"]})]})})]})]})})]})}),e.jsx(q,{className:"pt-6",children:v?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx($e,{className:"w-6 h-6 animate-spin text-purple-500 mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading users..."})]}):p.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(Xe,{className:"w-6 h-6 text-gray-400"})}),e.jsx("p",{className:"font-medium text-gray-700",children:"No users found"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:N==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2","data-testid":"users-list",children:p.map(U=>e.jsx("div",{className:"border-2 border-gray-100 hover:border-purple-200 hover:shadow-md transition-all rounded-lg bg-white p-4","data-testid":`user-${U.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 ${je(U.role)} flex items-center justify-center shadow-sm`,children:ve(U.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:U.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:U.email}),U.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[U.department,U.designation?`${U.designation}`:""]})]})]}),e.jsx(J,{className:`${je(U.role)} shrink-0`,"data-testid":`role-badge-${U.role}`,children:U.role})]})},U.userId))}),R>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 ",(T-1)*P+1," to ",Math.min(T*P,b)," of ",b," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>de(T-1),disabled:T===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,R)},(U,V)=>{let te;return R<=5||T<=3?te=V+1:T>=R-2?te=R-4+V:te=T-2+V,e.jsx(I,{variant:T===te?"default":"outline",size:"sm",onClick:()=>de(te),className:`w-9 h-9 p-0 ${T===te?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${te}-button`,children:te},te)})}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>de(T+1),disabled:T===R,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})})]})}function X1({open:t,onClose:s,success:a,message:r}){return e.jsx(ut,{open:t,onOpenChange:s,children:e.jsxs(it,{className:"sm:max-w-md",children:[e.jsx(ht,{children:e.jsxs(ot,{className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]})}),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(xe,{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(et,{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",children:r||"Unable to enable push notifications. Please check your browser settings and try again."}),e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 text-left w-full",children:[e.jsx("p",{className:"text-xs text-amber-800 font-medium mb-2",children:"💡 Troubleshooting Tips:"}),e.jsxs("ul",{className:"text-xs text-amber-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Check if notifications are blocked in browser settings"}),e.jsx("li",{children:"Ensure your browser supports push notifications"}),e.jsx("li",{children:"Try refreshing the page and enabling again"})]})]})]})})}),e.jsx(Et,{children:e.jsx(I,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}function J1(){const{user:t}=Zt(),s=Us(t),[a,r]=g.useState(!1),[n,i]=g.useState(!1),[o,l]=g.useState(),[c,m]=g.useState(!1),d=async()=>{m(!0),r(!1);try{await q1(),i(!0),l("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),r(!0)}catch(u){console.error("[Settings] Error enabling notifications:",u),i(!1);const h=(u==null?void 0:u.message)||"Unknown error occurred";l(h.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":h.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":h.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${h}`),r(!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(W,{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(q,{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(aa,{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"})]})]})})]}),s?e.jsxs(Dr,{defaultValue:"user",className:"w-full",children:[e.jsxs(Er,{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(lt,{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(aa,{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(lt,{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(At,{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(lt,{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(Bc,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(lt,{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(qe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Holidays"}),e.jsx("span",{className:"sm:hidden",children:"Holidays"})]})]}),e.jsxs("div",{className:"w-full min-h-[600px]",children:[e.jsx(ct,{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(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(Q,{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(Ft,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold text-gray-900",children:"Notifications"}),e.jsx(le,{className:"text-sm text-gray-600",children:"Manage notification preferences"})]})]})}),e.jsx(q,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs(I,{onClick:d,disabled:c,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(Ft,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Enabling...":"Enable Push Notifications"]})})})]}),e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(Q,{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(An,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(le,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(q,{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:"Security settings will be available soon"})})})})]}),e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(Q,{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(vo,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(le,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(q,{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(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(Q,{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(At,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(le,{className:"text-sm text-gray-600",children:"Application preferences"})]})]})}),e.jsx(q,{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-xl border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"User preferences will be available soon"})})})})]})]})}),e.jsx(ct,{value:"roles",className:"mt-0",children:e.jsx(Z1,{})}),e.jsx(ct,{value:"system",className:"mt-0",children:e.jsx(K1,{})}),e.jsx(ct,{value:"holidays",className:"mt-0",children:e.jsx(G1,{})})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(Q,{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(Ft,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold text-gray-900",children:"Notifications"}),e.jsx(le,{className:"text-sm text-gray-600",children:"Manage notification preferences"})]})]})}),e.jsx(q,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs(I,{onClick:d,disabled:c,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(Ft,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Enabling...":"Enable Push Notifications"]})})})]}),e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(Q,{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(An,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(le,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(q,{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:"Security settings will be available soon"})})})})]}),e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(Q,{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(vo,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(le,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(q,{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(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(Q,{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(At,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(le,{className:"text-sm text-gray-600",children:"Application preferences"})]})]})}),e.jsx(q,{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:"User preferences will be available soon"})})})})]})]}),e.jsx(W,{className:"shadow-xl border-0 rounded-md bg-gradient-to-br from-blue-50 to-blue-100/50",children:e.jsx(q,{className:"p-5 sm:p-6",children:e.jsxs("div",{className:"flex items-start sm:items-center gap-3 sm:gap-4",children:[e.jsx("div",{className:"p-2 sm:p-2.5 bg-blue-500 rounded-lg shrink-0",children:e.jsx(Re,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 mb-1",children:"Admin Features Not Accessible"}),e.jsx("p",{className:"text-xs text-gray-700",children:"System configuration and holiday management require admin privileges. Contact your administrator for access."})]})]})})})]})]}),e.jsx(X1,{open:a,onClose:()=>r(!1),success:n,message:o})]})}function Q1({onNavigate:t}){const[s,a]=g.useState([]),[r,n]=g.useState(!0),[i,o]=g.useState(1),[l,c]=g.useState(1),[m,d]=g.useState(0),[u,h]=g.useState("all"),[x,p]=g.useState(!1),f=20,v=async(M=i,b=u==="unread")=>{var A,P;try{n(M===1);const B=await Ws.list({page:M,limit:f,unreadOnly:b}),E=((A=B.data)==null?void 0:A.notifications)||[],L=((P=B.data)==null?void 0:P.total)||0;a(E),d(L),c(Math.ceil(L/f))}catch(B){console.error("[Notifications] Failed to fetch:",B)}finally{n(!1),p(!1)}};g.useEffect(()=>{v(1,u==="unread")},[u]);const j=async M=>{var b;try{if(M.isRead||(await Ws.markAsRead(M.notificationId),a(A=>A.map(P=>P.notificationId===M.notificationId?{...P,isRead:!0}:P))),M.actionUrl&&t){const A=(b=M.metadata)==null?void 0:b.requestNumber;if(A){let P=`request/${A}`;(M.notificationType==="mention"||M.notificationType==="comment"||M.notificationType==="worknote")&&(P+="?tab=worknotes"),t(P)}}}catch(A){console.error("[Notifications] Error handling notification click:",A)}},y=async()=>{try{p(!0),await Ws.markAllAsRead(),await v(i,u==="unread")}catch(M){console.error("[Notifications] Error marking all as read:",M),p(!1)}},w=async M=>{try{await Ws.delete(M),a(b=>b.filter(A=>A.notificationId!==M)),d(b=>b-1)}catch(b){console.error("[Notifications] Error deleting notification:",b)}},N=()=>{p(!0),v(i,u==="unread")},S=M=>{M<1||M>l||(o(M),v(M,u==="unread"))},T=M=>{const b="w-6 h-6";switch(M){case"mention":case"comment":return e.jsx(Ns,{className:`${b} text-blue-600`});case"worknote":return e.jsx(we,{className:`${b} text-purple-600`});case"assignment":return e.jsx(Cr,{className:`${b} text-indigo-600`});case"approval":return e.jsx(xe,{className:`${b} text-green-600`});case"rejection":return e.jsx(et,{className:`${b} text-red-600`});case"tat_alert":return e.jsx(Pe,{className:`${b} text-orange-600`});case"tat_breach":return e.jsx(Re,{className:`${b} text-red-600`});case"tat_breach_initiator":return e.jsx(as,{className:`${b} text-amber-600`});default:return e.jsx(Ft,{className:`${b} text-gray-600`})}},F=M=>{switch(M==null?void 0:M.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"}},R=s.filter(M=>!M.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(Ft,{className:"w-8 h-8 text-blue-600"}),"Notifications"]}),e.jsxs("p",{className:"text-gray-600 mt-1",children:[m," total notification",m!==1?"s":"",R>0&&`${R} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(I,{variant:"outline",size:"sm",onClick:N,disabled:x,className:"gap-2",children:[e.jsx(Ot,{className:`w-4 h-4 ${x?"animate-spin":""}`}),"Refresh"]}),R>0&&e.jsxs(I,{variant:"outline",size:"sm",onClick:y,disabled:x,className:"gap-2",children:[e.jsx(wp,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(I,{variant:u==="all"?"default":"outline",size:"sm",onClick:()=>{h("all"),o(1)},children:"All Notifications"}),e.jsxs(I,{variant:u==="unread"?"default":"outline",size:"sm",onClick:()=>{h("unread"),o(1)},children:["Unread",R>0&&e.jsx(J,{className:"ml-2 bg-red-500 text-white",children:R})]})]}),e.jsxs(W,{children:[e.jsxs(Q,{children:[e.jsx(ee,{children:"Recent Activity"}),e.jsx(le,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(q,{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(Ft,{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:u==="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(M=>{var b;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${M.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>j(M),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:T(M.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 ${M.isRead?"font-semibold":"font-bold"} text-gray-900`,children:M.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M.priority&&M.priority!=="LOW"&&e.jsx(J,{variant:"outline",className:`text-xs ${F(M.priority)}`,children:M.priority}),!M.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:M.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[kc(new Date(M.createdAt),{addSuffix:!0}),((b=M.metadata)==null?void 0:b.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",M.metadata.requestNumber]})]}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:A=>{A.stopPropagation(),w(M.notificationId)},children:e.jsx(xi,{className:"w-3.5 h-3.5"})})]})]})]})},M.notificationId)})})})]}),!r&&l>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,m)," of ",m," notifications"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(I,{variant:"outline",size:"sm",onClick:()=>S(i-1),disabled:i===1,children:[e.jsx($c,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,l)},(M,b)=>{let A;return l<=5||i<=3?A=b+1:i>=l-2?A=l-4+b:A=i-2+b,e.jsx(I,{variant:i===A?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>S(A),children:A},A)})}),e.jsxs(I,{variant:"outline",size:"sm",onClick:()=>S(i+1),disabled:i===l,children:["Next",e.jsx(ui,{className:"w-4 h-4"})]})]})]})]})}function e2({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(I,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(ra,{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(we,{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 oo({dateRange:t,customStartDate:s,customEndDate:a,showCustomDatePicker:r,tempCustomStartDate:n,tempCustomEndDate:i,onDateRangeChange:o,onShowCustomDatePickerChange:l,onStartDateChange:c,onEndDateChange:m,onApply:d,onCancel:u,testIdPrefix:h="date-filter"}){const x=s&&a?`${ye(s,"MMM d, yyyy")} - ${ye(a,"MMM d, yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${h}-container`,children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Se,{value:t,onValueChange:o,"data-testid":`${h}-select`,children:[e.jsx(Te,{className:"w-[160px]",children:e.jsx(Ae,{placeholder:"Date Range"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"today",children:"Today"}),e.jsx(H,{value:"week",children:"This Week"}),e.jsx(H,{value:"month",children:"This Month"}),e.jsx(H,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(Zs,{open:r,onOpenChange:l,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${h}-custom-trigger`,children:[e.jsx(qe,{className:"w-4 h-4"}),x]})}),e.jsx(Js,{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(X,{htmlFor:`${h}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(me,{id:`${h}-start-date`,type:"date",value:n?ye(n,"yyyy-MM-dd"):"",onChange:p=>{const f=p.target.value?new Date(p.target.value):void 0;c(f)},max:ye(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":`${h}-start-input`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:`${h}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(me,{id:`${h}-end-date`,type:"date",value:i?ye(i,"yyyy-MM-dd"):"",onChange:p=>{const f=p.target.value?new Date(p.target.value):void 0;m(f)},min:n?ye(n,"yyyy-MM-dd"):void 0,max:ye(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":`${h}-end-input`})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(I,{size:"sm",onClick:d,disabled:!n||!i,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":`${h}-apply-button`,children:"Apply"}),e.jsx(I,{size:"sm",variant:"outline",onClick:u,"data-testid":`${h}-cancel-button`,children:"Cancel"})]})]})})]})]})}function t2(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 gu(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 fu(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 s2(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function a2({lifecycleRequests:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:m,tempCustomEndDate:d,exporting:u,onDateRangeChange:h,onShowCustomDatePickerChange:x,onStartDateChange:p,onEndDateChange:f,onApplyCustomDate:v,onCancelCustomDate:j,onPageChange:y,onExport:w,onViewRequest:N}){return e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(Q,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Bt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(le,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",onClick:w,disabled:u,"data-testid":"export-lifecycle-button",children:[e.jsx(ts,{className:"w-4 h-4"}),u?"Exporting...":"Download CSV"]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(oo,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:m,tempCustomEndDate:d,onDateRangeChange:h,onShowCustomDatePickerChange:x,onStartDateChange:p,onEndDateChange:f,onApply:v,onCancel:j,testIdPrefix:"lifecycle"})})]}),e.jsxs(q,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx($e,{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(Re,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"lifecycle-empty",children:e.jsx("p",{className:"text-sm",children:"No lifecycle data available"})}):e.jsx("div",{className:"space-y-4",children:t.map(S=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${S.id}`,children:e.jsx("div",{className:"p-4 bg-gradient-to-r from-gray-50 to-white hover:bg-gray-100 cursor-pointer transition-all",onClick:()=>N(S.requestId||S.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("button",{onClick:T=>{T.stopPropagation(),N(S.requestId||S.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${S.id}`,children:S.id}),e.jsx(J,{className:gu(S.priority),"data-testid":`lifecycle-priority-${S.id}`,children:S.priority}),e.jsx(J,{className:fu(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(I,{variant:"ghost",size:"sm",onClick:()=>N(S.requestId||S.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${S.id}`,children:e.jsx(ui,{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($e,{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(I,{variant:"outline",size:"sm",onClick:()=>y(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>y(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function lo({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:ce("w-full caption-bottom text-sm",t),...s})})}function co({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:ce("[&_tr]:border-b",t),...s})}function mo({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:ce("[&_tr:last-child]:border-0",t),...s})}function sa({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:ce("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function nt({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:ce("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 at({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:ce("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function r2({activityLog:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:m,tempCustomEndDate:d,filterCategory:u,filterSeverity:h,exporting:x,onDateRangeChange:p,onShowCustomDatePickerChange:f,onStartDateChange:v,onEndDateChange:j,onApplyCustomDate:y,onCancelCustomDate:w,onCategoryChange:N,onSeverityChange:S,onClearFilters:T,onPageChange:F,onExport:R,onViewRequest:M}){const b=u!=="all"||h!=="all"||i!=="month"||o||l;return e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(Q,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-indigo-100 rounded-lg",children:e.jsx(Cp,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(le,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",onClick:R,disabled:x,"data-testid":"export-activity-button",children:[e.jsx(ts,{className:"w-4 h-4"}),x?"Exporting...":"Download CSV"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(oo,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:m,tempCustomEndDate:d,onDateRangeChange:p,onShowCustomDatePickerChange:f,onStartDateChange:v,onEndDateChange:j,onApply:y,onCancel:w,testIdPrefix:"activity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Category:"}),e.jsxs(Se,{value:u,onValueChange:N,"data-testid":"activity-category-filter",children:[e.jsx(Te,{className:"w-40",children:e.jsx(Ae,{placeholder:"All Categories"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Categories"}),e.jsx(H,{value:"WORKFLOW",children:"Workflow"}),e.jsx(H,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(H,{value:"DOCUMENT",children:"Document"}),e.jsx(H,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(H,{value:"SYSTEM",children:"System"}),e.jsx(H,{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(Se,{value:h,onValueChange:S,"data-testid":"activity-severity-filter",children:[e.jsx(Te,{className:"w-40",children:e.jsx(Ae,{placeholder:"All Severities"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"all",children:"All Severities"}),e.jsx(H,{value:"INFO",children:"Info"}),e.jsx(H,{value:"WARNING",children:"Warning"}),e.jsx(H,{value:"ERROR",children:"Error"}),e.jsx(H,{value:"CRITICAL",children:"Critical"})]})]})]}),b&&e.jsx(I,{variant:"ghost",size:"sm",onClick:T,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(q,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx($e,{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(Re,{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(lo,{children:[e.jsx(co,{children:e.jsxs(sa,{className:"bg-gray-50",children:[e.jsx(nt,{className:"font-semibold",children:"Timestamp"}),e.jsx(nt,{className:"font-semibold",children:"User"}),e.jsx(nt,{className:"font-semibold",children:"Action"}),e.jsx(nt,{className:"font-semibold",children:"Details"}),e.jsx(nt,{className:"font-semibold",children:"IP Address"}),e.jsx(nt,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(mo,{children:t.map((A,P)=>e.jsxs(sa,{className:"hover:bg-gray-50","data-testid":`activity-row-${P}`,children:[e.jsx(at,{className:"text-xs font-medium",children:A.timestamp}),e.jsx(at,{className:"text-sm",children:A.user}),e.jsx(at,{children:e.jsx(J,{className:t2(A.action),"data-testid":`activity-action-${P}`,children:A.action})}),e.jsx(at,{className:"text-sm text-gray-600",children:A.details}),e.jsx(at,{className:"text-xs font-mono text-gray-500",children:A.ip&&A.ip!=="N/A"?e.jsx("span",{title:A.userAgent||"",children:A.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(at,{children:A.requestId!=="-"&&A.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const B=A.requestId;B&&M(B)},className:"hover:underline","data-testid":`activity-request-link-${P}`,children:e.jsx(J,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:A.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},P))})]}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"activity-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx($e,{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(I,{variant:"outline",size:"sm",onClick:()=>F(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>F(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function n2({agingWorkflows:t,loading:s,loadingPage:a,error:r,pagination:n,threshold:i,thresholdError:o,dateRange:l,customStartDate:c,customEndDate:m,showCustomDatePicker:d,tempCustomStartDate:u,tempCustomEndDate:h,searchQuery:x,exporting:p,onThresholdChange:f,onThresholdBlur:v,onDateRangeChange:j,onShowCustomDatePickerChange:y,onStartDateChange:w,onEndDateChange:N,onApplyCustomDate:S,onCancelCustomDate:T,onSearchChange:F,onPageChange:R,onExport:M,onViewRequest:b}){return e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(Q,{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(pi,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(le,{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(me,{type:"number",min:"1",value:i,onChange:A=>f(A.target.value),onBlur:v,className:`w-24 ${o?"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"})]}),o&&e.jsx("span",{className:"text-xs text-red-600",children:o})]})]}),e.jsxs(J,{variant:"outline",className:"font-semibold","data-testid":"aging-total-badge",children:[n.totalRecords," workflows"]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",onClick:M,disabled:p,"data-testid":"export-aging-button",children:[e.jsx(ts,{className:"w-4 h-4"}),p?"Exporting...":"Download CSV"]})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(oo,{dateRange:l,customStartDate:c,customEndDate:m,showCustomDatePicker:d,tempCustomStartDate:u,tempCustomEndDate:h,onDateRangeChange:j,onShowCustomDatePickerChange:y,onStartDateChange:w,onEndDateChange:N,onApply:S,onCancel:T,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(me,{placeholder:"Search by Request ID, Title, or Initiator...",value:x,onChange:A=>F(A.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(q,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx($e,{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(Re,{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(lo,{children:[e.jsx(co,{children:e.jsxs(sa,{className:"bg-gray-50",children:[e.jsx(nt,{className:"font-semibold",children:"Request ID"}),e.jsx(nt,{className:"font-semibold",children:"Title"}),e.jsx(nt,{className:"font-semibold",children:"Initiator"}),e.jsx(nt,{className:"font-semibold",children:"Start Date"}),e.jsx(nt,{className:"font-semibold",children:"Days Open"}),e.jsx(nt,{className:"font-semibold",children:"Current Stage"}),e.jsx(nt,{className:"font-semibold",children:"Assigned To"}),e.jsx(nt,{className:"font-semibold",children:"Priority"}),e.jsx(nt,{className:"font-semibold",children:"Status"})]})}),e.jsx(mo,{children:t.map(A=>e.jsxs(sa,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${A.id}`,children:[e.jsx(at,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>b(A.requestId||A.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${A.id}`,children:A.id})}),e.jsx(at,{className:"text-sm",children:A.title}),e.jsx(at,{className:"text-sm",children:A.initiator}),e.jsx(at,{className:"text-sm text-gray-600",children:A.startDate}),e.jsx(at,{children:e.jsxs(J,{className:`${s2(A.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${A.id}`,children:[A.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(at,{className:"text-sm",children:A.currentStage}),e.jsx(at,{className:"text-sm",children:A.assignedTo&&A.assignedTo!=="N/A"?A.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(at,{children:e.jsx(J,{className:gu(A.priority),"data-testid":`aging-priority-${A.id}`,children:A.priority})}),e.jsx(at,{children:e.jsx(J,{className:fu(A.status),"data-testid":`aging-status-${A.id}`,children:A.status})})]},A.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($e,{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(I,{variant:"outline",size:"sm",onClick:()=>R(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>R(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function Nn(t="month"){const[s,a]=g.useState(t),[r,n]=g.useState(void 0),[i,o]=g.useState(void 0),[l,c]=g.useState(!1),[m,d]=g.useState(void 0),[u,h]=g.useState(void 0),x=g.useCallback(N=>{const S=N;a(S),S!=="custom"?(n(void 0),o(void 0),d(void 0),h(void 0),c(!1)):(d(r),h(i),c(!0))},[r,i]),p=g.useCallback(()=>{if(m&&u){if(m>u){const N=m;n(u),o(N),d(u),h(N)}else n(m),o(u);c(!1)}},[m,u]),f=g.useCallback(()=>{c(!1),d(r),h(i),(!r||!i)&&(n(void 0),o(void 0),a("month"))},[r,i]),v=g.useCallback(N=>{N?(d(N),u&&N>u&&h(N)):d(void 0)},[u]),j=g.useCallback(N=>{N?(h(N),m&&N<m&&d(N)):h(void 0)},[m]),y=g.useCallback(()=>r&&i?`${ye(r,"MMM d, yyyy")} - ${ye(i,"MMM d, yyyy")}`:"Select dates",[r,i]),w=g.useCallback(()=>{a("month"),n(void 0),o(void 0),c(!1),d(void 0),h(void 0)},[]);return{dateRange:s,customStartDate:r,customEndDate:i,showCustomDatePicker:l,tempCustomStartDate:m,tempCustomEndDate:u,setShowCustomDatePicker:c,handleDateRangeChange:x,handleApplyCustomDate:p,handleCancelCustomDate:f,handleStartDateChange:v,handleEndDateChange:j,getDisplayDateRange:y,reset:w}}function i2(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return Je(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${Je(r)}`:`${a}d`}function yu(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 zs(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"),o=String(s.getMinutes()).padStart(2,"0");return`${a}-${r}-${n} ${i}:${o}`}catch{return t}}function vu(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 o2=10;function l2({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=g.useState([]),[i,o]=g.useState(!0),[l,c]=g.useState(!1),[m,d]=g.useState(null),[u,h]=g.useState({page:1,totalPages:1,totalRecords:0}),x=g.useRef(!0),p=g.useCallback(async(f=1)=>{const v=f===1&&x.current;try{v?o(!0):c(!0),d(null);const j=await We.getLifecycleReport(f,o2,t,s,a),y=j.lifecycleData.map(w=>{const N=i2(w.overallTATHours);return{id:w.requestNumber,requestId:w.requestId,title:w.title,priority:w.priority||"medium",status:w.status,initiator:w.initiatorName||"Unknown",initDate:yu(w.submissionDate),currentStage:w.currentStageName||`Level ${w.currentLevel}`,overallTAT:N,currentLevel:w.currentLevel,totalLevels:w.totalLevels,breachCount:w.breachCount||0}});n(y),h({page:j.pagination.currentPage,totalPages:j.pagination.totalPages,totalRecords:j.pagination.totalRecords})}catch(j){console.error("Failed to fetch lifecycle data:",j),d((j==null?void 0:j.message)||"Failed to load lifecycle data")}finally{v?o(!1):c(!1)}v&&(x.current=!1)},[t,s,a]);return g.useEffect(()=>{t==="custom"&&(!s||!a)||p(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:l,error:m,pagination:u,fetchData:p}}const c2=20;function d2({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,o]=g.useState([]),[l,c]=g.useState(!0),[m,d]=g.useState(!1),[u,h]=g.useState(null),[x,p]=g.useState({page:1,totalPages:1,totalRecords:0}),f=g.useRef(!0),v=g.useCallback(async(j=1)=>{const y=j===1&&f.current;try{y?c(!0):d(!0),h(null);const w=await We.getActivityLogReport(j,c2,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),N=w.activities.map(S=>{const T=vu(S.type||"",S.details),F=(S.type||"").toLowerCase()==="login"||S.requestId==="00000000-0000-0000-0000-000000000001"||S.requestId==="SYSTEM_LOGIN",R=F?S.details||"User login":S.requestTitle||S.requestNumber||S.details||"N/A";return{timestamp:S.timestamp?yu(S.timestamp):"N/A",user:S.userName||"Unknown",action:T,details:R,ip:S.ipAddress||"N/A",userAgent:S.userAgent||null,requestId:F?"System Login":S.requestNumber||S.requestId||"-",userId:S.userId}});o(N),p({page:w.pagination.currentPage,totalPages:w.pagination.totalPages,totalRecords:w.pagination.totalRecords})}catch(w){console.error("Failed to fetch activity data:",w),h((w==null?void 0:w.message)||"Failed to load activity data")}finally{y?c(!1):d(!1)}y&&(f.current=!1)},[r,n,t,s,a]);return g.useEffect(()=>{t==="custom"&&(!s||!a)||v(1)},[r,n,t,s,a]),{activityLog:i,loading:l,loadingPage:m,error:u,pagination:x,fetchData:v}}const m2=20;function u2({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,o]=g.useState([]),[l,c]=g.useState(!0),[m,d]=g.useState(!1),[u,h]=g.useState(null),[x,p]=g.useState({page:1,totalPages:1,totalRecords:0}),f=g.useRef(!0),v=g.useCallback(async(y=1)=>{const w=y===1&&f.current;try{w?c(!0):d(!0),h(null);const N=parseInt(t,10);if(isNaN(N)||N<1){h("Please enter a valid threshold (minimum 1 day)");return}const S=await We.getWorkflowAgingReport(N,y,m2,s,a,r),T=S.agingData.map(F=>({id:F.requestNumber||F.requestId,requestId:F.requestId,title:F.title,initiator:F.initiatorName||"Unknown",startDate:F.submissionDate?new Date(F.submissionDate).toLocaleDateString():"N/A",daysOpen:F.daysOpen,currentStage:F.currentStageName||`Level ${F.currentLevel}`,assignedTo:F.currentApproverName||"N/A",priority:F.priority||"medium",status:F.status||"pending"}));o(T),p({page:S.pagination.currentPage,totalPages:S.pagination.totalPages,totalRecords:S.pagination.totalRecords})}catch(N){console.error("Failed to fetch aging data:",N),h((N==null?void 0:N.message)||"Failed to load aging data")}finally{w?c(!1):d(!1)}w&&(f.current=!1)},[t,s,a,r]),j=g.useMemo(()=>i.filter(y=>{var N,S,T;if(!n)return!0;const w=n.toLowerCase();return((N=y.id)==null?void 0:N.toLowerCase().includes(w))||((S=y.title)==null?void 0:S.toLowerCase().includes(w))||((T=y.initiator)==null?void 0:T.toLowerCase().includes(w))}),[i,n]);return g.useEffect(()=>{s==="custom"&&(!a||!r)||v(1)},[t,s,a,r]),{agingWorkflows:j,loading:l,loadingPage:m,error:u,pagination:x,fetchData:v}}function h2(t="7"){const[s,a]=g.useState(t),[r,n]=g.useState(null),i=g.useCallback(l=>{if(l===""){a(""),n(null);return}const c=parseInt(l,10);isNaN(c)||c<1?(n("Minimum threshold is 1 day"),a(l)):(n(null),a(l))},[]),o=g.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:o}}async function p2(t,s,a){const r=await We.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 o=await Ks(i.requestId||i.requestNumber),l=i.submissionDate?zs(i.submissionDate):"N/A",c=i.closureDate?zs(i.closureDate):"N/A",m=i.overallTATHours||0,d=m>0?(m/8).toFixed(2):"0",u=i.totalLevels||1,h=Math.min(Math.max(1,i.currentLevel||1),u),x=(o==null?void 0:o.approvals)||[];if(x.length===0){const p=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,l,c,u.toString(),h.toString(),m.toString(),d,(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(p.join(","))}else x.forEach(p=>{const f=p.levelStartTime?zs(p.levelStartTime):"N/A",v=p.levelEndTime||p.completedAt?zs(p.levelEndTime||p.completedAt):"N/A",j=p.tatHours||0,y=p.tatDays||(j>0?(j/8).toFixed(2):"0");let w="N/A",N="N/A",S="N/A",T="N/A";if(p.levelStartTime){const R=new Date(p.levelStartTime);if(N=(((p.levelEndTime||p.completedAt?new Date(p.levelEndTime||p.completedAt):new Date).getTime()-R.getTime())/(1e3*60*60)).toFixed(2),j>0){const A=parseFloat(N);S=Math.max(0,j-A).toFixed(2),T=(A/j*100).toFixed(2),p.status==="APPROVED"||p.status==="REJECTED"?w=A<=j?"Compliant":"Breached":p.status==="IN_PROGRESS"||p.status==="PENDING"?w=A<=j?"On Track":"At Risk":w="N/A"}}const F=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,l,c,(i.totalLevels||0).toString(),(i.currentLevel||0).toString(),m.toString(),d,(i.breachCount||0).toString(),(p.levelNumber||"").toString(),`"${(p.levelName||`Level ${p.levelNumber}`).replace(/"/g,'""')}"`,`"${(p.approverName||"N/A").replace(/"/g,'""')}"`,`"${(p.approverEmail||"N/A").replace(/"/g,'""')}"`,p.status||"PENDING",f,v,j.toString(),y.toString(),w,N,S,T];n.push(F.join(","))})}catch(o){console.error(`Failed to fetch details for request ${i.requestNumber}:`,o);const l=i.submissionDate?zs(i.submissionDate):"N/A",c=i.overallTATHours||0,m=c>0?(c/8).toFixed(2):"0",d=i.totalLevels||1,u=Math.min(Math.max(1,i.currentLevel||1),d),h=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,l,"N/A",d.toString(),u.toString(),c.toString(),m,(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(h.join(","))}uo(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function x2(t,s,a,r,n){const i=await We.getActivityLogReport(1,1e4,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),o=[["Timestamp","User","Action","Details","IP Address","User Agent","Request ID"].join(",")];i.activities.forEach(l=>{const c=vu(l.type||"",l.details),d=[l.timestamp?zs(l.timestamp):"N/A",`"${(l.userName||"Unknown").replace(/"/g,'""')}"`,`"${c.replace(/"/g,'""')}"`,`"${(l.requestTitle||l.requestNumber||l.details||"N/A").replace(/"/g,'""')}"`,l.ipAddress||"N/A",`"${(l.userAgent||"").replace(/"/g,'""')}"`,l.requestNumber||l.requestId||"-"];o.push(d.join(","))}),uo(o,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function g2(t,s,a,r){const n=await We.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(o=>{const l=o.submissionDate?zs(o.submissionDate):"N/A",c=[o.requestNumber||o.requestId||"",`"${(o.title||"").replace(/"/g,'""')}"`,`"${(o.initiatorName||"Unknown").replace(/"/g,'""')}"`,l,(o.daysOpen||0).toString(),`"${(o.currentStageName||`Level ${o.currentLevel}`).replace(/"/g,'""')}"`,`"${(o.currentApproverName||"N/A").replace(/"/g,'""')}"`,o.priority||"medium",o.status||"pending"];i.push(c.join(","))}),uo(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function uo(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 f2(){const[t,s]=g.useState(!1),[a,r]=g.useState(!1),[n,i]=g.useState(!1),o=g.useCallback(async(m,d,u)=>{try{s(!0),await p2(m,d,u)}catch(h){console.error("Failed to export lifecycle data:",h),alert("Failed to export lifecycle data. Please try again.")}finally{s(!1)}},[]),l=g.useCallback(async(m,d,u,h,x)=>{try{r(!0),await x2(m,d,u,h,x)}catch(p){console.error("Failed to export activity data:",p),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),c=g.useCallback(async(m,d,u,h)=>{try{i(!0),await g2(m,d,u,h)}catch(x){console.error("Failed to export aging data:",x),alert("Failed to export aging data. Please try again.")}finally{i(!1)}},[]);return{exportingLifecycle:t,exportingActivity:a,exportingAging:n,handleExportLifecycle:o,handleExportActivity:l,handleExportAging:c}}function y2({onBack:t}){const s=ya(),[a,r]=g.useState(""),[n,i]=g.useState("all"),[o,l]=g.useState("all"),c=Nn("month"),m=Nn("month"),d=Nn("month"),u=h2("7"),h=l2({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),x=d2({dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,filterCategory:n,filterSeverity:o}),p=u2({threshold:u.threshold,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,searchQuery:a}),f=f2(),v=g.useCallback(()=>{t?t():s("/dashboard")},[t,s]),j=g.useCallback(T=>{s(`/request/${T}`)},[s]),y=g.useCallback(()=>{f.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[f,c]),w=g.useCallback(()=>{f.handleExportActivity(m.dateRange,m.customStartDate,m.customEndDate,n,o)},[f,m,n,o]),N=g.useCallback(()=>{const T=parseInt(u.threshold,10);!isNaN(T)&&T>=1&&f.handleExportAging(T,d.dateRange,d.customStartDate,d.customEndDate)},[f,u.threshold,d]),S=g.useCallback(()=>{i("all"),l("all"),m.reset()},[m]);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(e2,{onBack:v}),e.jsx(a2,{lifecycleRequests:h.lifecycleRequests,loading:h.loading,loadingPage:h.loadingPage,error:h.error,pagination:h.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:h.fetchData,onExport:y,onViewRequest:j}),e.jsx(r2,{activityLog:x.activityLog,loading:x.loading,loadingPage:x.loadingPage,error:x.error,pagination:x.pagination,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,showCustomDatePicker:m.showCustomDatePicker,tempCustomStartDate:m.tempCustomStartDate,tempCustomEndDate:m.tempCustomEndDate,filterCategory:n,filterSeverity:o,exporting:f.exportingActivity,onDateRangeChange:m.handleDateRangeChange,onShowCustomDatePickerChange:m.setShowCustomDatePicker,onStartDateChange:m.handleStartDateChange,onEndDateChange:m.handleEndDateChange,onApplyCustomDate:m.handleApplyCustomDate,onCancelCustomDate:m.handleCancelCustomDate,onCategoryChange:i,onSeverityChange:l,onClearFilters:S,onPageChange:x.fetchData,onExport:w,onViewRequest:j}),e.jsx(n2,{agingWorkflows:p.agingWorkflows,loading:p.loading,loadingPage:p.loadingPage,error:p.error,pagination:p.pagination,threshold:u.threshold,thresholdError:u.thresholdError,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,showCustomDatePicker:d.showCustomDatePicker,tempCustomStartDate:d.tempCustomStartDate,tempCustomEndDate:d.tempCustomEndDate,searchQuery:a,exporting:f.exportingAging,onThresholdChange:u.handleThresholdChange,onThresholdBlur:u.handleThresholdBlur,onDateRangeChange:d.handleDateRangeChange,onShowCustomDatePickerChange:d.setShowCustomDatePicker,onStartDateChange:d.handleStartDateChange,onEndDateChange:d.handleEndDateChange,onApplyCustomDate:d.handleApplyCustomDate,onCancelCustomDate:d.handleCancelCustomDate,onSearchChange:r,onPageChange:p.fetchData,onExport:N,onViewRequest:j})]})})}function v2({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(X,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(Se,{value:t,onValueChange:a,children:[e.jsx(Te,{id:"default-period",children:e.jsx(Ae,{})}),e.jsx(ke,{children:n.map(i=>e.jsx(H,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(me,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function b2({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(ss,{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(ss,{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(ss,{checked:a,onCheckedChange:i})]})]})}function bu({className:t,...s}){return e.jsx(Sh,{"data-slot":"checkbox",className:ce("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(Ah,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(fa,{className:"size-3.5"})})})}const j2=["CSV","Excel","PDF","JSON"];function N2({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(X,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:j2.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(bu,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(X,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function w2({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(me,{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 C2(){const[t,s]=g.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{Me.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(W,{children:[e.jsxs(Q,{children:[e.jsx(ee,{children:"Analytics & Reporting Configuration"}),e.jsx(le,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(v2,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(Nt,{}),e.jsx(b2,{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(Nt,{}),e.jsx(N2,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(w2,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const S2=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"}},A2=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function T2({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(lo,{children:[e.jsx(co,{children:e.jsxs(sa,{children:[e.jsx(nt,{children:"User"}),e.jsx(nt,{children:"Role"}),e.jsx(nt,{children:"Department"}),e.jsx(nt,{children:"Status"}),e.jsx(nt,{className:"text-right",children:"Actions"})]})}),e.jsx(mo,{children:t.length===0?e.jsx(sa,{children:e.jsx(at,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(sa,{className:"hover:bg-muted/50",children:[e.jsx(at,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(gt,{className:"size-10",children:e.jsx(ft,{className:"bg-re-green text-white",children:A2(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(at,{children:e.jsx(J,{className:S2(n.role),children:n.role})}),e.jsx(at,{children:n.department}),e.jsx(at,{children:e.jsxs(J,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Sn,{className:"w-3 h-3 mr-1"}),n.status]})}),e.jsx(at,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx(Wa,{className:"w-4 h-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(Sp,{className:"w-4 h-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(xi,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function k2({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 R2(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function P2(){const[t,s]=g.useState(""),[a,r]=g.useState([]),[n,i]=g.useState(!1),[o,l]=g.useState(null),[c,m]=g.useState("USER"),[d,u]=g.useState(!1),[h,x]=g.useState(!1),[p,f]=g.useState(null),[v,j]=g.useState([]),[y,w]=g.useState(!1),[N,S]=g.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[T,F]=g.useState("ELEVATED"),[R,M]=g.useState(1),[b,A]=g.useState(1),[P,B]=g.useState(0),E=10,L=g.useRef(null),C=g.useCallback(R2(async $=>{var G,ae,he;if(!$||$.length<2){r([]);return}i(!0);try{const _e=((G=(await Wt.searchUsers($,20)).data)==null?void 0:G.data)||[];r(_e)}catch(be){console.error("Search failed:",be),f({type:"error",text:((he=(ae=be.response)==null?void 0:ae.data)==null?void 0:he.message)||"Failed to search users"})}finally{i(!1)}},300),[]),k=$=>{const G=$.target.value;s(G),C(G)},D=async $=>{var G,ae;try{const he=v.find(Ue=>Ue.email.toLowerCase()===$.toLowerCase());if(he)return he.role;const Oe=(((ae=(G=(await Wt.getUsersByRole("ALL",1,1e3)).data)==null?void 0:G.data)==null?void 0:ae.users)||[]).find(Ue=>{var tt;return((tt=Ue.email)==null?void 0:tt.toLowerCase())===$.toLowerCase()});return Oe&&Oe.role?Oe.role:null}catch(he){return console.error("Failed to fetch user role:",he),null}},z=async $=>{l($),s($.email),r([]),x(!0);try{const G=await D($.email);m(G||"USER")}catch(G){console.error("Failed to fetch user role:",G),m("USER")}finally{x(!1)}},K=async()=>{var $,G;if(!o||!c){f({type:"error",text:"Please select a user and role"});return}u(!0),f(null);try{await Wt.assignRole(o.email,c),f({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),m("USER"),await Y(),await de(),Me.success("Role assigned successfully")}catch(ae){console.error("Role assignment failed:",ae);const he=((G=($=ae.response)==null?void 0:$.data)==null?void 0:G.error)||"Failed to assign role";f({type:"error",text:he}),Me.error(he)}finally{u(!1)}},Y=async($=R)=>{var G,ae,he,be,_e,Oe;w(!0);try{const Ue=await Wt.getUsersByRole(T,$,E),tt=((ae=(G=Ue.data)==null?void 0:G.data)==null?void 0:ae.users)||[],Be=(be=(he=Ue.data)==null?void 0:he.data)==null?void 0:be.pagination,kt=(Oe=(_e=Ue.data)==null?void 0:_e.data)==null?void 0:Oe.summary;j(tt.map(Le=>({userId:Le.userId,email:Le.email,displayName:Le.displayName||Le.email,role:Le.role||"USER",department:Le.department,designation:Le.designation,isActive:Le.isActive!==!1}))),Be&&(M(Be.currentPage),A(Be.totalPages),B(Be.totalUsers)),kt&&S(Le=>({...Le,admins:kt.ADMIN||0,management:kt.MANAGEMENT||0,users:kt.USER||0,total:(kt.ADMIN||0)+(kt.MANAGEMENT||0)+(kt.USER||0)}))}catch(Ue){console.error("Failed to fetch users:",Ue),Me.error("Failed to load users")}finally{w(!1)}},de=async()=>{var $,G,ae,he,be,_e;try{const Oe=await Wt.getRoleStatistics(),Ue=((G=($=Oe.data)==null?void 0:$.data)==null?void 0:G.statistics)||((ae=Oe.data)==null?void 0:ae.statistics)||[],tt={admins:parseInt(((he=Ue.find(Be=>Be.role==="ADMIN"))==null?void 0:he.count)||"0"),management:parseInt(((be=Ue.find(Be=>Be.role==="MANAGEMENT"))==null?void 0:be.count)||"0"),users:parseInt(((_e=Ue.find(Be=>Be.role==="USER"))==null?void 0:_e.count)||"0")};S(Be=>({...Be,...tt,total:tt.admins+tt.management+tt.users,active:Be.active||tt.admins+tt.management+tt.users,inactive:Be.inactive||0}))}catch(Oe){console.error("Failed to fetch statistics:",Oe)}};g.useEffect(()=>{Y(1),de()},[T]);const Z=$=>{F($),M(1)},je=$=>{Y($)},ve=async($,G)=>{var ae,he;try{await Wt.updateUserRole($,G),Me.success("User role updated successfully"),await Y(),await de()}catch(be){console.error("Failed to update user role:",be),Me.error(((he=(ae=be.response)==null?void 0:ae.data)==null?void 0:he.error)||"Failed to update user role")}},U=async $=>{v.find(ae=>ae.userId===$)&&Me.info("User status toggle functionality coming soon")},V=async $=>{const G=v.find(ae=>ae.userId===$);if(G){if(G.role==="ADMIN"){Me.error("Cannot delete admin user");return}Me.info("User deletion functionality coming soon")}};g.useEffect(()=>{const $=G=>{L.current&&!L.current.contains(G.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",$),()=>{document.removeEventListener("mousedown",$)}},[a]);const te={total:N.total,active:N.active,inactive:N.inactive,admins:N.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(k2,{stats:te}),e.jsxs(W,{children:[e.jsx(Q,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Assign User Role"}),e.jsx(le,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(I,{onClick:K,disabled:!o||d,className:"bg-re-green hover:bg-re-green/90",children:d?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ps,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(q,{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(ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(me,{type:"text",placeholder:"Type name or email address...",value:t,onChange:k,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx($e,{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 typing to search across all Okta users"}),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($=>e.jsxs("button",{onClick:()=>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:$.displayName||$.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:$.email}),$.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[$.department,$.designation?`${$.designation}`:""]})]},$.userId))})]})]}),o&&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:(o.displayName||o.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-gray-900",children:o.displayName||o.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o.email}),o.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[o.department,o.designation?`${o.designation}`:""]}),h&&e.jsxs("p",{className:"text-xs text-re-green mt-1 flex items-center gap-1",children:[e.jsx($e,{className:"w-3 h-3 animate-spin"}),"Checking current role..."]})]})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{l(null),s(""),m("USER"),x(!1)},children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Select Role"}),e.jsxs(Se,{value:c,onValueChange:$=>m($),disabled:h,children:[e.jsx(Te,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ae,{placeholder:h?"Loading current role...":"Select role"})}),e.jsxs(ke,{className:"rounded-lg",children:[e.jsx(H,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(H,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(H,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(na,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),p&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${p.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:[p.type==="success"?e.jsx(xe,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Re,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${p.type==="success"?"text-green-800":"text-red-800"}`,children:p.text})]})})]})]}),e.jsxs(W,{children:[e.jsx(Q,{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(ee,{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(le,{children:["View and manage user accounts and roles (",P," ",T!=="ALL"&&T!=="ELEVATED"?T.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Se,{value:T,onValueChange:Z,children:[e.jsx(Te,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ae,{placeholder:"Filter by role"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",N.admins+N.management,")"]})]})}),e.jsx(H,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(na,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",N.admins,")"]})]})}),e.jsx(H,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",N.management,")"]})]})}),e.jsx(H,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",N.users,")"]})]})}),e.jsx(H,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",N.admins+N.management+N.users,")"]})]})})]})]})})]})}),e.jsx(q,{className:"pt-6",children:y?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx($e,{className:"w-6 h-6 animate-spin text-re-green mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading users..."})]}):v.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(Xe,{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:T==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(T2,{users:v.map($=>({id:$.userId,name:$.displayName,email:$.email,role:$.role,department:$.department||"N/A",status:$.isActive?"active":"inactive"})),onEdit:$=>{const G=v.find(ae=>ae.userId===$);if(G){const ae=G.role==="USER"?"MANAGEMENT":G.role==="MANAGEMENT"?"ADMIN":"USER";ve($,ae)}},onToggleStatus:U,onDelete:V}),b>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 ",(R-1)*E+1," to ",Math.min(R*E,P)," of ",P," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>je(R-1),disabled:R===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,b)},($,G)=>{let ae;return b<=5||R<=3?ae=G+1:R>=b-2?ae=b-4+G:ae=R-2+G,e.jsx(I,{variant:R===ae?"default":"outline",size:"sm",onClick:()=>je(ae),className:`w-9 h-9 p-0 ${R===ae?"bg-re-green hover:bg-re-green/90":""}`,children:ae},ae)})}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>je(R+1),disabled:R===b,children:"Next"})]})]})]})})]})]})}function D2({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(Q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{className:"w-5 h-5 text-re-green"}),e.jsx(ee,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(le,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(q,{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(X,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(me,{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(Pe,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(me,{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(Pe,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function E2({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(Q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"w-5 h-5 text-re-green"}),e.jsx(ee,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(le,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(q,{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(X,{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(si,{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(Ft,{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(X,{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(si,{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 Ra=[{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 M2({workStartHour:t,workEndHour:s,workStartDay:a,workEndDay:r,onWorkStartHourChange:n,onWorkEndHourChange:i,onWorkStartDayChange:o,onWorkEndDayChange:l}){var c,m,d;return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(Q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-5 h-5 text-re-green"}),e.jsx(ee,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(le,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(q,{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(X,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(me,{id:"work-start-hour",type:"number",min:"0",max:"23",value:t,onChange:u=>n(parseInt(u.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(Pe,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(me,{id:"work-end-hour",type:"number",min:"0",max:"23",value:s,onChange:u=>i(parseInt(u.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(Pe,{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(X,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(Se,{value:a.toString(),onValueChange:u=>o(parseInt(u)),children:[e.jsx(Te,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ae,{placeholder:"Select start day"})}),e.jsx(ke,{children:Ra.map(u=>e.jsx(H,{value:u.value.toString(),children:u.label},u.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(X,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(Se,{value:r.toString(),onValueChange:u=>l(parseInt(u)),children:[e.jsx(Te,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ae,{placeholder:"Select end day"})}),e.jsx(ke,{children:Ra.map(u=>e.jsx(H,{value:u.value.toString(),children:u.label},u.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=Ra.find(u=>u.value===a))==null?void 0:c.label} only`:` ${(m=Ra.find(u=>u.value===a))==null?void 0:m.label} to ${(d=Ra.find(u=>u.value===r))==null?void 0:d.label}`]})})]})]})}function I2(){const[t,s]=g.useState(!0),[a,r]=g.useState(!1),[n,i]=g.useState({expressHours:24,standardHours:72,reminderThreshold1:50,reminderThreshold2:75,workStartHour:9,workEndHour:18,workStartDay:1,workEndDay:5});g.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const m=await Mr("TAT_SETTINGS"),d={};m.forEach(u=>{d[u.configKey]=u.configValue}),i({expressHours:parseInt(d.DEFAULT_TAT_EXPRESS_HOURS||"24"),standardHours:parseInt(d.DEFAULT_TAT_STANDARD_HOURS||"72"),reminderThreshold1:parseInt(d.TAT_REMINDER_THRESHOLD_1||"50"),reminderThreshold2:parseInt(d.TAT_REMINDER_THRESHOLD_2||"75"),workStartHour:parseInt(d.WORK_START_HOUR||"9"),workEndHour:parseInt(d.WORK_END_HOUR||"18"),workStartDay:parseInt(d.WORK_START_DAY||"1"),workEndDay:parseInt(d.WORK_END_DAY||"5")})}catch(m){console.error("Failed to load TAT configurations:",m),Me.error("Failed to load TAT configurations")}finally{s(!1)}},l=async()=>{var m,d;try{r(!0),await Promise.all([dt("DEFAULT_TAT_EXPRESS_HOURS",n.expressHours.toString()),dt("DEFAULT_TAT_STANDARD_HOURS",n.standardHours.toString()),dt("TAT_REMINDER_THRESHOLD_1",n.reminderThreshold1.toString()),dt("TAT_REMINDER_THRESHOLD_2",n.reminderThreshold2.toString()),dt("WORK_START_HOUR",n.workStartHour.toString()),dt("WORK_END_HOUR",n.workEndHour.toString()),dt("WORK_START_DAY",n.workStartDay.toString()),dt("WORK_END_DAY",n.workEndDay.toString())]),Me.success("TAT configuration saved successfully"),await o()}catch(u){console.error("Failed to save TAT configuration:",u),Me.error(((d=(m=u.response)==null?void 0:m.data)==null?void 0:d.error)||"Failed to save TAT configuration")}finally{r(!1)}},c=m=>{i(d=>({...d,...m}))};return t?e.jsx(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(q,{className:"p-12 text-center",children:[e.jsx($e,{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(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(Q,{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(ee,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(le,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(D2,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:m=>c({expressHours:m}),onStandardChange:m=>c({standardHours:m})}),e.jsx(Nt,{}),e.jsx(M2,{workStartHour:n.workStartHour,workEndHour:n.workEndHour,workStartDay:n.workStartDay,workEndDay:n.workEndDay,onWorkStartHourChange:m=>c({workStartHour:m}),onWorkEndHourChange:m=>c({workEndHour:m}),onWorkStartDayChange:m=>c({workStartDay:m}),onWorkEndDayChange:m=>c({workEndDay:m})}),e.jsx(Nt,{}),e.jsx(E2,{reminderThreshold1:n.reminderThreshold1,reminderThreshold2:n.reminderThreshold2,onReminderThreshold1Change:m=>c({reminderThreshold1:m}),onReminderThreshold2Change:m=>c({reminderThreshold2:m})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(I,{onClick:l,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($e,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function L2({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(ss,{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(ss,{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(ss,{checked:a,onCheckedChange:i})]})]})}function F2({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(X,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(Se,{value:t,onValueChange:a,children:[e.jsx(Te,{id:"notification-frequency",children:e.jsx(Ae,{placeholder:"Select frequency"})}),e.jsxs(ke,{children:[e.jsx(H,{value:"Immediate",children:"Immediate"}),e.jsx(H,{value:"Hourly",children:"Hourly"}),e.jsx(H,{value:"Daily",children:"Daily"}),e.jsx(H,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(me,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function _2({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(us,{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 O2(){const[t,s]=g.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=()=>{Me.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(W,{children:[e.jsxs(Q,{children:[e.jsx(ee,{children:"Notification Configuration"}),e.jsx(le,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(L2,{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(Nt,{}),e.jsx(F2,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(_2,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function $2({maxFileSizeMB:t,retentionDays:s,onMaxFileSizeChange:a,onRetentionDaysChange:r}){const n=Math.round(s/365*10)/10;return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(Q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pa,{className:"w-5 h-5 text-re-green"}),e.jsx(ee,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(le,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(q,{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(X,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(me,{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(pa,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(me,{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(hi,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const U2=[{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 V2({allowedFileTypes:t,onAllowedFileTypesChange:s}){const a=t.split(",").map(o=>o.trim().toLowerCase()),r=(o,l)=>{const c=new Set(a);l?o.forEach(m=>c.add(m)):o.forEach(m=>c.delete(m)),s(Array.from(c).join(","))},n=o=>o.some(l=>a.includes(l)),i=o=>{s(o)};return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(Q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ap,{className:"w-5 h-5 text-re-green"}),e.jsx(ee,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(le,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:U2.map(o=>{const l=n(o.extensions);return e.jsxs("div",{onClick:()=>r(o.extensions,!l),className:`flex items-center justify-between p-3 rounded-md border-2 cursor-pointer transition-all ${l?"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 ${l?"bg-re-green border-re-green":"bg-white border-gray-300"}`,children:l&&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 ${l?"text-re-green":"text-gray-600"}`,children:o.label})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:o.extensions.join(", ")})]},o.label)})}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(X,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(me,{id:"file-types-manual",type:"text",value:t,onChange:o=>i(o.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 B2(){const[t,s]=g.useState(!0),[a,r]=g.useState(!1),[n,i]=g.useState({maxFileSizeMB:10,retentionDays:365,allowedFileTypes:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"});g.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const m=await Mr("DOCUMENT_POLICY"),d={};m.forEach(u=>{d[u.configKey]=u.configValue}),i({maxFileSizeMB:parseInt(d.MAX_FILE_SIZE_MB||"10"),retentionDays:parseInt(d.DOCUMENT_RETENTION_DAYS||"365"),allowedFileTypes:d.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"})}catch(m){console.error("Failed to load document configurations:",m),Me.error("Failed to load document configurations")}finally{s(!1)}},l=async()=>{var m,d;try{r(!0),await Promise.all([dt("MAX_FILE_SIZE_MB",n.maxFileSizeMB.toString()),dt("DOCUMENT_RETENTION_DAYS",n.retentionDays.toString()),dt("ALLOWED_FILE_TYPES",n.allowedFileTypes)]),Me.success("Document policy saved successfully"),await o()}catch(u){console.error("Failed to save document configuration:",u),Me.error(((d=(m=u.response)==null?void 0:m.data)==null?void 0:d.error)||"Failed to save document configuration")}finally{r(!1)}},c=m=>{i(d=>({...d,...m}))};return t?e.jsx(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(q,{className:"p-12 text-center",children:[e.jsx($e,{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(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(Q,{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(we,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(le,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(q,{className:"space-y-6",children:[e.jsx($2,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:m=>c({maxFileSizeMB:m}),onRetentionDaysChange:m=>c({retentionDays:m})}),e.jsx(Nt,{}),e.jsx(V2,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:m=>c({allowedFileTypes:m})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(I,{onClick:l,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($e,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function z2(){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 H2=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],W2=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 q2({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(J,{className:W2(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:H2.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(bu,{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 K2(){const[t,s]=g.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=()=>{Me.success("Dashboard layout saved successfully")},r=(i,o,l)=>{s(c=>({...c,[i]:{...c[i],[o]:l}}))},n=["Initiator","Approver","Spectator"];return e.jsxs(W,{children:[e.jsxs(Q,{children:[e.jsx(ee,{children:"Dashboard Layout Configuration"}),e.jsx(le,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsx(z2,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(q2,{role:i,kpis:t[i]||{},onKPIToggle:(o,l)=>r(i,o,l)},i))}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}const G2=[{value:"claude",label:"Claude (Anthropic)",description:"Advanced AI by Anthropic"},{value:"openai",label:"OpenAI (GPT-4)",description:"GPT-4 by OpenAI"},{value:"gemini",label:"Gemini (Google)",description:"Gemini by Google"}];function Y2({aiEnabled:t,aiProvider:s,claudeApiKey:a,openaiApiKey:r,geminiApiKey:n,showApiKeys:i,onAiEnabledChange:o,onProviderChange:l,onClaudeApiKeyChange:c,onOpenaiApiKeyChange:m,onGeminiApiKeyChange:d,onToggleApiKeyVisibility:u,maskApiKey:h}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(Q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zc,{className:"w-5 h-5 text-re-green"}),e.jsx(ee,{className:"text-base font-semibold",children:"AI Provider & API Keys"})]}),e.jsx(le,{className:"text-sm",children:"Select your AI provider and configure API keys"})]}),e.jsxs(q,{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(ss,{checked:t,onCheckedChange:o})]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"ai-provider",className:"text-sm font-medium",children:"AI Provider"}),e.jsxs(Se,{value:s,onValueChange:x=>l(x),children:[e.jsx(Te,{id:"ai-provider",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ae,{placeholder:"Select AI provider"})}),e.jsx(ke,{children:G2.map(x=>e.jsx(H,{value:x.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"-"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.description})]})},x.value))})]})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs(X,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Tp,{className:"w-4 h-4"}),"API Keys"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"claude-key",className:"text-xs text-muted-foreground",children:"Claude API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(me,{id:"claude-key",type:i.claude?"text":"password",value:a,onChange:x=>c(x.target.value),placeholder:i.claude?"sk-ant-...":h(a)||"sk-ant-...",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20 font-mono text-sm"}),e.jsx(I,{type:"button",variant:"outline",size:"icon",onClick:()=>u("claude"),className:"border-gray-200",children:i.claude?e.jsx(qr,{className:"w-4 h-4"}):e.jsx(Tt,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Get your API key from console.anthropic.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"openai-key",className:"text-xs text-muted-foreground",children:"OpenAI API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(me,{id:"openai-key",type:i.openai?"text":"password",value:r,onChange:x=>m(x.target.value),placeholder:i.openai?"sk-...":h(r)||"sk-...",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20 font-mono text-sm"}),e.jsx(I,{type:"button",variant:"outline",size:"icon",onClick:()=>u("openai"),className:"border-gray-200",children:i.openai?e.jsx(qr,{className:"w-4 h-4"}):e.jsx(Tt,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Get your API key from platform.openai.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"gemini-key",className:"text-xs text-muted-foreground",children:"Gemini API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(me,{id:"gemini-key",type:i.gemini?"text":"password",value:n,onChange:x=>d(x.target.value),placeholder:i.gemini?"AIza...":h(n)||"AIza...",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20 font-mono text-sm"}),e.jsx(I,{type:"button",variant:"outline",size:"icon",onClick:()=>u("gemini"),className:"border-gray-200",children:i.gemini?e.jsx(qr,{className:"w-4 h-4"}):e.jsx(Tt,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Get your API key from ai.google.dev"})]})]})]})]})]})}function Z2({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(Q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"w-5 h-5 text-re-green"}),e.jsx(ee,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(le,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(q,{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(ss,{checked:t,onCheckedChange:s})]})})})]})}function X2({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(Q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bc,{className:"w-5 h-5 text-re-green"}),e.jsx(ee,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(le,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(q,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Characters"}),e.jsx(me,{id:"max-remark-chars",type:"number",min:"100",max:"2000",value:t,onChange:a=>s(parseInt(a.target.value)||500),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 limit for AI-generated conclusion remarks (100-2000 characters)"})]})})]})}function J2(){const[t,s]=g.useState(!0),[a,r]=g.useState(!1),[n,i]=g.useState({claude:!1,openai:!1,gemini:!1}),[o,l]=g.useState({aiEnabled:!0,aiProvider:"claude",claudeApiKey:"",openaiApiKey:"",geminiApiKey:"",aiRemarkGeneration:!0,maxRemarkChars:500});g.useEffect(()=>{c()},[]);const c=async()=>{try{s(!0);const x=await Mr("AI_CONFIGURATION"),p={};x.forEach(f=>{p[f.configKey]=f.configValue}),l({aiEnabled:p.AI_ENABLED==="true",aiProvider:p.AI_PROVIDER||"claude",claudeApiKey:p.CLAUDE_API_KEY||"",openaiApiKey:p.OPENAI_API_KEY||"",geminiApiKey:p.GEMINI_API_KEY||"",aiRemarkGeneration:p.AI_REMARK_GENERATION_ENABLED==="true",maxRemarkChars:parseInt(p.AI_REMARK_MAX_CHARACTERS||"500")})}catch(x){console.error("Failed to load AI configurations:",x),Me.error("Failed to load AI configurations")}finally{s(!1)}},m=async()=>{var x,p;try{r(!0),await Promise.all([dt("AI_ENABLED",o.aiEnabled.toString()),dt("AI_PROVIDER",o.aiProvider),dt("CLAUDE_API_KEY",o.claudeApiKey),dt("OPENAI_API_KEY",o.openaiApiKey),dt("GEMINI_API_KEY",o.geminiApiKey),dt("AI_REMARK_GENERATION_ENABLED",o.aiRemarkGeneration.toString()),dt("AI_REMARK_MAX_CHARACTERS",o.maxRemarkChars.toString())]),Me.success("AI configuration saved successfully"),await c()}catch(f){console.error("Failed to save AI configuration:",f),Me.error(((p=(x=f.response)==null?void 0:x.data)==null?void 0:p.error)||"Failed to save AI configuration")}finally{r(!1)}},d=x=>{l(p=>({...p,...x}))},u=x=>{i(p=>({...p,[x]:!p[x]}))},h=x=>!x||x.length===0?"":x.length<=8?"••••••••":x.substring(0,4)+"••••••••"+x.substring(x.length-4);return t?e.jsx(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(q,{className:"p-12 text-center",children:[e.jsx($e,{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(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(Q,{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(Ar,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(le,{className:"text-sm text-gray-600",children:"Configure AI provider, API keys, and enable/disable AI-powered features"})]})]})}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(Y2,{aiEnabled:o.aiEnabled,aiProvider:o.aiProvider,claudeApiKey:o.claudeApiKey,openaiApiKey:o.openaiApiKey,geminiApiKey:o.geminiApiKey,showApiKeys:n,onAiEnabledChange:x=>d({aiEnabled:x}),onProviderChange:x=>d({aiProvider:x}),onClaudeApiKeyChange:x=>d({claudeApiKey:x}),onOpenaiApiKeyChange:x=>d({openaiApiKey:x}),onGeminiApiKeyChange:x=>d({geminiApiKey:x}),onToggleApiKeyVisibility:u,maskApiKey:h}),e.jsx(Nt,{}),e.jsx(Z2,{aiRemarkGeneration:o.aiRemarkGeneration,onRemarkGenerationChange:x=>d({aiRemarkGeneration:x})}),e.jsx(Nt,{}),e.jsx(X2,{maxRemarkChars:o.maxRemarkChars,onMaxRemarkCharsChange:x=>d({maxRemarkChars:x})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(I,{onClick:m,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($e,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const mc=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function Q2({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(X,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(Se,{value:t,onValueChange:a,children:[e.jsx(Te,{id:"spectator-permission",children:e.jsx(Ae,{placeholder:"Select permission"})}),e.jsx(ke,{children:mc.map(n=>e.jsx(H,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(Se,{value:s,onValueChange:r,children:[e.jsx(Te,{id:"link-sharing-permission",children:e.jsx(Ae,{placeholder:"Select permission"})}),e.jsx(ke,{children:mc.map(n=>e.jsx(H,{value:n,children:n},n))})]})]})]})}function eC({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(ss,{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(ss,{checked:s,onCheckedChange:r})]})]})}function tC(){const[t,s]=g.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{Me.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(W,{children:[e.jsxs(Q,{children:[e.jsx(ee,{children:"Workflow Sharing Policy"}),e.jsx(le,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(Q2,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(Nt,{}),e.jsx(eC,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function sC(){const{user:t}=Zt(),[s,a]=g.useState(""),[r,n]=g.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"}]}],o=i.map(m=>({...m,kpis:m.kpis.filter(d=>d.title.toLowerCase().includes(s.toLowerCase())||d.description.toLowerCase().includes(s.toLowerCase())||d.category.toLowerCase().includes(s.toLowerCase()))})).filter(m=>m.kpis.length>0),l=i.reduce((m,d)=>m+d.count,0),c=m=>{switch(m){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 items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-re-black flex items-center gap-2",children:[e.jsx(At,{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(J,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]}),e.jsx(Nt,{}),e.jsxs(Dr,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(Er,{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(lt,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(Uc,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(lt,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Ms,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(lt,{value:"users",className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(lt,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(lt,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(lt,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(we,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(lt,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(kp,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(lt,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(zc,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(lt,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(Vc,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(ct,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(W,{children:[e.jsx(Q,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"KPI Configuration"}),e.jsx(le,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(J,{className:"bg-blue-50 text-blue-700",children:[l," / ",l," KPIs Active"]})]})}),e.jsxs(q,{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(ns,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(me,{placeholder:"Search KPIs by name, description, or category...",value:s,onChange:m=>a(m.target.value),className:"pl-10"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:i.map(m=>e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:m.name}),e.jsx("p",{className:"text-2xl font-semibold",children:m.count})]},m.name))}),o.map(m=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:m.name}),e.jsxs(J,{variant:"outline",className:"ml-auto",children:[m.kpis.length," Active"]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:m.kpis.map(d=>e.jsx("div",{className:`p-4 border rounded-lg ${d.bgColor} ${d.borderColor} transition-all hover:shadow-md ${d.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:d.title}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:d.description})]}),e.jsx(J,{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:d.value}),d.unit&&e.jsx("span",{className:"text-lg text-muted-foreground",children:d.unit})]})}),d.change!==void 0&&e.jsxs("div",{className:`flex items-center gap-1 text-xs px-2 py-1 rounded ${d.changeType==="up"?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:[d.changeType==="up"?e.jsx(Rp,{className:"w-3 h-3"}):e.jsx(Pp,{className:"w-3 h-3"}),e.jsxs("span",{className:"font-semibold",children:[Math.abs(d.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:"}),d.visibleTo.map(u=>e.jsx(J,{className:`${c(u)} text-xs px-1.5 py-0`,children:u},u))]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Period: ",d.period]}),d.thresholdBreached&&e.jsxs("div",{className:"flex items-center gap-1 text-orange-600",children:[e.jsx(Re,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},d.id))})]},m.name))]})]})}),e.jsx(ct,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(C2,{})}),e.jsx(ct,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(P2,{})}),e.jsx(ct,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(I2,{})}),e.jsx(ct,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(O2,{})}),e.jsx(ct,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(B2,{})}),e.jsx(ct,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(K2,{})}),e.jsx(ct,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(J2,{})}),e.jsx(ct,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(tC,{})})]})]})}function aC({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[o,l]=g.useState(""),[c,m]=g.useState(!1),d=async()=>{if(!(!o.trim()||o.length>500)){m(!0);try{await i(a,o.trim()),l(""),s()}catch(f){console.error("Error submitting approval action:",f)}finally{m(!1)}}},u=()=>{l(""),s()},x=a==="approve"?{title:"Approve Request",description:"Please provide your approval comments and remarks",icon:xe,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:et,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..."},p=x.icon;return e.jsx(ut,{open:t,onOpenChange:u,children:e.jsxs(it,{className:"max-w-2xl bg-white",children:[e.jsxs(ht,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:`p-2 rounded-lg ${a==="approve"?"bg-green-100":"bg-red-100"}`,children:e.jsx(p,{className:`w-6 h-6 ${x.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ot,{className:"text-xl",children:x.title}),e.jsx(Xt,{className:"mt-1",children:x.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(J,{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(J,{className:x.badgeColor,variant:"outline",children:[e.jsx(p,{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(X,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(us,{id:"comment",placeholder:x.placeholder,value:o,onChange:f=>l(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:[o.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(xe,{className:"w-4 h-4 text-green-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium text-green-800",children:"Approval Confirmation"}),e.jsx("p",{className:"text-green-700 mt-1",children:"This request will be forwarded to the next approver or completed if this is the final step."})]})]})})]}),e.jsxs(Et,{className:"gap-2",children:[e.jsx(I,{variant:"outline",onClick:u,disabled:c,children:"Cancel"}),e.jsx(I,{onClick:d,disabled:!o.trim()||c||o.length>500,className:x.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(p,{className:"w-4 h-4 mr-2"}),a==="approve"?"Approve Request":"Reject Request"]})})]})]})})}var rC=(t,s,a,r,n,i,o,l)=>{let c=document.documentElement,m=["light","dark"];function d(x){(Array.isArray(t)?t:[t]).forEach(p=>{let f=p==="class",v=f&&i?n.map(j=>i[j]||j):n;f?(c.classList.remove(...v),c.classList.add(i&&i[x]?i[x]:x)):c.setAttribute(p,x)}),u(x)}function u(x){l&&m.includes(x)&&(c.style.colorScheme=x)}function h(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)d(r);else try{let x=localStorage.getItem(s)||a,p=o&&x==="system"?h():x;d(p)}catch{}},nC=g.createContext(void 0),iC={setTheme:t=>{},themes:[]},oC=()=>{var t;return(t=g.useContext(nC))!=null?t:iC};g.memo(({forcedTheme:t,storageKey:s,attribute:a,enableSystem:r,enableColorScheme:n,defaultTheme:i,value:o,themes:l,nonce:c,scriptProps:m})=>{let d=JSON.stringify([a,s,i,t,l,o,r,n]).slice(1,-1);return g.createElement("script",{...m,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${rC.toString()})(${d})`}})});const lC=({...t})=>{const{theme:s="system"}=oC();return e.jsx(Dp,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function cC({onLogout:t}){const s=ya(),[a,r]=g.useState(null),[n,i]=g.useState([]),[o,l]=g.useState(""),[c,m]=g.useState("");g.useEffect(()=>{const y=localStorage.getItem("dynamicRequests");if(y)try{const w=JSON.parse(y);i(w)}catch(w){console.error("Error parsing dynamic requests:",w)}},[]),g.useEffect(()=>{n.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(n))},[n]);const d=y=>{if(y==="profile"){s("/profile");return}if(y==="settings"){s("/settings");return}y.startsWith("/")?s(y):s(`/${y}`)},u=async(y,w,N)=>{l(y),m(w||"Unknown Request");const S=(N==null?void 0:N.toLowerCase())==="draft"||N==="DRAFT";s(S?`/edit-request/${y}`:`/request/${y}`)},h=()=>{s(-1)},x=()=>{s("/new-request")},p=y=>{var S,T,F,R,M,b,A,P,B,E,L;if(y.templateType){y.templateType==="claim-management"&&s("/claim-management");return}const w=`RE-REQ-2024-${String(Object.keys(dd).length+n.length+1).padStart(3,"0")}`,N={id:w,title:y.title,description:y.description||"",category:y.category||"General",subcategory:y.subcategory||"",status:"pending",priority:y.priority||"standard",amount:y.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:((S=y.approvers)==null?void 0:S.length)||1,currentApprover:((F=(T=y.approvers)==null?void 0:T[0])==null?void 0:F.name)||((b=(M=(R=y.approvers)==null?void 0:R[0])==null?void 0:M.email)==null?void 0:b.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((A=y.approvers)==null?void 0:A.length)||1}`,template:"custom",initiator:{name:"Current User",role:y.initiatorRole||"Employee",department:y.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:y.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:(y.approvers||[]).filter(C=>C).map((C,k)=>{var K;const D=(C==null?void 0:C.name)||((K=C==null?void 0:C.email)==null?void 0:K.split("@")[0])||`Approver ${k+1}`,z=(C==null?void 0:C.email)||"";return{step:k+1,approver:`${D}${z?` (${z})`:""}`,role:(C==null?void 0:C.role)||`Level ${(C==null?void 0:C.level)||k+1} Approver`,status:k===0?"pending":"waiting",tatHours:C!=null&&C.tat?typeof C.tat=="string"?parseInt(C.tat):C.tat:48,elapsedHours:0,assignedAt:k===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(y.spectators||[]).filter(C=>C&&(C.name||C.email)).map(C=>{var D;const k=(C==null?void 0:C.name)||((D=C==null?void 0:C.email)==null?void 0:D.split("@")[0])||"Observer";return{name:k,role:(C==null?void 0:C.role)||(C==null?void 0:C.department)||"Observer",avatar:k.split(" ").map(z=>z[0]).join("").toUpperCase().slice(0,2)||"OB"}}),auditTrail:[{type:"created",action:"Request Created",details:`Custom request "${y.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 ${((B=(P=y.approvers)==null?void 0:P[0])==null?void 0:B.name)||((L=(E=y.approvers)==null?void 0:E[0])==null?void 0:L.email)||"first approver"}`,user:"System",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}],tags:y.tags||["custom-request"]};i([...n,N]),s("/my-requests"),Me.success("Request Submitted Successfully!",{description:`Your request "${y.title}" (${w}) has been created and sent for approval.`,duration:5e3})},f=(y,w)=>new Promise(N=>{setTimeout(()=>{y==="approve"?Me.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):Me.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),r(null),N(!0)},1e3)}),v=()=>{r(null)},j=y=>{var S;const N={id:`RE-REQ-2024-CM-${String(n.length+2).padStart(3,"0")}`,title:`${y.activityName} - Claim Request`,description:y.requestDescription,category:"Dealer Operations",subcategory:"Claim Management",status:"pending",priority:"standard",amount:"TBD",slaProgress:0,slaRemaining:"7 days",slaEndDate:new Date(Date.now()+7*24*60*60*1e3).toISOString(),currentStep:1,totalSteps:8,templateType:"claim-management",templateName:"Claim Management",initiator:{name:"Current User",role:"Regional Marketing Coordinator",department:"Marketing",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:"Marketing",createdAt:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),updatedAt:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),dueDate:new Date(Date.now()+7*24*60*60*1e3).toISOString(),conclusionRemark:"",claimDetails:{activityName:y.activityName,activityType:y.activityType,activityDate:y.activityDate?new Date(y.activityDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"",location:y.location,dealerCode:y.dealerCode,dealerName:y.dealerName,dealerEmail:y.dealerEmail||"N/A",dealerPhone:y.dealerPhone||"N/A",dealerAddress:y.dealerAddress||"N/A",requestDescription:y.requestDescription,estimatedBudget:y.estimatedBudget||"TBD",periodStart:y.periodStartDate?new Date(y.periodStartDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"",periodEnd:y.periodEndDate?new Date(y.periodEndDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):""},approvalFlow:y.workflowSteps||[{step:1,approver:`${y.dealerName} (Dealer)`,role:"Dealer - Document Upload",status:"pending",tatHours:72,elapsedHours:0,assignedAt:new Date().toISOString(),comment:null,timestamp:null,description:"Dealer uploads proposal document, cost breakup, timeline for closure, and other supporting documents"},{step:2,approver:"Current User (Initiator)",role:"Initiator Evaluation",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator reviews dealer documents and approves or requests modifications"},{step:3,approver:"System Auto-Process",role:"IO Confirmation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Automatic IO (Internal Order) confirmation generated upon initiator approval"},{step:4,approver:"Rajesh Kumar",role:"Department Lead Approval",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Department head approves and blocks budget in IO for this activity"},{step:5,approver:`${y.dealerName} (Dealer)`,role:"Dealer - Completion Documents",status:"waiting",tatHours:120,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Dealer submits activity completion documents and description"},{step:6,approver:"Current User (Initiator)",role:"Initiator Verification",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator verifies completion documents and can modify approved amount"},{step:7,approver:"System Auto-Process",role:"E-Invoice Generation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Auto-generate e-invoice based on final approved amount"},{step:8,approver:"Finance Team",role:"Credit Note Issuance",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Finance team issues credit note to dealer"}],documents:[],spectators:[],auditTrail:[{type:"created",action:"Request Created",details:`Claim request for ${y.activityName} created`,user:"Current User",timestamp:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}],tags:["claim-management","new-request",(S=y.activityType)==null?void 0:S.toLowerCase().replace(/\s+/g,"-")]};i(T=>[...T,N]),Me.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),s("/my-requests")};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(Ip,{children:[e.jsx(pt,{path:"/login/callback",element:e.jsx(Jc,{})}),e.jsx(pt,{path:"/",element:e.jsx(It,{currentPage:"dashboard",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(Eo,{onNavigate:d,onNewRequest:x})})}),e.jsx(pt,{path:"/dashboard",element:e.jsx(It,{currentPage:"dashboard",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(Eo,{onNavigate:d,onNewRequest:x})})}),e.jsx(pt,{path:"/open-requests",element:e.jsx(It,{currentPage:"open-requests",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(Bg,{onViewRequest:u})})}),e.jsx(pt,{path:"/closed-requests",element:e.jsx(It,{currentPage:"closed-requests",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(sf,{onViewRequest:u})})}),e.jsx(pt,{path:"/my-requests",element:e.jsx(It,{currentPage:"my-requests",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(i1,{onViewRequest:u,dynamicRequests:n})})}),e.jsx(pt,{path:"/requests",element:e.jsx(It,{currentPage:"requests",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(C1,{onViewRequest:u})})}),e.jsx(pt,{path:"/approver-performance",element:e.jsx(It,{currentPage:"approver-performance",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx($1,{})})}),e.jsx(pt,{path:"/request/:requestId",element:e.jsx(It,{currentPage:"request-detail",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(Yf,{requestId:"",onBack:h,dynamicRequests:n})})}),e.jsx(pt,{path:"/work-notes/:requestId",element:e.jsx(Zf,{})}),e.jsx(pt,{path:"/new-request",element:e.jsx(rc,{onBack:h,onSubmit:p})}),e.jsx(pt,{path:"/edit-request/:requestId",element:e.jsx(rc,{onBack:h,onSubmit:p,requestId:void 0,isEditMode:!0})}),e.jsx(pt,{path:"/claim-management",element:e.jsx(Yw,{onBack:h,onSubmit:j})}),e.jsx(pt,{path:"/profile",element:e.jsx(It,{currentPage:"profile",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(U1,{})})}),e.jsx(pt,{path:"/settings",element:e.jsx(It,{currentPage:"settings",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(J1,{})})}),e.jsx(pt,{path:"/notifications",element:e.jsx(It,{currentPage:"notifications",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(Q1,{onNavigate:d})})}),e.jsx(pt,{path:"/detailed-reports",element:e.jsx(It,{currentPage:"detailed-reports",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(y2,{})})}),e.jsx(pt,{path:"/admin",element:e.jsx(It,{currentPage:"admin",onNavigate:d,onNewRequest:x,onLogout:t,children:e.jsx(sC,{})})})]}),e.jsx(lC,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),a&&e.jsx(aC,{isOpen:!!a,onClose:v,action:a,requestId:o,requestTitle:c,onSubmit:f})]})}function dC(t){const{onLogout:s}=t||{};return e.jsx(Mp,{children:e.jsx(cC,{onLogout:s})})}function mC(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=Zt(),[i,o]=g.useState(!1),l=typeof window<"u"&&window.location.pathname==="/login/callback",c=async()=>{try{if(!n){console.error("🔵 ERROR: logout function is undefined!");return}await n()}catch(m){console.error("🔵 Logout error in handleLogout:",m);try{localStorage.clear(),sessionStorage.clear(),window.location.href="/"}catch(d){console.error("🔵 Error during emergency cleanup:",d)}}};return g.useEffect(()=>{},[t,s,a,r]),l?e.jsx(Jc,{}):s?e.jsx("div",{className:"flex items-center justify-center min-h-screen bg-gradient-to-br from-slate-50 to-slate-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-slate-900 border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading authentication..."})]})}):a?(console.error("Authentication Error:",a),e.jsx("div",{className:"flex items-center justify-center min-h-screen bg-gradient-to-br from-slate-50 to-slate-100",children:e.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 px-6 py-4 rounded-lg max-w-md",children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Authentication Error"}),e.jsx("p",{className:"text-sm mb-4",children:a.message}),e.jsx("button",{onClick:()=>window.location.reload(),className:"bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700",children:"Retry"})]})})):t?e.jsxs(e.Fragment,{children:[e.jsx(dC,{onLogout:c}),i&&e.jsx(Ax,{isOpen:i,onClose:()=>o(!1)})]}):e.jsx(Cx,{})}Rn.createRoot(document.getElementById("root")).render(e.jsx(Mh.StrictMode,{children:e.jsx(Wp,{children:e.jsx(mC,{})})}));export{oe as a};
//# sourceMappingURL=index-DRwsycIY.js.map