Re_Backend/build/assets/index-BY7hqx1l.js

56 lines
925 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-DY1a2we-.js","assets/radix-vendor-BP4rDxsU.js","assets/charts-vendor-Cji9-Yri.js","assets/utils-vendor-DHm03ykU.js","assets/ui-vendor-CHsmPIhP.js","assets/socket-vendor-TjCxX7sJ.js","assets/router-vendor-1fSSvDCY.js"])))=>i.map(i=>d[i]);
var Eu=Object.defineProperty;var Mu=(t,s,a)=>s in t?Eu(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Wr=(t,s,a)=>Mu(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as fc,R as yc,I as vc,F as bc,a as Iu,T as Fu,P as Lu,C as _u,b as Ou,O as jc,c as Nc,d as $u,e as Uu,f as Vu,D as Bu,g as zu,A as Hu,h as qu,i as Wu,k as Ku,V as Gu,l as Yu,m as Zu,n as Xu,o as Ju,p as Qu,q as eh,r as th,s as sh,t as ah,u as rh,v as nh,w as ih,x as oh,y as lh,z as ch,B as dh,E as mh,L as uh,G as hh,H as ph,J as wc,K as Cc,M as xh,N as Sc,Q as Ac,U as gh,W as fh,X as yh,Y as vh,Z as bh,_ as jh,$ as Nh,a0 as wh,a1 as Ch,a2 as Sh,a3 as Ah,a4 as Th,a5 as kh,a6 as Rh,a7 as Dh,a8 as Ph,a9 as Eh,aa as Mh,ab as Ih}from"./radix-vendor-BP4rDxsU.js";import{a as Fh,r as x,c as Tc,d as oi,B as Lh,C as kc,X as Rc,Y as Dc,T as li,L as Pc,e as Kr,P as _h,f as Oh,g as $h,h as Uh,i as yo,j as ci,k as di,b as Vh}from"./charts-vendor-Cji9-Yri.js";import{a as Ec,f as Mc,b as xe,d as Bh,c as zh,e as Hh,s as zt,g as mi,h as vo,i as qh,j as ls,k as _a,l as ui,m as Ic,n as Ft,o as Vt,p as Gr,q as fs,r as Wh,t as Tn,u as Kh,v as kn,w as Gh,x as Yh,y as Zh,z as Xh,A as Yr,B as bo,C as Jh,D as Fc,E as Lc,F as hi,G as pi,H as Qh,I as ep,J as _c}from"./utils-vendor-DHm03ykU.js";import{S as kt,L as tp,C as Pe,a as Rn,b as $e,X as dt,H as sp,c as ap,U as rt,F as Te,d as ye,e as Nr,P as Es,f as rp,g as np,B as Lt,h as ra,i as Zr,Z as wr,A as Ht,j as Oc,k as ya,l as ip,m as qa,n as Be,R as Et,I as Cr,T as et,o as Re,p as ns,q as op,r as gt,s as as,M as js,t as Sr,u as lp,D as ts,v as Je,w as qt,x as $c,y as Uc,z as Ze,E as ke,G as Ar,J as Dn,O as Pn,K as Ms,N as Vc,Q as Bc,V as jo,W as er,Y as cp,_ as dp,$ as Ls,a0 as bt,a1 as xa,a2 as mp,a3 as up,a4 as hp,a5 as xi,a6 as Tr,a7 as pp,a8 as xp,a9 as gp,aa as fp,ab as yp,ac as vp,ad as ir,ae as kr,af as En,ag as bp,ah as zc,ai as jp,aj as Np,ak as wp,al as gi,am as Hc,an as Cp,ao as Sp,ap as Rr,aq as Dr,ar as fi,as as Ap,at as qc,au as No,av as Tp,aw as _s,ax as kp,ay as Rp,az as yi,aA as ia,aB as Dp,aC as Wc,aD as wo,aE as Pp,aF as Ep,aG as Mp,aH as Ip,aI as Kc,aJ as Fp,aK as Lp,aL as _p,aM as Op,aN as $p}from"./ui-vendor-CHsmPIhP.js";import{l as Up}from"./socket-vendor-TjCxX7sJ.js";import{u as Pr,a as Wa,b as Os,B as Vp,R as Bp,c as ot}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 Mn={},Co=Fh;Mn.createRoot=Co.createRoot,Mn.hydrateRoot=Co.hydrateRoot;var In=function(t,s){return In=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])},In(t,s)};function zp(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");In(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var hr=function(){return hr=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},hr.apply(this,arguments)};var Ws=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function vi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function bi(t,s){return t(s={exports:{}},s.exports),s.exports}var Bs=bi(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()}});vi(Bs);var Hp=vi(bi(function(t,s){var a=Ws&&Ws.__awaiter||function(d,u,h,g){return new(h||(h=Promise))(function(p,f){function v(N){try{y(g.next(N))}catch(b){f(b)}}function j(N){try{y(g.throw(N))}catch(b){f(b)}}function y(N){N.done?p(N.value):new h(function(b){b(N.value)}).then(v,j)}y((g=g.apply(d,u||[])).next())})},r=Ws&&Ws.__generator||function(d,u){var h,g,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(N){return function(b){if(h)throw new TypeError("Generator is already executing.");for(;v;)try{if(h=1,g&&(p=2&b[0]?g.return:b[0]?g.throw||((p=g.return)&&p.call(g),0):g.next)&&!(p=p.call(g,b[1])).done)return p;switch(g=0,p&&(b=[2&b[0],p.value]),b[0]){case 0:case 1:p=b;break;case 4:return v.label++,{value:b[1],done:!1};case 5:v.label++,g=b[1],b=[0];continue;case 7:b=v.ops.pop(),v.trys.pop();continue;default:if(p=v.trys,!((p=p.length>0&&p[p.length-1])||b[0]!==6&&b[0]!==2)){v=0;continue}if(b[0]===3&&(!p||b[1]>p[0]&&b[1]<p[3])){v.label=b[1];break}if(b[0]===6&&v.label<p[1]){v.label=p[1],p=b;break}if(p&&v.label<p[2]){v.label=p[2],v.ops.push(b);break}p[2]&&v.ops.pop(),v.trys.pop();continue}b=u.call(d,v)}catch(C){b=[6,C],g=0}finally{h=p=0}if(5&b[0])throw b[1];return{value:b[0]?b[1]:void 0,done:!0}}([y,N])}}},n=Ws;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="",g=0;g<d;g++)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 g,p,f,v,j,y,N;return r(this,function(b){switch(b.label){case 0:g=Date.now()+c(4),p=Date.now()+h,f=i+"-"+u,v=this.storageHandler===void 0?o:this.storageHandler,b.label=1;case 1:return Date.now()<p?[4,l(30)]:[3,8];case 2:return b.sent(),v.getItemSync(f)!==null?[3,5]:(j=this.id+"-"+u+"-"+g,[4,l(Math.floor(25*Math.random()))]);case 3:return b.sent(),v.setItemSync(f,JSON.stringify({id:this.id,iat:g,timeoutKey:j,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,l(30)];case 4:return b.sent(),(y=v.getItemSync(f))!==null&&(N=JSON.parse(y)).id===this.id&&N.iat===g?(this.acquiredIatSet.add(g),this.refreshLockWhileAcquired(f,g),[2,!0]):[3,7];case 5:return d.lockCorrector(this.storageHandler===void 0?o:this.storageHandler),[4,this.waitForSomethingToChange(p)];case 6:b.sent(),b.label=7;case 7:return g=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 g=this;return r(this,function(p){return setTimeout(function(){return a(g,void 0,void 0,function(){var f,v,j;return r(this,function(y){switch(y.label){case 0:return[4,Bs.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?(Bs.default().unlock(h),[2]):((j=JSON.parse(v)).timeRefreshed=Date.now(),f.setItemSync(u,JSON.stringify(j)),Bs.default().unlock(h),this.refreshLockWhileAcquired(u,h),[2])):(Bs.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(g){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 N=50-(Date.now()-f);N>0?setTimeout(g,N):g(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,g,p,f;return r(this,function(v){switch(v.label){case 0:return h=this.storageHandler===void 0?o:this.storageHandler,g=i+"-"+u,(p=h.getItemSync(g))===null?[2]:(f=JSON.parse(p)).id!==this.id?[3,2]:[4,Bs.default().lock(f.iat)];case 1:v.sent(),this.acquiredIatSet.delete(f.iat),h.removeItemSync(g),Bs.default().unlock(f.iat),d.notifyWaiters(),v.label=2;case 2:return[2]}})})},d.lockCorrector=function(u){for(var h=Date.now()-5e3,g=u,p=[],f=0;;){var v=g.keySync(f);if(v===null)break;p.push(v),f++}for(var j=!1,y=0;y<p.length;y++){var N=p[y];if(N.includes(i)){var b=g.getItemSync(N);if(b!==null){var C=JSON.parse(b);(C.timeRefreshed===void 0&&C.timeAcquired<h||C.timeRefreshed!==void 0&&C.timeRefreshed<h)&&(g.removeItemSync(N),j=!0)}}}j&&d.notifyWaiters()},d.waiters=void 0,d}();s.default=m}));new TextEncoder;new TextDecoder;var Gs=bi(function(t,s){var a=Ws&&Ws.__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 g=d[h].split("="),p=g.slice(1).join("=");p.charAt(0)==='"'&&(p=p.slice(1,-1));try{m[g[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}))}});vi(Gs),Gs.encode,Gs.parse,Gs.getAll;Gs.get;Gs.set;Gs.remove;var So;(function(t){t.Code="code",t.ConnectCode="connect_code"})(So||(So={}));var Ao;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(Ao||(Ao={}));new Hp;var qp={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},It=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},Wp=hr(hr({},qp),{buildAuthorizeUrl:It,buildLogoutUrl:It,getAccessTokenSilently:It,getAccessTokenWithPopup:It,getIdTokenClaims:It,loginWithRedirect:It,loginWithPopup:It,connectAccountWithRedirect:It,logout:It,handleRedirectCallback:It,getDpopNonce:It,setDpopNonce:It,generateDpopProof:It,createFetcher:It}),Kp=x.createContext(Wp);(function(t){zp(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 Gp=function(t){return t===void 0&&(t=Kp),x.useContext(t)};const As="accessToken",Ts="refreshToken",zs="idToken",Da="userData",ws={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(){[As,Ts,zs,Da].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 Oe{static setAccessToken(s){this.isLocalhost()?(localStorage.setItem(As,s),ws.set(As,s,1)):localStorage.setItem(As,s)}static getAccessToken(){return this.isLocalhost()&&ws.get(As)||localStorage.getItem(As)}static setRefreshToken(s){this.isLocalhost()?(localStorage.setItem(Ts,s),ws.set(Ts,s,7)):localStorage.setItem(Ts,s)}static getRefreshToken(){return this.isLocalhost()&&ws.get(Ts)||localStorage.getItem(Ts)}static setIdToken(s){localStorage.setItem(zs,s),this.isLocalhost()&&ws.set(zs,s,1)}static getIdToken(){return this.isLocalhost()&&ws.get(zs)||localStorage.getItem(zs)}static setUserData(s){localStorage.setItem(Da,JSON.stringify(s)),this.isLocalhost()&&ws.set(Da,JSON.stringify(s),7)}static getUserData(){const s=localStorage.getItem(Da);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)}[As,Ts,zs,Da,"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)}ws.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 Gc="https://reflow-uat.royalenfield.com/api/v1",le=Ec.create({baseURL:Gc,headers:{"Content-Type":"application/json"},withCredentials:!0});le.interceptors.request.use(t=>{const s=Oe.getAccessToken();return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t));le.interceptors.response.use(t=>t,async t=>{var a,r;const s=t.config;if(t.code==="ERR_NETWORK"||t.code==="ECONNREFUSED"||(a=t.message)!=null&&a.includes("ERR_CONNECTION_REFUSED"),((r=t.response)==null?void 0:r.status)===401&&!s._retry){s._retry=!0;try{const n=Oe.getRefreshToken();if(!n)throw new Error("No refresh token available");const i=await Ec.post(`${Gc}/auth/refresh`,{refreshToken:n},{withCredentials:!0}),{accessToken:o}=i.data.data||i.data;if(o)return Oe.setAccessToken(o),s.headers.Authorization=`Bearer ${o}`,le(s)}catch(n){return Oe.clearAll(),window.location.href="/",Promise.reject(n)}}return Promise.reject(t)});async function Yp(t,s){var a,r;try{const n=await le.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?(Oe.setAccessToken(o.accessToken),Oe.setRefreshToken(o.refreshToken),Oe.setUserData(o.user),o.idToken&&Oe.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 Zp(){var n;const t=Oe.getRefreshToken();if(!t)throw new Error("No refresh token available");const a=(await le.post("/auth/refresh",{refreshToken:t})).data,r=((n=a.data)==null?void 0:n.accessToken)||a.accessToken;if(r)return Oe.setAccessToken(r),r;throw new Error("Failed to refresh token")}async function To(){const s=(await le.get("/auth/me")).data;return s.data||s}async function Xp(){var t,s;try{await le.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 Yc=x.createContext(void 0);function Jp({children:t}){const[s,a]=x.useState(!1),[r,n]=x.useState(!0),[i,o]=x.useState(null),[l,c]=x.useState(null),[m,d]=x.useState(!1);x.useEffect(()=>{const y=sessionStorage.getItem("__logout_in_progress__"),N=sessionStorage.getItem("__force_logout__");if(y==="true"||N==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),Oe.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(I){console.error("Error clearing storage:",I)}a(!1),o(null),n(!1),c(null);return}const b=new URLSearchParams(window.location.search);if(b.has("logout")||b.has("okta_logged_out")){Oe.clearAll(),localStorage.clear(),sessionStorage.clear(),a(!1),o(null),n(!1);const I=new URLSearchParams;b.has("okta_logged_out")&&I.set("okta_logged_out","true");const w=I.toString()?`/?${I.toString()}`:"/";window.history.replaceState({},document.title,w);return}const C=Oe.getAccessToken(),k=Oe.getRefreshToken(),L=Oe.getUserData();if(!(C||k||L)){a(!1),o(null),n(!1);return}m?n(!1):h()},[m]),x.useEffect(()=>{if(!s)return;const N=setInterval(async()=>{const b=Oe.getAccessToken();if(b&&tr(b,5))try{await v()}catch(C){console.error("Silent refresh failed:",C)}},5*60*1e3);return()=>clearInterval(N)},[s]);const u=x.useRef(!1);x.useEffect(()=>{if(u.current||window.location.pathname!=="/login/callback")return;(async()=>{u.current=!0;const N=new URLSearchParams(window.location.search),b=N.get("code"),C=N.get("error");if(window.history.replaceState({},document.title,"/login/callback"),C){c(new Error(`Authentication error: ${C}`)),n(!1);return}if(!b){n(!1);return}try{n(!0),a(!1),c(null);const k=`${window.location.origin}/login/callback`,L=await Yp(b,k);o(L.user),a(!0),c(null),window.history.replaceState({},document.title,"/")}catch(k){console.error("❌ Token exchange error in AuthContext:",k),c(k),a(!1),o(null),u.current=!1}finally{n(!1)}})()},[]);const h=async()=>{if(m){n(!1);return}try{n(!0);const y=Oe.getAccessToken(),N=Oe.getUserData();if(!y){a(!1),o(null),n(!1);return}if(tr(y))try{await v();const b=Oe.getAccessToken();if(b&&!tr(b)){const C=Oe.getUserData();if(C)o(C),a(!0);else try{const k=await To();o(k),Oe.setUserData(k),a(!0)}catch{Oe.clearAll(),a(!1),o(null)}}else Oe.clearAll(),a(!1),o(null)}catch{Oe.clearAll(),a(!1),o(null)}else if(N)o(N),a(!0);else try{const b=await To();o(b),Oe.setUserData(b),a(!0)}catch{Oe.clearAll(),a(!1),o(null)}}catch(y){console.error("Error checking auth status:",y),c(y),Oe.clearAll(),a(!1),o(null)}finally{n(!1)}},g=async()=>{try{c(null);const y="https://dev-830839.oktapreview.com",N="0oa2j8slwj5S4bG5k0h8",b=`${window.location.origin}/login/callback`,C="code",k="openid profile email",L=Math.random().toString(36).substring(7),R=new URLSearchParams(window.location.search),I=R.has("logout")||R.has("okta_logged_out");let w=`${y}/oauth2/default/v1/authorize?client_id=${N}&redirect_uri=${encodeURIComponent(b)}&response_type=${C}&scope=${encodeURIComponent(k)}&state=${L}`;I&&(w+="&prompt=login"),window.location.href=w}catch(y){throw c(y),y}},p=async()=>{try{Oe.getIdToken(),sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),d(!0),a(!1),o(null),c(null),n(!0);try{await Xp()}catch(C){console.error("🚪 Logout API error:",C),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const y=sessionStorage.getItem("__logout_in_progress__"),N=sessionStorage.getItem("__force_logout__");Oe.clearAll(),y&&sessionStorage.setItem("__logout_in_progress__",y),N&&sessionStorage.setItem("__force_logout__",N),await new Promise(C=>setTimeout(C,100));const b=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(b)}catch(y){console.error("🚪 Logout error:",y);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const N=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(N)}catch{window.location.replace("/?logout="+Date.now())}}},f=async()=>{const y=Oe.getAccessToken();if(y&&!tr(y))return y;try{return await v(),Oe.getAccessToken()}catch{return null}},v=async()=>{try{if(await Zp())return;throw new Error("Failed to refresh token")}catch(y){throw Oe.clearAll(),a(!1),o(null),y}},j={isAuthenticated:s,isLoading:r,user:i,error:l,login:g,logout:p,getAccessTokenSilently:f,refreshTokenSilently:v};return e.jsx(Yc.Provider,{value:j,children:t})}function Qp({children:t}){return e.jsx(Jp,{children:t})}function $t(){const t=x.useContext(Yc);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Hs(t){return(t==null?void 0:t.role)==="ADMIN"}function Sa(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function Er(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const ko=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,Ro=Tc,Zc=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return Ro(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=ko(d)||ko(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,...g}=d;return Object.entries(g).every(p=>{let[f,v]=p;return Array.isArray(v)?v.includes({...i,...l}[f]):{...i,...l}[f]===v})?[...m,u,h]:m},[]);return Ro(t,o,c,a==null?void 0:a.class,a==null?void 0:a.className)},ji="-",ex=t=>{const s=sx(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:o=>{const l=o.split(ji);return l[0]===""&&l.length!==1&&l.shift(),Xc(l,s)||tx(o)},getConflictingClassGroupIds:(o,l)=>{const c=a[o]||[];return l&&r[o]?[...c,...r[o]]:c}}},Xc=(t,s)=>{var o;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Xc(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(ji);return(o=s.validators.find(({validator:l})=>l(i)))==null?void 0:o.classGroupId},Do=/^\[(.+)\]$/,tx=t=>{if(Do.test(t)){const s=Do.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},sx=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return rx(Object.entries(t.classGroups),a).forEach(([i,o])=>{Fn(o,r,i,s)}),r},Fn=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:Po(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(ax(n)){Fn(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,o])=>{Fn(o,Po(s,i),a,r)})})},Po=(t,s)=>{let a=t;return s.split(ji).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},ax=t=>t.isThemeGetter,rx=(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,nx=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)}}},Jc="!",ix=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),g=h.startsWith(Jc),p=g?h.substring(1):h,f=u&&u>d?u-d:void 0;return{modifiers:c,hasImportantModifier:g,baseClassName:p,maybePostfixModifierPosition:f}};return a?l=>a({className:l,parseClassName:o}):o},ox=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},lx=t=>({cache:nx(t.cacheSize),parseClassName:ix(t),...ex(t)}),cx=/\s+/,dx=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],o=t.trim().split(cx);let l="";for(let c=o.length-1;c>=0;c-=1){const m=o[c],{modifiers:d,hasImportantModifier:u,baseClassName:h,maybePostfixModifierPosition:g}=a(m);let p=!!g,f=r(p?h.substring(0,g):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=ox(d).join(":"),j=u?v+Jc:v,y=j+f;if(i.includes(y))continue;i.push(y);const N=n(f,p);for(let b=0;b<N.length;++b){const C=N[b];i.push(j+C)}l=m+(l.length>0?" "+l:l)}return l};function mx(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=Qc(s))&&(r&&(r+=" "),r+=a);return r}const Qc=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=Qc(t[r]))&&(a&&(a+=" "),a+=s);return a};function ux(t,...s){let a,r,n,i=o;function o(c){const m=s.reduce((d,u)=>u(d),t());return a=lx(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=dx(c,a);return n(c,d),d}return function(){return i(mx.apply(null,arguments))}}const We=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},ed=/^\[(?:([a-z-]+):)?(.+)\]$/i,hx=/^\d+\/\d+$/,px=new Set(["px","full","screen"]),xx=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,gx=/\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$/,fx=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,yx=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,vx=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ps=t=>ua(t)||px.has(t)||hx.test(t),Cs=t=>va(t,"length",Tx),ua=t=>!!t&&!Number.isNaN(Number(t)),Xr=t=>va(t,"number",ua),Aa=t=>!!t&&Number.isInteger(Number(t)),bx=t=>t.endsWith("%")&&ua(t.slice(0,-1)),De=t=>ed.test(t),Ss=t=>xx.test(t),jx=new Set(["length","size","percentage"]),Nx=t=>va(t,jx,td),wx=t=>va(t,"position",td),Cx=new Set(["image","url"]),Sx=t=>va(t,Cx,Rx),Ax=t=>va(t,"",kx),Ta=()=>!0,va=(t,s,a)=>{const r=ed.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},Tx=t=>gx.test(t)&&!fx.test(t),td=()=>!1,kx=t=>yx.test(t),Rx=t=>vx.test(t),Dx=()=>{const t=We("colors"),s=We("spacing"),a=We("blur"),r=We("brightness"),n=We("borderColor"),i=We("borderRadius"),o=We("borderSpacing"),l=We("borderWidth"),c=We("contrast"),m=We("grayscale"),d=We("hueRotate"),u=We("invert"),h=We("gap"),g=We("gradientColorStops"),p=We("gradientColorStopPositions"),f=We("inset"),v=We("margin"),j=We("opacity"),y=We("padding"),N=We("saturate"),b=We("scale"),C=We("sepia"),k=We("skew"),L=We("space"),R=We("translate"),I=()=>["auto","contain","none"],w=()=>["auto","hidden","clip","visible","scroll"],A=()=>["auto",De,s],P=()=>[De,s],q=()=>["",ps,Cs],M=()=>["auto",ua,De],F=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],S=()=>["solid","dashed","dotted","double","none"],T=()=>["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"],H=()=>["","0",De],O=()=>["auto","avoid","all","avoid-page","page","left","right","column"],_=()=>[ua,De];return{cacheSize:500,separator:":",theme:{colors:[Ta],spacing:[ps,Cs],blur:["none","",Ss,De],brightness:_(),borderColor:[t],borderRadius:["none","","full",Ss,De],borderSpacing:P(),borderWidth:q(),contrast:_(),grayscale:H(),hueRotate:_(),invert:H(),gap:P(),gradientColorStops:[t],gradientColorStopPositions:[bx,Cs],inset:A(),margin:A(),opacity:_(),padding:P(),saturate:_(),scale:_(),sepia:H(),skew:_(),space:P(),translate:P()},classGroups:{aspect:[{aspect:["auto","square","video",De]}],container:["container"],columns:[{columns:[Ss]}],"break-after":[{"break-after":O()}],"break-before":[{"break-before":O()}],"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:[...F(),De]}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:I()}],"overscroll-x":[{"overscroll-x":I()}],"overscroll-y":[{"overscroll-y":I()}],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,De]}],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",De]}],grow:[{grow:H()}],shrink:[{shrink:H()}],order:[{order:["first","last","none",Aa,De]}],"grid-cols":[{"grid-cols":[Ta]}],"col-start-end":[{col:["auto",{span:["full",Aa,De]},De]}],"col-start":[{"col-start":M()}],"col-end":[{"col-end":M()}],"grid-rows":[{"grid-rows":[Ta]}],"row-start-end":[{row:["auto",{span:[Aa,De]},De]}],"row-start":[{"row-start":M()}],"row-end":[{"row-end":M()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",De]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",De]}],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":[L]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[L]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",De,s]}],"min-w":[{"min-w":[De,s,"min","max","fit"]}],"max-w":[{"max-w":[De,s,"none","full","min","max","fit","prose",{screen:[Ss]},Ss]}],h:[{h:[De,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[De,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[De,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[De,s,"auto","min","max","fit"]}],"font-size":[{text:["base",Ss,Cs]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Xr]}],"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",De]}],"line-clamp":[{"line-clamp":["none",ua,Xr]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",ps,De]}],"list-image":[{"list-image":["none",De]}],"list-style-type":[{list:["none","disc","decimal",De]}],"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:[...S(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",ps,Cs]}],"underline-offset":[{"underline-offset":["auto",ps,De]}],"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",De]}],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",De]}],"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:[...F(),wx]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Nx]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Sx]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[p]}],"gradient-via-pos":[{via:[p]}],"gradient-to-pos":[{to:[p]}],"gradient-from":[{from:[g]}],"gradient-via":[{via:[g]}],"gradient-to":[{to:[g]}],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:[...S(),"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:S()}],"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:["",...S()]}],"outline-offset":[{"outline-offset":[ps,De]}],"outline-w":[{outline:[ps,Cs]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:q()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[ps,Cs]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Ss,Ax]}],"shadow-color":[{shadow:[Ta]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...T(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":T()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Ss,De]}],grayscale:[{grayscale:[m]}],"hue-rotate":[{"hue-rotate":[d]}],invert:[{invert:[u]}],saturate:[{saturate:[N]}],sepia:[{sepia:[C]}],"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":[N]}],"backdrop-sepia":[{"backdrop-sepia":[C]}],"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",De]}],duration:[{duration:_()}],ease:[{ease:["linear","in","out","in-out",De]}],delay:[{delay:_()}],animate:[{animate:["none","spin","ping","pulse","bounce",De]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[b]}],"scale-x":[{"scale-x":[b]}],"scale-y":[{"scale-y":[b]}],rotate:[{rotate:[Aa,De]}],"translate-x":[{"translate-x":[R]}],"translate-y":[{"translate-y":[R]}],"skew-x":[{"skew-x":[k]}],"skew-y":[{"skew-y":[k]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",De]}],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",De]}],"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",De]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[ps,Cs,Xr]}],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"]}}},Px=ux(Dx);function he(...t){return Px(Tc(t))}const Oa=Zc("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),E=x.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const o=r?fc:"button";return e.jsx(o,{"data-slot":"button",className:he(Oa({variant:s,size:a,className:t})),ref:i,...n})});E.displayName="Button";function W({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:he("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function se({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:he("@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 ae({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:he("leading-none",t),...s})}function ue({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:he("text-muted-foreground",t),...s})}function K({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:he("px-6 [&:last-child]:pb-6",t),...s})}function Ex(){const{login:t,isLoading:s,error:a}=$t(),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(se,{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(kt,{className:"w-8 h-8 text-white"})})}),e.jsx(ae,{className:"text-3xl font-bold text-gray-900",children:"Royal Enfield"}),e.jsx(ue,{className:"text-lg text-gray-600 mt-2",children:"Approval & Request Management Portal"})]}),e.jsxs(K,{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(E,{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(tp,{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 sd(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=$t(),[n,i]=x.useState("exchanging");x.useEffect(()=>{if(a){i("error");return}if(s){const c=new URLSearchParams(window.location.search).get("code");i(c&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else 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(Pe,{className:"w-16 h-16 text-red-500"})}),e.jsx(Pe,{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(Rn,{className:"w-16 h-16 text-green-500"})}),e.jsx(Rn,{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 Mx=Zc("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function Q({className:t,variant:s,asChild:a=!1,...r}){const n=a?fc:"span";return e.jsx(n,{"data-slot":"badge",className:he(Mx({variant:s}),t),...r})}function Ix({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=Gp();return x.useEffect(()=>{},[a,r,n,i]),t?e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4",children:e.jsxs(W,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(se,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ae,{children:"Authentication Debug Information"}),e.jsx(E,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(dt,{className:"h-4 w-4"})})]})}),e.jsxs(K,{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(Q,{variant:r?"default":"destructive",children:n?"Loading...":r?"Authenticated":"Not Authenticated"})]}),i&&e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded p-3",children:[e.jsx("p",{className:"text-sm text-red-700 font-semibold",children:"Error:"}),e.jsx("p",{className:"text-sm text-red-600",children:i.message})]}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-semibold",children:"User Information:"}),e.jsx("pre",{className:"bg-gray-50 p-3 rounded text-xs overflow-auto",children:JSON.stringify(a,null,2)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-semibold",children:"All Auth Claims:"}),e.jsx("pre",{className:"bg-gray-50 p-3 rounded text-xs overflow-auto",children:JSON.stringify({isAuthenticated:r,isLoading:n,error:(i==null?void 0:i.message)||null,hasUser:!!a},null,2)})]})]})]})}):null}const ft=x.forwardRef(({className:t,...s},a)=>e.jsx(yc,{ref:a,"data-slot":"avatar",className:he("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));ft.displayName=yc.displayName;const Mr=x.forwardRef(({className:t,...s},a)=>e.jsx(vc,{ref:a,"data-slot":"avatar-image",className:he("aspect-square size-full",t),...s}));Mr.displayName=vc.displayName;const yt=x.forwardRef(({className:t,...s},a)=>e.jsx(bc,{ref:a,"data-slot":"avatar-fallback",className:he("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));yt.displayName=bc.displayName;function Eo({...t}){return e.jsx(Iu,{"data-slot":"dropdown-menu",...t})}function Mo({...t}){return e.jsx(Fu,{"data-slot":"dropdown-menu-trigger",...t})}function Io({className:t,sideOffset:s=4,...a}){return e.jsx(Lu,{children:e.jsx(_u,{"data-slot":"dropdown-menu-content",sideOffset:s,className:he("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 Jr({className:t,inset:s,variant:a="default",...r}){return e.jsx(Ou,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:he("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 Fx({...t}){return e.jsx(Uu,{"data-slot":"alert-dialog",...t})}function Lx({...t}){return e.jsx($u,{"data-slot":"alert-dialog-portal",...t})}const ad=x.forwardRef(({className:t,...s},a)=>e.jsx(jc,{"data-slot":"alert-dialog-overlay",className:he("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}));ad.displayName=jc.displayName;const rd=x.forwardRef(({className:t,...s},a)=>e.jsxs(Lx,{children:[e.jsx(ad,{}),e.jsx(Nc,{"data-slot":"alert-dialog-content",ref:a,className:he("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})]}));rd.displayName=Nc.displayName;function _x({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:he("flex flex-col gap-2 text-center sm:text-left",t),...s})}function Ox({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:he("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function $x({className:t,...s}){return e.jsx(Vu,{"data-slot":"alert-dialog-title",className:he("text-lg font-semibold",t),...s})}function Ux({className:t,...s}){return e.jsx(Bu,{"data-slot":"alert-dialog-description",className:he("text-muted-foreground text-sm",t),...s})}function Vx({className:t,...s}){return e.jsx(Hu,{className:he(Oa(),t),...s})}function Bx({className:t,...s}){return e.jsx(zu,{className:he(Oa({variant:"outline"}),t),...s})}const zx="/assets/Re_Logo-By51taPS.png";class Hx{async list(s){return(await le.get("/notifications",{params:s})).data}async getUnreadCount(){return(await le.get("/notifications/unread-count")).data.data.unreadCount}async markAsRead(s){return(await le.patch(`/notifications/${s}/read`)).data}async markAllAsRead(){return(await le.post("/notifications/mark-all-read")).data}async delete(s){return(await le.delete(`/notifications/${s}`)).data}}const Ys=new Hx;let Us=null;function qx(){return"https://reflow-uat.royalenfield.com"}function pr(t){const s=qx();return Us||(Us=Up(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),Us.on("connect",()=>{}),Us.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),Us.on("disconnect",a=>{}),Us)}function Ln(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function nd(t,s){t.emit("leave:request",s)}function Wx(t,s){t.emit("join:user",{userId:s})}function St({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,o]=x.useState(!1),[l,c]=x.useState(!1),[m,d]=x.useState([]),[u,h]=x.useState(0),[g,p]=x.useState(!1),{user:f}=$t(),v=()=>{var C,k;try{if(f!=null&&f.displayName&&typeof f.displayName=="string"){const L=f.displayName.split(" ").filter(Boolean);return L.length>=2?`${((C=L[0])==null?void 0:C[0])||""}${((k=L[L.length-1])==null?void 0:k[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(L){return console.error("[PageLayout] Error getting user initials:",L),"U"}},j=x.useMemo(()=>{const C=[{id:"dashboard",label:"Dashboard",icon:sp},{id:"requests",label:"All Requests",icon:ap}];return C.push({id:"my-requests",label:"My Requests",icon:rt},{id:"open-requests",label:"Open Requests",icon:Te},{id:"closed-requests",label:"Closed Requests",icon:ye},{id:"shared-summaries",label:"Shared Summary",icon:Nr}),C},[]),y=()=>{o(!i)},N=async C=>{var k;try{if(C.isRead||(await Ys.markAsRead(C.notificationId),d(L=>L.map(R=>R.notificationId===C.notificationId?{...R,isRead:!0}:R)),h(L=>Math.max(0,L-1))),C.actionUrl&&a){const L=(k=C.metadata)==null?void 0:k.requestNumber;if(L){let R=`request/${L}`;(C.notificationType==="mention"||C.notificationType==="comment"||C.notificationType==="worknote")&&(R+="?tab=worknotes"),a(R)}}p(!1)}catch(L){console.error("[PageLayout] Error handling notification click:",L)}},b=async()=>{try{await Ys.markAllAsRead(),d(C=>C.map(k=>({...k,isRead:!0}))),h(0)}catch(C){console.error("[PageLayout] Error marking all as read:",C)}};return x.useEffect(()=>{const C=f==null?void 0:f.userId;if(!C)return;let k=!0;(async()=>{var I,w;try{const A=await Ys.list({page:1,limit:4,unreadOnly:!1});if(!k)return;const P=((I=A.data)==null?void 0:I.notifications)||[];d(P),h(((w=A.data)==null?void 0:w.unreadCount)||0)}catch(A){console.error("[PageLayout] Failed to fetch notifications:",A)}})();const R=pr();if(R){Wx(R,C);const I=w=>{k&&(d(A=>[w.notification,...A].slice(0,4)),h(A=>A+1))};return R.on("notification:new",I),()=>{k=!1,R.off("notification:new",I)}}return()=>{k=!1}},[f]),x.useEffect(()=>{const C=()=>{window.innerWidth>=768?o(!0):o(!1)};return C(),window.addEventListener("resize",C),()=>window.removeEventListener("resize",C)},[]),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 flex-col items-center justify-center",children:[e.jsx("img",{src:zx,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain"}),e.jsx("p",{className:"text-xs text-gray-400 text-center mt-1 truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"p-3 flex-1 overflow-y-auto",children:[e.jsx("div",{className:"space-y-2",children:j.map(C=>e.jsxs("button",{onClick:()=>{a==null||a(C.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===C.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(C.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:C.label})]},C.id))}),e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(E,{onClick:r,className:"w-full bg-re-green hover:bg-re-green/90 text-white text-sm font-medium",size:"sm",children:[e.jsx(Es,{className:"w-4 h-4 mr-2"}),"Raise New Request"]})})]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("header",{className:"h-16 border-b border-gray-200 bg-white flex items-center justify-between px-6 shrink-0",children:[e.jsx("div",{className:"flex items-center gap-4 min-w-0 flex-1",children:e.jsx(E,{variant:"ghost",size:"icon",onClick:y,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(rp,{className:"w-5 h-5 text-gray-600"}):e.jsx(np,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[e.jsxs(E,{onClick:r,className:"bg-re-green hover:bg-re-green/90 text-white gap-2 hidden md:flex text-sm",size:"sm",children:[e.jsx(Es,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(Eo,{open:g,onOpenChange:p,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(E,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(Lt,{className:"w-5 h-5"}),u>0&&e.jsx(Q,{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(Io,{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(E,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:C=>{C.stopPropagation(),b()},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(Lt,{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(C=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${C.isRead?"":"bg-blue-50"}`,onClick:()=>N(C),children:e.jsxs("div",{className:"flex gap-2",children:[!C.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 ${C.isRead?"font-medium":"font-semibold"}`,children:C.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:C.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:Mc(new Date(C.createdAt),{addSuffix:!0})})]})]})},C.notificationId))})}),m.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(E,{variant:"ghost",className:"w-full text-sm text-blue-600 hover:text-blue-700",onClick:()=>{p(!1),a==null||a("notifications")},children:"View all notifications"})})]})]}),e.jsxs(Eo,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(ft,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Mr,{src:(f==null?void 0:f.picture)||""}),e.jsx(yt,{className:"bg-re-green text-white text-sm",children:v()})]})}),e.jsxs(Io,{align:"end",children:[e.jsxs(Jr,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(rt,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(Jr,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(ra,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(Jr,{onClick:()=>c(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(Zr,{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(Fx,{open:l,onOpenChange:c,children:e.jsxs(rd,{children:[e.jsxs(_x,{children:[e.jsxs($x,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(Ux,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(Ox,{children:[e.jsx(Bx,{onClick:()=>c(!1),children:"Cancel"}),e.jsxs(Vx,{onClick:async()=>{if(c(!1),n)try{await n()}catch(C){console.error("🔴 Error calling onLogout:",C)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(Zr,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}function Kx(){const[t,s]=x.useState("month"),[a,r]=x.useState(void 0),[n,i]=x.useState(void 0),[o,l]=x.useState(!1),c=x.useCallback(u=>{const h=u;s(h),h!=="custom"?(r(void 0),i(void 0),l(!1)):l(!0)},[]),m=x.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=x.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 Gx(){const[t,s]=x.useState({page:1,totalPages:1,totalRecords:0}),[a,r]=x.useState({page:1,totalPages:1,totalRecords:0}),[n,i]=x.useState({page:1,totalPages:1,totalRecords:0}),[o,l]=x.useState({page:1,totalPages:1,totalRecords:0}),c=x.useCallback((v,j,y)=>{s({page:v,totalPages:j,totalRecords:y})},[]),m=x.useCallback((v,j,y)=>{r({page:v,totalPages:j,totalRecords:y})},[]),d=x.useCallback((v,j,y)=>{i({page:v,totalPages:j,totalRecords:y})},[]),u=x.useCallback((v,j,y)=>{l({page:v,totalPages:j,totalRecords:y})},[]),h=x.useCallback((v,j)=>{v>=1&&v<=t.totalPages&&(s(y=>({...y,page:v})),j(v))},[t.totalPages]),g=x.useCallback((v,j)=>{v>=1&&v<=a.totalPages&&(r(y=>({...y,page:v})),j(v))},[a.totalPages]),p=x.useCallback((v,j)=>{v>=1&&v<=n.totalPages&&(i(y=>({...y,page:v})),j(v))},[n.totalPages]),f=x.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:g,handleDeadlinesPageChange:p,handleApproverPageChange:f}}class Yx{async getKPIs(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await le.get("/dashboard/kpis",{params:n})).data.data}catch(n){throw console.error("Failed to fetch KPIs:",n),n}}async getRequestStats(s,a,r,n,i,o,l,c,m,d){try{const u={dateRange:s};return s==="custom"&&a&&r&&(u.startDate=a,u.endDate=r),n&&n!=="all"&&(u.priority=n),i&&i!=="all"&&(u.department=i),o&&o!=="all"&&(u.initiator=o),l&&l!=="all"&&(u.approver=l),c&&(u.approverType=c),m&&(u.search=m),d&&d!=="all"&&(u.slaCompliance=d),(await le.get("/dashboard/stats/requests",{params:u})).data.data}catch(u){throw console.error("Failed to fetch request stats:",u),u}}async getTATEfficiency(s){try{return(await le.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 le.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 le.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 le.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 le.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 le.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 le.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 le.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 le.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 le.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 le.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 le.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 le.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 le.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 le.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 le.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 Ve=new Yx;function Zx({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,onPaginationUpdate:n}){const[i,o]=x.useState(null),[l,c]=x.useState([]),[m,d]=x.useState([]),[u,h]=x.useState([]),[g,p]=x.useState([]),[f,v]=x.useState([]),[j,y]=x.useState(null),[N,b]=x.useState([]),[C,k]=x.useState(!0),[L,R]=x.useState(!1),I=x.useRef(n);I.current=n;const w=x.useCallback(async(F=!1)=>{try{F?R(!0):k(!0);const S=[Ve.getKPIs(s,a,r),Ve.getRecentActivity(1,10),Ve.getCriticalRequests(1,10),Ve.getUpcomingDeadlines(1,10)],T=t?[Ve.getDepartmentStats(s,a,r),Ve.getPriorityDistribution(s,a,r),Ve.getAIRemarkUtilization(s,a,r),Ve.getApproverPerformance(s,1,10,a,r)]:[],D=await Promise.all([...S,...T]),H=D[0],O=D[1],_=D[2],ee=D[3];if(o(H),c(O.activities),I.current.activity(O.pagination.currentPage,O.pagination.totalPages,O.pagination.totalRecords),d(_.criticalRequests),I.current.critical(_.pagination.currentPage,_.pagination.totalPages,_.pagination.totalRecords),v(ee.deadlines),I.current.deadlines(ee.pagination.currentPage,ee.pagination.totalPages,ee.pagination.totalRecords),t&&D.length>=8){const G=D[4],Y=D[5],me=D[6],X=D[7];h(G),p(Y),y(me),b(X.performance),I.current.approver(X.pagination.currentPage,X.pagination.totalPages,X.pagination.totalRecords)}else t||(h([]),p([]),y(null),b([]))}catch(S){console.error("Failed to fetch dashboard data:",S)}finally{k(!1),R(!1)}},[t,s,a,r]),A=x.useCallback(async(F=1)=>{try{const S=await Ve.getRecentActivity(F,10);c(S.activities),I.current.activity(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch recent activities:",S)}},[]),P=x.useCallback(async(F=1)=>{try{const S=await Ve.getCriticalRequests(F,10);d(S.criticalRequests),I.current.critical(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch critical requests:",S)}},[]),q=x.useCallback(async(F=1)=>{try{const S=await Ve.getUpcomingDeadlines(F,10);v(S.deadlines),I.current.deadlines(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch upcoming deadlines:",S)}},[]),M=x.useCallback(async(F=1)=>{try{const S=await Ve.getApproverPerformance(s,F,10,a,r);b(S.performance),I.current.approver(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch approver performance:",S)}},[s,a,r]);return{kpis:i,recentActivity:l,criticalRequests:m,departmentStats:u,priorityDistribution:g,upcomingDeadlines:f,aiRemarkUtilization:j,approverPerformance:N,loading:C,refreshing:L,fetchDashboardData:w,fetchRecentActivities:A,fetchCriticalRequests:P,fetchUpcomingDeadlines:q,fetchApproverPerformance:M}}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 Xx{constructor(){Wr(this,"config",null);Wr(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 le.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 Jx=new Xx;let Qx=9,eg=18,tg=1,sg=5,Fo=!1;async function ag(){if(!Fo)try{const t=await Jx.getConfig();Qx=t.workingHours.START_HOUR,eg=t.workingHours.END_HOUR,tg=t.workingHours.START_DAY,sg=t.workingHours.END_DAY,Fo=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}ag().catch(()=>{});function Qe(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 rg(t,s,a){const r=[];let n=1,i=!0;const o=100;for(;i&&n<=o;){const h=await Ve.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 g=[`"${(h.approverName||"Unknown").replace(/"/g,'""')}"`,h.totalApproved||0,h.tatCompliancePercent||0,Qe(h.avgResponseHours),h.pendingCount||0];l.push(g.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 ng(t,s,a){const r=await Ve.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 ig(){const[t,s]=x.useState(!1),[a,r]=x.useState(!1),n=x.useCallback(async(o,l,c)=>{try{s(!0),await ng(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=x.useCallback(async(o,l,c)=>{try{r(!0),await rg(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 og({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(K,{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(kt,{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(E,{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(wr,{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(Ht,{className:"w-6 h-6 text-white/80"})})]})]})})]})}function Ne({...t}){return e.jsx(qu,{"data-slot":"select",...t})}function we({...t}){return e.jsx(Gu,{"data-slot":"select-value",...t})}function Ce({className:t,size:s="default",children:a,...r}){return e.jsxs(Wu,{"data-slot":"select-trigger","data-size":s,className:he("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(Ku,{asChild:!0,children:e.jsx(Oc,{className:"size-4 opacity-50"})})]})}function Se({className:t,children:s,position:a="popper",...r}){return e.jsx(Yu,{children:e.jsxs(Zu,{"data-slot":"select-content",className:he("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(lg,{}),e.jsx(Xu,{className:he("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(cg,{})]})})}function z({className:t,children:s,...a}){return e.jsxs(Ju,{"data-slot":"select-item",className:he("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(Qu,{children:e.jsx(ya,{className:"size-4"})})}),e.jsx(eh,{children:s})]})}function lg({className:t,...s}){return e.jsx(th,{"data-slot":"select-scroll-up-button",className:he("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(ip,{className:"size-4"})})}function cg({className:t,...s}){return e.jsx(sh,{"data-slot":"select-scroll-down-button",className:he("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Oc,{className:"size-4"})})}function jt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(ah,{"data-slot":"separator-root",decorative:a,orientation:s,className:he("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 Rs({...t}){return e.jsx(rh,{"data-slot":"popover",...t})}function Ds({...t}){return e.jsx(nh,{"data-slot":"popover-trigger",...t})}function Ps({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(ih,{children:e.jsx(oh,{"data-slot":"popover-content",align:s,sideOffset:a,className:he("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 pe({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:he("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground flex h-9 w-full min-w-0 rounded-md border border-gray-400 bg-white px-3 py-1 text-base text-gray-900 transition-all outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","hover:border-gray-500","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...a})}function J({className:t,...s}){return e.jsx(lh,{"data-slot":"label",className:he("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 dg({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(K,{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(qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(Q,{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(Be,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ne,{value:s,onValueChange:o,"data-testid":"date-range-select",children:[e.jsx(Ce,{className:"w-[140px]",children:e.jsx(we,{placeholder:"Select period"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"today",children:"Today"}),e.jsx(z,{value:"week",children:"This Week"}),e.jsx(z,{value:"month",children:"This Month"}),e.jsx(z,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(Rs,{open:n,onOpenChange:m,children:[e.jsx(Ds,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(Be,{className:"w-4 h-4"}),a&&r?`${xe(a,"MMM d, yyyy")} - ${xe(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Ps,{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(J,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(pe,{id:"start-date",type:"date",value:a?xe(a,"yyyy-MM-dd"):"",onChange:g=>{const p=g.target.value?new Date(g.target.value):void 0;p?(l(p),r&&p>r&&c(p)):l(void 0)},max:xe(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(pe,{id:"end-date",type:"date",value:r?xe(r,"yyyy-MM-dd"):"",onChange:g=>{const p=g.target.value?new Date(g.target.value):void 0;p?(c(p),a&&p<a&&l(p)):c(void 0)},min:a?xe(a,"yyyy-MM-dd"):void 0,max:xe(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(E,{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(E,{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(Be,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ne,{value:s,onValueChange:g=>o(g),"data-testid":"date-range-select-user",children:[e.jsx(Ce,{className:"w-[140px]",children:e.jsx(we,{placeholder:"Select period"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"today",children:"Today"}),e.jsx(z,{value:"week",children:"This Week"}),e.jsx(z,{value:"month",children:"This Month"})]})]})]}),e.jsx(jt,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(E,{variant:"outline",size:"sm",onClick:h,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx(Et,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function Zs({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(se,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ae,{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(Cr,{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(K,{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 At({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 cs({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(ch,{"data-slot":"progress",className:he("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(dh,{"data-slot":"progress-indicator",className:he("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function mg({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(Zs,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Te,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(At,{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(At,{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(At,{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(At,{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(Zs,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:et,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(cs,{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(At,{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(At,{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(Zs,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?Qe(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:Re,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(At,{label:"Express",value:(()=>{const l=s.find(m=>m.priority==="express"),c=l?Number(l.avgCycleTimeHours):0;return c>0?Qe(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(At,{label:"Standard",value:(()=>{const l=s.find(m=>m.priority==="standard"),c=l?Number(l.avgCycleTimeHours):0;return c>0?Qe(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:l=>{l.stopPropagation(),i({...o(),priority:"standard"})}})]})})})]})}function ug({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(Zs,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Te,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(At,{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(At,{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(At,{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(At,{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(Zs,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:Re,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(At,{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(At,{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(Zs,{title:"Critical Alerts",value:s.length,icon:ns,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(At,{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(At,{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(Zs,{title:"Success Rate",value:`${u.toFixed(0)}%`,icon:ye,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(cs,{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 hg=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)))},pg=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 xg({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=hg(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(op,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(Q,{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(Q,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:pg(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(cs,{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 gg(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 fg(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function yg(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 vg(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 id(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 bg({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(se,{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(ns,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(ue,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(Q,{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(K,{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(ye,{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(xg,{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(E,{variant:"outline",size:"sm",onClick:()=>r(a.page-1),disabled:a.page===1,className:"h-7 w-7 p-0","data-testid":"critical-pagination-prev",children:e.jsx(gt,{className:"h-3 w-3 rotate-180"})}),id(a.page,a.totalPages,3).map(i=>e.jsx(E,{variant:i===a.page?"default":"outline",size:"sm",onClick:()=>r(i),className:`h-7 w-7 p-0 text-xs ${i===a.page?"bg-red-600 text-white hover:bg-red-700":""}`,"data-testid":`critical-pagination-page-${i}`,children:i},i)),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>r(a.page+1),disabled:a.page===a.totalPages,className:"h-7 w-7 p-0","data-testid":"critical-pagination-next",children:e.jsx(gt,{className:"h-3 w-3"})})]})]})})]})}const jg=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"}},Ng=t=>{const s=new Date,a=new Date(t),r=Bh(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=zh(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=Hh(s,a);return`${i} day${i>1?"s":""} ago`},wg=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()},Cg=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(ye,{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(js,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(ns,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(Te,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(Sr,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(Ht,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function Sg({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(ft,{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(Mr,{src:""}),e.jsx(yt,{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:Cg(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(Q,{variant:"outline",className:`text-xs ${jg(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:wg(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:Ng(t.timestamp)})]})]}),e.jsx(gt,{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 Ag({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(se,{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(Ht,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(ae,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(ue,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(E,{variant:"ghost",size:"sm",className:"text-blue-600 hover:bg-blue-50 font-medium flex-shrink-0 h-8 sm:h-9 px-2 sm:px-3 sm:min-w-[100px]",onClick:i,disabled:r,"data-testid":"activity-refresh-button",children:[e.jsx(Et,{className:`w-3 h-3 sm:w-4 sm:h-4 ${r?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline ml-2 sm:w-[60px] sm:text-center",children:r?"Refreshing...":"Refresh"})]})]})}),e.jsx(K,{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(Ht,{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(Sg,{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(E,{variant:"outline",size:"sm",onClick:()=>n(a.page-1),disabled:a.page===1,className:"h-7 w-7 p-0","data-testid":"activity-pagination-prev",children:e.jsx(gt,{className:"h-3 w-3 rotate-180"})}),id(a.page,a.totalPages,3).map(d=>e.jsx(E,{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(E,{variant:"outline",size:"sm",onClick:()=>n(a.page+1),disabled:a.page===a.totalPages,className:"h-7 w-7 p-0","data-testid":"activity-pagination-next",children:e.jsx(gt,{className:"h-3 w-3"})})]})]})})]})}function Tg({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(se,{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(Ht,{className:"h-4 w-4 text-blue-600"})}),e.jsx(ae,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(K,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl sm:text-3xl font-bold text-blue-600",children:s.length}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"levels"})]}),e.jsx(jt,{}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg Time/Level"}),e.jsxs("span",{className:"font-semibold",children:[s.length>0?(t.tatEfficiency.avgCycleTimeHours/s.length).toFixed(1):"0","h"]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"At Risk"}),e.jsx("span",{className:"font-semibold text-red-600",children:a.filter(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(se,{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(js,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ae,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(K,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center p-2 bg-indigo-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-indigo-600",children:t.engagement.workNotesAdded})]}),e.jsxs("div",{className:"text-center p-2 bg-purple-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Files"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-purple-600",children:t.engagement.attachmentsUploaded})]})]}),e.jsx(jt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[t.requestVolume.totalRequests>0?(t.engagement.workNotesAdded/t.requestVolume.totalRequests).toFixed(1):"0"," ","avg notes per request"]})]})})]})]}),r.length>0&&e.jsxs(W,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(se,{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(lp,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(ue,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2 self-start sm:self-auto",onClick:()=>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(K,{children:e.jsx(oi,{width:"100%",height:400,children:e.jsxs(Lh,{data:r,children:[e.jsx(kc,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Rc,{dataKey:"department",stroke:"#999",tick:u=>{const{x:h,y:g,payload:p}=u;return e.jsx("g",{transform:`translate(${h},${g})`,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(Dc,{stroke:"#999",tick:{fontSize:11}}),e.jsx(li,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Pc,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Kr,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(Kr,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(Kr,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function kg({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(se,{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(js,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ae,{className:"text-sm",children:"My Activity"})]})}),e.jsx(K,{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(se,{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(Re,{className:"h-4 w-4 text-purple-600"})}),e.jsx(ae,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(K,{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:Qe(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(jt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function Rg({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(se,{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(et,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(ue,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(K,{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: ",Qe(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(oi,{width:"100%",height:300,children:e.jsxs(_h,{children:[e.jsx(Oh,{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($h,{fill:a.priority==="express"?"#ef4444":"#3b82f6",style:{cursor:"pointer"}},`cell-${r}`))}),e.jsx(li,{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 na({currentPage:t,totalPages:s,itemsPerPage:a,totalRecords:r,onPageChange:n,loading:i=!1,itemLabel:o="items",testIdPrefix:l="pagination"}){const c=()=>{const u=[];let g=Math.max(1,t-Math.floor(2.5)),p=Math.min(s,g+5-1);p-g<4&&(g=Math.max(1,p-5+1));for(let f=g;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(K,{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(K,{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(E,{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(gt,{className:"h-4 w-4 rotate-180"})}),t>3&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>n(1),className:"h-8 w-8 p-0","data-testid":`${l}-page-1`,children:"1"}),e.jsx("span",{className:"text-muted-foreground","data-testid":`${l}-ellipsis-start`,children:"..."})]}),c().map(u=>e.jsx(E,{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(E,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${l}-page-${s}`,children:s})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>n(t+1),disabled:t===s,className:"h-8 w-8 p-0","data-testid":`${l}-next-btn`,"aria-label":"Next page",children:e.jsx(gt,{className:"h-4 w-4"})})]})]})})})}function Dg({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(se,{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(ae,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsx(ue,{className:"text-xs sm:text-sm",children:"Requests that breached defined turnaround time"})]})]}),e.jsxs(Q,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[t.length," ",t.length===1?"Breach":"Breaches"]})]})}),e.jsxs(K,{children:[e.jsx("div",{className:"overflow-x-auto -mx-4 sm:mx-0",children:e.jsxs("table",{className:"w-full min-w-[1000px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 bg-gray-50",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Request ID"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[250px]",children:"Title"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Department"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Approver"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Level"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[140px]",children:"Breach Time"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[300px]",children:"Reason"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Priority"})]})}),e.jsx("tbody",{children:t.map((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 w-[250px]",children:e.jsx("p",{className:"break-words leading-relaxed",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 w-[140px]",children:e.jsx("span",{className:"bg-red-500 text-white px-2 py-1 rounded text-xs font-medium whitespace-nowrap",children:yg(u)})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 w-[300px]",children:e.jsx("div",{className:"max-h-32 overflow-y-auto",children:e.jsx("p",{className:"whitespace-pre-line break-words leading-relaxed",children:m.breachReason||"TAT Exceeded"})})}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(Q,{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(na,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function Pg({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(se,{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(Be,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(ue,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(K,{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(Q,{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(Q,{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(cs,{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:[Qe(c)," elapsed"]}),e.jsxs("span",{children:[Qe(m)," left"]})]})]})]},o)})}),e.jsx("div",{className:"mt-4",children:e.jsx(na,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function Eg({aiRemarkUtilization:t}){return t?e.jsxs(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(se,{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(wr,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(ue,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(K,{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(oi,{width:"100%",height:250,children:e.jsxs(Uh,{data:t.monthlyTrends,children:[e.jsx(kc,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Rc,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(Dc,{stroke:"#999",tick:{fontSize:11}}),e.jsx(li,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Pc,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(yo,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(yo,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function Mg({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(se,{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(Je,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(ue,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(E,{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(Et,{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(K,{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 g=new URLSearchParams;g.set("approverId",d.approverId),g.set("approverName",d.approverName),g.set("dateRange",a),a==="custom"&&r&&n&&(g.set("startDate",r.toISOString()),g.set("endDate",n.toISOString())),m==null||m(`/approver-performance?${g.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 ${vg(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:Qe(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(na,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:l,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function Ig(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 Fg(t,s,a){const r=[{label:"New Request",icon:Te,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"},{label:"View Pending",icon:Re,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:ra,action:()=>a==null?void 0:a("settings"),color:"bg-slate-600 hover:bg-slate-700"}];return t&&r.splice(2,0,{label:"Reports",icon:Ht,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),r}function Lo({onNavigate:t,onNewRequest:s}){const{user:a}=$t(),r=x.useMemo(()=>Er(a),[a]),n=Kx(),{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,handleDateRangeChange:m,handleApplyCustomDate:d,resetCustomDates:u,setCustomStartDate:h,setCustomEndDate:g,setShowCustomDatePicker:p}=n,f=Gx(),{activity:v,critical:j,deadlines:y,approver:N,updateActivityPagination:b,updateCriticalPagination:C,updateDeadlinesPagination:k,updateApproverPagination:L,handleActivityPageChange:R,handleCriticalPageChange:I,handleDeadlinesPageChange:w,handleApproverPageChange:A}=f,P=Zx({isAdmin:r,dateRange:i,customStartDate:o,customEndDate:l,onPaginationUpdate:{activity:b,critical:C,deadlines:k,approver:L}}),{kpis:q,recentActivity:M,criticalRequests:F,departmentStats:S,priorityDistribution:T,upcomingDeadlines:D,aiRemarkUtilization:H,approverPerformance:O,loading:_,refreshing:ee,fetchDashboardData:G,fetchRecentActivities:Y,fetchCriticalRequests:me,fetchUpcomingDeadlines:X,fetchApproverPerformance:B}=P,ne=ig(),{exportingDeptStats:V,exportingApproverPerformance:Z,handleExportDepartmentStats:re,handleExportApproverPerformance:ge}=ne,ve=x.useMemo(()=>gg(F),[F]),Ue=x.useMemo(()=>fg(D),[D]),Ie=x.useCallback(()=>{G(!0)},[i,o,l,G]),Le=x.useCallback(()=>{d(()=>{o&&l&&G(!1)})},[o,l,d,G]),tt=x.useCallback(Mt=>{R(Mt,Y)},[R,Y]),He=x.useCallback(Mt=>{I(Mt,me)},[I,me]),Dt=x.useCallback(Mt=>{w(Mt,X)},[w,X]),_e=x.useCallback(Mt=>{A(Mt,()=>B(Mt))},[A,B]);x.useEffect(()=>{i==="custom"?o&&l&&G(!1):G(!1)},[i,o,l]);const wa=x.useMemo(()=>Fg(r,s,t),[r,s,t]),Ns=x.useCallback(Mt=>{const Ca=Ig(Mt);t==null||t(Ca)},[t]);return _?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Et,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto p-3 sm:p-4","data-testid":"dashboard",children:[e.jsx(og,{isAdmin:r,quickActions:wa}),e.jsx(dg,{isAdmin:r,dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,refreshing:ee,onDateRangeChange:m,onCustomStartDateChange:h,onCustomEndDateChange:g,onShowCustomDatePickerChange:p,onApplyCustomDate:Le,onResetCustomDates:u,onRefresh:Ie}),r?e.jsx(mg,{kpis:q,priorityDistribution:T,dateRange:i,customStartDate:o,customEndDate:l,onKPIClick:Ns}):e.jsx(ug,{kpis:q,criticalRequests:F,dateRange:i,customStartDate:o,customEndDate:l,onKPIClick:Ns,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(bg,{isAdmin:r,breachedRequests:ve,pagination:j,onPageChange:He,onNavigate:t}),e.jsx(Ag,{isAdmin:r,recentActivity:M,pagination:v,refreshing:ee,onPageChange:tt,onRefresh:Ie,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),r&&q&&e.jsx(Tg,{kpis:q,upcomingDeadlines:D,criticalRequests:F,departmentStats:S,dateRange:i,customStartDate:o,customEndDate:l,exportingDeptStats:V,onKPIClick:Ns,onExportDepartmentStats:re}),!r&&q&&e.jsx(kg,{kpis:q}),r&&T.length>0&&e.jsx(Rg,{priorityDistribution:T,onNavigate:t}),r&&ve.length>0&&e.jsx(Dg,{breachedRequests:ve,pagination:j,dateRange:i,customStartDate:o,customEndDate:l,onPageChange:He,onKPIClick:Ns,onNavigate:t}),Ue.length>0&&e.jsx(Pg,{isAdmin:r,upcomingDeadlines:Ue,pagination:y,onPageChange:Dt,onNavigate:t}),r&&H&&e.jsx(Eg,{aiRemarkUtilization:H}),r&&O.length>0&&e.jsx(Mg,{approverPerformance:O,pagination:N,dateRange:i,customStartDate:o,customEndDate:l,loading:_,exportingApproverPerformance:Z,onPageChange:_e,onExport:ge,onNavigate:t})]})}function Qr(){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 Lg(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,g=u.tat??"";let p=0;typeof g=="number"&&(p=u.tatType==="days"?g*24:g);const f=u.email||"",v=u.name&&u.name.trim()||f.split("@")[0]||`Approver ${h}`;return{levelNumber:h,levelName:`Level ${h}`,approverId:Qr(),approverEmail:f,approverName:v,tatHours:p>0?p:24,isFinalApprover:h===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:Qr(),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:Qr(),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 le.post("/workflows",n),o=((l=i.data)==null?void 0:l.data)||i.data;return{id:o.id||o.workflowId||""}}async function od(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]||{},g=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"?g*24:g||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 le.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 _g(t={}){var p;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:m,dateRange:d,startDate:u,endDate:h}=t,g=await le.get("/workflows",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:m,dateRange:d,startDate:u,endDate:h}});return((p=g.data)==null?void 0:p.data)||g.data}async function Og(t={}){var f,v,j,y,N;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,initiator:l,approver:c,approverType:m,slaCompliance:d,dateRange:u,startDate:h,endDate:g}=t,p=await le.get("/workflows/participant-requests",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,initiator:l,approver:c,approverType:m,slaCompliance:d,dateRange:u,startDate:h,endDate:g}});return{data:((v=(f=p.data)==null?void 0:f.data)==null?void 0:v.data)||((j=p.data)==null?void 0:j.data)||[],pagination:((N=(y=p.data)==null?void 0:y.data)==null?void 0:N.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function $g(t={}){var p,f,v,j,y;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:m,dateRange:d,startDate:u,endDate:h}=t,g=await le.get("/workflows/my",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:m,dateRange:d,startDate:u,endDate:h}});return{data:((f=(p=g.data)==null?void 0:p.data)==null?void 0:f.data)||((v=g.data)==null?void 0:v.data)||[],pagination:((y=(j=g.data)==null?void 0:j.data)==null?void 0:y.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Ug(t={}){var u,h,g,p,f;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,dateRange:l,startDate:c,endDate:m}=t,d=await le.get("/workflows/my-initiated",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,dateRange:l,startDate:c,endDate:m}});return{data:((h=(u=d.data)==null?void 0:u.data)==null?void 0:h.data)||((g=d.data)==null?void 0:g.data)||[],pagination:((f=(p=d.data)==null?void 0:p.data)==null?void 0:f.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Vg(t={}){var m,d,u,h,g;const{page:s=1,limit:a=20,search:r,status:n,priority:i,sortBy:o,sortOrder:l}=t,c=await le.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:((g=(h=c.data)==null?void 0:h.data)==null?void 0:g.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Bg(t={}){var m,d,u,h,g;const{page:s=1,limit:a=20,search:r,status:n,priority:i,sortBy:o,sortOrder:l}=t,c=await le.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:((g=(h=c.data)==null?void 0:h.data)==null?void 0:g.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Xs(t){var a;const s=await le.get(`/workflows/${t}/details`);return((a=s.data)==null?void 0:a.data)||s.data}async function ha(t){var a;const s=await le.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function ld(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 le.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 cd(t,s,a,r){var i;const n=await le.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 zg(t,s,a){var n;const r=await le.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function dd(t,s){var r;const a=await le.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}function Hg(t){return`https://reflow-uat.royalenfield.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function md(t){return`https://reflow-uat.royalenfield.com/api/v1/workflows/documents/${t}/preview`}async function _n(t){var n;const s="https://reflow-uat.royalenfield.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 _o(t){var n;const s="https://reflow-uat.royalenfield.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 Ot={createWorkflowFromForm:Lg,createWorkflowMultipart:od,listWorkflows:_g,listParticipantRequests:Og,listMyWorkflows:$g,listMyInitiatedWorkflows:Ug,listOpenForMe:Vg,listClosedByMe:Bg,submitWorkflow:ud,getWorkflowDetails:Xs,getWorkNotes:ha,createWorkNoteMultipart:ld};async function ud(t){var a;const s=await le.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function qg(t,s){var r;const a=await le.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function Wg(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 le.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((l=o.data)==null?void 0:l.data)||o.data}async function Kg(t,s,a){var n;const r=await le.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function Gg(t,s,a,r){var i;const n=await le.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 Yg(t,s){const a=await le.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}function Gt(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 hd(t){return Gt(t,{includeTime:!1,format:"short"})}function ds(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 Zg=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ns,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:et,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:et,iconColor:"text-gray-600"}}},Xg=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Re,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Pe,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ze,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ye,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600",label:t}}};function Jg({onViewRequest:t}){const[s]=Pr(),[a,r]=x.useState(s.get("search")||""),[n,i]=x.useState(s.get("priority")||"all"),[o,l]=x.useState(s.get("status")||"all"),[c,m]=x.useState(s.get("sortBy")||"created"),[d,u]=x.useState(s.get("sortOrder")||"desc"),[h,g]=x.useState([]),[p,f]=x.useState(!1),[v,j]=x.useState(!1),[y,N]=x.useState(1),[b,C]=x.useState(1),[k,L]=x.useState(0),[R]=x.useState(10),I=x.useCallback(async(T=1,D)=>{try{T===1&&(f(!0),g([]));const H=await Ot.listOpenForMe({page:T,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}),O=Array.isArray(H==null?void 0:H.data)?H.data:[],_=H==null?void 0:H.pagination;_&&(N(_.page||1),C(_.totalPages||1),L(_.total||0));const ee=O.map(G=>{var me,X,B,ne;const Y=G.submittedAt||G.submitted_at||G.createdAt||G.created_at;return{id:G.requestNumber||G.request_number||G.requestId,requestId:G.requestId,displayId:G.requestNumber||G.request_number||G.requestId,title:G.title,description:G.description,status:(G.status||"").toString().toLowerCase().replace("_","-"),priority:(G.priority||"").toString().toLowerCase(),initiator:{name:((me=G.initiator)==null?void 0:me.displayName)||((X=G.initiator)==null?void 0:X.email)||"—",avatar:(((B=G.initiator)==null?void 0:B.displayName)||((ne=G.initiator)==null?void 0:ne.email)||"NA").split(" ").map(V=>V[0]).join("").slice(0,2).toUpperCase()},currentApprover:G.currentApprover?{name:G.currentApprover.name||G.currentApprover.email||"—",avatar:(G.currentApprover.name||G.currentApprover.email||"CA").split(" ").map(V=>V[0]).join("").slice(0,2).toUpperCase(),sla:G.currentApprover.sla}:void 0,createdAt:Y||"—",approvalStep:G.currentLevel?`Step ${G.currentLevel} of ${G.totalLevels||"?"}`:void 0,department:G.department,currentLevelSLA:G.currentLevelSLA}});g(ee)}finally{f(!1),j(!1)}},[R]),w=()=>{j(!0),I(y,{search:a||void 0,status:o!=="all"?o:void 0,priority:n!=="all"?n:void 0,sortBy:c,sortOrder:d})},A=T=>{T>=1&&T<=b&&(N(T),I(T,{search:a||void 0,status:o!=="all"?o:void 0,priority:n!=="all"?n:void 0,sortBy:c,sortOrder:d}))},P=()=>{const T=[];let H=Math.max(1,y-Math.floor(2.5)),O=Math.min(b,H+5-1);O-H<4&&(H=Math.max(1,O-5+1));for(let _=H;_<=O;_++)T.push(_);return T},q=x.useRef(!0);x.useEffect(()=>{q.current&&(q.current=!1,I(1,{search:a||void 0,status:o!=="all"?o:void 0,priority:n!=="all"?n:void 0,sortBy:c,sortOrder:d}))},[]),x.useEffect(()=>{if(q.current)return;const T=setTimeout(()=>{N(1),I(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(T)},[a,o,n,c,d,I]);const M=h,F=()=>{r(""),i("all"),l("all")},S=[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(Te,{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(Q,{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…":`${k||h.length} open`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:w,disabled:v,children:[e.jsx(Et,{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(se,{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(qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ue,{className:"text-xs sm:text-sm",children:S>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[S," filter",S>1?"s":""," active"]})})]})]}),S>0&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:F,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(dt,{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(K,{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(qt,{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(pe,{placeholder:"Search requests, IDs...",value:a,onChange:T=>r(T.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(Ne,{value:n,onValueChange:i,children:[e.jsx(Ce,{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(we,{placeholder:"All Priorities"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Priorities"}),e.jsx(z,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ns,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(z,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(et,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Ne,{value:o,onValueChange:l,children:[e.jsx(Ce,{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(we,{placeholder:"All Statuses"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Statuses"}),e.jsx(z,{value:"pending",children:"Pending (In Approval)"}),e.jsx(z,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ne,{value:c,onValueChange:T=>m(T),children:[e.jsx(Ce,{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(we,{placeholder:"Sort by"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"due",children:"Due Date"}),e.jsx(z,{value:"created",children:"Date Created"}),e.jsx(z,{value:"priority",children:"Priority"}),e.jsx(z,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(E,{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($c,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Uc,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]}),e.jsx("div",{className:"space-y-3",children:M.map(T=>{const D=Zg(T.priority),H=Xg(T.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(T.id,T.title),children:e.jsx(K,{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:T.displayId||T.id}),e.jsxs(Q,{variant:"outline",className:`${H.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(H.icon,{className:"w-3.5 h-3.5 mr-1"}),H.label||T.status]}),T.department&&e.jsx(Q,{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(Q,{variant:"outline",className:`${D.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}),T.currentLevelSLA&&e.jsxs("div",{className:`p-2 rounded-md ${T.currentLevelSLA.status==="breached"?"bg-red-50 border border-red-200":T.currentLevelSLA.status==="critical"?"bg-orange-50 border border-orange-200":T.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(Re,{className:"w-3.5 h-3.5 text-gray-600"}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",T.currentLevelSLA.percentageUsed,"%"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:T.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${T.currentLevelSLA.status==="breached"?"text-red-600":T.currentLevelSLA.status==="critical"?"text-orange-600":"text-gray-700"}`,children:[T.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(cs,{value:T.currentLevelSLA.percentageUsed,className:`h-1.5 ${T.currentLevelSLA.status==="breached"?"[&>div]:bg-red-600":T.currentLevelSLA.status==="critical"?"[&>div]:bg-orange-600":T.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(ft,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(yt,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:T.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:T.initiator.name})]}),T.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ft,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(yt,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:T.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:T.currentApprover.name})]}),T.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Pe,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:T.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Be,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",T.createdAt!=="—"?ds(T.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(gt,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},T.id)})}),M.length===0&&e.jsx(W,{className:"shadow-lg border-0",children:e.jsxs(K,{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(Te,{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||S>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),S>0&&e.jsx(E,{variant:"outline",className:"mt-4",onClick:F,children:"Clear all filters"})]})}),b>1&&!p&&e.jsx(W,{className:"shadow-md",children:e.jsx(K,{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,k)," of ",k," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>A(y-1),disabled:y===1,className:"h-8 w-8 p-0",children:e.jsx(gt,{className:"h-4 w-4 rotate-180"})}),y>3&&b>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{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(T=>e.jsx(E,{variant:T===y?"default":"outline",size:"sm",onClick:()=>A(T),className:`h-8 w-8 p-0 ${T===y?"bg-re-green text-white hover:bg-re-green/90":""}`,children:T},T)),y<b-2&&b>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>A(b),className:"h-8 w-8 p-0",children:b})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>A(y+1),disabled:y===b,className:"h-8 w-8 p-0",children:e.jsx(gt,{className:"h-4 w-4"})})]})]})})})]})}function Qg({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(Te,{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(Q,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold","data-testid":"closed-requests-count",children:[s?"Loading…":`${t} closed`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:r,disabled:a,"data-testid":"closed-requests-refresh",children:[e.jsx(Et,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${a?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:a?"Refreshing...":"Refresh"})]})]})]})}function ef({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(se,{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(qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ue,{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(E,{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(dt,{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(K,{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(qt,{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(pe,{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(Ne,{value:s,onValueChange:l,children:[e.jsx(Ce,{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(we,{placeholder:"All Priorities"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Priorities"}),e.jsx(z,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ns,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(z,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(et,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Ne,{value:a,onValueChange:c,children:[e.jsx(Ce,{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(we,{placeholder:"All Statuses"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Statuses"}),e.jsx(z,{value:"closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"Closed"})]})}),e.jsx(z,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Rejected"})]})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ne,{value:r,onValueChange:h=>m(h),children:[e.jsx(Ce,{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(we,{placeholder:"Sort by"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"due",children:"Due Date"}),e.jsx(z,{value:"created",children:"Date Created"}),e.jsx(z,{value:"priority",children:"Priority"})]})]}),e.jsx(E,{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($c,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Uc,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function tf(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ns,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:et,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:et,iconColor:"text-gray-600"}}}function sf(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:ye,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:Ze,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600",label:t,description:""}}}function af({request:t,onViewRequest:s}){const a=tf(t.priority),r=sf(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(K,{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(Q,{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(Q,{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(Q,{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(ft,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(yt,{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(ye,{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(Be,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?ds(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ye,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",ds(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(gt,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function rf({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(af,{request:r,onViewRequest:a},r.id))})}function nf({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(W,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(K,{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(Te,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:t||s>0?"Try adjusting your filters or search terms to see more results.":"No closed requests available at the moment."}),s>0&&e.jsx(E,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function of(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 lf({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const o=of(a,r);return e.jsx(W,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(K,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(a-1)*i+1," to ",Math.min(a*i,n)," of ",n," closed requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>s(a-1),disabled:a===1,className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-prev",children:e.jsx(gt,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>s(1),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-first",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),o.map(l=>e.jsx(E,{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(E,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>s(a+1),disabled:a===r,className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-next",children:e.jsx(gt,{className:"h-4 w-4"})})]})]})})})}function cf(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 df(t){return t.map(cf)}function mf({itemsPerPage:t=10,initialFilters:s}={}){const[a,r]=x.useState([]),[n,i]=x.useState(!1),[o,l]=x.useState(!1),[c,m]=x.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=x.useRef(!0),u=x.useCallback(async(g=1,p)=>{try{g===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 Ot.listClosedByMe({page:g,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:[],N=df(j).filter(C=>C.status==="rejected"||C.status==="closed");r(N);const b=v==null?void 0:v.pagination;b&&m({currentPage:b.page||1,totalPages:b.totalPages||1,totalRecords:b.total||0,itemsPerPage:t})}catch(f){console.error("[ClosedRequests] Error fetching requests:",f),r([])}finally{i(!1),l(!1)}},[t]);x.useEffect(()=>{d.current&&(u(1,s),d.current=!1)},[]);const h=x.useCallback(g=>{l(!0),u(c.currentPage,g)},[u,c.currentPage]);return{requests:a,loading:n,refreshing:o,pagination:c,fetchRequests:u,handleRefresh:h}}function uf({onFiltersChange:t,debounceMs:s=500}={}){const[a,r]=x.useState(""),[n,i]=x.useState("all"),[o,l]=x.useState("all"),[c,m]=x.useState("due"),[d,u]=x.useState("desc"),h=x.useRef(null),g=x.useRef(!0),p=x.useCallback(()=>({search:a,status:o,priority:n,sortBy:c,sortOrder:d}),[a,o,n,c,d]);x.useEffect(()=>{if(g.current){g.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=x.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 hf({onViewRequest:t}){const s=mf({itemsPerPage:10}),a=x.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=uf({onFiltersChange:x.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=x.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=x.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(Qg,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:i}),e.jsx(ef,{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(rf,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(nf,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(lf,{pagination:s.pagination,onPageChange:n})]})}function Ir({className:t,...s}){return e.jsx(mh,{"data-slot":"tabs",className:he("flex flex-col gap-2",t),...s})}function Fr({className:t,...s}){return e.jsx(uh,{"data-slot":"tabs-list",className:he("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function ht({className:t,...s}){return e.jsx(hh,{"data-slot":"tabs-trigger",className:he("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 pt({className:t,...s}){return e.jsx(ph,{"data-slot":"tabs-content",className:he("flex-1 outline-none",t),...s})}const pd={"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"]}},pf={"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 xf(t,s=[],a){const[r,n]=x.useState(null),[i,o]=x.useState(!1),[l,c]=x.useState(null),[m,d]=x.useState(!1),u=(j,y)=>(j||y||"NA").toString().split(" ").map(b=>b[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()},g=async()=>{var j,y,N,b,C,k,L,R,I;o(!0);try{const w=await Ot.getWorkflowDetails(t);if(!w){console.warn("[useRequestDetails] No details returned from API");return}const A=w.workflow||{},P=Array.isArray(w.approvals)?w.approvals:[],q=Array.isArray(w.participants)?w.participants:[],M=Array.isArray(w.documents)?w.documents:[],F=w.summary||{},S=Array.isArray(w.tatAlerts)?w.tatAlerts:[];S.length>0;const T=(F==null?void 0:F.currentLevel)||A.currentLevel||1,D=P.map(B=>{const ne=B.levelNumber||0,V=(B.status||"").toString().toUpperCase(),Z=B.levelId||B.level_id;let re=h(B.status);ne>T&&V!=="APPROVED"&&V!=="REJECTED"?re="waiting":ne===T&&V==="PENDING"&&(re="pending");const ge=S.filter(ve=>ve.levelId===Z);return{step:ne,levelId:Z,role:B.levelName||B.approverName||"Approver",status:re,approver:B.approverName||B.approverEmail,approverId:B.approverId||B.approver_id,approverEmail:B.approverEmail,tatHours:Number(B.tatHours||0),elapsedHours:Number(B.elapsedHours||0),remainingHours:Number(B.remainingHours||0),tatPercentageUsed:Number(B.tatPercentageUsed||0),actualHours:B.levelEndTime&&B.levelStartTime?Math.max(0,(new Date(B.levelEndTime).getTime()-new Date(B.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:B.comments||void 0,timestamp:B.actionDate||void 0,levelStartTime:B.levelStartTime||B.tatStartTime,tatAlerts:ge,skipReason:B.skipReason||void 0,isSkipped:V==="SKIPPED"||B.isSkipped||!1}}),H=q.filter(B=>(B.participantType||B.participant_type||"").toUpperCase()==="SPECTATOR").map(B=>({name:B.userName||B.user_name||B.userEmail||B.user_email,role:"Spectator",email:B.userEmail||B.user_email,avatar:u(B.userName||B.user_name,B.userEmail||B.user_email)})),O=B=>{var V,Z;if(!B)return;const ne=q.find(re=>re.userId===B||re.user_id===B);return ne!=null&&ne.userName||ne!=null&&ne.user_name?ne.userName||ne.user_name:A.initiatorId===B?((V=A.initiator)==null?void 0:V.displayName)||((Z=A.initiator)==null?void 0:Z.email):B},_=M.map(B=>{const ne=Number(B.fileSize||B.file_size||0),V=(ne/(1024*1024)).toFixed(2)+" MB";return{documentId:B.documentId||B.document_id,name:B.originalFileName||B.fileName||B.file_name,fileType:B.fileType||B.file_type||"",size:V,sizeBytes:ne,uploadedBy:O(B.uploadedBy||B.uploaded_by),uploadedAt:B.uploadedAt||B.uploaded_at}}),ee=Array.isArray(w.activities)?w.activities.filter(B=>(B.type||"").toLowerCase()!=="sla_warning"):[],G={...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:q,documents:_,spectators:H,summary:F,initiator:{name:((j=A.initiator)==null?void 0:j.displayName)||((y=A.initiator)==null?void 0:y.email),role:((N=A.initiator)==null?void 0:N.designation)||void 0,department:((b=A.initiator)==null?void 0:b.department)||void 0,email:((C=A.initiator)==null?void 0:C.email)||void 0,phone:((k=A.initiator)==null?void 0:k.phone)||void 0,avatar:u((L=A.initiator)==null?void 0:L.displayName,(R=A.initiator)==null?void 0:R.email)},createdAt:A.createdAt,updatedAt:A.updatedAt,totalSteps:A.totalLevels||1,currentStepRaw:(F==null?void 0:F.currentLevel)||A.currentLevel||1,currentStep:Math.min(Math.max(1,(F==null?void 0:F.currentLevel)||A.currentLevel||1),A.totalLevels||1),auditTrail:ee,conclusionRemark:A.conclusionRemark||null,closureDate:A.closureDate||null};n(G);const Y=(I=a==null?void 0:a.email)==null?void 0:I.toLowerCase(),me=P.find(B=>{const ne=(B.status||"").toString().toUpperCase(),V=(B.approverEmail||"").toLowerCase(),Z=B.levelNumber||0;return(ne==="PENDING"||ne==="IN_PROGRESS")&&V===Y&&Z===T});c(me||null);const X=a==null?void 0:a.userId;if(X){const B=q.some(ne=>(ne.participantType||ne.participant_type||"").toUpperCase()==="SPECTATOR"&&(ne.userId||ne.user_id)===X);d(B)}else d(!1)}catch(w){console.error("[useRequestDetails] Error refreshing details:",w),alert("Failed to refresh request details. Please try again.")}finally{o(!1)}};x.useEffect(()=>{if(!t)return;let j=!0;return(async()=>{var y,N,b,C,k,L,R,I,w;try{const A=await Ot.getWorkflowDetails(t);if(!j||!A)return;const P=A.workflow||{},q=Array.isArray(A.approvals)?A.approvals:[],M=Array.isArray(A.participants)?A.participants:[],F=Array.isArray(A.documents)?A.documents:[],S=A.summary||{},T=Array.isArray(A.tatAlerts)?A.tatAlerts:[],D=(P.priority||"").toString().toLowerCase(),H=(S==null?void 0:S.currentLevel)||P.currentLevel||1,O=q.map(V=>{const Z=V.levelNumber||0,re=(V.status||"").toString().toUpperCase(),ge=V.levelId||V.level_id;let ve=h(V.status);Z>H&&re!=="APPROVED"&&re!=="REJECTED"?ve="waiting":Z===H&&re==="PENDING"&&(ve="pending");const Ue=T.filter(Ie=>Ie.levelId===ge);return{step:Z,levelId:ge,role:V.levelName||V.approverName||"Approver",status:ve,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.elapsedHours!==void 0&&V.elapsedHours!==null?Number(V.elapsedHours):void 0,comment:V.comments||void 0,timestamp:V.actionDate||void 0,levelStartTime:V.levelStartTime||V.tatStartTime,tatAlerts:Ue}}),_=M.filter(V=>(V.participantType||"").toUpperCase()==="SPECTATOR").map(V=>({name:V.userName||V.userEmail,role:"Spectator",avatar:u(V.userName,V.userEmail)})),ee=V=>{var re,ge;if(!V)return;const Z=M.find(ve=>ve.userId===V);return Z!=null&&Z.userName?Z.userName:P.initiatorId===V?((re=P.initiator)==null?void 0:re.displayName)||((ge=P.initiator)==null?void 0:ge.email):V},G=F.map(V=>{const Z=Number(V.fileSize||0),re=(Z/(1024*1024)).toFixed(2)+" MB";return{documentId:V.documentId||V.document_id,name:V.originalFileName||V.fileName,fileType:V.fileType||V.file_type||"",size:re,sizeBytes:Z,uploadedBy:ee(V.uploadedBy),uploadedAt:V.uploadedAt}}),Y=Array.isArray(A.activities)?A.activities.filter(V=>(V.type||"").toLowerCase()!=="sla_warning"):[],me={id:P.requestNumber||P.requestId,requestId:P.requestId,title:P.title,description:P.description,priority:D,status:h(P.status),summary:S,initiator:{name:((y=P.initiator)==null?void 0:y.displayName)||((N=P.initiator)==null?void 0:N.email),role:((b=P.initiator)==null?void 0:b.designation)||void 0,department:((C=P.initiator)==null?void 0:C.department)||void 0,email:((k=P.initiator)==null?void 0:k.email)||void 0,phone:((L=P.initiator)==null?void 0:L.phone)||void 0,avatar:u((R=P.initiator)==null?void 0:R.displayName,(I=P.initiator)==null?void 0:I.email)},createdAt:P.createdAt,updatedAt:P.updatedAt,totalSteps:P.totalLevels||1,currentStepRaw:(S==null?void 0:S.currentLevel)||P.currentLevel||1,currentStep:Math.min(Math.max(1,(S==null?void 0:S.currentLevel)||P.currentLevel||1),P.totalLevels||1),approvalFlow:O,approvals:q,documents:G,spectators:_,auditTrail:Y,conclusionRemark:P.conclusionRemark||null,closureDate:P.closureDate||null};n(me);const X=(w=a==null?void 0:a.email)==null?void 0:w.toLowerCase(),B=q.find(V=>{const Z=(V.status||"").toString().toUpperCase(),re=(V.approverEmail||"").toLowerCase(),ge=V.levelNumber||0;return(Z==="PENDING"||Z==="IN_PROGRESS")&&re===X&&ge===H});c(B||null);const ne=a==null?void 0:a.userId;if(ne){const V=M.some(Z=>(Z.participantType||"").toUpperCase()==="SPECTATOR"&&Z.userId===ne);d(V)}else d(!1)}catch(A){console.error("[useRequestDetails] Error loading request details:",A),j&&n(null)}})(),()=>{j=!1}},[t,a]);const p=x.useMemo(()=>{if(r)return r;const j=pd[t];if(j)return j;const y=pf[t];if(y)return y;const N=s.find(b=>b.id===t||b.requestNumber===t||b.request_number===t);return N||null},[t,s,r]),f=x.useMemo(()=>{var N,b,C;if(!p||!a)return!1;const j=(N=a==null?void 0:a.email)==null?void 0:N.toLowerCase(),y=(C=(b=p.initiator)==null?void 0:b.email)==null?void 0:C.toLowerCase();return j===y},[p,a]),v=x.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(N=>{N.approverEmail&&j.push({email:N.approverEmail.toLowerCase(),participantType:"APPROVER",name:N.approver})}),p.spectators&&Array.isArray(p.spectators)&&p.spectators.forEach(N=>{N.email&&j.push({email:N.email.toLowerCase(),participantType:"SPECTATOR",name:N.name})}),p.participants&&Array.isArray(p.participants)&&p.participants.forEach(N=>{const b=(N.userEmail||N.email||"").toLowerCase(),C=(N.participantType||N.participant_type||"").toUpperCase(),k=N.userName||N.user_name||N.name;b&&C&&!j.find(L=>L.email===b)&&j.push({email:b,participantType:C,name:k})}),j},[p]);return{request:p,apiRequest:r,refreshing:i,refreshDetails:g,currentApprovalLevel:l,isSpectator:m,isInitiator:f,existingParticipants:v}}function gf(t,s,a,r){const[n,i]=x.useState([]),[o,l]=x.useState(0),[c,m]=x.useState([]);return x.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 Ot.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=pr();if(!h){console.error("[useRequestSocket] Socket not available");return}const g=r==null?void 0:r.userId,p=()=>{Ln(h,u,g)};return h.connected?p():h.on("connect",p),()=>{d&&(h.off("connect",p),nd(h,u))}})(),()=>{d=!1}},[t,r]),x.useEffect(()=>{!t||!s||(async()=>{try{const d=await ha(t),u=s.auditTrail||[],h=[...d,...u];h.sort((g,p)=>{const f=new Date(g.createdAt||g.created_at||g.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]),x.useEffect(()=>{if(!t)return;const d=pr();if(!d)return;const u=g=>{a!=="worknotes"&&l(p=>p+1),(async()=>{try{const p=await ha(t),f=(s==null?void 0:s.auditTrail)||[],v=[...p,...f].sort((j,y)=>{const N=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime(),b=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime();return N-b});i(v)}catch(p){console.error("[useRequestSocket] Failed to refresh messages:",p)}})()},h=g=>{const p=g.type==="breach"?"⏰":g.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const f=await Ot.getWorkflowDetails(t);f&&(Array.isArray(f.tatAlerts)&&f.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${p} TAT Alert`,{body:g.message,icon:"/favicon.ico",tag:`tat-${g.requestId}-${g.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]),x.useEffect(()=>{a==="worknotes"&&l(0)},[a]),{mergedMessages:n,unreadWorkNotes:o,workNoteAttachments:c,setWorkNoteAttachments:m}}async function ff(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 le.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 ea=async t=>{const s=t?{category:t}:{};return(await le.get("/users/configurations",{params:s})).data.data},Lr=async t=>{const s=t?{category:t}:{};return(await le.get("/admin/configurations",{params:s})).data.data},xt=async(t,s)=>{await le.put(`/admin/configurations/${t}`,{configValue:s})},yf=async t=>{await le.post(`/admin/configurations/${t}/reset`)},vf=async t=>{const s=t?{year:t}:{};return(await le.get("/admin/holidays",{params:s})).data.data},bf=async t=>(await le.post("/admin/holidays",t)).data.data,jf=async(t,s)=>(await le.put(`/admin/holidays/${t}`,s)).data.data,Nf=async t=>{await le.delete(`/admin/holidays/${t}`)};function wf(t,s){const[a,r]=x.useState(!1),[n,i]=x.useState(null),[o,l]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,m]=x.useState({show:!1,errors:[]});x.useEffect(()=>{(async()=>{try{const p=await ea("DOCUMENT_POLICY"),f={};p.forEach(N=>{f[N.configKey]=N.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(N=>N.trim().toLowerCase());l({maxFileSizeMB:v,allowedFileTypes:y})}catch(p){console.error("Failed to load document policy:",p)}})()},[]);const d=g=>{const p=o.maxFileSizeMB*1024*1024;if(g.size>p)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${o.maxFileSizeMB}MB. Current size: ${(g.size/(1024*1024)).toFixed(2)}MB`};const f=g.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 g=>{var y,N;const p=g.target.files;if(!p||p.length===0)return;const f=Array.from(p),v=[],j=[];if(f.forEach(b=>{const C=d(b);C.valid?j.push(b):v.push({fileName:b.name,reason:C.reason||"Unknown validation error"})}),v.length>0&&m({show:!0,errors:v}),j.length===0){g.target&&(g.target.value="");return}r(!0);try{const b=j[0],C=t==null?void 0:t.requestId;if(!C){ke.error("Request ID not found");return}b&&await ff(b,C,"SUPPORTING"),await s(),j.length<f.length?ke.warning(`${j.length} of ${f.length} file(s) were uploaded. ${v.length} file(s) were rejected.`):ke.success("Document uploaded successfully")}catch(b){console.error("[useDocumentUpload] Upload error:",b),ke.error(((N=(y=b==null?void 0:b.response)==null?void 0:y.data)==null?void 0:N.error)||"Failed to upload document")}finally{r(!1),g.target&&(g.target.value="")}};return{uploadingDocument:a,handleDocumentUpload:u,triggerFileInput:()=>{const g=document.createElement("input");g.type="file",g.accept=o.allowedFileTypes.map(p=>`.${p}`).join(","),g.onchange=u,g.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:o,documentError:c,setDocumentError:m}}const Cf="modulepreload",Sf=function(t){return"/"+t},Oo={},en=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=Sf(c),c in Oo)return;Oo[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":Cf,m||(u.as="script"),u.crossOrigin="",u.href=c,l&&u.setAttribute("nonce",l),document.head.appendChild(u),m)return new Promise((h,g)=>{u.addEventListener("load",h),u.addEventListener("error",()=>g(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 Af(t,s,a,r,n,i,o){const[l,c]=x.useState(""),[m,d]=x.useState(!1),[u,h]=x.useState(!1),[g,p]=x.useState(!1),f=async()=>{try{const{getConclusion:y}=await en(async()=>{const{getConclusion:b}=await import("./conclusionApi-DY1a2we-.js");return{getConclusion:b}},__vite__mapDeps([0,1,2,3,4,5,6])),N=await y(t.requestId||s);N&&N.aiGeneratedRemark&&(c(N.finalRemark||N.aiGeneratedRemark),p(!!N.aiGeneratedRemark))}catch{}},v=async()=>{try{d(!0);const{generateConclusion:y}=await en(async()=>{const{generateConclusion:b}=await import("./conclusionApi-DY1a2we-.js");return{generateConclusion:b}},__vite__mapDeps([0,1,2,3,4,5,6])),N=await y(t.requestId||s);c(N.aiGeneratedRemark),p(!0)}catch(y){console.error("[useConclusionRemark] AI generation failed:",y),c(""),p(!1)}finally{d(!1)}},j=async()=>{var y,N;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:b}=await en(async()=>{const{finalizeConclusion:C}=await import("./conclusionApi-DY1a2we-.js");return{finalizeConclusion:C}},__vite__mapDeps([0,1,2,3,4,5,6]));await b(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(b){i==null||i({success:!1,title:"Error",message:((N=(y=b.response)==null?void 0:y.data)==null?void 0:N.error)||"Failed to finalize conclusion"}),o==null||o(!0)}finally{h(!1)}};return x.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:g,handleGenerateConclusion:v,handleFinalizeConclusion:j}}function Tf(t,s,a){const[r,n]=x.useState(!1),[i,o]=x.useState(!1),[l,c]=x.useState(!1),[m,d]=x.useState(!1),[u,h]=x.useState(!1),[g,p]=x.useState(!1),[f,v]=x.useState(null),[j,y]=x.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:o,showAddApproverModal:l,setShowAddApproverModal:c,showAddSpectatorModal:m,setShowAddSpectatorModal:d,showSkipApproverModal:u,setShowSkipApproverModal:h,showActionStatusModal:g,setShowActionStatusModal:p,skipApproverData:f,setSkipApproverData:v,actionStatus:j,setActionStatus:y,handleApproveConfirm:async R=>{var w,A;const I=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!I){alert("Approval level not found");return}await Kg(t,I,R||""),await a(),(w=window==null?void 0:window.closeModal)==null||w.call(window),(A=window==null?void 0:window.toast)==null||A.call(window,"Approved successfully")},handleRejectConfirm:async R=>{var w,A;if(!(R!=null&&R.trim())){alert("Comments & remarks are required");return}const I=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!I){alert("Approval level not found");return}await Gg(t,I,R.trim(),R.trim()),await a(),(w=window==null?void 0:window.closeModal)==null||w.call(window),(A=window==null?void 0:window.toast)==null||A.call(window,"Rejected successfully")},handleAddApprover:async(R,I,w)=>{var A,P;try{await cd(t,R,I,w),await a(),c(!1),y==null||y({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${w} with ${I}h TAT`}),p==null||p(!0)}catch(q){throw y==null||y({success:!1,title:"Failed to Add Approver",message:((P=(A=q==null?void 0:q.response)==null?void 0:A.data)==null?void 0:P.error)||"Failed to add approver. Please try again."}),p==null||p(!0),q}},handleSkipApprover:async R=>{var I,w;if(f)try{await zg(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:((w=(I=A==null?void 0:A.response)==null?void 0:I.data)==null?void 0:w.error)||"Failed to skip approver. Please try again."}),p==null||p(!0),A}},handleAddSpectator:async R=>{var I,w;try{await dd(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:((w=(I=A==null?void 0:A.response)==null?void 0:I.data)==null?void 0:w.error)||"Failed to add spectator. Please try again."}),p==null||p(!0),A}}}}const kf=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"}}},Rf=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}}},Df=t=>{switch(t){case"approval":case"approved":return e.jsx(ye,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(Ze,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(js,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Et,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(Ar,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Te,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(Re,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(Sr,{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(Ht,{className:"w-5 h-5 text-gray-600"})}};function Pf({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(Dn,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(ye,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(Ze,{className:"h-4 w-4 text-red-600"}):e.jsx(Re,{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(Re,{className:"h-4 w-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:"SLA Progress"})]}),e.jsxs(Q,{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(cs,{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||Qe(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||Qe(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${a}-deadline`,children:["Due: ",ds(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(Pn,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function Ef({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i}){var c,m;const o=kf((t==null?void 0:t.priority)||"standard"),l=Rf((t==null?void 0:t.status)||"pending");return e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-300 mb-4 sm:mb-6","data-testid":"request-detail-header",children:[e.jsxs("div",{className:"p-3 sm:p-4 md:p-6 border-b border-gray-300",children:[e.jsxs("div",{className:"flex items-start sm:items-center justify-between gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:a,className:"rounded-lg flex-shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"back-button",children:e.jsx(Ms,{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(Te,{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(Q,{className:`${o.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:o.label}),e.jsx(Q,{className:`${l.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:l.label})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&i&&((c=t==null?void 0:t.status)==null?void 0:c.toLowerCase())==="closed"&&e.jsxs(E,{variant:"default",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:n,"data-testid":"share-summary-button",children:[e.jsx(Nr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Share Summary"})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:r,disabled:s,"data-testid":"refresh-button",children:[e.jsx(Et,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:s?"Refreshing...":"Refresh"})]})]})]}),e.jsx("div",{className:"mt-3 ml-0 sm:ml-14",children:e.jsx("h2",{className:"text-base sm:text-lg md:text-xl font-semibold text-gray-900 line-clamp-2","data-testid":"request-title",children:t.title})})]}),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(Pf,{sla:((m=t.summary)==null?void 0:m.sla)||t.sla,requestStatus:t.status,testId:"request-sla"})})]})}function mt({...t}){return e.jsx(fh,{"data-slot":"dialog",...t})}function Mf({...t}){return e.jsx(gh,{"data-slot":"dialog-portal",...t})}const xd=x.forwardRef(({className:t,...s},a)=>e.jsx(wc,{ref:a,"data-slot":"dialog-overlay",className:he("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}));xd.displayName=wc.displayName;const nt=x.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(Mf,{"data-slot":"dialog-portal",children:[e.jsx(xd,{}),e.jsxs(Cc,{ref:r,"data-slot":"dialog-content",className:he("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(xh,{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(dt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));nt.displayName=Cc.displayName;const ut=x.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:he("flex flex-col gap-2 text-center sm:text-left",t),...s}));ut.displayName="DialogHeader";const Rt=x.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:he("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));Rt.displayName="DialogFooter";const it=x.forwardRef(({className:t,...s},a)=>e.jsx(Sc,{ref:a,"data-slot":"dialog-title",className:he("text-lg leading-none font-semibold",t),...s}));it.displayName=Sc.displayName;const Xt=x.forwardRef(({className:t,...s},a)=>e.jsx(Ac,{ref:a,"data-slot":"dialog-description",className:he("text-muted-foreground text-sm",t),...s}));Xt.displayName=Ac.displayName;function Ni({className:t,...s}){return e.jsx(yh,{"data-slot":"checkbox",className:he("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(vh,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(ya,{className:"size-3.5"})})})}async function If(t){return(await le.post("/summaries",{requestId:t})).data.data}async function Ff(t){return(await le.get(`/summaries/${t}`)).data.data}async function Lf(t,s){return(await le.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function _f(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await le.get("/summaries/shared",{params:{page:s,limit:a}});return{data:((n=r.data.data)==null?void 0:n.data)||r.data.data||[],pagination:((i=r.data.data)==null?void 0:i.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function gd(t){await le.patch(`/summaries/shared/${t}/view`)}async function ms(t,s=10){return await le.get("/users/search",{params:{q:t,limit:s}})}async function ys(t){var a;const s=await le.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function Of(t,s,a){return await le.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 $f(t,s){return await le.put(`/admin/users/${t}/role`,{role:s})}async function Uf(t,s=1,a=10){return await le.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function Vf(){return await le.get("/admin/users/role-statistics")}async function Bf(){var s,a;return((a=(s=(await le.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const Bt={searchUsers:ms,ensureUserExists:ys,assignRole:Of,updateUserRole:$f,getUsersByRole:Uf,getRoleStatistics:Vf,getAllUsers:Bf};function zf({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,o]=x.useState(""),[l,c]=x.useState([]),[m,d]=x.useState(new Set),[u,h]=x.useState(!1),[g,p]=x.useState(!1);x.useEffect(()=>{if(!t||!i.trim()){c([]);return}const y=setTimeout(async()=>{var N;try{h(!0);const b=await ms(i),C=((N=b==null?void 0:b.data)==null?void 0:N.data)||(b==null?void 0:b.data)||[];c(Array.isArray(C)?C:[])}catch(b){console.error("Failed to search users:",b),ke.error("Failed to search users")}finally{h(!1)}},300);return()=>clearTimeout(y)},[i,t]);const f=y=>{d(N=>{const b=new Set(N);return b.has(y)?b.delete(y):b.add(y),b})},v=async()=>{var y,N;if(m.size===0){ke.error("Please select at least one user to share with");return}try{p(!0),await Lf(a,Array.from(m)),ke.success(`Summary shared with ${m.size} user(s)`),d(new Set),o(""),c([]),n==null||n(),s()}catch(b){console.error("Failed to share summary:",b),ke.error(((N=(y=b==null?void 0:b.response)==null?void 0:y.data)==null?void 0:N.message)||"Failed to share summary")}finally{p(!1)}},j=()=>{d(new Set),o(""),c([]),s()};return e.jsx(mt,{open:t,onOpenChange:j,children:e.jsxs(nt,{className:"sm:max-w-[500px]",children:[e.jsx(ut,{children:e.jsx(it,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-sm font-medium text-gray-700",children:"Request"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:r})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(qt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(pe,{id:"user-search",placeholder:"Search by name or email...",value:i,onChange:y=>o(y.target.value),className:"pl-10"})]})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx($e,{className:"h-5 w-5 animate-spin text-blue-600"})}),!u&&l.length>0&&e.jsx("div",{className:"border rounded-lg max-h-[300px] overflow-y-auto",children:l.map(y=>e.jsxs("div",{className:"flex items-center gap-3 p-3 hover:bg-gray-50 border-b last:border-b-0 cursor-pointer",onClick:()=>f(y.userId),children:[e.jsx(Ni,{checked:m.has(y.userId),onCheckedChange:()=>f(y.userId)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:y.displayName||y.email})]}),(y.designation||y.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:y.designation||y.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:y.email})]})]},y.userId))}),!u&&i&&l.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),m.size>0&&e.jsxs("div",{className:"border rounded-lg p-3 bg-blue-50",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-700 mb-2",children:["Selected (",m.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(m).map(y=>{const N=l.find(b=>b.userId===y);return e.jsxs("div",{className:"flex items-center gap-1 bg-white px-2 py-1 rounded-full text-xs",children:[e.jsx("span",{children:(N==null?void 0:N.displayName)||(N==null?void 0:N.email)||y}),e.jsx("button",{onClick:()=>f(y),className:"ml-1 hover:text-red-600",children:e.jsx(dt,{className:"h-3 w-3"})})]},y)})})]})]}),e.jsxs(Rt,{children:[e.jsx(E,{variant:"outline",onClick:j,disabled:g,children:"Cancel"}),e.jsx(E,{onClick:v,disabled:g||m.size===0,children:g?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${m.size} user(s)`})]})]})})}function us({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:he("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 Hf({request:t,isInitiator:s,needsClosure:a,conclusionRemark:r,setConclusionRemark:n,conclusionLoading:i,conclusionSubmitting:o,aiGenerated:l,handleGenerateConclusion:c,handleFinalizeConclusion:m}){var d,u,h,g,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(se,{className:"pb-3 sm:pb-4",children:e.jsxs(ae,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(rt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(K,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(ft,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(yt,{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:((g=t.initiator)==null?void 0:g.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(Vc,{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(Bc,{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(se,{className:"pb-3 sm:pb-4",children:e.jsxs(ae,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Te,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(K,{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:Gt(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:Gt(t.updatedAt)})]})]})]})]}),t.claimDetails&&e.jsxs(W,{children:[e.jsx(se,{className:"pb-4",children:e.jsxs(ae,{className:"flex items-center gap-2 text-base",children:[e.jsx(Te,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(K,{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?hd(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(se,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(ae,{className:"flex items-center gap-2 text-base",children:[e.jsx(ye,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(ue,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(K,{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 ",Gt(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(se,{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(ae,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(ye,{className:"w-5 h-5 text-green-600"}),"Conclusion Remark - Final Step"]}),e.jsx(ue,{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(E,{variant:"outline",size:"sm",onClick:c,disabled:i,className:"gap-2 shrink-0","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Et,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),l?"Regenerate":"Generate with AI"]})]})}),e.jsx(K,{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(E,{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(ye,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function or({delayDuration:t=0,...s}){return e.jsx(bh,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function tn({...t}){return e.jsx(or,{children:e.jsx(jh,{"data-slot":"tooltip",...t})})}function sn({...t}){return e.jsx(Nh,{"data-slot":"tooltip-trigger",...t})}function an({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(wh,{children:e.jsxs(Ch,{"data-slot":"tooltip-content",sideOffset:s,className:he("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(Sh,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}const $o=t=>{if(t<8)return Qe(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${Qe(r)}`:`${a}d`},qf=(t,s)=>{if(s)return e.jsx(Pe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(ye,{className:"w-4 h-4 sm:w-5 sm:w-5 text-green-600"});case"rejected":return e.jsx(Ze,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"pending":case"in-review":return e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function Wf({step:t,index:s,approval:a,isCurrentUser:r=!1,isInitiator:n=!1,onSkipApprover:i,onRefresh:o,testId:l="approval-step"}){const{user:c}=$t(),[m,d]=x.useState(!1),[u,h]=x.useState(""),[g,p]=x.useState(!1),f=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";x.useEffect(()=>{m||h("")},[m]);const v=t.status==="pending"||t.status==="in-review",j=t.status==="approved",y=t.status==="rejected",N=t.status==="waiting",b=Number(t.tatHours||0),C=t.actualHours??0,k=j&&C?Math.max(0,b-C):0,L=b>0?C/b*100:0,R=L>=100,I=(c==null?void 0:c.role)==="ADMIN",w=Er(c),A=t.approverId===(c==null?void 0:c.userId),P=I||w||A,q=async()=>{var M,F;if(!u.trim()){ke.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}p(!0);try{await Yg(t.levelId,u.trim()),d(!1),h(""),ke.success("Breach Reason Updated",{description:"The breach reason has been saved and will appear in the TAT Breach Report.",duration:5e3}),o?await o():setTimeout(()=>{window.location.reload()},1e3)}catch(S){console.error("Error updating breach reason:",S);const T=((F=(M=S==null?void 0:S.response)==null?void 0:M.data)==null?void 0:F.error)||(S==null?void 0:S.message)||"Failed to update breach reason. Please try again.";ke.error("Failed to Update Breach Reason",{description:T,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":N?"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":N?"bg-gray-200":"bg-gray-100"}`,children:qf(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(Q,{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":N?"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(or,{delayDuration:200,children:e.jsxs(tn,{children:[e.jsx(sn,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:M=>M.stopPropagation(),children:e.jsx(Pe,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(an,{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(jo,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),j&&C&&e.jsx(Q,{className:"bg-green-600 text-white text-xs","data-testid":`${l}-completion-time`,children:$o(C)})]}),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:[b," hours"]})]})]}),j&&C!==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?Gt(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:$o(C)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const M=Math.min(100,L);return e.jsxs(e.Fragment,{children:[e.jsx(cs,{value:M,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(M),"% of TAT used"]}),R&&P&&e.jsx(or,{children:e.jsxs(tn,{children:[e.jsx(sn,{asChild:!0,children:e.jsx(E,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{h(f),d(!0)},children:e.jsx(er,{className:"w-3 h-3"})})}),e.jsx(an,{children:e.jsx("p",{children:f?"Edit breach reason":"Add breach reason"})})]})})]}),k>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",Qe(k)]})]})]})})()}),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(js,{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?ds(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(Re,{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," / ",Qe(b)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(cs,{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(or,{children:e.jsxs(tn,{children:[e.jsx(sn,{asChild:!0,children:e.jsx(E,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{h(f),d(!0)},children:e.jsx(er,{className:"w-3 h-3"})})}),e.jsx(an,{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(Pn,{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"]})]})]})]}),N&&e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"bg-gray-100 border border-gray-300 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-gray-600 mb-1 flex items-center gap-1.5",children:[e.jsx(cp,{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 ",b," 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(Ze,{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(jo,{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 ",Gt(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((M,F)=>{var S,T,D,H,O,_;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${M.isBreached?"bg-red-50 border-red-200":(M.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${l}-tat-alert-${F}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(M.thresholdPercentage||0)===50&&e.jsx(dp,{className:"w-5 h-5 text-yellow-600"}),(M.thresholdPercentage||0)===75&&e.jsx(as,{className:"w-5 h-5 text-orange-600"}),(M.thresholdPercentage||0)===100&&e.jsx(Pn,{className:"w-5 h-5 text-red-600"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-2 mb-1",children:[e.jsxs("p",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:["Reminder ",F+1," - ",M.thresholdPercentage||0,"% TAT"]}),e.jsx(Q,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${M.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:M.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[M.thresholdPercentage||0,"% of SLA breach reminder have been sent"]}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-1.5 sm:gap-2 text-[10px] sm:text-xs",children:[e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Allocated:"}),e.jsx("span",{className:"ml-1 font-medium text-gray-900",children:Qe(Number(M.tatHoursAllocated||0))})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Elapsed:"}),e.jsxs("span",{className:"ml-1 font-medium text-gray-900",children:[Qe(Number(M.tatHoursElapsed||0)),((S=M.metadata)==null?void 0:S.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(M.tatHoursElapsed||0)*60).toFixed(0),"m)"]})]})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Remaining:"}),e.jsxs("span",{className:`ml-1 font-medium ${(M.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[Qe(Number(M.tatHoursRemaining||0)),((T=M.metadata)==null?void 0:T.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(M.tatHoursRemaining||0)*60).toFixed(0),"m)"]})]})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Due by:"}),e.jsx("span",{className:"ml-1 font-medium text-gray-900",children:M.expectedCompletionTime?ds(M.expectedCompletionTime,!0):"N/A"})]})]}),e.jsxs("div",{className:"mt-2 pt-2 border-t border-gray-200",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1",children:[e.jsx("p",{className:"text-[10px] sm:text-xs text-gray-500",children:"Reminder sent by system automatically"}),(((D=M.metadata)==null?void 0:D.testMode)||((H=M.metadata)==null?void 0:H.tatTestMode))&&e.jsx(Q,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-300 text-[10px] px-1.5 py-0 shrink-0",children:"TEST MODE"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs text-gray-600 font-medium mt-0.5",children:["Sent at: ",M.alertSentAt?Gt(M.alertSentAt):"N/A"]}),(((O=M.metadata)==null?void 0:O.testMode)||((_=M.metadata)==null?void 0:_.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},F)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[j?"Approved":y?"Rejected":"Actioned"," on ",Gt(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(E,{variant:"outline",size:"sm",className:"w-full border-orange-300 text-orange-700 hover:bg-orange-50 h-9 sm:h-10 text-xs sm:text-sm",onClick:()=>i({levelId:t.levelId,approverName:t.approver,levelNumber:t.step}),"data-testid":`${l}-skip-button`,children:[e.jsx(Pe,{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(mt,{open:m,onOpenChange:d,children:e.jsxs(nt,{className:"sm:max-w-[500px]",children:[e.jsxs(ut,{children:[e.jsx(it,{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:M=>h(M.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(Rt,{children:[e.jsx(E,{variant:"outline",onClick:()=>{d(!1),h("")},disabled:g,children:"Cancel"}),e.jsx(E,{onClick:q,disabled:!u.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function Kf({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(W,{children:[e.jsx(se,{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(ae,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ls,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(ue,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var g;const i=t.totalSteps||1,o=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,l=((g=t.approvalFlow)==null?void 0:g.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(Q,{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(Q,{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(Q,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",h," of ",i," - ",l," completed"]})})()]})}),e.jsx(K,{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,g;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=(g=i.approverEmail)==null?void 0:g.toLowerCase(),d=c&&m&&c===m;return e.jsx(Wf,{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 Gf=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 Uo({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(Te,{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 ",Gt(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&Gf(t.fileType)&&s&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>s({fileName:t.name,fileType:t.fileType,documentId:t.documentId,fileSize:t.sizeBytes}),title:"Preview file","data-testid":`${n}-preview-btn`,children:e.jsx(bt,{className:"w-4 h-4"})}),a&&e.jsx(E,{variant:"ghost",size:"sm",onClick:async()=>{if(!t.documentId){alert("Document ID not available");return}try{await a(t.documentId)}catch{alert("Failed to download document")}},title:"Download file","data-testid":`${n}-download-btn`,children:e.jsx(ts,{className:"w-4 h-4"})})]})]})}function Yf({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(se,{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(ae,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Te,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx(ue,{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(E,{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(xa,{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(K,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((l,c)=>e.jsx(Uo,{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(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(js,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(ue,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(K,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((l,c)=>e.jsx(Uo,{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 Zf({request:t}){return e.jsxs(W,{children:[e.jsxs(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ht,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(ue,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(K,{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:Df(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:Gt(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(Ht,{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 wi({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:o,onClose:l}){const[c,m]=x.useState(100),[d,u]=x.useState(0),[h,g]=x.useState(null),[p,f]=x.useState(!1),[v,j]=x.useState(null),y=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),N=s.toLowerCase().includes("pdf"),b=y||N;x.useEffect(()=>{if(!o||!b||!a){g(null);return}return(async()=>{f(!0),j(null);try{const w=localStorage.getItem("accessToken");let A=a;a.startsWith("/")&&!a.startsWith("//")&&(A=`${window.location.origin}${a}`);const P=await fetch(A,{headers:{Authorization:`Bearer ${w}`,Accept:N?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!P.ok){const F=await P.text().catch(()=>"");throw new Error(`Failed to load file: ${P.status} ${P.statusText}. ${F}`)}const q=await P.blob();if(q.size===0)throw new Error("File is empty or could not be loaded");N&&!q.type.includes("pdf")&&q.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${q.type}`);const M=window.URL.createObjectURL(q);g(M)}catch(w){console.error("Failed to load file for preview:",w),j(w instanceof Error?w.message:"Failed to load file for preview")}finally{f(!1)}})(),()=>{h&&(window.URL.revokeObjectURL(h),g(null))}},[o,a,b,N]);const C=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},k=()=>m(I=>Math.min(I+25,200)),L=()=>m(I=>Math.max(I-25,50)),R=()=>u(I=>(I+90)%360);return e.jsx(mt,{open:o,onOpenChange:l,children:e.jsx(nt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ut,{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(bt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(it,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[y&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:L,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(mp,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[c,"%"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:k,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(up,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:R,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(hp,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(E,{variant:"outline",size:"sm",onClick:C,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(dt,{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(E,{onClick:C,className:"gap-2",children:[e.jsx(ts,{className:"h-4 w-4"}),"Download ",t]})]}):b&&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"})}),N&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:h,className:"w-full h-full rounded-lg border-0",title:t,style:{minHeight:"70vh",height:"100%"},onError:()=>{j("Failed to load PDF preview")}})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(bt,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),i&&n&&e.jsxs(E,{onClick:C,className:"gap-2",children:[e.jsx(ts,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function fd({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(nt,{className:"sm:max-w-lg",children:[e.jsxs(ut,{children:[e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Pe,{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(Rt,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}function yd({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=x.useState(""),[o,l]=x.useState(!1),[c,m]=x.useState([]),[d,u]=x.useState(!1),[h,g]=x.useState(null),p=x.useRef(null),f=x.useRef(null),[v,j]=x.useState({open:!1,type:"error",email:"",message:""}),[y,N]=x.useState({open:!1,violations:[]}),[b,C]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});x.useEffect(()=>{t&&(async()=>{var A;try{const P=await ea("WORKFLOW_SHARING"),q=await ea("TAT_SETTINGS"),M=[...P,...q],F={};M.forEach(S=>{F[S.configKey]=S.configValue}),C({maxApprovalLevels:parseInt(F.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(F.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((A=F.ALLOW_ADD_SPECTATOR)==null?void 0:A.toLowerCase())==="true",maxSpectators:parseInt(F.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(P){console.error("Failed to load system policy:",P)}})()},[t]);const k=async()=>{var T,D;const w=n.trim().toLowerCase();if(!w){j({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(w)){j({open:!0,type:"error",email:w,message:"Please enter a valid email address"});return}const P=r.find(H=>(H.email||"").toLowerCase()===w);if(P){const H=((T=P.participantType)==null?void 0:T.toUpperCase())||"PARTICIPANT",O=P.name||w;if(H==="INITIATOR"){j({open:!0,type:"error",email:w,message:`${O} is the request initiator and cannot be added as a spectator.`});return}else if(H==="APPROVER"){j({open:!0,type:"error",email:w,message:`${O} is already an approver on this request and cannot be added as a spectator.`});return}else if(H==="SPECTATOR"){j({open:!0,type:"error",email:w,message:`${O} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:w,message:`${O} is already a participant on this request.`});return}}const q=[];b.allowSpectators||q.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const F=r.filter(H=>(H.participantType||"").toUpperCase()==="SPECTATOR").length;F>=b.maxSpectators&&q.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:F,maxValue:b.maxSpectators});const S=r.length+1;if(S>b.maxParticipants&&q.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:S,maxValue:b.maxParticipants}),q.length>0){N({open:!0,violations:q});return}if(!h||h.email.toLowerCase()!==w)try{const O=((D=(await ms(w,1)).data)==null?void 0:D.data)||[];if(O.length===0){j({open:!0,type:"not-found",email:w,message:""});return}const _=O[0];await ys({userId:_.userId,email:_.email,displayName:_.displayName,firstName:_.firstName,lastName:_.lastName,department:_.department,phone:_.phone,mobilePhone:_.mobilePhone,designation:_.designation,jobTitle:_.jobTitle,manager:_.manager,employeeId:_.employeeId,employeeNumber:_.employeeNumber,secondEmail:_.secondEmail,location:_.location})}catch(H){console.error("Failed to validate spectator:",H),j({open:!0,type:"error",email:w,message:"Failed to validate user. Please try again."});return}try{l(!0),await a(w),i(""),g(null),s()}catch(H){console.error("Failed to add spectator:",H)}finally{l(!1)}},L=()=>{o||(i(""),g(null),m([]),u(!1),s())};x.useEffect(()=>{c.length>0&&f.current&&f.current.scrollTo({top:f.current.scrollHeight,behavior:"smooth"})},[c.length]),x.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const R=w=>{if(i(w),h&&h.email.toLowerCase()!==w.toLowerCase()&&g(null),p.current&&clearTimeout(p.current),!w||!w.startsWith("@")||w.length<2){m([]),u(!1);return}u(!0),p.current=setTimeout(async()=>{var A;try{const P=w.slice(1),M=((A=(await ms(P,10)).data)==null?void 0:A.data)||[];m(M)}catch(P){console.error("Search failed:",P),m([])}finally{u(!1)}},300)},I=async w=>{try{await ys({userId:w.userId,email:w.email,displayName:w.displayName,firstName:w.firstName,lastName:w.lastName,department:w.department,phone:w.phone,mobilePhone:w.mobilePhone,designation:w.designation,jobTitle:w.jobTitle,manager:w.manager,employeeId:w.employeeId,employeeNumber:w.employeeNumber,secondEmail:w.secondEmail,location:w.location}),i(w.email),g(w),m([]),u(!1)}catch(A){console.error("Failed to ensure user exists:",A),j({open:!0,type:"error",email:w.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(mt,{open:t,onOpenChange:L,children:[e.jsxs(nt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:L,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(dt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ut,{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(bt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(it,{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(xi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(pe,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:w=>R(w.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(w=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>I(w),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ft,{className:"h-8 w-8",children:e.jsx(yt,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(w.displayName||w.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:w.displayName||[w.firstName,w.lastName].filter(Boolean).join(" ")||w.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:w.email}),w.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:w.designation})]})]})},w.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:L,className:"flex-1 h-11 border-gray-300",disabled:o,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:k,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:o||!n.trim(),children:[e.jsx(bt,{className:"w-4 h-4 mr-2"}),o?"Adding...":"Add Spectator"]})]})]}),e.jsx(mt,{open:v.open,onOpenChange:w=>j(A=>({...A,open:w})),children:e.jsxs(nt,{className:"sm:max-w-md",children:[e.jsxs(ut,{children:[e.jsx(it,{className:"flex items-center gap-2",children:v.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{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(Tr,{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(Rt,{children:e.jsx(E,{onClick:()=>j(w=>({...w,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(fd,{open:y.open,onClose:()=>N({open:!1,violations:[]}),violations:y.violations,policyDetails:{maxApprovalLevels:b.maxApprovalLevels,maxParticipants:b.maxParticipants,allowSpectators:b.allowSpectators,maxSpectators:b.maxSpectators}})]})}function vd({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[]}){const[i,o]=x.useState(""),[l,c]=x.useState(24),[m,d]=x.useState(null),[u,h]=x.useState(!1),[g,p]=x.useState([]),[f,v]=x.useState(!1),[j,y]=x.useState(null),N=x.useRef(null),b=x.useRef(null),[C,k]=x.useState({open:!1,type:"error",email:"",message:""}),L=n.filter(S=>S&&(S.status==="approved"||S.status==="rejected"||S.status==="skipped")),R=Math.max(1,L.length+1),I=Math.max(1,n.length+1),w=I>=R?Array.from({length:I-R+1},(S,T)=>R+T):[R];x.useEffect(()=>{w.length>0&&m===null&&d(w[0]||null)},[w.length,m]);const A=async()=>{var H,O;const S=i.trim().toLowerCase();if(!S){k({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(S)){k({open:!0,type:"error",email:S,message:"Please enter a valid email address"});return}if(!l||l<=0){k({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(l>720){k({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!m){k({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(m<R){k({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(_=>(_.email||"").toLowerCase()===S);if(D){const _=((H=D.participantType)==null?void 0:H.toUpperCase())||"PARTICIPANT",ee=D.name||S;if(_==="INITIATOR"){k({open:!0,type:"error",email:S,message:`${ee} is the request initiator and cannot be added as an approver.`});return}else if(_==="APPROVER"){k({open:!0,type:"error",email:S,message:`${ee} is already an approver on this request.`});return}else if(_==="SPECTATOR"){k({open:!0,type:"error",email:S,message:`${ee} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{k({open:!0,type:"error",email:S,message:`${ee} is already a participant on this request.`});return}}if(!j||j.email.toLowerCase()!==S)try{const ee=((O=(await ms(S,1)).data)==null?void 0:O.data)||[];if(ee.length===0){k({open:!0,type:"not-found",email:S,message:""});return}const G=ee[0];await ys({userId:G.userId,email:G.email,displayName:G.displayName,firstName:G.firstName,lastName:G.lastName,department:G.department,phone:G.phone,mobilePhone:G.mobilePhone,designation:G.designation,jobTitle:G.jobTitle,manager:G.manager,employeeId:G.employeeId,employeeNumber:G.employeeNumber,secondEmail:G.secondEmail,location:G.location})}catch(_){console.error("Failed to validate approver:",_),k({open:!0,type:"error",email:S,message:"Failed to validate user. Please try again."});return}try{h(!0),await a(S,l,m),o(""),c(24),d(null),y(null),s()}catch(_){console.error("Failed to add approver:",_)}finally{h(!1)}},P=()=>{u||(o(""),c(24),d(null),y(null),p([]),v(!1),s())},q=S=>{const T=S.toLowerCase();return T==="approved"?e.jsx(ye,{className:"w-4 h-4 text-green-600"}):T==="rejected"?e.jsx(Ze,{className:"w-4 h-4 text-red-600"}):T==="skipped"?e.jsx(Pe,{className:"w-4 h-4 text-orange-600"}):T==="in-review"||T==="pending"?e.jsx(Re,{className:"w-4 h-4 text-blue-600"}):e.jsx(Re,{className:"w-4 h-4 text-gray-400"})};x.useEffect(()=>{g.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[g.length]),x.useEffect(()=>()=>{N.current&&clearTimeout(N.current)},[]);const M=S=>{if(o(S),j&&j.email.toLowerCase()!==S.toLowerCase()&&y(null),N.current&&clearTimeout(N.current),!S||!S.startsWith("@")||S.length<2){p([]),v(!1);return}v(!0),N.current=setTimeout(async()=>{var T;try{const D=S.slice(1),O=((T=(await ms(D,10)).data)==null?void 0:T.data)||[];p(O)}catch(D){console.error("Search failed:",D),p([])}finally{v(!1)}},300)},F=async S=>{try{await ys({userId:S.userId,email:S.email,displayName:S.displayName,firstName:S.firstName,lastName:S.lastName,department:S.department,phone:S.phone,mobilePhone:S.mobilePhone,designation:S.designation,jobTitle:S.jobTitle,manager:S.manager,employeeId:S.employeeId,employeeNumber:S.employeeNumber,secondEmail:S.secondEmail,location:S.location}),o(S.email),y(S),p([]),v(!1)}catch(T){console.error("Failed to ensure user exists:",T),k({open:!0,type:"error",email:S.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(mt,{open:t,onOpenChange:P,children:[e.jsxs(nt,{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(dt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ut,{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(Je,{className:"w-5 h-5 text-blue-600"})}),e.jsx(it,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:b,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(J,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(S=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${S.status==="approved"?"bg-green-100 border border-green-200":S.status==="rejected"?"bg-red-100 border border-red-200":S.status==="skipped"?"bg-orange-100 border border-orange-200":"bg-white border border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-blue-600 text-white text-xs font-semibold flex items-center justify-center",children:S.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:S.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[S.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[q(S.status),e.jsx(Q,{variant:"outline",className:`text-xs ${S.status==="approved"?"bg-green-50 text-green-700 border-green-300":S.status==="rejected"?"bg-red-50 text-red-700 border-red-300":S.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:S.status})]})]},S.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:[" New approver can only be added at level ",R," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(Ne,{value:(m==null?void 0:m.toString())||"",onValueChange:S=>d(Number(S)),disabled:u,children:[e.jsx(Ce,{className:"h-11 border-gray-300",children:e.jsx(we,{placeholder:"Select level"})}),e.jsx(Se,{children:w.map(S=>e.jsx(z,{value:S.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",S]}),S<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",S,")"]})]})},S))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Choose where to insert the new approver. Existing levels will be automatically shifted."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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(pe,{type:"number",min:"1",max:"720",value:l,onChange:S=>c(Number(S.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(Re,{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(xi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(pe,{type:"text",placeholder:"@username or user@example.com",value:i,onChange:S=>M(S.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(f||g.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..."}):g.length>0?e.jsx("ul",{className:"divide-y",children:g.map(S=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>F(S),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ft,{className:"h-8 w-8",children:e.jsx(yt,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(S.displayName||S.email).split(" ").map(T=>T[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:S.displayName||[S.firstName,S.lastName].filter(Boolean).join(" ")||S.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:S.email}),S.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:S.designation})]})]})},S.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:P,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(E,{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(Je,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${m||"?"}`]})]})]}),e.jsx(mt,{open:C.open,onOpenChange:S=>k(T=>({...T,open:S})),children:e.jsxs(nt,{className:"sm:max-w-md",children:[e.jsxs(ut,{children:[e.jsx(it,{className:"flex items-center gap-2",children:C.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[C.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:C.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(Tr,{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."]})})]}),C.type==="error"&&e.jsxs(e.Fragment,{children:[C.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:C.email}),"."]}),C.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:C.message})})]})]})})]}),e.jsx(Rt,{children:e.jsx(E,{onClick:()=>k(S=>({...S,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Xf=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"}},Jf=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},Qf=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 />"),e0=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Vo=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Te,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(fp,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Te,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Te,{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(yp,{className:`${s} text-purple-600`}):e.jsx(Sr,{className:`${s} text-gray-600`})};function bd({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=Wa(),u=t||d.requestId||"",[h,g]=x.useState(""),[p,f]=x.useState(""),[v,j]=x.useState(!1),[y,N]=x.useState([]),[b,C]=x.useState(!1),[k,L]=x.useState([]),[R,I]=x.useState(null),[w,A]=x.useState(null),[P,q]=x.useState(!1),[M,F]=x.useState(!1),S=x.useRef(null),T=x.useRef(null),D=x.useRef(null),H=x.useRef(!1),[O,_]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[ee,G]=x.useState({open:!1,errors:[]}),Y=x.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[me,X]=x.useState([]),B=me.filter(U=>U.status==="online"),ne=y.filter(U=>U.content.toLowerCase().includes(p.toLowerCase())||U.user.name.toLowerCase().includes(p.toLowerCase())),V=x.useMemo(()=>l!==void 0?l:!R||me.length===0?!1:me.some(U=>{const te=U.userId||U.user_id,$=(U.role||"").toString().toUpperCase(),ie=(U.participantType||U.participant_type||"").toString().toUpperCase();return te===R&&($==="SPECTATOR"||ie==="SPECTATOR")}),[l,R,me]);x.useEffect(()=>{},[me]),x.useEffect(()=>{!u||!R||s||(async()=>{try{const U=await ha(u),te=Array.isArray(U)?U.map($=>{const ie=$.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:ie===R,attachments:Array.isArray($.attachments)?$.attachments.map(oe=>({attachmentId:oe.attachmentId||oe.attachment_id,name:oe.fileName||oe.file_name||oe.name,fileName:oe.fileName||oe.file_name||oe.name,url:oe.storageUrl||oe.storage_url||oe.url||"#",type:oe.fileType||oe.file_type||oe.type||"file",fileType:oe.fileType||oe.file_type||oe.type||"file",fileSize:oe.fileSize||oe.file_size})):void 0}}):[];N(te)}catch(U){console.error("[WorkNoteChat] Failed to load messages:",U)}})()},[u,R,s]);const Z=x.useMemo(()=>{const U=[];return y.forEach(te=>{te.attachments&&te.attachments.length>0&&te.attachments.forEach($=>{U.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:te.user.name,uploadedAt:te.timestamp,url:$.storageUrl||$.storage_url||$.url||"#"})})}),U},[y]);x.useEffect(()=>{i&&Z.length>=0&&i(Z)},[Z,i]);const re=x.useMemo(()=>me.map(U=>({email:(U.email||"").toLowerCase(),participantType:U.role==="Initiator"?"INITIATOR":U.role==="Approver"?"APPROVER":U.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:U.name})),[me]),ge=U=>{if(!U)return"Participant";switch(U.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return U.charAt(0).toUpperCase()+U.slice(1).toLowerCase()}},ve=()=>{var U;(U=S.current)==null||U.scrollIntoView({behavior:"smooth"})};x.useEffect(()=>{ve()},[y]);const Ue=U=>{switch(U.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return U.charAt(0).toUpperCase()+U.slice(1).toLowerCase()}};x.useEffect(()=>{H.current||u&&(async()=>{try{const U=await Xs(u),te=Array.isArray(U==null?void 0:U.participants)?U.participants:[];if(te.length===0)return;const $=te.map(ce=>{const Ae=ce.participantType||ce.participant_type||"participant",de=ce.userId||ce.user_id||"";return{name:ce.userName||ce.user_name||ce.user_email||ce.userEmail||"User",avatar:(ce.userName||ce.user_name||ce.user_email||"U").toString().split(" ").map(Ee=>Ee[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ue(Ae.toString()),status:"offline",email:ce.userEmail||ce.user_email||"",permissions:["read","write","mention"],userId:de}});H.current=!0,X($);let ie=0;const oe=3,fe=()=>{D.current&&D.current.connected?(D.current.emit("request:online-users",{requestId:u}),ie++,ie<oe&&setTimeout(fe,500)):(ie++,ie<oe&&setTimeout(fe,200))};setTimeout(fe,100)}catch(U){console.error("[WorkNoteChat] ❌ Failed to load participants:",U)}})()},[u]),x.useEffect(()=>()=>{u&&(H.current=!1)},[u]),x.useEffect(()=>{const U=localStorage.getItem("userData");if(U)try{const te=JSON.parse(U),$=(te==null?void 0:te.id)||(te==null?void 0:te.userId)||(te==null?void 0:te.user_id)||null;I($)}catch(te){console.error("[WorkNoteChat] Failed to parse userData:",te)}},[]),x.useEffect(()=>{(async()=>{try{const te=await ea("DOCUMENT_POLICY"),$={};te.forEach(ce=>{$[ce.configKey]=ce.configValue});const ie=parseInt($.MAX_FILE_SIZE_MB||"10"),fe=($.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(ce=>ce.trim().toLowerCase());_({maxFileSizeMB:ie,allowedFileTypes:fe})}catch(te){console.error("Failed to load document policy:",te)}})()},[]),x.useEffect(()=>{if(!R)return;let U=u;return(async()=>{var te;try{const $=await Xs(u);(te=$==null?void 0:$.workflow)!=null&&te.requestId&&(U=$.workflow.requestId)}catch{}try{const $=pr();r?X(Fe=>Fe.map(qe=>qe.userId===R?{...qe,status:"online"}:qe)):(Ln($,U,R),X(Fe=>Fe.map(qe=>qe.userId===R?{...qe,status:"online"}:qe)));const ie=Fe=>{const Me=(Fe==null?void 0:Fe.note)||Fe;if(!Me)return;const qe=Me.noteId||Me.id;N(Jt=>{if(Jt.some(Ge=>Ge.id===qe))return Jt;const Nt=Me.userName||Me.user_name||"User",fo=Me.userRole||Me.user_role,qr=ge(fo),Du=Me.userId||Me.user_id,Pu={id:qe||String(Date.now()),user:{name:Nt,avatar:Nt.split(" ").map(Ge=>Ge[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:qr},content:Me.message||"",timestamp:Me.createdAt||new Date().toISOString(),isCurrentUser:Du===R,attachments:Array.isArray(Me.attachments)?Me.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,Pu]})},oe=Fe=>{X(Me=>Me.length===0||!Me.find(Nt=>Nt.userId===Fe.userId)?Me:Me.map(Nt=>Nt.userId===Fe.userId?{...Nt,status:"online"}:Nt))},fe=Fe=>{Fe.userId!==R&&X(Me=>Me.length===0||!Me.find(Nt=>Nt.userId===Fe.userId)?Me:Me.map(Nt=>Nt.userId===Fe.userId?{...Nt,status:"offline"}:Nt))},ce=Fe=>{X(Me=>Me.length===0?Me:Me.map(Jt=>{const Nt=Jt.userId||"";if(Nt===R)return{...Jt,status:"online"};const qr=Fe.userIds.includes(Nt);return{...Jt,status:qr?"online":"offline"}}))},Ae=()=>{X(Fe=>Fe.map(qe=>qe.userId===R?{...qe,status:"online"}:qe)),r||Ln($,U,R),H.current&&($.emit("request:online-users",{requestId:U}),setTimeout(()=>$.emit("request:online-users",{requestId:U}),300),setTimeout(()=>$.emit("request:online-users",{requestId:U}),800))},de=Fe=>{console.error("[WorkNoteChat] ❌ Socket error:",Fe)},Ee=Fe=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",Fe),X(Me=>Me.map(qe=>qe.userId===R?qe:{...qe,status:"offline"}))},hs=Fe=>{Fe.includes("presence")||Fe.includes("worknote")||Fe.includes("request")};$.on("connect",Ae),$.on("disconnect",Ee),$.on("error",de),$.on("worknote:new",ie),$.on("presence:join",oe),$.on("presence:leave",fe),$.on("presence:online",ce),$.onAny(hs),D.current=$,$.connected&&H.current&&($.emit("request:online-users",{requestId:U}),setTimeout(()=>{$.emit("request:online-users",{requestId:U})},300),setTimeout(()=>{$.emit("request:online-users",{requestId:U})},800),setTimeout(()=>{$.emit("request:online-users",{requestId:U})},1500));const Ct=()=>{$.off("connect",Ae),$.off("disconnect",Ee),$.off("error",de),$.off("worknote:new",ie),$.off("presence:join",oe),$.off("presence:leave",fe),$.off("presence:online",ce),$.offAny(hs),r||nd($,U),D.current=null};window.__wn_cleanup=Ct}catch{}})(),()=>{var te;try{(te=window.__wn_cleanup)==null||te.call(window)}catch{}}},[u,R,r]);const Ie=async()=>{if(h.trim()||k.length>0){const U=Ca(h),te=U.map(oe=>{const fe=me.find(ce=>ce.name.toLowerCase().includes(oe.toLowerCase()));return fe==null?void 0:fe.userId}).filter(Boolean),$=k.map(oe=>({name:oe.name,url:URL.createObjectURL(oe),type:oe.type.split("/")[1]||"file"})),ie={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:U,isHighPriority:h.includes("!important")||h.includes("urgent"),attachments:$.length>0?$:void 0,isCurrentUser:!0};if(a)try{await a(h,k)}catch{}else try{await ld(u,{message:h,mentions:te},k);const oe=await ha(u),fe=Array.isArray(oe)?oe.map(ce=>{const Ae=ce.userId||ce.user_id;return{id:ce.noteId||ce.id||String(Math.random()),user:{name:ce.userName||"User",avatar:(ce.userName||"U").slice(0,2).toUpperCase(),role:ce.userRole||"Participant"},content:ce.message||"",timestamp:ce.createdAt||new Date().toISOString(),isCurrentUser:Ae===R,attachments:Array.isArray(ce.attachments)?ce.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}}):[];N(fe)}catch{N(oe=>[...oe,ie])}g(""),L([])}};x.useEffect(()=>{if(s&&Array.isArray(s))try{const te=s.filter($=>($.type||"").toLowerCase()!=="sla_warning").map($=>{var oe;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 fe=$.userName||$.user_name||((oe=$.user)==null?void 0:oe.name)||"User",ce=$.userRole||$.user_role,Ae=ge(ce),de=$.userId||$.user_id;return{id:$.noteId||$.note_id||$.id||String(Math.random()),user:{name:fe,avatar:fe.split(" ").map(Ee=>Ee[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ae},content:$.message||$.content||"",timestamp:$.createdAt||$.created_at||$.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray($.attachments)?$.attachments.map(Ee=>({attachmentId:Ee.attachmentId||Ee.attachment_id,name:Ee.fileName||Ee.file_name||Ee.name,fileName:Ee.fileName||Ee.file_name||Ee.name,url:Ee.storageUrl||Ee.storage_url||Ee.url||"#",type:Ee.fileType||Ee.file_type||Ee.type||"file",fileType:Ee.fileType||Ee.file_type||Ee.type||"file",fileSize:Ee.fileSize||Ee.file_size})):void 0,isCurrentUser:de===R}}}).sort(($,ie)=>new Date($.timestamp).getTime()-new Date(ie.timestamp).getTime());N(te)}catch(U){console.error("[WorkNoteChat] Error mapping messages:",U)}else(async()=>{try{const U=await ha(u),te=Array.isArray(U)?U.map($=>{const ie=$.userName||$.user_name||"User",oe=$.userRole||$.user_role,fe=ge(oe),ce=$.userId||$.user_id;return{id:$.noteId||$.note_id||$.id||String(Math.random()),user:{name:ie,avatar:ie.split(" ").map(Ae=>Ae[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:fe},content:$.message||"",timestamp:$.createdAt||$.created_at||new Date().toISOString(),attachments:Array.isArray($.attachments)?$.attachments.map(Ae=>({attachmentId:Ae.attachmentId||Ae.attachment_id,name:Ae.fileName||Ae.file_name||Ae.name,fileName:Ae.fileName||Ae.file_name||Ae.name,url:Ae.storageUrl||Ae.storage_url||Ae.url||"#",type:Ae.fileType||Ae.file_type||Ae.type||"file",fileType:Ae.fileType||Ae.file_type||Ae.type||"file",fileSize:Ae.fileSize||Ae.file_size})):void 0,isCurrentUser:ce===R}}):[];N(te)}catch(U){console.error("[WorkNoteChat] Error loading work notes:",U)}})()},[s,u,me]);const Le=U=>{const te=O.maxFileSizeMB*1024*1024;if(U.size>te)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${O.maxFileSizeMB}MB. Current size: ${(U.size/(1024*1024)).toFixed(2)}MB`};const $=U.name.toLowerCase(),ie=$.substring($.lastIndexOf(".")+1);return O.allowedFileTypes.includes(ie)?{valid:!0}:{valid:!1,reason:`File type "${ie}" is not allowed. Allowed types: ${O.allowedFileTypes.join(", ")}`}},tt=U=>{if(!U.target.files||U.target.files.length===0)return;const te=Array.from(U.target.files),$=[],ie=[];te.forEach(oe=>{const fe=Le(oe);fe.valid?ie.push(oe):$.push({fileName:oe.name,reason:fe.reason||"Unknown validation error"})}),$.length>0&&G({open:!0,errors:$}),ie.length>0&&(L(oe=>[...oe,...ie]),ie.length<te.length?ke.warning(`${ie.length} of ${te.length} file(s) were added. ${$.length} file(s) were rejected.`):ke.success(`${ie.length} file(s) added successfully`)),U.target&&(U.target.value="")},He=U=>{L(te=>te.filter(($,ie)=>ie!==U)),T.current&&(T.current.value="")},Dt=U=>{g(te=>te+U),j(!1)},_e=()=>{var U;(U=T.current)==null||U.click()},wa=async U=>{var te,$;try{await dd(u,U);const ie=await Xs(u),oe=Array.isArray(ie==null?void 0:ie.participants)?ie.participants:[];if(oe.length){const fe=oe.map(ce=>{const Ae=ce.participantType||ce.participant_type||"participant",de=ce.userId||ce.user_id||"",Ee=ce.userName||ce.user_name||ce.userEmail||ce.user_email||"User",hs=ce.userEmail||ce.user_email||"",Ct=Ee.split(" ").map(Fe=>Fe[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Ee,avatar:Ct,role:Ue(Ae),status:"offline",email:hs,lastSeen:void 0,permissions:["read"],userId:de}});X(fe),D.current&&D.current.connected&&D.current.emit("request:online-users",{requestId:u})}q(!1),alert("Spectator added successfully")}catch(ie){throw console.error("Failed to add spectator:",ie),alert((($=(te=ie==null?void 0:ie.response)==null?void 0:te.data)==null?void 0:$.error)||"Failed to add spectator"),ie}},Ns=async(U,te,$)=>{var ie,oe;if(m)await m(U,te,$),F(!1);else try{await cd(u,U,te,$);const fe=await Xs(u),ce=Array.isArray(fe==null?void 0:fe.participants)?fe.participants:[];if(ce.length){const Ae=ce.map(de=>{const Ee=de.participantType||de.participant_type||"participant",hs=de.userId||de.user_id||"",Ct=de.userName||de.user_name||de.userEmail||de.user_email||"User",Fe=de.userEmail||de.user_email||"",Me=Ct.split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Ct,avatar:Me,role:Ue(Ee),status:"offline",email:Fe,lastSeen:void 0,permissions:["read"],userId:hs}});X(Ae),D.current&&D.current.connected&&D.current.emit("request:online-users",{requestId:u})}F(!1),alert(`Approver added successfully at Level ${$} with ${te}h TAT`)}catch(fe){throw console.error("Failed to add approver:",fe),alert(((oe=(ie=fe==null?void 0:fe.response)==null?void 0:ie.data)==null?void 0:oe.error)||"Failed to add approver"),fe}},Mt=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","","","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],Ca=U=>{const te=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,$=[];let ie;for(;(ie=te.exec(U))!==null;)if(ie[1]){const oe=ie.index+ie[0].length,fe=U.slice(oe),ce=U[oe];(fe.startsWith("@")||!ce||/\s|[.,!?;:]|@/.test(ce))&&$.push(ie[1].trim())}return $},zr=U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),Ie())},Hr=(U,te)=>{N($=>$.map(ie=>{if(ie.id===U){const oe=ie.reactions||[],fe=oe.find(ce=>ce.emoji===te);if(fe)if(fe.users.includes("You")){if(fe.users=fe.users.filter(ce=>ce!=="You"),fe.users.length===0)return{...ie,reactions:oe.filter(ce=>ce.emoji!==te)}}else fe.users.push("You");else oe.push({emoji:te,users:["You"]});return{...ie,reactions:oe}}return ie}))};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(js,{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:Y.title}),e.jsx(Q,{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:[B.slice(0,3).map((U,te)=>e.jsx(ft,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(yt,{className:"bg-blue-500 text-white text-xs font-semibold",children:U.avatar})},te)),B.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:["+",B.length-3]})]})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>C(!b),className:"lg:hidden",children:e.jsx(Je,{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(qt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(pe,{placeholder:"Search messages...",value:p,onChange:U=>f(U.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:[ne.map(U=>{const te=U.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${U.isSystem?"justify-center":te?"justify-end":""}`,children:[!U.isSystem&&!te&&e.jsx(ft,{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(yt,{className:`text-white font-semibold text-xs sm:text-sm ${U.user.role==="Initiator"?"bg-green-600":U.user.role==="Current User"?"bg-blue-500":U.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:U.user.avatar})}),e.jsx("div",{className:`${te?"max-w-[70%]":"flex-1"} min-w-0 ${U.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:U.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(Ht,{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:U.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:Gt(U.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${te?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[U.user.name," ",te&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(Q,{variant:"outline",className:"text-xs flex-shrink-0",children:U.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(Re,{className:"w-3 h-3"}),Gt(U.timestamp)]}),U.isHighPriority&&e.jsxs(Q,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(pp,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${te?"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:Qf(U.content)}}),U.attachments&&U.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:U.attachments.map(($,ie)=>{const oe=$.fileSize||$.file_size,fe=$.fileName||$.file_name||$.name,ce=$.fileType||$.file_type||$.type||"",Ae=$.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(Vo,{type:ce})}),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:fe}),oe&&e.jsx("p",{className:"text-xs text-gray-500",children:e0(oe)})]}),Ae&&(()=>{const de=(ce||"").toLowerCase();return de.includes("image")||de.includes("pdf")||de.includes("jpg")||de.includes("jpeg")||de.includes("png")||de.includes("gif")})()&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-purple-100 hover:text-purple-600",onClick:de=>{de.preventDefault(),de.stopPropagation();const Ee=Hg(Ae);A({fileName:fe,fileType:ce,fileUrl:Ee,fileSize:oe,attachmentId:Ae})},title:"Preview file",children:e.jsx(bt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-blue-100 hover:text-blue-600",onClick:async de=>{if(de.preventDefault(),de.stopPropagation(),!Ae){alert("Cannot download: Attachment ID missing");return}try{await _o(Ae)}catch{alert("Failed to download file")}},title:"Download file",children:e.jsx(ts,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},ie)})})}),U.reactions&&U.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:[U.reactions.map(($,ie)=>e.jsxs("button",{onClick:()=>Hr(U.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})]},ie)),e.jsx(E,{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(Es,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!U.isSystem&&te&&e.jsx(ft,{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(yt,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:U.user.avatar})})]},U.id)}),e.jsx("div",{ref:S})]})}),e.jsx("div",{className:"bg-white border-t border-gray-200 p-2 sm:p-3 lg:p-6 flex-shrink-0",children:e.jsxs("div",{className:"max-w-full",children:[e.jsx("input",{type:"file",ref:T,onChange:tt,className:"hidden",multiple:!0,accept:O.allowedFileTypes.map(U=>`.${U}`).join(",")}),k.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:k.map((U,te)=>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(Vo,{type:U.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:U.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(U.size/1024).toFixed(1)," KB"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>He(te),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(dt,{className:"h-3 w-3 text-red-600"})})]},te))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const U=h.lastIndexOf("@"),te=U>=0;if(!te)return null;const $=h.slice(U+1),ie=$.trim(),oe=$.endsWith(" "),fe=ie.length>0,ce=ie.includes(" ")&&!oe,Ae=oe&&fe;if(!(te&&$.length<=20&&!ce&&!Ae))return null;const Ee=ie.toLowerCase(),hs=me.filter(Ct=>Ct.userId===R?!1:Ee?Ct.name.toLowerCase().includes(Ee):!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((Ct,Fe)=>e.jsxs("button",{type:"button",onClick:Me=>{Me.preventDefault(),Me.stopPropagation();const qe=h.lastIndexOf("@"),Jt=h.slice(0,qe);g(Jt+"@"+Ct.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(ft,{className:"h-10 w-10",children:e.jsx(yt,{className:`text-white text-sm font-semibold ${Ct.role==="Initiator"?"bg-green-600":Ct.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:Ct.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:Ct.name}),e.jsx("p",{className:"text-xs text-gray-600",children:Ct.role})]})]},Fe)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:Ee?`No participants found matching "${Ee}"`:"No other participants available"})})]})})(),e.jsx(us,{placeholder:"Type your message... Use @username to mention someone",value:h,onChange:U=>g(U.target.value),onKeyPress:zr,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(E,{variant:"ghost",size:"sm",onClick:()=>j(!1),className:"h-6 w-6 p-0",children:e.jsx(dt,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:Mt.map((U,te)=>e.jsx("button",{onClick:()=>Dt(U),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:U,children:U},te))})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-shrink-0",children:[e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:_e,title:"Attach file",children:e.jsx(Sr,{className:"h-4 w-4"})}),e.jsx(E,{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(xp,{className:"h-4 w-4"})}),e.jsx(E,{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:()=>g(U=>U+"@"),title:"Mention someone",children:e.jsx(xi,{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(E,{onClick:Ie,disabled:!h.trim()&&k.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(gp,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),b&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>C(!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
${b?"fixed right-0 top-0 bottom-0 z-50 shadow-xl":"hidden lg:flex"}
`,children:[e.jsxs("div",{className:"p-4 sm:p-6 border-b border-gray-200 flex-1 flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900",children:"Participants"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>C(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(dt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:me.map((U,te)=>{const $=U.userId===R;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ft,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(yt,{className:`text-white font-semibold text-sm ${U.role==="Initiator"?"bg-green-600":$?"bg-blue-500":"bg-slate-600"}`,children:U.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${Xf(U.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:[U.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:U.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:Jf(U.status)})]}),U.lastSeen&&U.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:U.lastSeen})]})]},te)})})]}),!V&&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(E,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>F(!0),children:[e.jsx(Ar,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>q(!0),children:[e.jsx(bt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),w&&e.jsx(wi,{fileName:w.fileName,fileType:w.fileType,fileUrl:w.fileUrl,fileSize:w.fileSize,attachmentId:w.attachmentId,onDownload:_o,open:!!w,onClose:()=>A(null)}),!V&&e.jsx(yd,{open:P,onClose:()=>q(!1),onConfirm:wa,requestIdDisplay:u,requestTitle:Y.title,existingParticipants:re}),!V&&o&&e.jsx(vd,{open:M,onClose:()=>F(!1),onConfirm:Ns,requestIdDisplay:u,requestTitle:Y.title,existingParticipants:re,currentLevels:c}),e.jsx(mt,{open:ee.open,onOpenChange:U=>G(te=>({...te,open:U})),children:e.jsxs(nt,{className:"sm:max-w-lg",children:[e.jsxs(ut,{children:[e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Pe,{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:ee.errors.map((U,te)=>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:U.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:U.reason})]},te))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",O.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",O.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Rt,{children:e.jsx(E,{onClick:()=>G({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}function t0({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(bd,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:o,onAddApprover:l})})}function s0({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(se,{className:"pb-2",children:e.jsx(ae,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(K,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:n,"data-testid":"add-approver-button",children:[e.jsx(Ar,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:i,"data-testid":"add-spectator-button",children:[e.jsx(bt,{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(E,{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(ye,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(E,{variant:"destructive",className:"w-full h-9 sm:h-10 text-xs sm:text-sm",onClick:l,"data-testid":"reject-request-button",children:[e.jsx(Ze,{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(se,{className:"pb-2",children:e.jsx(ae,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(K,{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(ft,{className:"h-8 w-8",children:e.jsx(yt,{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 a0({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:o}){const[l,c]=x.useState(r),[m,d]=x.useState(!1),u=(l==null?void 0:l.length)||0,h=x.useMemo(()=>l.slice(0,500),[l]),g=async()=>{try{d(!0),await a(h),s()}finally{d(!1)}};return e.jsx(mt,{open:t,onOpenChange:p=>!p&&s(),children:e.jsxs(nt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ut,{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(ye,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(it,{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(Q,{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(ye,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Approval Confirmation"}),e.jsx("div",{children:"This request will be forwarded to the next approver or completed if this is the final step."})]})]}),e.jsxs(Rt,{className:"mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:m,children:"Cancel"}),e.jsxs(E,{onClick:g,disabled:m,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(ye,{className:"w-4 h-4 mr-2"}),m?"Approving...":"Approve Request"]})]})]})})}function r0({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:o}){const[l,c]=x.useState(r),[m,d]=x.useState(!1),u=(l==null?void 0:l.length)||0,h=x.useMemo(()=>l.slice(0,500),[l]),g=async()=>{if(!h.trim()){alert("Comments & remarks are required");return}try{d(!0),await a(h),s()}finally{d(!1)}};return e.jsx(mt,{open:t,onOpenChange:p=>!p&&s(),children:e.jsxs(nt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ut,{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(Ze,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(it,{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(Q,{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(Pe,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Rejection Guidelines"}),e.jsx("div",{children:"Please provide specific, actionable feedback to help the initiator improve their request."})]})]}),e.jsxs(Rt,{className:"mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:m,children:"Cancel"}),e.jsxs(E,{variant:"destructive",onClick:g,disabled:m,children:[e.jsx(Ze,{className:"w-4 h-4 mr-2"}),m?"Rejecting...":"Reject Request"]})]})]})})}function n0({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:o}){const[l,c]=x.useState(""),[m,d]=x.useState(!1),u=async()=>{if(l.trim())try{d(!0),await a(l.trim()),c(""),s()}catch(g){console.error("Failed to skip approver:",g)}finally{d(!1)}},h=()=>{m||(c(""),s())};return e.jsx(mt,{open:t,onOpenChange:h,children:e.jsxs(nt,{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(dt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ut,{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(Pe,{className:"w-5 h-5 text-orange-600"})}),e.jsx(it,{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(Pe,{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(J,{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(J,{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(J,{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:g=>c(g.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(E,{type:"button",variant:"outline",onClick:h,className:"flex-1 h-11 border-gray-300",disabled:m,children:"Cancel"}),e.jsxs(E,{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(Pe,{className:"w-4 h-4 mr-2"}),m?"Skipping...":"Skip Approver"]})]})]})})}function i0({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(nt,{className:"sm:max-w-md",children:[e.jsx(ut,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[a?e.jsx(ye,{className:"w-5 h-5 text-green-600"}):e.jsx(Pe,{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(ye,{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(Ze,{className:"w-8 h-8 text-red-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation failed. Please try again."})]})})}),e.jsx(Rt,{children:e.jsx(E,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function o0({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:g,setShowRejectModal:p,setShowAddApproverModal:f,setShowAddSpectatorModal:v,setShowSkipApproverModal:j,setShowActionStatusModal:y,setPreviewDocument:N,setDocumentError:b,setSkipApproverData:C,setActionStatus:k,handleApproveConfirm:L,handleRejectConfirm:R,handleAddApprover:I,handleAddSpectator:w,handleSkipApprover:A,downloadDocument:P,documentPolicy:q}){return e.jsxs(e.Fragment,{children:[e.jsx(a0,{open:t,onClose:()=>g(!1),onConfirm:L,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(r0,{open:s,onClose:()=>p(!1),onConfirm:R,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(vd,{open:a,onClose:()=>f(!1),onConfirm:I,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u,currentLevels:h}),e.jsx(yd,{open:r,onClose:()=>v(!1),onConfirm:w,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u}),e.jsx(n0,{open:n,onClose:()=>{j(!1),C(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(wi,{fileName:o.fileName,fileType:o.fileType,fileUrl:md(o.documentId),fileSize:o.fileSize,attachmentId:o.documentId,onDownload:P,open:!!o,onClose:()=>N(null)}),d&&e.jsx(i0,{open:i,onClose:()=>{y(!1),k(null)},success:d.success,title:d.title,message:d.message}),e.jsx(mt,{open:l.show,onOpenChange:M=>b(F=>({...F,show:M})),children:e.jsxs(nt,{className:"sm:max-w-lg",children:[e.jsxs(ut,{children:[e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Pe,{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((M,F)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:M.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:M.reason})]},F))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",q.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",q.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Rt,{children:e.jsx(E,{onClick:()=>b({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}class l0 extends x.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("RequestDetail 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(E,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(E,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function c0({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=Wa().requestId||t||"",o=new URLSearchParams(window.location.search).get("tab")||"overview",[l,c]=x.useState(o),[m,d]=x.useState(!1),[u,h]=x.useState(null),{user:g}=$t(),{request:p,apiRequest:f,refreshing:v,refreshDetails:j,currentApprovalLevel:y,isSpectator:N,isInitiator:b,existingParticipants:C}=xf(n,a,g),{mergedMessages:k,unreadWorkNotes:L,workNoteAttachments:R,setWorkNoteAttachments:I}=gf(n,f,l,g),{uploadingDocument:w,triggerFileInput:A,previewDocument:P,setPreviewDocument:q,documentPolicy:M,documentError:F,setDocumentError:S}=wf(f,j),{showApproveModal:T,setShowApproveModal:D,showRejectModal:H,setShowRejectModal:O,showAddApproverModal:_,setShowAddApproverModal:ee,showAddSpectatorModal:G,setShowAddSpectatorModal:Y,showSkipApproverModal:me,setShowSkipApproverModal:X,showActionStatusModal:B,setShowActionStatusModal:ne,skipApproverData:V,setSkipApproverData:Z,actionStatus:re,setActionStatus:ge,handleApproveConfirm:ve,handleRejectConfirm:Ue,handleAddApprover:Ie,handleSkipApprover:Le,handleAddSpectator:tt}=Tf(n,y,j),{conclusionRemark:He,setConclusionRemark:Dt,conclusionLoading:_e,conclusionSubmitting:wa,aiGenerated:Ns,handleGenerateConclusion:Mt,handleFinalizeConclusion:Ca}=Af(p,n,b,j,s,ge,ne);x.useEffect(()=>{const ie=new URLSearchParams(window.location.search).get("tab");ie&&c(ie)},[n]);const zr=()=>{j()},Hr=async()=>{var $,ie,oe,fe,ce,Ae;if(!(f!=null&&f.requestId)){ke.error("Request ID not found");return}try{let de=u;de||(de=(await If(f.requestId)).summaryId,h(de)),d(!0)}catch(de){console.error("Failed to create/get summary:",de),(($=de==null?void 0:de.response)==null?void 0:$.status)===400&&((fe=(oe=(ie=de==null?void 0:de.response)==null?void 0:ie.data)==null?void 0:oe.message)!=null&&fe.includes("already exists"))?ke.error("Summary already exists. Please refresh the page."):ke.error(((Ae=(ce=de==null?void 0:de.response)==null?void 0:ce.data)==null?void 0:Ae.message)||"Failed to prepare summary for sharing")}},U=(p==null?void 0:p.status)==="approved"&&b,te=((p==null?void 0:p.approvalFlow)||[]).filter($=>$&&typeof $.step=="number").map($=>({levelNumber:$.step||0,approverName:$.approver||"Unknown",status:$.status||"pending",tatHours:$.tatHours||24}));return!p&&!f?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..."})]})}):p?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(Ef,{request:p,refreshing:v,onBack:s||(()=>window.history.back()),onRefresh:zr,onShareSummary:Hr,isInitiator:b}),e.jsxs(Ir,{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(Fr,{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(ht,{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(vp,{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(ht,{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(Ls,{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(ht,{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(Te,{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(ht,{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(Ht,{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(ht,{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(js,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),L>0&&e.jsx(Q,{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:L>9?"9+":L})]})]})}),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(pt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(Hf,{request:p,isInitiator:b,needsClosure:U,conclusionRemark:He,setConclusionRemark:Dt,conclusionLoading:_e,conclusionSubmitting:wa,aiGenerated:Ns,handleGenerateConclusion:Mt,handleFinalizeConclusion:Ca})}),e.jsx(pt,{value:"workflow",className:"mt-0",children:e.jsx(Kf,{request:p,user:g,isInitiator:b,onSkipApprover:$=>{if(!$.levelId){alert("Level ID not available");return}Z($),X(!0)},onRefresh:j})}),e.jsx(pt,{value:"documents",className:"mt-0",children:e.jsx(Yf,{request:p,workNoteAttachments:R,uploadingDocument:w,documentPolicy:M,triggerFileInput:A,setPreviewDocument:q,downloadDocument:_n})}),e.jsx(pt,{value:"activity",className:"mt-0",children:e.jsx(Zf,{request:p})}),e.jsx(pt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:l!=="worknotes",children:e.jsx(t0,{requestId:n,requestTitle:p.title,mergedMessages:k,setWorkNoteAttachments:I,isInitiator:b,isSpectator:N,currentLevels:te,onAddApprover:Ie})})]}),l!=="worknotes"&&e.jsx(s0,{request:p,isInitiator:b,isSpectator:N,currentApprovalLevel:y,onAddApprover:()=>ee(!0),onAddSpectator:()=>Y(!0),onApprove:()=>D(!0),onReject:()=>O(!0)})]})]})]})}),m&&u&&e.jsx(zf,{isOpen:m,onClose:()=>d(!1),summaryId:u,requestTitle:(p==null?void 0:p.title)||"N/A",onSuccess:()=>{j()}}),e.jsx(o0,{showApproveModal:T,showRejectModal:H,showAddApproverModal:_,showAddSpectatorModal:G,showSkipApproverModal:me,showActionStatusModal:B,previewDocument:P,documentError:F,request:p,skipApproverData:V,actionStatus:re,existingParticipants:C,currentLevels:te,setShowApproveModal:D,setShowRejectModal:O,setShowAddApproverModal:ee,setShowAddSpectatorModal:Y,setShowSkipApproverModal:X,setShowActionStatusModal:ne,setPreviewDocument:q,setDocumentError:S,setSkipApproverData:Z,setActionStatus:ge,handleApproveConfirm:ve,handleRejectConfirm:Ue,handleAddApprover:Ie,handleAddSpectator:tt,handleSkipApprover:Le,downloadDocument:_n,documentPolicy:M})]}):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(E,{onClick:s,children:"Go Back"})]})})}function d0(t){return e.jsx(l0,{children:e.jsx(c0,{...t})})}function m0({onViewSummary:t}){const s=Os(),[a,r]=x.useState([]),[n,i]=x.useState(!0),[o,l]=x.useState(""),[c,m]=x.useState(1),[d,u]=x.useState(1),[h,g]=x.useState(0),p=10,f=x.useCallback(async(N=1)=>{try{i(!0);const b=await _f({page:N,limit:p});r(b.data||[]),u(b.pagination.totalPages||1),g(b.pagination.total||0),m(b.pagination.page||1)}catch(b){console.error("Failed to fetch shared summaries:",b),ke.error("Failed to load shared summaries")}finally{i(!1)}},[]);x.useEffect(()=>{f(1)},[f]);const v=async N=>{try{await gd(N),r(b=>b.map(C=>C.sharedSummaryId===N?{...C,isRead:!0,viewedAt:new Date().toISOString()}:C)),t?t(N):s(`/shared-summaries/${N}`)}catch(b){console.error("Failed to mark as viewed:",b),t?t(N):s(`/shared-summaries/${N}`)}},j=N=>{N>=1&&N<=d&&f(N)},y=a.filter(N=>{var C,k,L,R;if(!o)return!0;const b=o.toLowerCase();return((C=N.title)==null?void 0:C.toLowerCase().includes(b))||((k=N.requestNumber)==null?void 0:k.toLowerCase().includes(b))||((L=N.initiatorName)==null?void 0:L.toLowerCase().includes(b))||((R=N.sharedByName)==null?void 0:R.toLowerCase().includes(b))});return e.jsx("div",{className:"min-h-screen bg-gray-50 p-4 sm:p-6",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-2",children:"Shared Summaries"}),e.jsx("p",{className:"text-sm text-gray-600",children:"View summaries of closed requests shared with you"})]}),e.jsx("div",{className:"mb-6",children:e.jsxs("div",{className:"relative",children:[e.jsx(qt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(pe,{placeholder:"Search by title, request number, or user...",value:o,onChange:N=>l(N.target.value),className:"pl-10"})]})}),n&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx($e,{className:"h-8 w-8 animate-spin text-blue-600"})}),!n&&y.length===0&&e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center",children:[e.jsx(Te,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"No shared summaries"}),e.jsx("p",{className:"text-gray-600",children:o?"No summaries match your search.":"You haven't received any shared summaries yet."})]}),!n&&y.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-4 mb-6",children:y.map(N=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${N.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>v(N.sharedSummaryId),children:e.jsx("div",{className:"p-4 sm:p-6",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-2 mb-2",children:[N.isRead?e.jsx(ir,{className:"h-4 w-4 text-gray-400"}):e.jsx(bt,{className:"h-4 w-4 text-blue-600"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 truncate",children:N.title}),!N.isRead&&e.jsx("span",{className:"px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded-full",children:"New"})]}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Request: ",e.jsx("span",{className:"font-medium",children:N.requestNumber})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(rt,{className:"h-4 w-4"}),e.jsxs("span",{children:["Initiator: ",N.initiatorName]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(rt,{className:"h-4 w-4"}),e.jsxs("span",{children:["Shared by: ",N.sharedByName]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Be,{className:"h-4 w-4"}),e.jsxs("span",{children:["Shared: ",xe(new Date(N.sharedAt),"MMM dd, yyyy HH:mm")]})]}),N.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(bt,{className:"h-4 w-4"}),e.jsxs("span",{children:["Viewed: ",xe(new Date(N.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:b=>{b.stopPropagation(),v(N.sharedSummaryId)},children:"View"})]})})},N.sharedSummaryId))}),d>1&&e.jsxs("div",{className:"flex items-center justify-between bg-white rounded-lg shadow-sm border border-gray-200 p-4",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(c-1)*p+1," to ",Math.min(c*p,h)," of ",h," summaries"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>j(c-1),disabled:c===1,children:"Previous"}),e.jsxs("span",{className:"text-sm text-gray-600",children:["Page ",c," of ",d]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>j(c+1),disabled:c===d,children:"Next"})]})]})]})]})})}function u0(){const{sharedSummaryId:t}=Wa(),s=Os(),[a,r]=x.useState(null),[n,i]=x.useState(!0);x.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var d,u;try{i(!0);try{await gd(t)}catch(g){console.warn("Failed to mark as viewed:",g)}const h=await Ff(t);r(h)}catch(h){console.error("Failed to fetch summary details:",h),ke.error(((u=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:u.message)||"Failed to load summary"),s("/shared-summaries")}finally{i(!1)}})()},[t,s]);const o=m=>{const d=m.toLowerCase();return d==="approved"?e.jsx(ye,{className:"h-4 w-4 text-green-600"}):d==="rejected"?e.jsx(Ze,{className:"h-4 w-4 text-red-600"}):d==="pending"||d==="in progress"?e.jsx(Re,{className:"h-4 w-4 text-orange-600"}):e.jsx(Te,{className:"h-4 w-4 text-gray-600"})},l=m=>{const d=m.toLowerCase();return d==="approved"?"bg-green-100 text-green-700 border-green-300":d==="rejected"?"bg-red-100 text-red-700 border-red-300":d==="pending"||d==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},c=(m,d)=>m&&m.trim()&&m.trim().toUpperCase()!=="N/A"?m:d&&d.trim()&&d.trim().toUpperCase()!=="N/A"?d:"N/A";return n?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx($e,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):a?e.jsx("div",{className:"min-h-screen bg-gray-50 p-4 sm:p-6",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs(E,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(Ms,{className:"h-4 w-4 mr-2"}),"Back to Shared Summaries"]}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-2",children:"Request Summary"})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 mb-6",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:a.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",a.requestNumber]})]}),e.jsxs(Q,{className:l(a.workflow.status),children:[o(a.workflow.status),e.jsx("span",{className:"ml-1 capitalize",children:a.workflow.status})]})]}),a.description&&e.jsx("p",{className:"text-gray-700 mb-4",children:a.description})]}),e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Initiator"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:xe(new Date(a.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),a.approvers&&a.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),a.approvers.map((m,d)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsxs("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:["Approver ",m.levelNumber]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:m.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(m.designation,m.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[o(m.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:m.status})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:xe(new Date(m.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:m.remarks})]})]},d))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),a.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(Q,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700 whitespace-pre-wrap",children:a.closingRemarks||"—"})]})]})]})]})]})}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Te,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Summary Not Found"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"The summary you're looking for doesn't exist."}),e.jsx(E,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function h0(){const{requestId:t}=Wa(),s=Os(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(St,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(bd,{requestId:t||""})})})}const Ci=x.createContext({});function Si(t){const s=x.useRef(null);return s.current===null&&(s.current=t()),s.current}const Ai=typeof window<"u",jd=Ai?x.useLayoutEffect:x.useEffect,_r=x.createContext(null);function Ti(t,s){t.indexOf(s)===-1&&t.push(s)}function ki(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const vs=(t,s,a)=>a>s?s:a<t?t:a;let Ri=()=>{};const bs={},Nd=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function wd(t){return typeof t=="object"&&t!==null}const Cd=t=>/^0[^.\s]+$/u.test(t);function Di(t){let s;return()=>(s===void 0&&(s=t()),s)}const Zt=t=>t,p0=(t,s)=>a=>s(t(a)),Ka=(...t)=>t.reduce(p0),$a=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class Pi{constructor(){this.subscriptions=[]}add(s){return Ti(this.subscriptions,s),()=>ki(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 is=t=>t*1e3,Yt=t=>t/1e3;function Sd(t,s){return s?t*(1e3/s):0}const Ad=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,x0=1e-7,g0=12;function f0(t,s,a,r,n){let i,o,l=0;do o=s+(a-s)/2,i=Ad(o,r,n)-t,i>0?a=o:s=o;while(Math.abs(i)>x0&&++l<g0);return o}function Ga(t,s,a,r){if(t===s&&a===r)return Zt;const n=i=>f0(i,0,1,t,a);return i=>i===0||i===1?i:Ad(n(i),s,r)}const Td=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,kd=t=>s=>1-t(1-s),Rd=Ga(.33,1.53,.69,.99),Ei=kd(Rd),Dd=Td(Ei),Pd=t=>(t*=2)<1?.5*Ei(t):.5*(2-Math.pow(2,-10*(t-1))),Mi=t=>1-Math.sin(Math.acos(t)),Ed=kd(Mi),Md=Td(Mi),y0=Ga(.42,0,1,1),v0=Ga(0,0,.58,1),Id=Ga(.42,0,.58,1),b0=t=>Array.isArray(t)&&typeof t[0]!="number",Fd=t=>Array.isArray(t)&&typeof t[0]=="number",j0={linear:Zt,easeIn:y0,easeInOut:Id,easeOut:v0,circIn:Mi,circInOut:Md,circOut:Ed,backIn:Ei,backInOut:Dd,backOut:Rd,anticipate:Pd},N0=t=>typeof t=="string",Bo=t=>{if(Fd(t)){Ri(t.length===4);const[s,a,r,n]=t;return Ga(s,a,r,n)}else if(N0(t))return j0[t];return t},sr=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function w0(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 C0=40;function Ld(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,o=sr.reduce((N,b)=>(N[b]=w0(i),N),{}),{setup:l,read:c,resolveKeyframes:m,preUpdate:d,update:u,preRender:h,render:g,postRender:p}=o,f=()=>{const N=bs.useManualTiming?n.timestamp:performance.now();a=!1,bs.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(N-n.timestamp,C0),1)),n.timestamp=N,n.isProcessing=!0,l.process(n),c.process(n),m.process(n),d.process(n),u.process(n),h.process(n),g.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((N,b)=>{const C=o[b];return N[b]=(k,L=!1,R=!1)=>(a||v(),C.schedule(k,L,R)),N},{}),cancel:N=>{for(let b=0;b<sr.length;b++)o[sr[b]].cancel(N)},state:n,steps:o}}const{schedule:Ke,cancel:Is,state:wt,steps:rn}=Ld(typeof requestAnimationFrame<"u"?requestAnimationFrame:Zt,!0);let lr;function S0(){lr=void 0}const _t={now:()=>(lr===void 0&&_t.set(wt.isProcessing||bs.useManualTiming?wt.timestamp:performance.now()),lr),set:t=>{lr=t,queueMicrotask(S0)}},_d=t=>s=>typeof s=="string"&&s.startsWith(t),Ii=_d("--"),A0=_d("var(--"),Fi=t=>A0(t)?T0.test(t.split("/*")[0].trim()):!1,T0=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,ba={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Ua={...ba,transform:t=>vs(0,1,t)},ar={...ba,default:1},Ea=t=>Math.round(t*1e5)/1e5,Li=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function k0(t){return t==null}const R0=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,_i=(t,s)=>a=>!!(typeof a=="string"&&R0.test(a)&&a.startsWith(t)||s&&!k0(a)&&Object.prototype.hasOwnProperty.call(a,s)),Od=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,o,l]=r.match(Li);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(o),alpha:l!==void 0?parseFloat(l):1}},D0=t=>vs(0,255,t),nn={...ba,transform:t=>Math.round(D0(t))},Js={test:_i("rgb","red"),parse:Od("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+nn.transform(t)+", "+nn.transform(s)+", "+nn.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 On={test:_i("#"),parse:P0,transform:Js.transform},Ya=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),ks=Ya("deg"),os=Ya("%"),be=Ya("px"),E0=Ya("vh"),M0=Ya("vw"),zo={...os,parse:t=>os.parse(t)/100,transform:t=>os.transform(t*100)},oa={test:_i("hsl","hue"),parse:Od("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+os.transform(Ea(s))+", "+os.transform(Ea(a))+", "+Ea(Ua.transform(r))+")"},lt={test:t=>Js.test(t)||On.test(t)||oa.test(t),parse:t=>Js.test(t)?Js.parse(t):oa.test(t)?oa.parse(t):On.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Js.transform(t):oa.transform(t),getAnimatableNone:t=>{const s=lt.parse(t);return s.alpha=0,lt.transform(s)}},I0=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function F0(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(Li))==null?void 0:s.length)||0)+(((a=t.match(I0))==null?void 0:a.length)||0)>0}const $d="number",Ud="color",L0="var",_0="var(",Ho="${}",O0=/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(O0,c=>(lt.test(c)?(r.color.push(i),n.push(Ud),a.push(lt.parse(c))):c.startsWith(_0)?(r.var.push(i),n.push(L0),a.push(c)):(r.number.push(i),n.push($d),a.push(parseFloat(c))),++i,Ho)).split(Ho);return{values:a,split:l,indexes:r,types:n}}function Vd(t){return Va(t).values}function Bd(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===$d?i+=Ea(n[o]):l===Ud?i+=lt.transform(n[o]):i+=n[o]}return i}}const $0=t=>typeof t=="number"?0:lt.test(t)?lt.getAnimatableNone(t):t;function U0(t){const s=Vd(t);return Bd(t)(s.map($0))}const Fs={test:F0,parse:Vd,createTransformer:Bd,getAnimatableNone:U0};function on(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 V0({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=on(c,l,t+1/3),i=on(c,l,t),o=on(c,l,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(o*255),alpha:r}}function xr(t,s){return a=>a>0?s:t}const Ye=(t,s,a)=>t+(s-t)*a,ln=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},B0=[On,Js,oa],z0=t=>B0.find(s=>s.test(t));function qo(t){const s=z0(t);if(!s)return!1;let a=s.parse(t);return s===oa&&(a=V0(a)),a}const Wo=(t,s)=>{const a=qo(t),r=qo(s);if(!a||!r)return xr(t,s);const n={...a};return i=>(n.red=ln(a.red,r.red,i),n.green=ln(a.green,r.green,i),n.blue=ln(a.blue,r.blue,i),n.alpha=Ye(a.alpha,r.alpha,i),Js.transform(n))},$n=new Set(["none","hidden"]);function H0(t,s){return $n.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function q0(t,s){return a=>Ye(t,s,a)}function Oi(t){return typeof t=="number"?q0:typeof t=="string"?Fi(t)?xr:lt.test(t)?Wo:G0:Array.isArray(t)?zd:typeof t=="object"?lt.test(t)?Wo:W0:xr}function zd(t,s){const a=[...t],r=a.length,n=t.map((i,o)=>Oi(i)(i,s[o]));return i=>{for(let o=0;o<r;o++)a[o]=n[o](i);return a}}function W0(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=Oi(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function K0(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 G0=(t,s)=>{const a=Fs.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?$n.has(t)&&!n.values.length||$n.has(s)&&!r.values.length?H0(t,s):Ka(zd(K0(r,n),n.values),a):xr(t,s)};function Hd(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?Ye(t,s,a):Oi(t)(t,s)}const Y0=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>Ke.update(s,a),stop:()=>Is(s),now:()=>wt.isProcessing?wt.timestamp:_t.now()}},qd=(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)})`},gr=2e4;function $i(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<gr;)s+=a,r=t.next(s);return s>=gr?1/0:s}function Z0(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min($i(r),gr);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:Yt(n)}}const X0=5;function Wd(t,s,a){const r=Math.max(s-X0,0);return Sd(a-t(r),s-r)}const Xe={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},cn=.001;function J0({duration:t=Xe.duration,bounce:s=Xe.bounce,velocity:a=Xe.velocity,mass:r=Xe.mass}){let n,i,o=1-s;o=vs(Xe.minDamping,Xe.maxDamping,o),t=vs(Xe.minDuration,Xe.maxDuration,Yt(t)),o<1?(n=m=>{const d=m*o,u=d*t,h=d-a,g=Un(m,o),p=Math.exp(-u);return cn-h/g*p},i=m=>{const u=m*o*t,h=u*a+a,g=Math.pow(o,2)*Math.pow(m,2)*t,p=Math.exp(-u),f=Un(Math.pow(m,2),o);return(-n(m)+cn>0?-1:1)*((h-g)*p)/f}):(n=m=>{const d=Math.exp(-m*t),u=(m-a)*t+1;return-cn+d*u},i=m=>{const d=Math.exp(-m*t),u=(a-m)*(t*t);return d*u});const l=5/t,c=ey(n,i,l);if(t=is(t),isNaN(c))return{stiffness:Xe.stiffness,damping:Xe.damping,duration:t};{const m=Math.pow(c,2)*r;return{stiffness:m,damping:o*2*Math.sqrt(r*m),duration:t}}}const Q0=12;function ey(t,s,a){let r=a;for(let n=1;n<Q0;n++)r=r-t(r)/s(r);return r}function Un(t,s){return t*Math.sqrt(1-s*s)}const ty=["duration","bounce"],sy=["stiffness","damping","mass"];function Ko(t,s){return s.some(a=>t[a]!==void 0)}function ay(t){let s={velocity:Xe.velocity,stiffness:Xe.stiffness,damping:Xe.damping,mass:Xe.mass,isResolvedFromDuration:!1,...t};if(!Ko(t,sy)&&Ko(t,ty))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*vs(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:Xe.mass,stiffness:n,damping:i}}else{const a=J0(t);s={...s,...a,mass:Xe.mass},s.isResolvedFromDuration=!0}return s}function fr(t=Xe.visualDuration,s=Xe.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:g}=ay({...a,velocity:-Yt(a.velocity||0)}),p=h||0,f=m/(2*Math.sqrt(c*d)),v=o-i,j=Yt(Math.sqrt(c/d)),y=Math.abs(v)<5;r||(r=y?Xe.restSpeed.granular:Xe.restSpeed.default),n||(n=y?Xe.restDelta.granular:Xe.restDelta.default);let N;if(f<1){const C=Un(j,f);N=k=>{const L=Math.exp(-f*j*k);return o-L*((p+f*j*v)/C*Math.sin(C*k)+v*Math.cos(C*k))}}else if(f===1)N=C=>o-Math.exp(-j*C)*(v+(p+j*v)*C);else{const C=j*Math.sqrt(f*f-1);N=k=>{const L=Math.exp(-f*j*k),R=Math.min(C*k,300);return o-L*((p+f*j*v)*Math.sinh(R)+C*v*Math.cosh(R))/C}}const b={calculatedDuration:g&&u||null,next:C=>{const k=N(C);if(g)l.done=C>=u;else{let L=C===0?p:0;f<1&&(L=C===0?is(p):Wd(N,C,k));const R=Math.abs(L)<=r,I=Math.abs(o-k)<=n;l.done=R&&I}return l.value=l.done?o:k,l},toString:()=>{const C=Math.min($i(b),gr),k=qd(L=>b.next(C*L).value,C,30);return C+"ms "+k},toTransition:()=>{}};return b}fr.applyToOptions=t=>{const s=Z0(t,100,fr);return t.ease=s.ease,t.duration=is(s.duration),t.type="keyframes",t};function Vn({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},g=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),N=R=>j+y(R),b=R=>{const I=y(R),w=N(R);h.done=Math.abs(I)<=m,h.value=h.done?j:w};let C,k;const L=R=>{g(h.value)&&(C=R,k=fr({keyframes:[h.value,p(h.value)],velocity:Wd(N,R,h.value),damping:n,stiffness:i,restDelta:m,restSpeed:d}))};return L(0),{calculatedDuration:null,next:R=>{let I=!1;return!k&&C===void 0&&(I=!0,b(R),L(R)),C!==void 0&&R>=C?k.next(R-C):(!I&&b(R),h)}}}function ry(t,s,a){const r=[],n=a||bs.mix||Hd,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]||Zt:s;l=Ka(c,l)}r.push(l)}return r}function ny(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(Ri(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=ry(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(vs(t[0],t[i-1],d)):m}function iy(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 oy(t){const s=[0];return iy(s,t.length-1),s}function ly(t,s){return t.map(a=>a*s)}function cy(t,s){return t.map(()=>s||Id).splice(0,t.length-1)}function Ma({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=b0(r)?r.map(Bo):Bo(r),i={done:!1,value:s[0]},o=ly(a&&a.length===s.length?a:oy(s),t),l=ny(o,s,{ease:Array.isArray(n)?n:cy(s,n)});return{calculatedDuration:t,next:c=>(i.value=l(c),i.done=c>=t,i)}}const dy=t=>t!==null;function Ui(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(dy),l=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!l||r===void 0?i[l]:r}const my={decay:Vn,inertia:Vn,tween:Ma,keyframes:Ma,spring:fr};function Kd(t){typeof t.type=="string"&&(t.type=my[t.type])}class Vi{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 uy=t=>t/100;class Bi extends Vi{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;Kd(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=Ka(uy,Hd(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=$i(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:g,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 N=this.currentTime,b=r;if(u){const R=Math.min(this.currentTime,n)/l;let I=Math.floor(R),w=R%1;!w&&R>=1&&(w=1),w===1&&I--,I=Math.min(I,u+1),!!(I%2)&&(h==="reverse"?(w=1-w,g&&(w-=g/l)):h==="mirror"&&(b=o)),N=vs(0,1,w)*l}const C=y?{done:!1,value:d[0]}:b.next(N);i&&(C.value=i(C.value));let{done:k}=C;!y&&c!==null&&(k=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const L=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&k);return L&&p!==Vn&&(C.value=Ui(d,this.options,v,this.speed)),f&&f(C.value),L&&this.finish(),C}then(s,a){return this.finished.then(s,a)}get duration(){return Yt(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+Yt(s)}get time(){return Yt(this.currentTime)}set time(s){var a;s=is(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=Yt(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=Y0,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 hy(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const Qs=t=>t*180/Math.PI,Bn=t=>{const s=Qs(Math.atan2(t[1],t[0]));return zn(s)},py={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Bn,rotateZ:Bn,skewX:t=>Qs(Math.atan(t[1])),skewY:t=>Qs(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},zn=t=>(t=t%360,t<0&&(t+=360),t),Go=Bn,Yo=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Zo=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),xy={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Yo,scaleY:Zo,scale:t=>(Yo(t)+Zo(t))/2,rotateX:t=>zn(Qs(Math.atan2(t[6],t[5]))),rotateY:t=>zn(Qs(Math.atan2(-t[2],t[0]))),rotateZ:Go,rotate:Go,skewX:t=>Qs(Math.atan(t[4])),skewY:t=>Qs(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Hn(t){return t.includes("scale")?1:0}function qn(t,s){if(!t||t==="none")return Hn(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=xy,n=a;else{const l=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=py,n=l}if(!n)return Hn(s);const i=r[s],o=n[1].split(",").map(fy);return typeof i=="function"?i(o):o[i]}const gy=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return qn(a,s)};function fy(t){return parseFloat(t.trim())}const ja=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Na=new Set(ja),Xo=t=>t===ba||t===be,yy=new Set(["x","y","z"]),vy=ja.filter(t=>!yy.has(t));function by(t){const s=[];return vy.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const ta={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})=>qn(s,"x"),y:(t,{transform:s})=>qn(s,"y")};ta.translateX=ta.x;ta.translateY=ta.y;const sa=new Set;let Wn=!1,Kn=!1,Gn=!1;function Gd(){if(Kn){const t=Array.from(sa).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=by(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)})}Kn=!1,Wn=!1,sa.forEach(t=>t.complete(Gn)),sa.clear()}function Yd(){sa.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Kn=!0)})}function jy(){Gn=!0,Yd(),Gd(),Gn=!1}class zi{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?(sa.add(this),Wn||(Wn=!0,Ke.read(Yd),Ke.resolveKeyframes(Gd))):(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])}hy(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),sa.delete(this)}cancel(){this.state==="scheduled"&&(sa.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Ny=t=>t.startsWith("--");function wy(t,s,a){Ny(s)?t.style.setProperty(s,a):t.style[s]=a}const Cy=Di(()=>window.ScrollTimeline!==void 0),Sy={};function Ay(t,s){const a=Di(t);return()=>Sy[s]??a()}const Zd=Ay(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Pa=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,Jo={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Pa([0,.65,.55,1]),circOut:Pa([.55,0,1,.45]),backIn:Pa([.31,.01,.66,-.59]),backOut:Pa([.33,1.53,.69,.99])};function Xd(t,s){if(t)return typeof t=="function"?Zd()?qd(t,s):"ease-out":Fd(t)?Pa(t):Array.isArray(t)?t.map(a=>Xd(a,s)||Jo.easeOut):Jo[t]}function Ty(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=Xd(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 Jd(t){return typeof t=="function"&&"applyToOptions"in t}function ky({type:t,...s}){return Jd(t)&&Zd()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class Ry extends Vi{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,Ri(typeof s.type!="string");const m=ky(s);this.animation=Ty(a,r,n,m,i),m.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const d=Ui(n,this.options,l,this.speed);this.updateMotionValue?this.updateMotionValue(d):wy(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 Yt(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+Yt(s)}get time(){return Yt(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=is(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&&Cy()?(this.animation.timeline=s,Zt):a(this)}}const Qd={anticipate:Pd,backInOut:Dd,circInOut:Md};function Dy(t){return t in Qd}function Py(t){typeof t.ease=="string"&&Dy(t.ease)&&(t.ease=Qd[t.ease])}const Qo=10;class Ey extends Ry{constructor(s){Py(s),Kd(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 Bi({...o,autoplay:!1}),c=is(this.finishedTime??this.time);a.setWithVelocity(l.sample(c-Qo).value,l.sample(c).value,Qo),l.stop()}}const el=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Fs.test(t)||t==="0")&&!t.startsWith("url("));function My(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 Iy(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=el(n,s),l=el(i,s);return!o||!l?!1:My(t)||(a==="spring"||Jd(a))&&r}function Yn(t){t.duration=0,t.type="keyframes"}const Fy=new Set(["opacity","clipPath","filter","transform"]),Ly=Di(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function _y(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 Ly()&&a&&Fy.has(a)&&(a!=="transform"||!m)&&!c&&!r&&n!=="mirror"&&i!==0&&o!=="inertia"}const Oy=40;class $y extends Vi{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},g=(d==null?void 0:d.KeyframeResolver)||zi;this.keyframeResolver=new g(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(),Iy(s,i,o,l)||((bs.instantAnimations||!c)&&(d==null||d(Ui(s,r,a))),s[0]=s[s.length-1],Yn(r),r.repeat=0);const h={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>Oy?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},g=!m&&_y(h)?new Ey({...h,element:h.motionValue.owner.current}):new Bi(h);g.finished.then(()=>this.notifyFinished()).catch(Zt),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}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(),jy()),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 Uy=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Vy(t){const s=Uy.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function em(t,s,a=1){const[r,n]=Vy(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const o=i.trim();return Nd(o)?parseFloat(o):o}return Fi(n)?em(n,s,a+1):n}function Hi(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const tm=new Set(["width","height","top","left","right","bottom",...ja]),By={test:t=>t==="auto",parse:t=>t},sm=t=>s=>s.test(t),am=[ba,be,os,ks,M0,E0,By],tl=t=>am.find(sm(t));function zy(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Cd(t):!0}const Hy=new Set(["brightness","contrast","saturate","opacity"]);function qy(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(Li)||[];if(!r)return t;const n=a.replace(r,"");let i=Hy.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const Wy=/\b([a-z-]*)\(.*?\)/gu,Zn={...Fs,getAnimatableNone:t=>{const s=t.match(Wy);return s?s.map(qy).join(" "):t}},sl={...ba,transform:Math.round},Ky={rotate:ks,rotateX:ks,rotateY:ks,rotateZ:ks,scale:ar,scaleX:ar,scaleY:ar,scaleZ:ar,skew:ks,skewX:ks,skewY:ks,distance:be,translateX:be,translateY:be,translateZ:be,x:be,y:be,z:be,perspective:be,transformPerspective:be,opacity:Ua,originX:zo,originY:zo,originZ:be},qi={borderWidth:be,borderTopWidth:be,borderRightWidth:be,borderBottomWidth:be,borderLeftWidth:be,borderRadius:be,radius:be,borderTopLeftRadius:be,borderTopRightRadius:be,borderBottomRightRadius:be,borderBottomLeftRadius:be,width:be,maxWidth:be,height:be,maxHeight:be,top:be,right:be,bottom:be,left:be,padding:be,paddingTop:be,paddingRight:be,paddingBottom:be,paddingLeft:be,margin:be,marginTop:be,marginRight:be,marginBottom:be,marginLeft:be,backgroundPositionX:be,backgroundPositionY:be,...Ky,zIndex:sl,fillOpacity:Ua,strokeOpacity:Ua,numOctaves:sl},Gy={...qi,color:lt,backgroundColor:lt,outlineColor:lt,fill:lt,stroke:lt,borderColor:lt,borderTopColor:lt,borderRightColor:lt,borderBottomColor:lt,borderLeftColor:lt,filter:Zn,WebkitFilter:Zn},rm=t=>Gy[t];function nm(t,s){let a=rm(t);return a!==Zn&&(a=Fs),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const Yy=new Set(["auto","none","0"]);function Zy(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!Yy.has(i)&&Va(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=nm(a,n)}class Xy extends zi{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(),Fi(m))){const d=em(m,a.current);d!==void 0&&(s[c]=d),c===s.length-1&&(this.finalKeyframe=m)}}if(this.resolveNoneKeyframes(),!tm.has(r)||s.length!==2)return;const[n,i]=s,o=tl(n),l=tl(i);if(o!==l)if(Xo(o)&&Xo(l))for(let c=0;c<s.length;c++){const m=s[c];typeof m=="string"&&(s[c]=parseFloat(m))}else ta[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||zy(s[n]))&&r.push(n);r.length&&Zy(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=ta[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]=ta[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 Jy(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 im=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function om(t){return wd(t)&&"offsetHeight"in t}const al=30,Qy=t=>!isNaN(parseFloat(t));class ev{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=Qy(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 Pi);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>al)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,al);return Sd(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 ga(t,s){return new ev(t,s)}const{schedule:Wi}=Ld(queueMicrotask,!1),Qt={x:!1,y:!1};function lm(){return Qt.x||Qt.y}function tv(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 cm(t,s){const a=Jy(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function rl(t){return!(t.pointerType==="touch"||lm())}function sv(t,s,a={}){const[r,n,i]=cm(t,a),o=l=>{if(!rl(l))return;const{target:c}=l,m=s(c,l);if(typeof m!="function"||!c)return;const d=u=>{rl(u)&&(m(u),c.removeEventListener("pointerleave",d))};c.addEventListener("pointerleave",d,n)};return r.forEach(l=>{l.addEventListener("pointerenter",o,n)}),i}const dm=(t,s)=>s?t===s?!0:dm(t,s.parentElement):!1,Ki=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,av=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function rv(t){return av.has(t.tagName)||t.tabIndex!==-1}const cr=new WeakSet;function nl(t){return s=>{s.key==="Enter"&&t(s)}}function dn(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const nv=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=nl(()=>{if(cr.has(a))return;dn(a,"down");const n=nl(()=>{dn(a,"up")}),i=()=>dn(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 il(t){return Ki(t)&&!lm()}function iv(t,s,a={}){const[r,n,i]=cm(t,a),o=l=>{const c=l.currentTarget;if(!il(l))return;cr.add(c);const m=s(c,l),d=(g,p)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",h),cr.has(c)&&cr.delete(c),il(g)&&typeof m=="function"&&m(g,{success:p})},u=g=>{d(g,c===window||c===document||a.useGlobalTarget||dm(c,g.target))},h=g=>{d(g,!1)};window.addEventListener("pointerup",u,n),window.addEventListener("pointercancel",h,n)};return r.forEach(l=>{(a.useGlobalTarget?window:l).addEventListener("pointerdown",o,n),om(l)&&(l.addEventListener("focus",m=>nv(m,n)),!rv(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),i}function mm(t){return wd(t)&&"ownerSVGElement"in t}function ov(t){return mm(t)&&t.tagName==="svg"}const Tt=t=>!!(t&&t.getVelocity),lv=[...am,lt,Fs],cv=t=>lv.find(sm(t)),Gi=x.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function ol(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function dv(...t){return s=>{let a=!1;const r=t.map(n=>{const i=ol(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():ol(t[n],null)}}}}function mv(...t){return x.useCallback(dv(...t),t)}class uv extends x.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=om(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 hv({children:t,isPresent:s,anchorX:a,root:r}){const n=x.useId(),i=x.useRef(null),o=x.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:l}=x.useContext(Gi),c=mv(i,t==null?void 0:t.ref);return x.useInsertionEffect(()=>{const{width:m,height:d,top:u,left:h,right:g}=o.current;if(s||!i.current||!m||!d)return;const p=a==="left"?`left: ${h}`:`right: ${g}`;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(uv,{isPresent:s,childRef:i,sizeRef:o,children:x.cloneElement(t,{ref:c})})}const pv=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:o,anchorX:l,root:c})=>{const m=Si(xv),d=x.useId();let u=!0,h=x.useMemo(()=>(u=!1,{id:d,initial:s,isPresent:a,custom:n,onExitComplete:g=>{m.set(g,!0);for(const p of m.values())if(!p)return;r&&r()},register:g=>(m.set(g,!1),()=>m.delete(g))}),[a,m,r]);return i&&u&&(h={...h}),x.useMemo(()=>{m.forEach((g,p)=>m.set(p,!1))},[a]),x.useEffect(()=>{!a&&!m.size&&r&&r()},[a]),o==="popLayout"&&(t=e.jsx(hv,{isPresent:a,anchorX:l,root:c,children:t})),e.jsx(_r.Provider,{value:h,children:t})};function xv(){return new Map}function um(t=!0){const s=x.useContext(_r);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=x.useId();x.useEffect(()=>{if(t)return n(i)},[t]);const o=x.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,o]:[!0]}const rr=t=>t.key||"";function ll(t){const s=[];return x.Children.forEach(t,a=>{x.isValidElement(a)&&s.push(a)}),s}const Or=({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]=um(o),u=x.useMemo(()=>ll(t),[t]),h=o&&!m?[]:u.map(rr),g=x.useRef(!0),p=x.useRef(u),f=Si(()=>new Map),[v,j]=x.useState(u),[y,N]=x.useState(u);jd(()=>{g.current=!1,p.current=u;for(let k=0;k<y.length;k++){const L=rr(y[k]);h.includes(L)?f.delete(L):f.get(L)!==!0&&f.set(L,!1)}},[y,h.length,h.join("-")]);const b=[];if(u!==v){let k=[...u];for(let L=0;L<y.length;L++){const R=y[L],I=rr(R);h.includes(I)||(k.splice(L,0,R),b.push(R))}return i==="wait"&&b.length&&(k=b),N(ll(k)),j(u),null}const{forceRender:C}=x.useContext(Ci);return e.jsx(e.Fragment,{children:y.map(k=>{const L=rr(k),R=o&&!m?!1:u===y||h.includes(L),I=()=>{if(f.has(L))f.set(L,!0);else return;let w=!0;f.forEach(A=>{A||(w=!1)}),w&&(C==null||C(),N(p.current),o&&(d==null||d()),r&&r())};return e.jsx(pv,{isPresent:R,initial:!g.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:R?void 0:I,anchorX:l,children:k},L)})})},hm=x.createContext({strict:!1}),cl={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"]},fa={};for(const t in cl)fa[t]={isEnabled:s=>cl[t].some(a=>!!s[a])};function gv(t){for(const s in t)fa[s]={...fa[s],...t[s]}}const fv=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 yr(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||fv.has(t)}let pm=t=>!yr(t);function yv(t){typeof t=="function"&&(pm=s=>s.startsWith("on")?!yr(s):t(s))}try{yv(require("@emotion/is-prop-valid").default)}catch{}function vv(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(pm(n)||a===!0&&yr(n)||!s&&!yr(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const $r=x.createContext({});function Ur(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Ba(t){return typeof t=="string"||Array.isArray(t)}const Yi=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Zi=["initial",...Yi];function Vr(t){return Ur(t.animate)||Zi.some(s=>Ba(t[s]))}function xm(t){return!!(Vr(t)||t.variants)}function bv(t,s){if(Vr(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 jv(t){const{initial:s,animate:a}=bv(t,x.useContext($r));return x.useMemo(()=>({initial:s,animate:a}),[dl(s),dl(a)])}function dl(t){return Array.isArray(t)?t.join(" "):t}const za={};function Nv(t){for(const s in t)za[s]=t[s],Ii(s)&&(za[s].isCSSVariable=!0)}function gm(t,{layout:s,layoutId:a}){return Na.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!za[t]||t==="opacity")}const wv={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Cv=ja.length;function Sv(t,s,a){let r="",n=!0;for(let i=0;i<Cv;i++){const o=ja[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=im(l,qi[o]);if(!c){n=!1;const d=wv[o]||o;r+=`${d}(${m}) `}a&&(s[o]=m)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function Xi(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(Na.has(c)){o=!0;continue}else if(Ii(c)){n[c]=m;continue}else{const d=im(m,qi[c]);c.startsWith("origin")?(l=!0,i[c]=d):r[c]=d}}if(s.transform||(o||a?r.transform=Sv(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 Ji=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function fm(t,s,a){for(const r in s)!Tt(s[r])&&!gm(r,a)&&(t[r]=s[r])}function Av({transformTemplate:t},s){return x.useMemo(()=>{const a=Ji();return Xi(a,s,t),Object.assign({},a.vars,a.style)},[s])}function Tv(t,s){const a=t.style||{},r={};return fm(r,a,t),Object.assign(r,Av(t,s)),r}function kv(t,s){const a={},r=Tv(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 Rv={offset:"stroke-dashoffset",array:"stroke-dasharray"},Dv={offset:"strokeDashoffset",array:"strokeDasharray"};function Pv(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?Rv:Dv;t[i.offset]=be.transform(-r);const o=be.transform(s),l=be.transform(a);t[i.array]=`${o} ${l}`}function ym(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:o=0,...l},c,m,d){if(Xi(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 vm=()=>({...Ji(),attrs:{}}),bm=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Ev(t,s,a,r){const n=x.useMemo(()=>{const i=vm();return ym(i,s,bm(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};fm(i,t.style,t),n.style={...i,...n.style}}return n}const Mv=["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 Qi(t){return typeof t!="string"||t.includes("-")?!1:!!(Mv.indexOf(t)>-1||/[A-Z]/u.test(t))}function Iv(t,s,a,{latestValues:r},n,i=!1){const l=(Qi(t)?Ev:kv)(s,r,n,t),c=vv(s,typeof t=="string",i),m=t!==x.Fragment?{...c,...l,ref:a}:{},{children:d}=s,u=x.useMemo(()=>Tt(d)?d.get():d,[d]);return x.createElement(t,{...m,children:u})}function ml(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function eo(t,s,a,r){if(typeof s=="function"){const[n,i]=ml(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]=ml(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function dr(t){return Tt(t)?t.get():t}function Fv({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:Lv(a,r,n,t),renderState:s()}}function Lv(t,s,a,r){const n={},i=r(t,{});for(const h in i)n[h]=dr(i[h]);let{initial:o,animate:l}=t;const c=Vr(t),m=xm(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"&&!Ur(u)){const h=Array.isArray(u)?u:[u];for(let g=0;g<h.length;g++){const p=eo(t,h[g]);if(p){const{transitionEnd:f,transition:v,...j}=p;for(const y in j){let N=j[y];if(Array.isArray(N)){const b=d?N.length-1:0;N=N[b]}N!==null&&(n[y]=N)}for(const y in f)n[y]=f[y]}}}return n}const jm=t=>(s,a)=>{const r=x.useContext($r),n=x.useContext(_r),i=()=>Fv(t,s,r,n);return a?i():Si(i)};function to(t,s,a){var i;const{style:r}=t,n={};for(const o in r)(Tt(r[o])||s.style&&Tt(s.style[o])||gm(o,t)||((i=a==null?void 0:a.getValue(o))==null?void 0:i.liveStyle)!==void 0)&&(n[o]=r[o]);return n}const _v=jm({scrapeMotionValuesFromProps:to,createRenderState:Ji});function Nm(t,s,a){const r=to(t,s,a);for(const n in t)if(Tt(t[n])||Tt(s[n])){const i=ja.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const Ov=jm({scrapeMotionValuesFromProps:Nm,createRenderState:vm}),$v=Symbol.for("motionComponentSymbol");function la(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Uv(t,s,a){return x.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):la(a)&&(a.current=r))},[s])}const so=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Vv="framerAppearId",wm="data-"+so(Vv),Cm=x.createContext({});function Bv(t,s,a,r,n){var f,v;const{visualElement:i}=x.useContext($r),o=x.useContext(hm),l=x.useContext(_r),c=x.useContext(Gi).reducedMotion,m=x.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=x.useContext(Cm);d&&!d.projection&&n&&(d.type==="html"||d.type==="svg")&&zv(m.current,a,n,u);const h=x.useRef(!1);x.useInsertionEffect(()=>{d&&h.current&&d.update(a,l)});const g=a[wm],p=x.useRef(!!g&&!((f=window.MotionHandoffIsComplete)!=null&&f.call(window,g))&&((v=window.MotionHasOptimisedAnimation)==null?void 0:v.call(window,g)));return jd(()=>{d&&(h.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),p.current&&d.animationState&&d.animationState.animateChanges())}),x.useEffect(()=>{d&&(!p.current&&d.animationState&&d.animationState.animateChanges(),p.current&&(queueMicrotask(()=>{var j;(j=window.MotionHandoffMarkAsComplete)==null||j.call(window,g)}),p.current=!1),d.enteringChildren=void 0)}),d}function zv(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:Sm(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!o||l&&la(l),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:m})}function Sm(t){if(t)return t.options.allowProjection!==!1?t.projection:Sm(t.parent)}function mn(t,{forwardMotionProps:s=!1}={},a,r){a&&gv(a);const n=Qi(t)?Ov:_v;function i(l,c){let m;const d={...x.useContext(Gi),...l,layoutId:Hv(l)},{isStatic:u}=d,h=jv(l),g=n(l,u);if(!u&&Ai){qv();const p=Wv(d);m=p.MeasureLayout,h.visualElement=Bv(t,g,d,r,p.ProjectionNode)}return e.jsxs($r.Provider,{value:h,children:[m&&h.visualElement?e.jsx(m,{visualElement:h.visualElement,...d}):null,Iv(t,l,Uv(g,h.visualElement,c),g,u,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const o=x.forwardRef(i);return o[$v]=t,o}function Hv({layoutId:t}){const s=x.useContext(Ci).id;return s&&t!==void 0?s+"-"+t:t}function qv(t,s){x.useContext(hm).strict}function Wv(t){const{drag:s,layout:a}=fa;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 Kv(t,s){if(typeof Proxy>"u")return mn;const a=new Map,r=(i,o)=>mn(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,mn(o,void 0,t,s)),a.get(o))})}function Am({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function Gv({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function Yv(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 un(t){return t===void 0||t===1}function Xn({scale:t,scaleX:s,scaleY:a}){return!un(t)||!un(s)||!un(a)}function qs(t){return Xn(t)||Tm(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Tm(t){return ul(t.x)||ul(t.y)}function ul(t){return t&&t!=="0%"}function vr(t,s,a){const r=t-a,n=s*r;return a+n}function hl(t,s,a,r,n){return n!==void 0&&(t=vr(t,n,r)),vr(t,a,r)+s}function Jn(t,s=0,a=1,r,n){t.min=hl(t.min,s,a,r,n),t.max=hl(t.max,s,a,r,n)}function km(t,{x:s,y:a}){Jn(t.x,s.translate,s.scale,s.originPoint),Jn(t.y,a.translate,a.scale,a.originPoint)}const pl=.999999999999,xl=1.0000000000001;function Zv(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&&da(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),o&&(s.x*=o.x.scale,s.y*=o.y.scale,km(t,o)),r&&qs(i.latestValues)&&da(t,i.latestValues))}s.x<xl&&s.x>pl&&(s.x=1),s.y<xl&&s.y>pl&&(s.y=1)}function ca(t,s){t.min=t.min+s,t.max=t.max+s}function gl(t,s,a,r,n=.5){const i=Ye(t.min,t.max,n);Jn(t,s,a,i,r)}function da(t,s){gl(t.x,s.x,s.scaleX,s.scale,s.originX),gl(t.y,s.y,s.scaleY,s.scale,s.originY)}function Rm(t,s){return Am(Yv(t.getBoundingClientRect(),s))}function Xv(t,s,a){const r=Rm(t,a),{scroll:n}=s;return n&&(ca(r.x,n.offset.x),ca(r.y,n.offset.y)),r}const fl=()=>({translate:0,scale:1,origin:0,originPoint:0}),ma=()=>({x:fl(),y:fl()}),yl=()=>({min:0,max:0}),st=()=>({x:yl(),y:yl()}),Qn={current:null},Dm={current:!1};function Jv(){if(Dm.current=!0,!!Ai)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>Qn.current=t.matches;t.addEventListener("change",s),s()}else Qn.current=!1}const Qv=new WeakMap;function eb(t,s,a){for(const r in s){const n=s[r],i=a[r];if(Tt(n))t.addValue(r,n);else if(Tt(i))t.addValue(r,ga(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,ga(o!==void 0?o:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const vl=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class tb{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=zi,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=Vr(a),this.isVariantNode=xm(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 g=u[h];c[h]!==void 0&&Tt(g)&&g.set(c[h])}}mount(s){var a;this.current=s,Qv.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)),Dm.current||Jv(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Qn.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Is(this.notifyUpdate),Is(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=Na.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 fa){const a=fa[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<vl.length;r++){const n=vl[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=eb(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=ga(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"&&(Nd(r)||Cd(r))?r=parseFloat(r):!cv(r)&&Fs.test(a)&&(r=nm(s,a)),this.setBaseTarget(s,Tt(r)?r.get():r)),Tt(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=eo(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&&!Tt(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 Pi),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){Wi.render(this.render)}}class Pm extends tb{constructor(){super(...arguments),this.KeyframeResolver=Xy}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;Tt(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Em(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 sb(t){return window.getComputedStyle(t)}class ab extends Pm{constructor(){super(...arguments),this.type="html",this.renderInstance=Em}readValueFromInstance(s,a){var r;if(Na.has(a))return(r=this.projection)!=null&&r.isProjecting?Hn(a):gy(s,a);{const n=sb(s),i=(Ii(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return Rm(s,a)}build(s,a,r){Xi(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return to(s,a,r)}}const Mm=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 rb(t,s,a,r){Em(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(Mm.has(n)?n:so(n),s.attrs[n])}class nb extends Pm{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=st}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Na.has(a)){const r=rm(a);return r&&r.default||0}return a=Mm.has(a)?a:so(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return Nm(s,a,r)}build(s,a,r){ym(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){rb(s,a,r,n)}mount(s){this.isSVGTag=bm(s.tagName),super.mount(s)}}const ib=(t,s)=>Qi(t)?new nb(s):new ab(s,{allowProjection:t!==x.Fragment});function pa(t,s,a){const r=t.getProps();return eo(r,s,a!==void 0?a:r.custom,t)}const ei=t=>Array.isArray(t);function ob(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,ga(a))}function lb(t){return ei(t)?t[t.length-1]||0:t}function cb(t,s){const a=pa(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const o in i){const l=lb(i[o]);ob(t,o,l)}}function db(t){return!!(Tt(t)&&t.add)}function ti(t,s){const a=t.getValue("willChange");if(db(a))return a.add(s);if(!a&&bs.WillChange){const r=new bs.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function Im(t){return t.props[wm]}const mb=t=>t!==null;function ub(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(mb),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const hb={type:"spring",stiffness:500,damping:25,restSpeed:10},pb=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),xb={type:"keyframes",duration:.8},gb={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},fb=(t,{keyframes:s})=>s.length>2?xb:Na.has(t)?t.startsWith("scale")?pb(s[1]):hb:gb;function yb({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 ao=(t,s,a,r={},n,i)=>o=>{const l=Hi(r,t)||{},c=l.delay||r.delay||0;let{elapsed:m=0}=r;m=m-is(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};yb(l)||Object.assign(d,fb(t,d)),d.duration&&(d.duration=is(d.duration)),d.repeatDelay&&(d.repeatDelay=is(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let u=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(Yn(d),d.delay===0&&(u=!0)),(bs.instantAnimations||bs.skipAnimations)&&(u=!0,Yn(d),d.delay=0),d.allowFlatten=!l.type&&!l.ease,u&&!i&&s.get()!==void 0){const h=ub(d.keyframes,l);if(h!==void 0){Ke.update(()=>{d.onUpdate(h),d.onComplete()});return}}return l.isSync?new Bi(d):new $y(d)};function vb({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Fm(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&&vb(m,d))continue;const g={delay:a,...Hi(i||{},d)},p=u.get();if(p!==void 0&&!u.isAnimating&&!Array.isArray(h)&&h===p&&!g.velocity)continue;let f=!1;if(window.MotionHandoffAnimation){const j=Im(t);if(j){const y=window.MotionHandoffAnimation(j,d,Ke);y!==null&&(g.startTime=y,f=!0)}}ti(t,d),u.start(ao(d,u,h,t.shouldReduceMotion&&tm.has(d)?{type:!1}:g,t,f));const v=u.animation;v&&c.push(v)}return o&&Promise.all(c).then(()=>{Ke.update(()=>{o&&cb(t,o)})}),c}function Lm(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 si(t,s,a={}){var c;const r=pa(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(Fm(t,r,a)):()=>Promise.resolve(),o=t.variantChildren&&t.variantChildren.size?(m=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:h}=n;return bb(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 bb(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(si(c,s,{...o,delay:a+(typeof r=="function"?0:r)+Lm(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(l)}function jb(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>si(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=si(t,s,a);else{const n=typeof s=="function"?pa(t,s,a.custom):s;r=Promise.all(Fm(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function _m(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=Zi.length;function Om(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?Om(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=Zi[a],n=t.props[r];(Ba(n)||n===!1)&&(s[r]=n)}return s}const wb=[...Yi].reverse(),Cb=Yi.length;function Sb(t){return s=>Promise.all(s.map(({animation:a,options:r})=>jb(t,a,r)))}function Ab(t){let s=Sb(t),a=bl(),r=!0;const n=c=>(m,d)=>{var h;const u=pa(t,d,c==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(u){const{transition:g,transitionEnd:p,...f}=u;m={...m,...f,...p}}return m};function i(c){s=c(t)}function o(c){const{props:m}=t,d=Om(t.parent)||{},u=[],h=new Set;let g={},p=1/0;for(let v=0;v<Cb;v++){const j=wb[v],y=a[j],N=m[j]!==void 0?m[j]:d[j],b=Ba(N),C=j===c?y.isActive:null;C===!1&&(p=v);let k=N===d[j]&&N!==m[j]&&b;if(k&&r&&t.manuallyAnimateOnMount&&(k=!1),y.protectedKeys={...g},!y.isActive&&C===null||!N&&!y.prevProp||Ur(N)||typeof N=="boolean")continue;const L=Tb(y.prevProp,N);let R=L||j===c&&y.isActive&&!k&&b||v>p&&b,I=!1;const w=Array.isArray(N)?N:[N];let A=w.reduce(n(j),{});C===!1&&(A={});const{prevResolvedValues:P={}}=y,q={...P,...A},M=T=>{R=!0,h.has(T)&&(I=!0,h.delete(T)),y.needsAnimating[T]=!0;const D=t.getValue(T);D&&(D.liveStyle=!1)};for(const T in q){const D=A[T],H=P[T];if(g.hasOwnProperty(T))continue;let O=!1;ei(D)&&ei(H)?O=!_m(D,H):O=D!==H,O?D!=null?M(T):h.add(T):D!==void 0&&h.has(T)?M(T):y.protectedKeys[T]=!0}y.prevProp=N,y.prevResolvedValues=A,y.isActive&&(g={...g,...A}),r&&t.blockInitialAnimation&&(R=!1);const F=k&&L;R&&(!F||I)&&u.push(...w.map(T=>{const D={type:j};if(typeof T=="string"&&r&&!F&&t.manuallyAnimateOnMount&&t.parent){const{parent:H}=t,O=pa(H,T);if(H.enteringChildren&&O){const{delayChildren:_}=O.transition||{};D.delay=Lm(H.enteringChildren,t,_)}}return{animation:T,options:D}}))}if(h.size){const v={};if(typeof m.initial!="boolean"){const j=pa(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),N=t.getValue(j);N&&(N.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 g;return(g=h.animationState)==null?void 0:g.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=bl()}}}function Tb(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!_m(s,t):!1}function Vs(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function bl(){return{animate:Vs(!0),whileInView:Vs(),whileHover:Vs(),whileTap:Vs(),whileDrag:Vs(),whileFocus:Vs(),exit:Vs()}}class $s{constructor(s){this.isMounted=!1,this.node=s}update(){}}class kb extends $s{constructor(s){super(s),s.animationState||(s.animationState=Ab(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Ur(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 Rb=0;class Db extends $s{constructor(){super(...arguments),this.id=Rb++}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:kb},exit:{Feature:Db}};function Ha(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function Za(t){return{point:{x:t.pageX,y:t.pageY}}}const Eb=t=>s=>Ki(s)&&t(s,Za(s));function Ia(t,s,a,r){return Ha(t,s,Eb(a),r)}const $m=1e-4,Mb=1-$m,Ib=1+$m,Um=.01,Fb=0-Um,Lb=0+Um;function Pt(t){return t.max-t.min}function _b(t,s,a){return Math.abs(t-s)<=a}function jl(t,s,a,r=.5){t.origin=r,t.originPoint=Ye(s.min,s.max,t.origin),t.scale=Pt(a)/Pt(s),t.translate=Ye(a.min,a.max,t.origin)-t.originPoint,(t.scale>=Mb&&t.scale<=Ib||isNaN(t.scale))&&(t.scale=1),(t.translate>=Fb&&t.translate<=Lb||isNaN(t.translate))&&(t.translate=0)}function Fa(t,s,a,r){jl(t.x,s.x,a.x,r?r.originX:void 0),jl(t.y,s.y,a.y,r?r.originY:void 0)}function Nl(t,s,a){t.min=a.min+s.min,t.max=t.min+Pt(s)}function Ob(t,s,a){Nl(t.x,s.x,a.x),Nl(t.y,s.y,a.y)}function wl(t,s,a){t.min=s.min-a.min,t.max=t.min+Pt(s)}function La(t,s,a){wl(t.x,s.x,a.x),wl(t.y,s.y,a.y)}function Kt(t){return[t("x"),t("y")]}const Vm=({current:t})=>t?t.ownerDocument.defaultView:null,Cl=(t,s)=>Math.abs(t-s);function $b(t,s){const a=Cl(t.x,s.x),r=Cl(t.y,s.y);return Math.sqrt(a**2+r**2)}class Bm{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=pn(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,p=$b(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!p)return;const{point:f}=h,{timestamp:v}=wt;this.history.push({...f,timestamp:v});const{onStart:j,onMove:y}=this.handlers;g||(j&&j(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),y&&y(this.lastMoveEvent,h)},this.handlePointerMove=(h,g)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=hn(g,this.transformPagePoint),Ke.update(this.updatePoint,!0)},this.handlePointerUp=(h,g)=>{this.end();const{onEnd:p,onSessionEnd:f,resumeAnimation:v}=this.handlers;if(this.dragSnapToOrigin&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=pn(h.type==="pointercancel"?this.lastMoveEventInfo:hn(g,this.transformPagePoint),this.history);this.startEvent&&p&&p(h,j),f&&f(h,j)},!Ki(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=o,this.contextWindow=n||window;const l=Za(s),c=hn(l,this.transformPagePoint),{point:m}=c,{timestamp:d}=wt;this.history=[{...m,timestamp:d}];const{onSessionStart:u}=a;u&&u(s,pn(c,this.history)),this.removeListeners=Ka(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(),Is(this.updatePoint)}}function hn(t,s){return s?{point:s(t.point)}:t}function Sl(t,s){return{x:t.x-s.x,y:t.y-s.y}}function pn({point:t},s){return{point:t,delta:Sl(t,zm(s)),offset:Sl(t,Ub(s)),velocity:Vb(s,.1)}}function Ub(t){return t[0]}function zm(t){return t[t.length-1]}function Vb(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=zm(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>is(s)));)a--;if(!r)return{x:0,y:0};const i=Yt(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 Bb(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 Al(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 zb(t,{top:s,left:a,bottom:r,right:n}){return{x:Al(t.x,a,n),y:Al(t.y,s,r)}}function Tl(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 Hb(t,s){return{x:Tl(t.x,s.x),y:Tl(t.y,s.y)}}function qb(t,s){let a=.5;const r=Pt(t),n=Pt(s);return n>r?a=$a(s.min,s.max-r,t.min):r>n&&(a=$a(t.min,t.max-n,s.min)),vs(0,1,a)}function Wb(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 ai=.35;function Kb(t=ai){return t===!1?t=0:t===!0&&(t=ai),{x:kl(t,"left","right"),y:kl(t,"top","bottom")}}function kl(t,s,a){return{min:Rl(t,s),max:Rl(t,a)}}function Rl(t,s){return typeof t=="number"?t:t[s]||0}const Gb=new WeakMap;class Yb{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(Za(u).point)},o=(u,h)=>{const{drag:g,dragPropagation:p,onDragStart:f}=this.getProps();if(g&&!p&&(this.openDragLock&&this.openDragLock(),this.openDragLock=tv(g),!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),Kt(j=>{let y=this.getAxisMotionValue(j).get()||0;if(os.test(y)){const{projection:N}=this.visualElement;if(N&&N.layout){const b=N.layout.layoutBox[j];b&&(y=Pt(b)*(parseFloat(y)/100))}}this.originPoint[j]=y}),f&&Ke.postRender(()=>f(u,h)),ti(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},l=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h;const{dragPropagation:g,dragDirectionLock:p,onDirectionLock:f,onDrag:v}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:j}=h;if(p&&this.currentDirection===null){this.currentDirection=Zb(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=()=>Kt(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 Bm(s,{onSessionStart:i,onStart:o,onMove:l,onSessionEnd:c,resumeAnimation:m},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:r,contextWindow:Vm(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=Bb(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&&la(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=zb(r.layoutBox,s):this.constraints=!1,this.elastic=Kb(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&Kt(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Wb(r.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!la(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=Xv(r,n.root,this.visualElement.getTransformPagePoint());let o=Hb(n.layout.layoutBox,i);if(a){const l=a(Gv(o));this.hasMutatedConstraints=!!l,l&&(o=Am(l))}return o}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},m=Kt(d=>{if(!nr(d,a,this.currentDirection))return;let u=c&&c[d]||{};o&&(u={min:0,max:0});const h=n?200:1e6,g=n?40:1e7,p={type:"inertia",velocity:r?s[d]:0,bounceStiffness:h,bounceDamping:g,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 ti(this.visualElement,s),r.start(ao(s,r,0,a,this.visualElement,!1))}stopAnimation(){Kt(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Kt(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){Kt(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(!la(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};Kt(o=>{const l=this.getAxisMotionValue(o);if(l&&this.constraints!==!1){const c=l.get();n[o]=qb({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(),Kt(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;Gb.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();la(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&&(Kt(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=ai,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 Zb(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class Xb extends $s{constructor(s){super(s),this.removeGroupControls=Zt,this.removeListeners=Zt,this.controls=new Yb(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Zt}unmount(){this.removeGroupControls(),this.removeListeners()}}const Dl=t=>(s,a)=>{t&&Ke.postRender(()=>t(s,a))};class Jb extends $s{constructor(){super(...arguments),this.removePointerDownListener=Zt}onPointerDown(s){this.session=new Bm(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Vm(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Dl(s),onStart:Dl(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 mr={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Pl(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(be.test(t))t=parseFloat(t);else return t;const a=Pl(t,s.target.x),r=Pl(t,s.target.y);return`${a}% ${r}%`}},Qb={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Fs.parse(t);if(n.length>5)return r;const i=Fs.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 xn=!1;class ej extends x.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;Nv(tj),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),xn&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),mr.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:o}=r;return o&&(o.isPresent=i,xn=!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(),Wi.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;xn=!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 Hm(t){const[s,a]=um(),r=x.useContext(Ci);return e.jsx(ej,{...t,layoutGroup:r,switchLayoutGroup:x.useContext(Cm),isPresent:s,safeToRemove:a})}const tj={borderRadius:{...ka,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:ka,borderTopRightRadius:ka,borderBottomLeftRadius:ka,borderBottomRightRadius:ka,boxShadow:Qb};function sj(t,s,a){const r=Tt(t)?t:ga(t);return r.start(ao("",r,s,a)),r.animation}const aj=(t,s)=>t.depth-s.depth;class rj{constructor(){this.children=[],this.isDirty=!1}add(s){Ti(this.children,s),this.isDirty=!0}remove(s){ki(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(aj),this.isDirty=!1,this.children.forEach(s)}}function nj(t,s){const a=_t.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Is(r),t(i-s))};return Ke.setup(r,!0),()=>Is(r)}const qm=["TopLeft","TopRight","BottomLeft","BottomRight"],ij=qm.length,El=t=>typeof t=="string"?parseFloat(t):t,Ml=t=>typeof t=="number"||be.test(t);function oj(t,s,a,r,n,i){n?(t.opacity=Ye(0,a.opacity??1,lj(r)),t.opacityExit=Ye(s.opacity??1,0,cj(r))):i&&(t.opacity=Ye(s.opacity??1,a.opacity??1,r));for(let o=0;o<ij;o++){const l=`border${qm[o]}Radius`;let c=Il(s,l),m=Il(a,l);if(c===void 0&&m===void 0)continue;c||(c=0),m||(m=0),c===0||m===0||Ml(c)===Ml(m)?(t[l]=Math.max(Ye(El(c),El(m),r),0),(os.test(m)||os.test(c))&&(t[l]+="%")):t[l]=m}(s.rotate||a.rotate)&&(t.rotate=Ye(s.rotate||0,a.rotate||0,r))}function Il(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const lj=Wm(0,.5,Ed),cj=Wm(.5,.95,Zt);function Wm(t,s,a){return r=>r<t?0:r>s?1:a($a(t,s,r))}function Fl(t,s){t.min=s.min,t.max=s.max}function Wt(t,s){Fl(t.x,s.x),Fl(t.y,s.y)}function Ll(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function _l(t,s,a,r,n){return t-=s,t=vr(t,1/a,r),n!==void 0&&(t=vr(t,1/n,r)),t}function dj(t,s=0,a=1,r=.5,n,i=t,o=t){if(os.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=_l(t.min,s,a,l,n),t.max=_l(t.max,s,a,l,n)}function Ol(t,s,[a,r,n],i,o){dj(t,s[a],s[r],s[n],s.scale,i,o)}const mj=["x","scaleX","originX"],uj=["y","scaleY","originY"];function $l(t,s,a,r){Ol(t.x,s,mj,a?a.x:void 0,r?r.x:void 0),Ol(t.y,s,uj,a?a.y:void 0,r?r.y:void 0)}function Ul(t){return t.translate===0&&t.scale===1}function Km(t){return Ul(t.x)&&Ul(t.y)}function Vl(t,s){return t.min===s.min&&t.max===s.max}function hj(t,s){return Vl(t.x,s.x)&&Vl(t.y,s.y)}function Bl(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Gm(t,s){return Bl(t.x,s.x)&&Bl(t.y,s.y)}function zl(t){return Pt(t.x)/Pt(t.y)}function Hl(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class pj{constructor(){this.members=[]}add(s){Ti(this.members,s),s.scheduleRender()}remove(s){if(ki(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 xj(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:g,skewY:p}=a;m&&(r=`perspective(${m}px) ${r}`),d&&(r+=`rotate(${d}deg) `),u&&(r+=`rotateX(${u}deg) `),h&&(r+=`rotateY(${h}deg) `),g&&(r+=`skewX(${g}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 gn=["","X","Y","Z"],gj=1e3;let fj=0;function fn(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Ym(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=Im(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&&Ym(r)}function Zm({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(o={},l=s==null?void 0:s()){this.id=fj++,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(bj),this.nodes.forEach(Cj),this.nodes.forEach(Sj),this.nodes.forEach(jj)},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 rj)}addEventListener(o,l){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new Pi),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=mm(o)&&!ov(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 g=window.innerWidth;g!==u&&(u=g,this.root.updateBlockedByResize=!0,d&&d(),d=nj(h,250),mr.hasAnimatedSinceResize&&(mr.hasAnimatedSinceResize=!1,this.nodes.forEach(Kl)))})}l&&this.root.registerSharedNode(l,this),this.options.animate!==!1&&m&&(l||c)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u,hasRelativeLayoutChanged:h,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const p=this.options.transition||m.getDefaultTransition()||Dj,{onLayoutAnimationStart:f,onLayoutAnimationComplete:v}=m.getProps(),j=!this.targetLayout||!Gm(this.targetLayout,g),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 N={...Hi(p,"layout"),onPlay:f,onComplete:v};(m.shouldReduceMotion||this.options.layoutRoot)&&(N.delay=0,N.type=!1),this.startAnimation(N),this.setAnimationOrigin(d,y)}else u||Kl(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}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(),Is(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(Aj),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&&Ym(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(ql);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Wl);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(wj),this.nodes.forEach(yj),this.nodes.forEach(vj)):this.nodes.forEach(Wl),this.clearAllSnapshots();const l=_t.now();wt.delta=vs(0,1e3/60,l-wt.timestamp),wt.timestamp=l,wt.isProcessing=!0,rn.update.process(wt),rn.preRender.process(wt),rn.render.process(wt),wt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Wi.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Nj),this.sharedNodes.forEach(Tj)}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&&!Pt(this.snapshot.measuredBox.x)&&!Pt(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&&!Km(this.projectionDelta),c=this.getTransformTemplate(),m=c?c(this.latestValues,""):void 0,d=m!==this.prevTransformTemplateValue;o&&this.instance&&(l||qs(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(Ej))){const{scroll:d}=this.root;d&&(ca(l.x,d.offset.x),ca(l.y,d.offset.y))}return l}removeElementScroll(o){var c;const l=st();if(Wt(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&&Wt(l,o),ca(l.x,u.offset.x),ca(l.y,u.offset.y))}return l}applyTransform(o,l=!1){const c=st();Wt(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&&da(c,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),qs(d.latestValues)&&da(c,d.latestValues)}return qs(this.latestValues)&&da(c,this.latestValues),c}removeTransform(o){const l=st();Wt(l,o);for(let c=0;c<this.path.length;c++){const m=this.path[c];if(!m.instance||!qs(m.latestValues))continue;Xn(m.latestValues)&&m.updateSnapshot();const d=st(),u=m.measurePageBox();Wt(d,u),$l(l,m.latestValues,m.snapshot?m.snapshot.layoutBox:void 0,d)}return qs(this.latestValues)&&$l(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!==wt.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=wt.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=st(),this.relativeTargetOrigin=st(),La(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),Wt(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(),Ob(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Wt(this.target,this.layout.layoutBox),km(this.target,this.targetDelta)):Wt(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const g=this.getClosestProjectingParent();g&&!!g.resumingFrom==!!this.resumingFrom&&!g.options.layoutScroll&&g.target&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=st(),this.relativeTargetOrigin=st(),La(this.relativeTargetOrigin,this.target,g.target),Wt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Xn(this.parent.latestValues)||Tm(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===wt.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;Wt(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,h=this.treeScale.y;Zv(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:g}=o;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Ll(this.prevProjectionDelta.x,this.projectionDelta.x),Ll(this.prevProjectionDelta.y,this.projectionDelta.y)),Fa(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==h||!Hl(this.projectionDelta.x,this.prevProjectionDelta.x)||!Hl(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}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=ma(),this.projectionDelta=ma(),this.projectionDeltaWithTransform=ma()}setAnimationOrigin(o,l=!1){const c=this.snapshot,m=c?c.latestValues:{},d={...this.latestValues},u=ma();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!l;const h=st(),g=c?c.source:void 0,p=this.layout?this.layout.source:void 0,f=g!==p,v=this.getStack(),j=!v||v.members.length<=1,y=!!(f&&!j&&this.options.crossfade===!0&&!this.path.some(Rj));this.animationProgress=0;let N;this.mixTargetDelta=b=>{const C=b/1e3;Gl(u.x,o.x,C),Gl(u.y,o.y,C),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(La(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),kj(this.relativeTarget,this.relativeTargetOrigin,h,C),N&&hj(this.relativeTarget,N)&&(this.isProjectionDirty=!1),N||(N=st()),Wt(N,this.relativeTarget)),f&&(this.animationValues=d,oj(d,m,this.latestValues,C,y,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=C},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&&(Is(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Ke.update(()=>{mr.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ga(0)),this.currentAnimation=sj(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(gj),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&&Xm(this.options.animationType,this.layout.layoutBox,m.layoutBox)){c=this.target||st();const u=Pt(this.layout.layoutBox.x);c.x.min=o.target.x.min,c.x.max=c.x.min+u;const h=Pt(this.layout.layoutBox.y);c.y.min=o.target.y.min,c.y.max=c.y.min+h}Wt(l,c),da(l,d),Fa(this.projectionDeltaWithTransform,this.layoutCorrected,l,d)}}registerSharedNode(o,l){this.sharedNodes.has(o)||this.sharedNodes.set(o,new pj),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&&fn("z",o,m,this.animationValues);for(let d=0;d<gn.length;d++)fn(`rotate${gn[d]}`,o,m,this.animationValues),fn(`skew${gn[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=dr(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=dr(l==null?void 0:l.pointerEvents)||""),this.hasProjected&&!qs(this.latestValues)&&(o.transform=c?c({},""):"none",this.hasProjected=!1);return}o.visibility="";const d=m.animationValues||m.latestValues;this.applyTransformsToTarget();let u=xj(this.projectionDeltaWithTransform,this.treeScale,d);c&&(u=c(d,u)),o.transform=u;const{x:h,y:g}=this.projectionDelta;o.transformOrigin=`${h.origin*100}% ${g.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 N=v.length;for(let b=0;b<N;b++)o[v[b]]=y}else j?this.options.visualElement.renderState.vars[p]=y:o[p]=y}this.options.layoutId&&(o.pointerEvents=m===this?dr(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(ql),this.root.sharedNodes.clear()}}}function yj(t){t.updateLayout()}function vj(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"?Kt(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],g=Pt(h);h.min=r[u].min,h.max=h.min+g}):Xm(i,s.layoutBox,r)&&Kt(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],g=Pt(r[u]);h.max=h.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+g)});const l=ma();Fa(l,r,s.layoutBox);const c=ma();o?Fa(c,t.applyTransform(n,!0),s.measuredBox):Fa(c,r,s.layoutBox);const m=!Km(l);let d=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:h,layout:g}=u;if(h&&g){const p=st();La(p,s.layoutBox,h.layoutBox);const f=st();La(f,r,g.layoutBox),Gm(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 bj(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 jj(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Nj(t){t.clearSnapshot()}function ql(t){t.clearMeasurements()}function Wl(t){t.isLayoutDirty=!1}function wj(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function Kl(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Cj(t){t.resolveTargetDelta()}function Sj(t){t.calcProjection()}function Aj(t){t.resetSkewAndRotation()}function Tj(t){t.removeLeadSnapshot()}function Gl(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 Yl(t,s,a,r){t.min=Ye(s.min,a.min,r),t.max=Ye(s.max,a.max,r)}function kj(t,s,a,r){Yl(t.x,s.x,a.x,r),Yl(t.y,s.y,a.y,r)}function Rj(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Dj={duration:.45,ease:[.4,0,.1,1]},Zl=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Xl=Zl("applewebkit/")&&!Zl("chrome/")?Math.round:Zt;function Jl(t){t.min=Xl(t.min),t.max=Xl(t.max)}function Pj(t){Jl(t.x),Jl(t.y)}function Xm(t,s,a){return t==="position"||t==="preserve-aspect"&&!_b(zl(s),zl(a),.2)}function Ej(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const Mj=Zm({attachResizeListener:(t,s)=>Ha(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),yn={current:void 0},Jm=Zm({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!yn.current){const t=new Mj({});t.mount(window),t.setOptions({layoutScroll:!0}),yn.current=t}return yn.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Ij={pan:{Feature:Jb},drag:{Feature:Xb,ProjectionNode:Jm,MeasureLayout:Hm}};function Ql(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,Za(s)))}class Fj extends $s{mount(){const{current:s}=this.node;s&&(this.unmount=sv(s,(a,r)=>(Ql(this.node,r,"Start"),n=>Ql(this.node,n,"End"))))}unmount(){}}class Lj extends $s{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=Ka(Ha(this.node.current,"focus",()=>this.onFocus()),Ha(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function ec(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,Za(s)))}class _j extends $s{mount(){const{current:s}=this.node;s&&(this.unmount=iv(s,(a,r)=>(ec(this.node,r,"Start"),(n,{success:i})=>ec(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const ri=new WeakMap,vn=new WeakMap,Oj=t=>{const s=ri.get(t.target);s&&s(t)},$j=t=>{t.forEach(Oj)};function Uj({root:t,...s}){const a=t||document;vn.has(a)||vn.set(a,{});const r=vn.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver($j,{root:t,...s})),r[n]}function Vj(t,s,a){const r=Uj(s);return ri.set(t,a),r.observe(t),()=>{ri.delete(t),r.unobserve(t)}}const Bj={some:0,all:1};class zj extends $s{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:Bj[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 Vj(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(Hj(s,a))&&this.startObserver()}unmount(){}}function Hj({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const qj={inView:{Feature:zj},tap:{Feature:_j},focus:{Feature:Lj},hover:{Feature:Fj}},Wj={layout:{ProjectionNode:Jm,MeasureLayout:Hm}},Kj={...Pb,...qj,...Ij,...Wj},vt=Kv(Kj,ib),tc=[{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:En,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:bp,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"]}];function Gj({open:t,onClose:s,onSelectTemplate:a}){var l;const[r,n]=x.useState(null),i=c=>{n(c)},o=()=>{r&&(a(r),s())};return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(nt,{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(it,{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(dt,{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(vt.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(kr,{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:tc.map((c,m)=>{const d=c.icon,u=r===c.id;return e.jsx(vt.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(se,{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(vt.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(ya,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ae,{className:"text-xl mb-2",children:c.name}),e.jsx(ue,{className:"text-sm leading-relaxed",children:c.description})]})]}),e.jsxs(K,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Q,{variant:"secondary",className:"text-xs",children:c.category})}),e.jsx(jt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Re,{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(et,{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,g)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(ye,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:h})]},g)),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(vt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"flex flex-col sm:flex-row justify-center gap-4 mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(E,{onClick: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(gt,{className:"w-4 h-4"})]})]}),e.jsx(Or,{children:r&&e.jsx(vt.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=tc.find(c=>c.id===r))==null?void 0:l.name})]})})})]})})]})})}const Yj={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 Zj(t,s,a){const[r,n]=x.useState(Yj),[i,o]=x.useState(null),[l,c]=x.useState(t),[m,d]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[u,h]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[g,p]=x.useState([]);return x.useEffect(()=>{(async()=>{var j;try{const y=await ea("DOCUMENT_POLICY"),N={};y.forEach(A=>{N[A.configKey]=A.configValue});const b=parseInt(N.MAX_FILE_SIZE_MB||"10"),k=(N.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(A=>A.trim().toLowerCase());h({maxFileSizeMB:b,allowedFileTypes:k});const L=await ea("WORKFLOW_SHARING"),R=await ea("TAT_SETTINGS"),I=[...L,...R],w={};I.forEach(A=>{w[A.configKey]=A.configValue}),d({maxApprovalLevels:parseInt(w.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(w.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((j=w.ALLOW_ADD_SPECTATOR)==null?void 0:j.toLowerCase())==="true",maxSpectators:parseInt(w.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(y){console.error("Failed to load policies:",y)}})()},[]),x.useEffect(()=>{if(!t||!s)return;let v=!0;return(async()=>{try{c(!0);const j=await Xs(s);if(!v||!j)return;const y=j.workflow||{},N=Array.isArray(j.approvals)?j.approvals:[],b=Array.isArray(j.participants)?j.participants:[],C=Array.isArray(j.documents)?j.documents.filter(P=>!P.isDeleted):[];p(C);const k=(y.priority||"").toString().toLowerCase(),L={standard:"standard",express:"express"},R=y.templateType==="TEMPLATE"?"existing-template":"custom",I=a.find(P=>P.id===R)||a[0]||null;o(I);const w=N.sort((P,q)=>(P.levelNumber||0)-(q.levelNumber||0)).map(P=>{const q=Number(P.tatHours||24),M=Math.floor(q/24),F=q%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:M>0?M:F,tatType:M>0?"days":"hours",userId:P.approverId}}),A=b.filter(P=>(P.participantType||P.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(P.userEmail||P.user_email||P.email):!1).map((P,q)=>{const M=P.userId||P.user_id||P.id,F=P.userName||P.user_name||P.name||"",S=P.userEmail||P.user_email||P.email||"",D=(F||S||"XX").split(" ").map(H=>H[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:M||`spectator-${s}-${q}-${Date.now()}`,userId:M,name:F||S||"Spectator",email:S,role:"Spectator",department:P.department||"",avatar:D,level:1,canClose:!1}});n(P=>({...P,template:R,title:y.title||"",description:y.description||"",priority:L[k]||"standard",approvers:w,approverCount:w.length||1,spectators:A,maxLevel:Math.max(...w.map(q=>q.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:g,setExistingDocuments:p}}const sc=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function Xj(t,s,a){const[r,n]=x.useState(t?2:1),i=sc.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:sc,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 Jj(){const[t,s]=x.useState({open:!1,type:"error",email:"",message:""}),[a,r]=x.useState({open:!1,violations:[]}),[n,i]=x.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(h,g,p="")=>{s({open:!0,type:h,email:g,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 Qj(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 eN(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 tN(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 Qm(t,s,a){const r=Qj(t),n=(t==null?void 0:t.userId)||"",i=eN(s,n),o=tN(a,n);return[r,...i,...o]}function sN(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 aN(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function rN(t,s,a){var n;const r=aN(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 nN(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return rN(a,n,n===s)})}function ac(t,s,a){const r=Qm(a,t.approvers||[],t.spectators||[]),n=sN(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 rc(t,s,a){const r=nN(t.approvers||[],t.approverCount||1),n=Qm(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 iN(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 eu(t,s){return{id:(await od(t,s||[],"SUPPORTING")).id}}async function tu(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await Wg(t,s,a||[],r):await qg(t,s)}async function su(t){await ud(t)}async function oN(t,s){const a=await eu(t,s);return await su(a.id),a}async function lN(t,s,a,r){await tu(t,s,a,r),await su(t)}function cN({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:o,onSubmit:l}){const[c,m]=x.useState(!1),[d,u]=x.useState(!1);return{submitting:c,savingDraft:d,handleSubmit:async()=>{if(c||d)return;const p=iN(t.approvers||[],t.approverCount||1);if(!p.valid){alert(p.message);return}m(!0);try{if(i&&o){const f=rc(t,n,r);await lN(o,f,a,r),l==null||l({...t,backendId:o,template:s})}else{const f=ac(t,s,n),v=await oN(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=rc(t,n,r);await tu(o,p,a,r),l==null||l({...t,backendId:o,template:s})}else{const p=ac(t,s,n),f=await eu(p,a);l==null||l({...t,backendId:f.id,template:s})}}catch(p){console.error("Failed to save draft:",p),u(!1)}}}}}async function dN(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 ms(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 ys({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 mN(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 dN(o,s);if(!l.success)return{success:!1,error:l.error};try{const d=(((n=(await ms(o.email,1)).data)==null?void 0:n.data)||[])[0];if(d){const u=await ys({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 uN({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]=x.useState(!1),[g,p]=x.useState(null);return{showTemplateModal:u,setShowTemplateModal:h,previewDocument:g,selectTemplate:C=>{s(C),a("template",C.id),a("category",C.category),a("priority",C.priority);const k=new Date;k.setDate(k.getDate()+C.suggestedSLA),a("slaEndDate",k),C.id==="existing-template"&&h(!0)},handleTemplateSelection:C=>{d&&d({templateType:C})},nextStep:async()=>{var C;if(i()){if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){const k=((C=c==null?void 0:c.email)==null?void 0:C.toLowerCase())||"",L=await mN(r.approvers,k);if(!L.success&&L.error){m(L.error.type,L.error.email,L.error.message);return}L.validatedApprovers&&a("approvers",L.validatedApprovers)}o()}},prevStep:()=>{l(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(C,k)=>{if(k){const L=C.documentId||C.document_id||"";p({fileName:C.originalFileName||C.fileName||"Document",fileType:C.fileType||C.file_type||"application/octet-stream",fileUrl:md(L),fileSize:Number(C.fileSize||C.file_size||0),documentId:L})}else{const L=URL.createObjectURL(C);p({fileName:C.name,fileType:C.type||"application/octet-stream",fileUrl:L,fileSize:C.size,file:C})}},closePreview:()=>{g!=null&&g.fileUrl&&(g!=null&&g.file)&&URL.revokeObjectURL(g.fileUrl),p(null)}}}const nc=[{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:Tr,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:Te,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];function hN({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(ya,{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 pN({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(E,{variant:"outline",onClick:r,disabled:t===1,size:"sm",className:"sm:size-lg order-2 sm:order-1","data-testid":"wizard-footer-prev-button",children:[e.jsx(Ms,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Previous"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 order-1 sm:order-2","data-testid":"wizard-footer-actions",children:[e.jsx(E,{variant:"outline",onClick: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"}),e.jsx("span",{children:d?"Updating...":"Saving..."})]}):e.jsx("span",{children:d?"Update Draft":"Save Draft"})}),t===s?e.jsx(E,{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(zc,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(E,{onClick:n,disabled:!a,size:"sm",className:"sm:size-lg flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-next-button",children:[e.jsx("span",{className:"hidden sm:inline",children:"Next Step"}),e.jsx("span",{className:"sm:hidden",children:"Next"}),e.jsx(gt,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const ic=t=>{switch(t){case"high":return e.jsx(ns,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(et,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ls,{className:"w-4 h-4 text-green-600"});default:return e.jsx(et,{className:"w-4 h-4 text-gray-600"})}};function xN({templates:t,selectedTemplate:s,onSelectTemplate:a}){return e.jsxs(vt.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(vt.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(se,{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(vt.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(ya,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ae,{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(Q,{variant:"secondary",className:"text-xs","data-testid":`template-card-${r.id}-category`,children:r.category}),ic(r.priority)]})]})]}),e.jsxs(K,{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(jt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${r.id}-estimated-time`,children:[e.jsx(Re,{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(Je,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[r.commonApprovers.length," approvers"]})]})]})]})]})},r.id))}),e.jsx(Or,{children:s&&e.jsx(vt.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(se,{children:e.jsxs(ae,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Cr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(K,{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(J,{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(J,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[ic(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(J,{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(J,{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(Q,{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 gN({className:t,...s}){return e.jsx(Ah,{"data-slot":"radio-group",className:he("grid gap-3",t),...s})}function oc({className:t,...s}){return e.jsx(Th,{"data-slot":"radio-group-item",className:he("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(kh,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(jp,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function fN({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(vt.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(Te,{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(J,{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(pe,{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(J,{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(J,{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(gN,{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(oc,{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(wr,{className:"w-4 h-4 text-red-600"}),e.jsx(J,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(Q,{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(oc,{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(Re,{className:"w-4 h-4 text-blue-600"}),e.jsx(J,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(Q,{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(J,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(pe,{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(J,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(Ne,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Ce,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(we,{})}),e.jsxs(Se,{children:[e.jsx(z,{value:"USD",children:"USD ($)"}),e.jsx(z,{value:"EUR",children:"EUR (€)"}),e.jsx(z,{value:"GBP",children:"GBP (£)"}),e.jsx(z,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(J,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(pe,{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(J,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(pe,{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(J,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(pe,{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 yN(){const[t,s]=x.useState([]),[a,r]=x.useState(!1),n=x.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),g=((d=(await ms(u,m)).data)==null?void 0:d.data)||[];s(g)}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 ys({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 vN(){const[t,s]=x.useState({}),[a,r]=x.useState({}),n=x.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),g=((d=(await ms(u,m)).data)==null?void 0:d.data)||[];s(p=>({...p,[l]:g}))}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 bN({formData:t,updateFormData:s,onValidationError:a}){const{userSearchResults:r,userSearchLoading:n,searchUsersForIndex:i,clearSearchForIndex:o}=vN();x.useEffect(()=>{const m=t.approverCount||1,d=t.approvers||[];if(d.length<m){const u=[...d];for(let h=d.length;h<m;h++)u[h]||(u[h]={email:"",name:"",level:h+1,tat:""});s("approvers",u)}else d.length>m&&s("approvers",d.slice(0,m))},[t.approverCount,s]);const l=(m,d)=>{var p,f,v,j,y;const u=[...t.approvers],g=((p=u[m])==null?void 0:p.email)!==d;if(u[m]={...u[m],email:d,level:m+1,userId:g||(f=u[m])==null?void 0:f.userId,name:g||(v=u[m])==null?void 0:v.name,department:g||(j=u[m])==null?void 0:j.department,avatar:g||(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)=>{var u,h;try{if((u=t.approvers)==null?void 0:u.some((j,y)=>{var N,b;return y!==m&&(j.userId===d.userId||((N=j.email)==null?void 0:N.toLowerCase())===((b=d.email)==null?void 0:b.toLowerCase()))})){a({type:"error",email:d.email,message:"This user is already added as an approver in another level."});return}if((h=t.spectators)==null?void 0:h.some(j=>{var y,N;return j.userId===d.userId||((y=j.email)==null?void 0:y.toLowerCase())===((N=d.email)==null?void 0:N.toLowerCase())})){a({type:"error",email:d.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const f=await ys({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}),v=[...t.approvers];v[m]={...v[m],email:d.email,name:d.displayName||[d.firstName,d.lastName].filter(Boolean).join(" "),userId:f.userId,level:m+1},s("approvers",v),o(m)}catch(g){console.error("Failed to ensure user exists:",g),a({type:"error",email:d.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(vt.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(Je,{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(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(ra,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(ue,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(K,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(J,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const 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(Np,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-2xl font-semibold w-12 text-center","data-testid":"approval-workflow-count-display",children:t.approverCount||1}),e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const 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(Es,{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(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(kt,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(ue,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(K,{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(rt,{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(Q,{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 p,f;const u=d+1,h=u===(t.approverCount||1),g=t.approvers[d]||{email:"",tat:""};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 ${g.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 ${g.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(Q,{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(J,{htmlFor:`approver-${u}`,className:"text-sm font-medium",children:"Email Address *"}),g.email&&g.userId&&e.jsxs(Q,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(ye,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{id:`approver-${u}`,type:"email",placeholder:"approver@royalenfield.com",value:g.email||"",onChange:v=>l(d,v.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]||(((p=r[d])==null?void 0:p.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:(f=r[d])==null?void 0:f.map(v=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>c(d,v),"data-testid":`approval-workflow-approver-${u}-search-result-${v.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:v.displayName||v.email}),e.jsx("div",{className:"text-xs text-gray-600",children:v.email})]},v.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${u}-tat-field`,children:[e.jsx(J,{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(pe,{id:`tat-${u}`,type:"number",placeholder:g.tatType==="days"?"7":"24",min:"1",max:g.tatType==="days"?"30":"720",value:g.tat||"",onChange:v=>{const j=[...t.approvers];j[d]={...j[d],tat:parseInt(v.target.value)||"",level:u,tatType:g.tatType||"hours"},s("approvers",j)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${u}-tat-input`}),e.jsxs(Ne,{value:g.tatType||"hours",onValueChange:v=>{const j=[...t.approvers];j[d]={...j[d],tatType:v,level:u,tat:""},s("approvers",j)},"data-testid":`approval-workflow-approver-${u}-tat-type-select`,children:[e.jsx(Ce,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(we,{})}),e.jsxs(Se,{children:[e.jsx(z,{value:"hours",children:"Hours"}),e.jsx(z,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},u)})]})]})]})]})}function jN({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=x.useState(""),{searchResults:o,searchLoading:l,searchUsersDebounced:c,clearSearch:m,ensureUser:d}=yN(),u=p=>{if(i(p),!p||!p.startsWith("@")||p.length<2){m();return}c(p,10)},h=async p=>{var f,v;if(p){if(p.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:p.email,message:"You cannot add yourself as a spectator."});return}const j=t.spectators.some(N=>{var b,C;return N.userId===p.userId||((b=N.email)==null?void 0:b.toLowerCase())===((C=p.email)==null?void 0:C.toLowerCase())}),y=(f=t.approvers)==null?void 0:f.some(N=>{var b,C;return N.userId===p.userId||((b=N.email)==null?void 0:b.toLowerCase())===((C=p.email)==null?void 0:C.toLowerCase())});if(j){a({type:"error",email:p.email,message:"This user is already added as a spectator."});return}if(y){a({type:"error",email:p.email,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}try{const N=await d(p),b={id:N.userId,userId:N.userId,name:N.displayName||p.email.split("@")[0],email:N.email,avatar:(N.displayName||N.email).substring(0,2).toUpperCase(),role:"Spectator",department:N.department||"",level:1,canClose:!1},C=[...t.spectators,b];s("spectators",C),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)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const j=t.spectators.some(N=>{var b;return((b=N.email)==null?void 0:b.toLowerCase())===n.toLowerCase()}),y=(v=t.approvers)==null?void 0:v.some(N=>{var b;return((b=N.email)==null?void 0:b.toLowerCase())===n.toLowerCase()});if(j){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(y){a({type:"error",email:n,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}}},g=p=>{const f=t.spectators.filter(v=>v.id!==p);s("spectators",f)};return e.jsxs(vt.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(bt,{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(se,{children:[e.jsxs(ae,{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(bt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(Q,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(ue,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(K,{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(pe,{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(E,{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(Cr,{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(ft,{className:"h-6 w-6",children:e.jsx(yt,{className:"bg-teal-600 text-white text-xs",children:p.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:p.name})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>g(p.id),"data-testid":`participants-spectator-${p.id}-remove`,children:e.jsx(dt,{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=[],N=[];v.forEach(b=>{if(b.size>j){y.push({fileName:b.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(b.size/1048576).toFixed(2)}MB`});return}const C=b.name.toLowerCase(),k=C.substring(C.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(k)){y.push({fileName:b.name,reason:`File type "${k}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}N.push(b)}),N.length>0&&i([...a,...N]),y.length>0&&m&&m(y),f.target&&(f.target.value="")},h=f=>{const v=a.filter((j,y)=>y!==f);i(v)},g=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(vt.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(xa,{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(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Te,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(ue,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(K,{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(xa,{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(E,{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(Es,{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(se,{children:e.jsxs(ae,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(Q,{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(K,{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(Te,{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(E,{variant:"ghost",size:"sm",onClick:()=>c(f,!0),"data-testid":`documents-existing-${v}-preview`,children:e.jsx(bt,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>g(v),"data-testid":`documents-existing-${v}-delete`,children:e.jsx(dt,{className:"h-4 w-4 text-red-600"})})]})]},v)})})})]}),a.length>0&&e.jsxs(W,{"data-testid":"documents-new-card",children:[e.jsx(se,{children:e.jsxs(ae,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(Q,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(K,{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(Te,{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(E,{variant:"ghost",size:"sm",onClick:()=>c(f,!1),"data-testid":`documents-new-${v}-preview`,children:e.jsx(bt,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>h(v),"data-testid":`documents-new-${v}-remove`,children:e.jsx(dt,{className:"h-4 w-4"})})]})]},v))})})]})]})]})}const wN=t=>{switch(t){case"high":return e.jsx(ns,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(et,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ls,{className:"w-4 h-4 text-green-600"});default:return e.jsx(et,{className:"w-4 h-4 text-gray-600"})}};function CN({formData:t,selectedTemplate:s}){return e.jsxs(vt.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(ye,{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(se,{children:e.jsxs(ae,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(zc,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(K,{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(J,{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(Q,{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(J,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[wN(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(J,{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(J,{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(se,{children:e.jsxs(ae,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Te,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(K,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(J,{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(wp,{className:"w-4 h-4 text-blue-600"}),e.jsx(J,{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(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(Je,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(ue,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(K,{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(Q,{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(se,{children:e.jsxs(ae,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(bt,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(K,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(J,{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(Q,{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(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(xa,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(ue,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(K,{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(Te,{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(K,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(ye,{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 SN({isEditing:t,currentStep:s,totalSteps:a,stepNames:r,onBack:n}){return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0","data-testid":"create-request-header",children:e.jsxs("div",{className:"flex items-center justify-between max-w-6xl mx-auto gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-1 min-w-0",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"create-request-back-button",children:e.jsx(Ms,{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 AN({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(Or,{mode:"wait",children:t})})})}function TN({modal:t,onClose:s}){return e.jsx(mt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(nt,{className:"sm:max-w-md",children:[e.jsxs(ut,{children:[e.jsxs(it,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Pe,{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(Tr,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use"," ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," ","sign to search and select users from the directory for guaranteed results."]})})]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:[t.email&&e.jsxs(e.Fragment,{children:["Failed to validate ",e.jsx("strong",{children:t.email}),"."]}),!t.email&&e.jsx(e.Fragment,{children:"An error occurred during validation."})]}),t.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:t.message})})]})]})})]}),e.jsx(Rt,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function kN({modal:t,documentPolicy:s,onClose:a}){return e.jsx(mt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(nt,{className:"sm:max-w-lg",children:[e.jsxs(ut,{children:[e.jsxs(it,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Pe,{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(Rt,{children:e.jsx(E,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function lc({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Wa(),i=Os(),o=n.requestId||a||"",l=r&&!!o,{user:c}=$t(),{formData:m,updateFormData:d,selectedTemplate:u,setSelectedTemplate:h,loadingDraft:g,systemPolicy:p,documentPolicy:f,existingDocuments:v,setExistingDocuments:j}=Zj(l,o,nc),{currentStep:y,totalSteps:N,stepNames:b,isStepValid:C,nextStep:k,prevStep:L}=Xj(l,u,m),[R,I]=x.useState([]),[w,A]=x.useState([]),P=x.useRef(null),{validationModal:q,policyViolationModal:M,documentErrorModal:F,openValidationModal:S,closeValidationModal:T,closePolicyViolationModal:D,openDocumentErrorModal:H,closeDocumentErrorModal:O}=Jj(),{submitting:_,savingDraft:ee,handleSubmit:G,handleSaveDraft:Y}=cN({formData:m,selectedTemplate:u,documents:R,documentsToDelete:w,user:c,isEditing:l,editRequestId:o,onSubmit:s}),{showTemplateModal:me,setShowTemplateModal:X,previewDocument:B,selectTemplate:ne,handleTemplateSelection:V,nextStep:Z,prevStep:re,handlePreviewDocument:ge,closePreview:ve}=uN({selectedTemplate:u,setSelectedTemplate:h,updateFormData:d,formData:m,currentStep:y,isStepValid:C,wizardNextStep:k,wizardPrevStep:L,user:c,openValidationModal:S,onSubmit:s}),Ue=x.useCallback(()=>{y===1||y===3||y===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):re()},[y,t,i,re]),Ie=x.useRef(!0),Le=x.useRef(!1);x.useEffect(()=>{Ie.current&&m.documents&&m.documents.length>0&&!Le.current&&(I(m.documents),Le.current=!0),Ie.current=!1},[m.documents]);const tt=x.useRef(!1),He=x.useRef(R);x.useEffect(()=>{if(tt.current){tt.current=!1,He.current=R;return}He.current!==R&&(d("documents",R),He.current=R)},[R]);const Dt=()=>{switch(y){case 1:return e.jsx(xN,{templates:nc,selectedTemplate:u,onSelectTemplate:ne});case 2:return e.jsx(fN,{formData:m,selectedTemplate:u,updateFormData:d});case 3:return e.jsx(bN,{formData:m,updateFormData:d,onValidationError:_e=>S(_e.type,_e.email,_e.message)});case 4:return e.jsx(jN,{formData:m,updateFormData:d,onValidationError:_e=>S(_e.type,_e.email,_e.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(NN,{documentPolicy:f,isEditing:l,documents:R,existingDocuments:v,documentsToDelete:w,onDocumentsChange:I,onExistingDocumentsChange:j,onDocumentsToDeleteChange:A,onPreviewDocument:ge,onDocumentErrors:_e=>H(_e),fileInputRef:P});case 6:return e.jsx(CN,{formData:m,selectedTemplate:u});default:return null}};return g?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(SN,{isEditing:l,currentStep:y,totalSteps:N,stepNames:b,onBack:Ue}),e.jsx(hN,{currentStep:y,totalSteps:N,stepNames:b}),e.jsx(AN,{children:Dt()}),e.jsx(pN,{currentStep:y,totalSteps:N,isStepValid:C(),onPrev:re,onNext:Z,onSubmit:G,onSaveDraft:Y,submitting:_,savingDraft:ee,loadingDraft:g,isEditing:l}),e.jsx(Gj,{open:me,onClose:()=>X(!1),onSelectTemplate:V}),B&&e.jsx(wi,{fileName:B.fileName,fileType:B.fileType,fileUrl:B.fileUrl,fileSize:B.fileSize,open:!!B,onClose:ve,onDownload:async()=>{if(B.file){const _e=document.createElement("a");_e.href=B.fileUrl,_e.download=B.fileName,document.body.appendChild(_e),_e.click(),document.body.removeChild(_e)}else B.documentId&&await _n(B.documentId)},attachmentId:B.documentId}),e.jsx(TN,{modal:q,onClose:T}),e.jsx(kN,{modal:F,documentPolicy:f,onClose:O}),e.jsx(fd,{open:M.open,onClose:D,violations:M.violations,policyDetails:{maxApprovalLevels:p.maxApprovalLevels,maxParticipants:p.maxParticipants,allowSpectators:p.allowSpectators,maxSpectators:p.maxSpectators}})]})}var je=function(){return je=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},je.apply(this,arguments)};function RN(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 au(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 Xa(t){return t.mode==="multiple"}function Ja(t){return t.mode==="range"}function Br(t){return t.mode==="single"}var DN={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 xe(t,"LLLL y",s)}function EN(t,s){return xe(t,"d",s)}function MN(t,s){return xe(t,"LLLL",s)}function IN(t){return"".concat(t)}function FN(t,s){return xe(t,"cccccc",s)}function LN(t,s){return xe(t,"yyyy",s)}var _N=Object.freeze({__proto__:null,formatCaption:PN,formatDay:EN,formatMonthCaption:MN,formatWeekNumber:IN,formatWeekdayName:FN,formatYearCaption:LN}),ON=function(t,s,a){return xe(t,"do MMMM (EEEE)",a)},$N=function(){return"Month: "},UN=function(){return"Go to next month"},VN=function(){return"Go to previous month"},BN=function(t,s){return xe(t,"cccc",s)},zN=function(t){return"Week n. ".concat(t)},HN=function(){return"Year: "},qN=Object.freeze({__proto__:null,labelDay:ON,labelMonthDropdown:$N,labelNext:UN,labelPrevious:VN,labelWeekNumber:zN,labelWeekday:BN,labelYearDropdown:HN});function WN(){var t="buttons",s=DN,a=qh,r={},n={},i=1,o={},l=new Date;return{captionLayout:t,classNames:s,formatters:_N,labels:qN,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:o,today:l,mode:"default"}}function KN(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,o=t.toDate;return r?i=zt(r):s&&(i=new Date(s,0,1)),n?o=mi(n):a&&(o=new Date(a,11,31)),{fromDate:i?vo(i):void 0,toDate:o?vo(o):void 0}}var ru=x.createContext(void 0);function GN(t){var s,a=t.initialProps,r=WN(),n=KN(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;(Br(a)||Xa(a)||Ja(a))&&(c=a.onSelect);var m=je(je(je({},r),a),{captionLayout:l,classNames:je(je({},r.classNames),a.classNames),components:je({},a.components),formatters:je(je({},r.formatters),a.formatters),fromDate:i,labels:je(je({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:je(je({},r.modifiers),a.modifiers),modifiersClassNames:je(je({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:je(je({},r.styles),a.styles),toDate:o});return e.jsx(ru.Provider,{value:m,children:t.children})}function ze(){var t=x.useContext(ru);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function nu(t){var s=ze(),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 YN(t){return e.jsx("svg",je({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 iu(t){var s,a,r=t.onChange,n=t.value,i=t.children,o=t.caption,l=t.className,c=t.style,m=ze(),d=(a=(s=m.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:YN;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 ZN(t){var s,a=ze(),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(Xh(r,n))for(var h=zt(r),g=r.getMonth();g<=n.getMonth();g++)u.push(Yr(h,g));else for(var h=zt(new Date),g=0;g<=11;g++)u.push(Yr(h,g));var p=function(v){var j=Number(v.target.value),y=Yr(zt(t.displayMonth),j);t.onChange(y)},f=(s=m==null?void 0:m.Dropdown)!==null&&s!==void 0?s:iu;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 XN(t){var s,a=t.displayMonth,r=ze(),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 g=n.getFullYear(),p=i.getFullYear(),f=g;f<=p;f++)h.push(bo(Jh(new Date),f));var v=function(y){var N=bo(zt(a),Number(y.target.value));t.onChange(N)},j=(s=m==null?void 0:m.Dropdown)!==null&&s!==void 0?s:iu;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 JN(t,s){var a=x.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function QN(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=ls(i,m)}return o&&_a(n,o)<0&&(n=o),zt(n)}function ew(){var t=ze(),s=QN(t),a=JN(s,t.month),r=a[0],n=a[1],i=function(o){var l;if(!t.disableNavigation){var c=zt(o);n(c),(l=t.onMonthChange)===null||l===void 0||l.call(t,c)}};return[r,i]}function tw(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=zt(t),i=zt(ls(n,r)),o=_a(i,n),l=[],c=0;c<o;c++){var m=ls(n,c);l.push(m)}return a&&(l=l.reverse()),l}function sw(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=zt(t);if(!a)return ls(l,o);var c=_a(a,t);if(!(c<i))return ls(l,o)}}function aw(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=zt(t);if(!a)return ls(l,-o);var c=_a(l,a);if(!(c<=0))return ls(l,-o)}}var ou=x.createContext(void 0);function rw(t){var s=ze(),a=ew(),r=a[0],n=a[1],i=tw(r,s),o=sw(r,s),l=aw(r,s),c=function(u){return i.some(function(h){return ui(u,h)})},m=function(u,h){c(u)||(h&&Ic(u,h)?n(ls(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(ou.Provider,{value:d,children:t.children})}function Qa(){var t=x.useContext(ou);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function cc(t){var s,a=ze(),r=a.classNames,n=a.styles,i=a.components,o=Qa().goToMonth,l=function(d){o(ls(d,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:nu,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(ZN,{onChange:l,displayMonth:t.displayMonth}),e.jsx(XN,{onChange:l,displayMonth:t.displayMonth})]})}function nw(t){return e.jsx("svg",je({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 iw(t){return e.jsx("svg",je({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 br=x.forwardRef(function(t,s){var a=ze(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var o=i.join(" "),l=je(je({},n.button_reset),n.button);return t.style&&Object.assign(l,t.style),e.jsx("button",je({},t,{ref:s,type:"button",className:o,style:l}))});function ow(t){var s,a,r=ze(),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}),g=[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:iw,j=(a=u==null?void 0:u.IconLeft)!==null&&a!==void 0?a:nw;return e.jsxs("div",{className:o.nav,style:l.nav,children:[!t.hidePrevious&&e.jsx(br,{name:"previous-month","aria-label":h,className:g,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(br,{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 dc(t){var s=ze().numberOfMonths,a=Qa(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,o=a.displayMonths,l=o.findIndex(function(p){return ui(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)},g=function(){n&&i(n)};return e.jsx(ow,{displayMonth:t.displayMonth,hideNext:d,hidePrevious:u,nextMonth:n,previousMonth:r,onPreviousClick:h,onNextClick:g})}function lw(t){var s,a=ze(),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:nu,m;return n?m=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):o==="dropdown"?m=e.jsx(cc,{displayMonth:t.displayMonth,id:t.id}):o==="dropdown-buttons"?m=e.jsxs(e.Fragment,{children:[e.jsx(cc,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(dc,{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(dc,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:m})}function cw(t){var s=ze(),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 dw(t,s,a){for(var r=a?hi(new Date):pi(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var o=Vt(r,i);n.push(o)}return n}function mw(){var t=ze(),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=dw(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 uw(){var t,s=ze(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:mw;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function hw(t){var s=ze(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var ro=x.createContext(void 0);function pw(t){if(!Xa(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(ro.Provider,{value:s,children:t.children})}return e.jsx(xw,{initialProps:t.initialProps,children:t.children})}function xw(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,o=function(m,d,u){var h,g;(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?au([],r):[];if(d.selected){var j=v.findIndex(function(y){return Ft(m,y)});v.splice(j,1)}else v.push(m);(g=s.onSelect)===null||g===void 0||g.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 Ft(h,m)});return!!(d&&!u)});var c={selected:r,onDayClick:o,modifiers:l};return e.jsx(ro.Provider,{value:c,children:a})}function no(){var t=x.useContext(ro);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function gw(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?Ft(n,t)&&Ft(r,t)?void 0:Ft(n,t)?{from:n,to:void 0}:Ft(r,t)?void 0:kn(r,t)?{from:t,to:n}:{from:r,to:t}:n?kn(t,n)?{from:n,to:t}:{from:t,to:n}:r?Ic(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var io=x.createContext(void 0);function fw(t){if(!Ja(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(io.Provider,{value:s,children:t.children})}return e.jsx(yw,{initialProps:t.initialProps,children:t.children})}function yw(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(g,p,f){var v,j;(v=s.onDayClick)===null||v===void 0||v.call(s,g,p,f);var y=gw(g,r);(j=s.onSelect)===null||j===void 0||j.call(s,y,g,p,f)},d={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(d.range_start=[i],o?(d.range_end=[o],Ft(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:Gr(i,l-1),before:Vt(i,l-1)}),i&&o&&d.disabled.push({after:i,before:Vt(i,l-1)}),!i&&o&&d.disabled.push({after:Gr(o,l-1),before:Vt(o,l-1)})),c){if(i&&!o&&(d.disabled.push({before:Vt(i,-c+1)}),d.disabled.push({after:Vt(i,c-1)})),i&&o){var u=fs(o,i)+1,h=c-u;d.disabled.push({before:Gr(i,h)}),d.disabled.push({after:Vt(o,h)})}!i&&o&&(d.disabled.push({before:Vt(o,-c+1)}),d.disabled.push({after:Vt(o,c-1)}))}return e.jsx(io.Provider,{value:{selected:r,onDayClick:m,modifiers:d},children:a})}function oo(){var t=x.useContext(io);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function ur(t){return Array.isArray(t)?au([],t):t!==void 0?[t]:[]}function vw(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=ur(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 bw=rs.Selected,gs=rs.Disabled,jw=rs.Hidden,Nw=rs.Today,bn=rs.RangeEnd,jn=rs.RangeMiddle,Nn=rs.RangeStart,ww=rs.Outside;function Cw(t,s,a){var r,n=(r={},r[bw]=ur(t.selected),r[gs]=ur(t.disabled),r[jw]=ur(t.hidden),r[Nw]=[t.today],r[bn]=[],r[jn]=[],r[Nn]=[],r[ww]=[],r);return t.fromDate&&n[gs].push({before:t.fromDate}),t.toDate&&n[gs].push({after:t.toDate}),Xa(t)?n[gs]=n[gs].concat(s.modifiers[gs]):Ja(t)&&(n[gs]=n[gs].concat(a.modifiers[gs]),n[Nn]=a.modifiers[Nn],n[jn]=a.modifiers[jn],n[bn]=a.modifiers[bn]),n}var lu=x.createContext(void 0);function Sw(t){var s=ze(),a=no(),r=oo(),n=Cw(s,a,r),i=vw(s.modifiers),o=je(je({},n),i);return e.jsx(lu.Provider,{value:o,children:t.children})}function cu(){var t=x.useContext(lu);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function Aw(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function Tw(t){return!!(t&&typeof t=="object"&&"from"in t)}function kw(t){return!!(t&&typeof t=="object"&&"after"in t)}function Rw(t){return!!(t&&typeof t=="object"&&"before"in t)}function Dw(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?Ft(n,t):r?Ft(r,t):!1}function Ew(t){return _c(t)}function Mw(t){return Array.isArray(t)&&t.every(_c)}function Iw(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(Ew(a))return Ft(t,a);if(Mw(a))return a.includes(t);if(Tw(a))return Pw(t,a);if(Dw(a))return a.dayOfWeek.includes(t.getDay());if(Aw(a)){var r=fs(a.before,t),n=fs(a.after,t),i=r>0,o=n<0,l=kn(a.before,a.after);return l?o&&i:i||o}return kw(a)?fs(t,a.after)>0:Rw(a)?fs(a.before,t)>0:typeof a=="function"?a(t):!1})}function lo(t,s,a){var r=Object.keys(s).reduce(function(i,o){var l=s[o];return Iw(t,l)&&i.push(o),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!ui(t,a)&&(n.outside=!0),n}function Fw(t,s){for(var a=zt(t[0]),r=mi(t[t.length-1]),n,i,o=a;o<=r;){var l=lo(o,s),c=!l.disabled&&!l.hidden;if(!c){o=Vt(o,1);continue}if(l.selected)return o;l.today&&!i&&(i=o),n||(n=o),o=Vt(o,1)}return i||n}var Lw=365;function du(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:Vt,week:Tn,month:ls,year:Gh,startOfWeek:function(v){return n.ISOWeek?hi(v):pi(v,{locale:u,weekStartsOn:c})},endOfWeek:function(v){return n.ISOWeek?Fc(v):Lc(v,{locale:u,weekStartsOn:c})}},g=h[a](t,r==="after"?1:-1);r==="before"&&m?g=Yh([m,g]):r==="after"&&d&&(g=Zh([d,g]));var p=!0;if(i){var f=lo(g,i);p=!f.disabled&&!f.hidden}return p?g:l.count>Lw?l.lastFocused:du(g,{moveBy:a,direction:r,context:n,modifiers:i,retry:je(je({},l),{count:l.count+1})})}var mu=x.createContext(void 0);function _w(t){var s=Qa(),a=cu(),r=x.useState(),n=r[0],i=r[1],o=x.useState(),l=o[0],c=o[1],m=Fw(s.displayMonths,a),d=n??(l&&s.isDateDisplayed(l))?l:m,u=function(){c(n),i(void 0)},h=function(v){i(v)},g=ze(),p=function(v,j){if(n){var y=du(n,{moveBy:v,direction:j,context:g,modifiers:a});Ft(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(mu.Provider,{value:f,children:t.children})}function co(){var t=x.useContext(mu);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function Ow(t,s){var a=cu(),r=lo(t,a,s);return r}var mo=x.createContext(void 0);function $w(t){if(!Br(t.initialProps)){var s={selected:void 0};return e.jsx(mo.Provider,{value:s,children:t.children})}return e.jsx(Uw,{initialProps:t.initialProps,children:t.children})}function Uw(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(mo.Provider,{value:n,children:a})}function uu(){var t=x.useContext(mo);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function Vw(t,s){var a=ze(),r=uu(),n=no(),i=oo(),o=co(),l=o.focusDayAfter,c=o.focusDayBefore,m=o.focusWeekAfter,d=o.focusWeekBefore,u=o.blur,h=o.focus,g=o.focusMonthBefore,p=o.focusMonthAfter,f=o.focusYearBefore,v=o.focusYearAfter,j=o.focusStartOfWeek,y=o.focusEndOfWeek,N=function(T){var D,H,O,_;Br(a)?(D=r.onDayClick)===null||D===void 0||D.call(r,t,s,T):Xa(a)?(H=n.onDayClick)===null||H===void 0||H.call(n,t,s,T):Ja(a)?(O=i.onDayClick)===null||O===void 0||O.call(i,t,s,T):(_=a.onDayClick)===null||_===void 0||_.call(a,t,s,T)},b=function(T){var D;h(t),(D=a.onDayFocus)===null||D===void 0||D.call(a,t,s,T)},C=function(T){var D;u(),(D=a.onDayBlur)===null||D===void 0||D.call(a,t,s,T)},k=function(T){var D;(D=a.onDayMouseEnter)===null||D===void 0||D.call(a,t,s,T)},L=function(T){var D;(D=a.onDayMouseLeave)===null||D===void 0||D.call(a,t,s,T)},R=function(T){var D;(D=a.onDayPointerEnter)===null||D===void 0||D.call(a,t,s,T)},I=function(T){var D;(D=a.onDayPointerLeave)===null||D===void 0||D.call(a,t,s,T)},w=function(T){var D;(D=a.onDayTouchCancel)===null||D===void 0||D.call(a,t,s,T)},A=function(T){var D;(D=a.onDayTouchEnd)===null||D===void 0||D.call(a,t,s,T)},P=function(T){var D;(D=a.onDayTouchMove)===null||D===void 0||D.call(a,t,s,T)},q=function(T){var D;(D=a.onDayTouchStart)===null||D===void 0||D.call(a,t,s,T)},M=function(T){var D;(D=a.onDayKeyUp)===null||D===void 0||D.call(a,t,s,T)},F=function(T){var D;switch(T.key){case"ArrowLeft":T.preventDefault(),T.stopPropagation(),a.dir==="rtl"?l():c();break;case"ArrowRight":T.preventDefault(),T.stopPropagation(),a.dir==="rtl"?c():l();break;case"ArrowDown":T.preventDefault(),T.stopPropagation(),m();break;case"ArrowUp":T.preventDefault(),T.stopPropagation(),d();break;case"PageUp":T.preventDefault(),T.stopPropagation(),T.shiftKey?f():g();break;case"PageDown":T.preventDefault(),T.stopPropagation(),T.shiftKey?v():p();break;case"Home":T.preventDefault(),T.stopPropagation(),j();break;case"End":T.preventDefault(),T.stopPropagation(),y();break}(D=a.onDayKeyDown)===null||D===void 0||D.call(a,t,s,T)},S={onClick:N,onFocus:b,onBlur:C,onKeyDown:F,onKeyUp:M,onMouseEnter:k,onMouseLeave:L,onPointerEnter:R,onPointerLeave:I,onTouchCancel:w,onTouchEnd:A,onTouchMove:P,onTouchStart:q};return S}function Bw(){var t=ze(),s=uu(),a=no(),r=oo(),n=Br(t)?s.selected:Xa(t)?a.selected:Ja(t)?r.selected:void 0;return n}function zw(t){return Object.values(rs).includes(t)}function Hw(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(zw(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function qw(t,s){var a=je({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=je(je({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function Ww(t,s,a){var r,n,i,o=ze(),l=co(),c=Ow(t,s),m=Vw(t,c),d=Bw(),u=!!(o.onDayClick||o.mode!=="default");x.useEffect(function(){var k;c.outside||l.focusedDay&&u&&Ft(l.focusedDay,t)&&((k=a.current)===null||k===void 0||k.focus())},[l.focusedDay,t,a,u,c.outside]);var h=Hw(o,c).join(" "),g=qw(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:hw,v=e.jsx(f,{date:t,displayMonth:s,activeModifiers:c}),j={style:g,className:h,children:v,role:"gridcell"},y=l.focusTarget&&Ft(l.focusTarget,t)&&!c.outside,N=l.focusedDay&&Ft(l.focusedDay,t),b=je(je(je({},j),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=N||y?0:-1,r)),m),C={isButton:u,isHidden:p,activeModifiers:c,selectedDays:d,buttonProps:b,divProps:j};return C}function Kw(t){var s=x.useRef(null),a=Ww(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(br,je({name:"day",ref:s},a.buttonProps)):e.jsx("div",je({},a.divProps))}function Gw(t){var s=t.number,a=t.dates,r=ze(),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(g){n(s,a,g)};return e.jsx(br,{name:"week-number","aria-label":u,className:o.weeknumber,style:i.weeknumber,onClick:h,children:d})}function Yw(t){var s,a,r=ze(),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:Kw,m=(a=l==null?void 0:l.WeekNumber)!==null&&a!==void 0?a:Gw,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})},Kh(u))})]})}function mc(t,s,a){for(var r=a!=null&&a.ISOWeek?Fc(s):Lc(s,a),n=a!=null&&a.ISOWeek?hi(t):pi(t,a),i=fs(r,n),o=[],l=0;l<=i;l++)o.push(Vt(n,l));var c=o.reduce(function(m,d){var u=a!=null&&a.ISOWeek?Qh(d):ep(d,a),h=m.find(function(g){return g.weekNumber===u});return h?(h.dates.push(d),m):(m.push({weekNumber:u,dates:[d]}),m)},[]);return c}function Zw(t,s){var a=mc(zt(t),mi(t),s);if(s!=null&&s.useFixedWeeks){var r=Wh(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],o=Tn(i,6-r),l=mc(Tn(i,1),o,s);a.push.apply(a,l)}}return a}function Xw(t){var s,a,r,n=ze(),i=n.locale,o=n.classNames,l=n.styles,c=n.hideHead,m=n.fixedWeeks,d=n.components,u=n.weekStartsOn,h=n.firstWeekContainsDate,g=n.ISOWeek,p=Zw(t.displayMonth,{useFixedWeeks:!!m,ISOWeek:g,locale:i,weekStartsOn:u,firstWeekContainsDate:h}),f=(s=d==null?void 0:d.Head)!==null&&s!==void 0?s:uw,v=(a=d==null?void 0:d.Row)!==null&&a!==void 0?a:Yw,j=(r=d==null?void 0:d.Footer)!==null&&r!==void 0?r:cw;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 Jw(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Qw=Jw()?x.useLayoutEffect:x.useEffect,wn=!1,e1=0;function uc(){return"react-day-picker-".concat(++e1)}function t1(t){var s,a=t??(wn?uc():null),r=x.useState(a),n=r[0],i=r[1];return Qw(function(){n===null&&i(uc())},[]),x.useEffect(function(){wn===!1&&(wn=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function s1(t){var s,a,r=ze(),n=r.dir,i=r.classNames,o=r.styles,l=r.components,c=Qa().displayMonths,m=t1(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,g=t.displayIndex===0,p=t.displayIndex===c.length-1,f=!g&&!p;n==="rtl"&&(s=[g,p],p=s[0],g=s[1]),g&&(u.push(i.caption_start),h=je(je({},h),o.caption_start)),p&&(u.push(i.caption_end),h=je(je({},h),o.caption_end)),f&&(u.push(i.caption_between),h=je(je({},h),o.caption_between));var v=(a=l==null?void 0:l.Caption)!==null&&a!==void 0?a:lw;return e.jsxs("div",{className:u.join(" "),style:h,children:[e.jsx(v,{id:m,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(Xw,{id:d,"aria-labelledby":m,displayMonth:t.displayMonth})]},t.displayIndex)}function a1(t){var s=ze(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function r1(t){var s,a,r=t.initialProps,n=ze(),i=co(),o=Qa(),l=x.useState(!1),c=l[0],m=l[1];x.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=je(je({},n.styles.root),n.style),h=Object.keys(r).filter(function(p){return p.startsWith("data-")}).reduce(function(p,f){var v;return je(je({},p),(v={},v[f]=r[f],v))},{}),g=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:a1;return e.jsx("div",je({className:d.join(" "),style:u,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},h,{children:e.jsx(g,{children:o.displayMonths.map(function(p,f){return e.jsx(s1,{displayIndex:f,displayMonth:p},f)})})}))}function n1(t){var s=t.children,a=RN(t,["children"]);return e.jsx(GN,{initialProps:a,children:e.jsx(rw,{children:e.jsx($w,{initialProps:a,children:e.jsx(pw,{initialProps:a,children:e.jsx(fw,{initialProps:a,children:e.jsx(Sw,{children:e.jsx(_w,{children:s})})})})})})})}function i1(t){return e.jsx(n1,je({},t,{children:e.jsx(r1,{initialProps:t})}))}function Cn({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(i1,{showOutsideDays:a,className:he("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:he(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:he("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:he(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(Hc,{className:he("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(gi,{className:he("size-4",n),...i})},...r})}const hu={"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 o1(t){return hu[t]||null}function l1(){return Object.values(hu)}function c1(t){return`${t.address}, ${t.city}, ${t.state}`}const d1=["Marketing Activity","Promotional Event","Dealer Training","Infrastructure Development","Customer Experience Initiative","Service Campaign"],m1=l1(),Sn=["Claim Details","Review & Submit"];function u1({onBack:t,onSubmit:s}){const[a,r]=x.useState(1),[n,i]=x.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:""}),o=Sn.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=o1(p);f&&(l("dealerCode",f.code),l("dealerName",f.name),l("dealerEmail",f.email),l("dealerPhone",f.phone),l("dealerAddress",c1(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"}]};ke.success("Claim Request Created",{description:"Your claim management request has been submitted successfully."}),s&&s(p)},g=()=>{switch(a){case 1:return e.jsxs(vt.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(En,{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(J,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(pe,{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(J,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(Ne,{value:n.activityType,onValueChange:p=>l("activityType",p),children:[e.jsx(Ce,{className:"mt-2 h-12",children:e.jsx(we,{placeholder:"Select activity type"})}),e.jsx(Se,{children:d1.map(p=>e.jsx(z,{value:p,children:p},p))})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"dealer",className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsxs(Ne,{value:n.dealerCode,onValueChange:u,children:[e.jsx(Ce,{className:"mt-2 h-12",children:e.jsx(we,{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(Se,{children:m1.map(p=>e.jsx(z,{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(J,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(Rs,{children:[e.jsx(Ds,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(Be,{className:"mr-2 h-4 w-4"}),n.activityDate?xe(n.activityDate,"PPP"):"Select date"]})}),e.jsx(Ps,{className:"w-auto p-0",align:"start",children:e.jsx(Cn,{mode:"single",selected:n.activityDate,onSelect:p=>l("activityDate",p),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(pe,{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(J,{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(J,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(Q,{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(J,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(Rs,{children:[e.jsx(Ds,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(Be,{className:"mr-2 h-4 w-4"}),n.periodStartDate?xe(n.periodStartDate,"PPP"):"Start date"]})}),e.jsx(Ps,{className:"w-auto p-0",align:"start",children:e.jsx(Cn,{mode:"single",selected:n.periodStartDate,onSelect:p=>l("periodStartDate",p),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(Rs,{children:[e.jsx(Ds,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(Be,{className:"mr-2 h-4 w-4"}),n.periodEndDate?xe(n.periodEndDate,"PPP"):"End date"]})}),e.jsx(Ps,{className:"w-auto p-0",align:"start",children:e.jsx(Cn,{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: ${xe(n.periodStartDate,"MMM dd, yyyy")} - ${xe(n.periodEndDate,"MMM dd, yyyy")}`:"Please select both start and end dates for the period"})]})]})]});case 2:return e.jsxs(vt.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(ye,{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(se,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(ae,{className:"flex items-center gap-2",children:[e.jsx(En,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(K,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(J,{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(J,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(Q,{variant:"secondary",className:"mt-1",children:n.activityType})]})]})})]}),e.jsxs(W,{className:"border-2",children:[e.jsx(se,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(ae,{className:"flex items-center gap-2",children:[e.jsx(Cp,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(K,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(J,{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(J,{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(J,{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(J,{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(J,{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(se,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(ae,{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(K,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(J,{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?xe(n.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(J,{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(Sp,{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(J,{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(se,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(ae,{className:"flex items-center gap-2",children:[e.jsx(Te,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(K,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(J,{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(se,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(ae,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(K,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(J,{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?xe(n.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(J,{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?xe(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(Cr,{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(E,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Ms,{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(Q,{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:Sn[a-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(cs,{value:a/o*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:Sn.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(K,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(Or,{mode:"wait",children:g()})})}),e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between gap-3 sm:gap-0 pb-4 sm:pb-0",children:[e.jsxs(E,{variant:"outline",onClick:d,disabled:a===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Ms,{className:"w-4 h-4"}),"Previous"]}),a<o?e.jsxs(E,{onClick:m,disabled:!c(),className:"gap-2 w-full sm:w-auto order-1 sm:order-2",children:["Next",e.jsx(gt,{className:"w-4 h-4"})]}):e.jsxs(E,{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(ya,{className:"w-4 h-4"}),"Submit Claim Request"]})]})]})})}function pu({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(Q,{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",onClick:c}){return e.jsx(W,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":l,onClick:c,children:e.jsx(K,{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 h1({stats:t,onStatusFilter:s}){const a=r=>{s&&s(r)};return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4","data-testid":"my-requests-stats",children:[e.jsx(es,{label:"Total",value:t.total,icon:Te,iconColor:"text-blue-600",gradient:"bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200",textColor:"text-blue-700",valueColor:"text-blue-900",testId:"stat-total",onClick:s?()=>a("all"):void 0}),e.jsx(es,{label:"Pending",value:t.pending,icon:Re,iconColor:"text-orange-600",gradient:"bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200",textColor:"text-orange-700",valueColor:"text-orange-900",testId:"stat-pending",onClick:s?()=>a("pending"):void 0}),e.jsx(es,{label:"Approved",value:t.approved,icon:ye,iconColor:"text-green-600",gradient:"bg-gradient-to-br from-green-50 to-green-100 border-green-200",textColor:"text-green-700",valueColor:"text-green-900",testId:"stat-approved",onClick:s?()=>a("approved"):void 0}),e.jsx(es,{label:"Rejected",value:t.rejected,icon:Ze,iconColor:"text-red-600",gradient:"bg-gradient-to-br from-red-50 to-red-100 border-red-200",textColor:"text-red-700",valueColor:"text-red-900",testId:"stat-rejected",onClick:s?()=>a("rejected"):void 0}),e.jsx(es,{label:"Draft",value:t.draft,icon:Rr,iconColor:"text-gray-600",gradient:"bg-gradient-to-br from-gray-50 to-gray-100 border-gray-200",textColor:"text-gray-700",valueColor:"text-gray-900",testId:"stat-draft",onClick:s?()=>a("draft"):void 0}),e.jsx(es,{label:"Closed",value:t.closed,icon:Dr,iconColor:"text-purple-600",gradient:"bg-gradient-to-br from-purple-50 to-purple-100 border-purple-200",textColor:"text-purple-700",valueColor:"text-purple-900",testId:"stat-closed",onClick:s?()=>a("closed"):void 0})]})}function p1({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(K,{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(qt,{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(pe,{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(Ne,{value:s,onValueChange:n,children:[e.jsx(Ce,{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(we,{placeholder:"Status"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Status"}),e.jsx(z,{value:"draft",children:"Draft"}),e.jsx(z,{value:"pending",children:"Pending"}),e.jsx(z,{value:"approved",children:"Approved"}),e.jsx(z,{value:"rejected",children:"Rejected"}),e.jsx(z,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ne,{value:a,onValueChange:i,children:[e.jsx(Ce,{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(we,{placeholder:"Priority"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Priority"}),e.jsx(z,{value:"express",children:"Express"}),e.jsx(z,{value:"standard",children:"Standard"})]})]})]})]})})})}function x1(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ns,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:et,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:et,iconColor:"text-gray-600"}}}function g1(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:ye,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ze,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Re,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ye,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Rr,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"}}}function f1({request:t,index:s,onViewRequest:a}){const r=g1(t.status),n=x1(t.priority),i=r.icon,o=n.icon;return e.jsx(vt.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(K,{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(Q,{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(Q,{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(Q,{variant:"secondary",className:"bg-purple-100 text-purple-700 text-xs shrink-0 hidden sm:inline-flex","data-testid":"template-badge",children:[e.jsx(Te,{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:"})," ",ds(t.submittedDate)]})]})]}),e.jsx(gt,{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(rt,{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(Ls,{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(Re,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ds(t.submittedDate)]})]})]})]})})})})}function y1({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(K,{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(K,{className:"p-12 text-center",children:[e.jsx(Te,{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(f1,{request:o,index:l,onViewRequest:i},o.id))})}function v1(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 xu(t){return Array.isArray(t)?t.map(v1):[]}function b1({itemsPerPage:t=10,initialFilters:s}={}){const[a,r]=x.useState([]),[n,i]=x.useState(!1),[o,l]=x.useState(!1),[c,m]=x.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=x.useRef(!0),u=x.useCallback(async(h=1,g)=>{try{h===1&&(i(!0),r([]));const p=await Ot.listMyInitiatedWorkflows({page:h,limit:t,search:g==null?void 0:g.search,status:g==null?void 0:g.status,priority:g==null?void 0:g.priority}),f=Array.isArray(p==null?void 0:p.data)?p.data:[],v=xu(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 x.useEffect(()=>{d.current&&(u(1,s),d.current=!1)},[]),{requests:a,loading:n,hasFetchedFromApi:o,pagination:c,fetchMyRequests:u}}function j1({onFiltersChange:t,debounceMs:s=500}={}){const[a,r]=x.useState(""),[n,i]=x.useState("all"),[o,l]=x.useState("all"),c=x.useRef(null),m=x.useCallback(()=>({search:a,status:n,priority:o}),[a,n,o]);x.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=x.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({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=$t(),r=b1({itemsPerPage:10}),n=x.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=j1({onFiltersChange:x.useCallback(f=>{n.current(1,{search:f.search||void 0,status:f.status!=="all"?f.status:void 0,priority:f.priority!=="all"?f.priority:void 0})},[])}),[o,l]=x.useState(null),[c,m]=x.useState(!1),d=x.useCallback(async()=>{if(a!=null&&a.userId)try{m(!0);const f=await Ve.getRequestStats("month",void 0,void 0,i.priorityFilter!=="all"?i.priorityFilter:void 0,void 0,void 0,void 0,void 0,i.searchTerm||void 0,void 0);l({total:f.totalRequests||0,pending:f.openRequests||0,approved:f.approvedRequests||0,rejected:f.rejectedRequests||0,draft:f.draftRequests||0,closed:f.closedRequests||0})}catch(f){console.error("Failed to fetch backend stats:",f),l(null)}finally{m(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter]);x.useEffect(()=>{const f=setTimeout(()=>{d()},i.searchTerm?500:0);return()=>clearTimeout(f)},[i.searchTerm,i.priorityFilter,d]);const u=xu(s),h=r.hasFetchedFromApi?r.requests:u,g=x.useMemo(()=>o?{total:o.total||0,pending:o.pending||0,approved:o.approved||0,rejected:o.rejected||0,draft:o.draft||0,closed:o.closed||0}:{total:0,pending:0,approved:0,rejected:0,draft:0,closed:0},[o]),p=x.useCallback(f=>{f>=1&&f<=r.pagination.totalPages&&r.fetchMyRequests(f,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0})},[r,i]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"my-requests-page",children:[e.jsx(pu,{icon:Te,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${g.total} total`,label:"requests",loading:r.loading||c},testId:"my-requests-header"}),e.jsx(h1,{stats:g,onStatusFilter:f=>{i.setStatusFilter(f)}}),e.jsx(p1,{searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onSearchChange:i.setSearchTerm,onStatusChange:i.setStatusFilter,onPriorityChange:i.setPriorityFilter}),e.jsx(y1,{requests:h,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(na,{currentPage:r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:p,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function gu({isOrgLevel:t,loading:s,exporting:a,onExport:r}){return e.jsxs("div",{className:"flex items-start justify-between gap-4","data-testid":"requests-header-container",children:[e.jsx(pu,{icon:Te,title:t?"All Requests (Organization)":"All 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",testId:"requests-header"}),e.jsx(E,{onClick:r,disabled:a||s,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-button",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function fu({stats:t,onStatusFilter:s}){const a=r=>{s&&s(r)};return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3 sm:gap-4","data-testid":"requests-stats",children:[e.jsx(es,{label:"Total",value:t.total,icon:Te,iconColor:"text-blue-600",gradient:"bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200",textColor:"text-blue-700",valueColor:"text-blue-900",testId:"stat-total",onClick:s?()=>a("all"):void 0}),e.jsx(es,{label:"Pending",value:t.pending,icon:Re,iconColor:"text-orange-600",gradient:"bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200",textColor:"text-orange-700",valueColor:"text-orange-900",testId:"stat-pending",onClick:s?()=>a("pending"):void 0}),e.jsx(es,{label:"Approved",value:t.approved,icon:ye,iconColor:"text-green-600",gradient:"bg-gradient-to-br from-green-50 to-green-100 border-green-200",textColor:"text-green-700",valueColor:"text-green-900",testId:"stat-approved",onClick:s?()=>a("approved"):void 0}),e.jsx(es,{label:"Rejected",value:t.rejected,icon:Ze,iconColor:"text-red-600",gradient:"bg-gradient-to-br from-red-50 to-red-100 border-red-200",textColor:"text-red-700",valueColor:"text-red-900",testId:"stat-rejected",onClick:s?()=>a("rejected"):void 0}),e.jsx(es,{label:"Closed",value:t.closed,icon:Dr,iconColor:"text-purple-600",gradient:"bg-gradient-to-br from-purple-50 to-purple-100 border-purple-200",textColor:"text-purple-700",valueColor:"text-purple-900",testId:"stat-closed",onClick:s?()=>a("closed"):void 0})]})}const w1=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ns,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:et,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:et,iconColor:"text-gray-600"}}},C1=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:ye,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ze,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Re,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ye,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Rr,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"}}};function S1({request:t,index:s,onViewRequest:a}){const r=C1(t.status),n=w1(t.priority),i=r.icon,o=n.icon;return e.jsx(vt.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(K,{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(Q,{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(Q,{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(Q,{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:"})," ",ds(t.submittedDate)]})]})]}),e.jsx(gt,{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(rt,{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(Ls,{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(Re,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ds(t.submittedDate)]})]})]})]})})})})}function yu({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(W,{"data-testid":"loading-state",children:e.jsx(K,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(W,{"data-testid":"empty-state",children:e.jsxs(K,{className:"p-12 text-center",children:[e.jsx(Te,{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(S1,{request:n,index:i,onViewRequest:r},n.id))})}function vu(){const[t,s]=Pr(),[a,r]=x.useState(t.get("search")||""),[n,i]=x.useState(t.get("status")||"all"),[o,l]=x.useState(t.get("priority")||"all"),[c,m]=x.useState(t.get("slaCompliance")||"all"),[d,u]=x.useState(t.get("department")||"all"),[h,g]=x.useState(t.get("initiator")||"all"),[p,f]=x.useState(t.get("approver")||"all"),[v,j]=x.useState(t.get("approverType")==="any"?"any":"current"),[y,N]=x.useState(t.get("dateRange")||"month"),[b,C]=x.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[k,L]=x.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[R,I]=x.useState(!1);x.useEffect(()=>{const F=new URLSearchParams;a&&F.set("search",a),n!=="all"&&F.set("status",n),o!=="all"&&F.set("priority",o),c!=="all"&&F.set("slaCompliance",c),d!=="all"&&F.set("department",d),h!=="all"&&F.set("initiator",h),p!=="all"&&(F.set("approver",p),F.set("approverType",v)),y&&F.set("dateRange",y),b&&F.set("startDate",b.toISOString()),k&&F.set("endDate",k.toISOString()),s(F,{replace:!0})},[a,n,o,c,d,h,p,v,y,b,k,s]);const w=x.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:b,endDate:k}),[a,n,o,c,d,h,p,v,y,b,k]),A=x.useCallback(()=>{r(""),i("all"),l("all"),m("all"),u("all"),g("all"),f("all"),j("current"),N("month"),C(void 0),L(void 0),I(!1)},[]),P=x.useCallback(F=>{const S=F;N(S),S!=="custom"?(C(void 0),L(void 0),I(!1)):I(!0)},[]),q=x.useCallback(()=>{if(b&&k){if(b>k){const F=b;C(k),L(F)}I(!1)}},[b,k]);return{searchTerm:a,statusFilter:n,priorityFilter:o,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:h,approverFilter:p,approverFilterType:v,dateRange:y,customStartDate:b,customEndDate:k,showCustomDatePicker:R,hasActiveFilters:!!(a||n!=="all"||o!=="all"||c!=="all"||d!=="all"||h!=="all"||p!=="all"||y!=="month"||b||k),setSearchTerm:r,setStatusFilter:i,setPriorityFilter:l,setSlaComplianceFilter:m,setDepartmentFilter:u,setInitiatorFilter:g,setApproverFilter:f,setApproverFilterType:j,setDateRange:N,setCustomStartDate:C,setCustomEndDate:L,setShowCustomDatePicker:I,getFilters:w,clearFilters:A,handleDateRangeChange:P,handleApplyCustomDate:q}}function jr({allUsers:t,filterValue:s,onFilterChange:a}){const[r,n]=x.useState(""),[i,o]=x.useState([]),[l,c]=x.useState(!1),[m,d]=x.useState(null),u=x.useRef(null);x.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]),x.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const h=x.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 N=(y.email||"").toLowerCase(),b=(y.displayName||"").toLowerCase();return N.includes(v)||b.includes(v)});o(j.slice(0,10)),c(j.length>0)},300)},[t]),g=x.useCallback(f=>{d(f),a(f.userId),n(f.displayName||f.email),c(!1),o([])},[a]),p=x.useCallback(()=>{d(null),a("all"),n(""),c(!1),o([])},[a]);return{searchQuery:r,searchResults:i,showResults:l,selectedUser:m,handleSearch:h,handleSelect:g,handleClear:p,setShowResults:c}}function A1(t){var m,d,u,h,g,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((N,b)=>{const C=N.levelNumber||N.level_number||0;return(b.levelNumber||b.level_number||0)-C})[0];y&&(n=y.approverName||((h=y.approver)==null?void 0:h.name)||((g=y.approver)==null?void 0:g.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 ni(t){return Array.isArray(t)?t.map(A1):[]}function T1(t,s,a,r,n,i){if(t.length>0){const o=t.length,l=t.filter(h=>{const g=(h.status||"").toString().toUpperCase();return g==="PENDING"||g==="IN_PROGRESS"}).length,c=t.filter(h=>(h.status||"").toString().toUpperCase()==="APPROVED").length,m=t.filter(h=>(h.status||"").toString().toUpperCase()==="REJECTED").length,d=t.filter(h=>(h.status||"").toString().toUpperCase()==="DRAFT").length,u=t.filter(h=>(h.status||"").toString().toUpperCase()==="CLOSED").length;return{total:o,pending:l,approved:c,rejected:m,draft:d,closed:u}}else return s&&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 bu={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(ci,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",o="second",l="minute",c="hour",m="day",d="week",u="month",h="quarter",g="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(M){var F=["th","st","nd","rd"],S=M%100;return"["+M+(F[(S-20)%10]||F[S]||F[0])+"]"}},N=function(M,F,S){var T=String(M);return!T||T.length>=F?M:""+Array(F+1-T.length).join(S)+M},b={s:N,z:function(M){var F=-M.utcOffset(),S=Math.abs(F),T=Math.floor(S/60),D=S%60;return(F<=0?"+":"-")+N(T,2,"0")+":"+N(D,2,"0")},m:function M(F,S){if(F.date()<S.date())return-M(S,F);var T=12*(S.year()-F.year())+(S.month()-F.month()),D=F.clone().add(T,u),H=S-D<0,O=F.clone().add(T+(H?-1:1),u);return+(-(T+(S-D)/(H?D-O:O-D))||0)},a:function(M){return M<0?Math.ceil(M)||0:Math.floor(M)},p:function(M){return{M:u,y:g,w:d,d:m,D:p,h:c,m:l,s:o,ms:i,Q:h}[M]||String(M||"").toLowerCase().replace(/s$/,"")},u:function(M){return M===void 0}},C="en",k={};k[C]=y;var L="$isDayjsObject",R=function(M){return M instanceof P||!(!M||!M[L])},I=function M(F,S,T){var D;if(!F)return C;if(typeof F=="string"){var H=F.toLowerCase();k[H]&&(D=H),S&&(k[H]=S,D=H);var O=F.split("-");if(!D&&O.length>1)return M(O[0])}else{var _=F.name;k[_]=F,D=_}return!T&&D&&(C=D),D||!T&&C},w=function(M,F){if(R(M))return M.clone();var S=typeof F=="object"?F:{};return S.date=M,S.args=arguments,new P(S)},A=b;A.l=I,A.i=R,A.w=function(M,F){return w(M,{locale:F.$L,utc:F.$u,x:F.$x,$offset:F.$offset})};var P=function(){function M(S){this.$L=I(S.locale,null,!0),this.parse(S),this.$x=this.$x||S.x||{},this[L]=!0}var F=M.prototype;return F.parse=function(S){this.$d=function(T){var D=T.date,H=T.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 O=D.match(v);if(O){var _=O[2]-1||0,ee=(O[7]||"0").substring(0,3);return H?new Date(Date.UTC(O[1],_,O[3]||1,O[4]||0,O[5]||0,O[6]||0,ee)):new Date(O[1],_,O[3]||1,O[4]||0,O[5]||0,O[6]||0,ee)}}return new Date(D)}(S),this.init()},F.init=function(){var S=this.$d;this.$y=S.getFullYear(),this.$M=S.getMonth(),this.$D=S.getDate(),this.$W=S.getDay(),this.$H=S.getHours(),this.$m=S.getMinutes(),this.$s=S.getSeconds(),this.$ms=S.getMilliseconds()},F.$utils=function(){return A},F.isValid=function(){return this.$d.toString()!==f},F.isSame=function(S,T){var D=w(S);return this.startOf(T)<=D&&D<=this.endOf(T)},F.isAfter=function(S,T){return w(S)<this.startOf(T)},F.isBefore=function(S,T){return this.endOf(T)<w(S)},F.$g=function(S,T,D){return A.u(S)?this[T]:this.set(D,S)},F.unix=function(){return Math.floor(this.valueOf()/1e3)},F.valueOf=function(){return this.$d.getTime()},F.startOf=function(S,T){var D=this,H=!!A.u(T)||T,O=A.p(S),_=function(V,Z){var re=A.w(D.$u?Date.UTC(D.$y,Z,V):new Date(D.$y,Z,V),D);return H?re:re.endOf(m)},ee=function(V,Z){return A.w(D.toDate()[V].apply(D.toDate("s"),(H?[0,0,0,0]:[23,59,59,999]).slice(Z)),D)},G=this.$W,Y=this.$M,me=this.$D,X="set"+(this.$u?"UTC":"");switch(O){case g:return H?_(1,0):_(31,11);case u:return H?_(1,Y):_(0,Y+1);case d:var B=this.$locale().weekStart||0,ne=(G<B?G+7:G)-B;return _(H?me-ne:me+(6-ne),Y);case m:case p:return ee(X+"Hours",0);case c:return ee(X+"Minutes",1);case l:return ee(X+"Seconds",2);case o:return ee(X+"Milliseconds",3);default:return this.clone()}},F.endOf=function(S){return this.startOf(S,!1)},F.$set=function(S,T){var D,H=A.p(S),O="set"+(this.$u?"UTC":""),_=(D={},D[m]=O+"Date",D[p]=O+"Date",D[u]=O+"Month",D[g]=O+"FullYear",D[c]=O+"Hours",D[l]=O+"Minutes",D[o]=O+"Seconds",D[i]=O+"Milliseconds",D)[H],ee=H===m?this.$D+(T-this.$W):T;if(H===u||H===g){var G=this.clone().set(p,1);G.$d[_](ee),G.init(),this.$d=G.set(p,Math.min(this.$D,G.daysInMonth())).$d}else _&&this.$d[_](ee);return this.init(),this},F.set=function(S,T){return this.clone().$set(S,T)},F.get=function(S){return this[A.p(S)]()},F.add=function(S,T){var D,H=this;S=Number(S);var O=A.p(T),_=function(Y){var me=w(H);return A.w(me.date(me.date()+Math.round(Y*S)),H)};if(O===u)return this.set(u,this.$M+S);if(O===g)return this.set(g,this.$y+S);if(O===m)return _(1);if(O===d)return _(7);var ee=(D={},D[l]=r,D[c]=n,D[o]=a,D)[O]||1,G=this.$d.getTime()+S*ee;return A.w(G,this)},F.subtract=function(S,T){return this.add(-1*S,T)},F.format=function(S){var T=this,D=this.$locale();if(!this.isValid())return D.invalidDate||f;var H=S||"YYYY-MM-DDTHH:mm:ssZ",O=A.z(this),_=this.$H,ee=this.$m,G=this.$M,Y=D.weekdays,me=D.months,X=D.meridiem,B=function(Z,re,ge,ve){return Z&&(Z[re]||Z(T,H))||ge[re].slice(0,ve)},ne=function(Z){return A.s(_%12||12,Z,"0")},V=X||function(Z,re,ge){var ve=Z<12?"AM":"PM";return ge?ve.toLowerCase():ve};return H.replace(j,function(Z,re){return re||function(ge){switch(ge){case"YY":return String(T.$y).slice(-2);case"YYYY":return A.s(T.$y,4,"0");case"M":return G+1;case"MM":return A.s(G+1,2,"0");case"MMM":return B(D.monthsShort,G,me,3);case"MMMM":return B(me,G);case"D":return T.$D;case"DD":return A.s(T.$D,2,"0");case"d":return String(T.$W);case"dd":return B(D.weekdaysMin,T.$W,Y,2);case"ddd":return B(D.weekdaysShort,T.$W,Y,3);case"dddd":return Y[T.$W];case"H":return String(_);case"HH":return A.s(_,2,"0");case"h":return ne(1);case"hh":return ne(2);case"a":return V(_,ee,!0);case"A":return V(_,ee,!1);case"m":return String(ee);case"mm":return A.s(ee,2,"0");case"s":return String(T.$s);case"ss":return A.s(T.$s,2,"0");case"SSS":return A.s(T.$ms,3,"0");case"Z":return O}return null}(Z)||O.replace(":","")})},F.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},F.diff=function(S,T,D){var H,O=this,_=A.p(T),ee=w(S),G=(ee.utcOffset()-this.utcOffset())*r,Y=this-ee,me=function(){return A.m(O,ee)};switch(_){case g:H=me()/12;break;case u:H=me();break;case h:H=me()/3;break;case d:H=(Y-G)/6048e5;break;case m:H=(Y-G)/864e5;break;case c:H=Y/n;break;case l:H=Y/r;break;case o:H=Y/a;break;default:H=Y}return D?H:A.a(H)},F.daysInMonth=function(){return this.endOf(u).$D},F.$locale=function(){return k[this.$L]},F.locale=function(S,T){if(!S)return this.$L;var D=this.clone(),H=I(S,T,!0);return H&&(D.$L=H),D},F.clone=function(){return A.w(this.$d,this)},F.toDate=function(){return new Date(this.valueOf())},F.toJSON=function(){return this.isValid()?this.toISOString():null},F.toISOString=function(){return this.$d.toISOString()},F.toString=function(){return this.$d.toUTCString()},M}(),q=P.prototype;return w.prototype=q,[["$ms",i],["$s",o],["$m",l],["$H",c],["$W",m],["$M",u],["$y",g],["$D",p]].forEach(function(M){q[M[1]]=function(F){return this.$g(F,M[0],M[1])}}),w.extend=function(M,F){return M.$i||(M(F,P,w),M.$i=!0),w},w.locale=I,w.isDayjs=R,w.unix=function(M){return w(1e3*M)},w.en=k[C],w.Ls=k,w.p={},w})})(bu);var k1=bu.exports;const Ut=di(k1);var ju={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(ci,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(ju);var R1=ju.exports;const Nu=di(R1);var wu={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(ci,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(wu);var D1=wu.exports;const Cu=di(D1);Ut.extend(Cu);Ut.extend(Nu);function P1(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 g=(h.status||"").toString().toUpperCase();return g==="IN_PROGRESS"||g==="PENDING"}))==null?void 0:m.approverId)||((u=(d=n.approvals)==null?void 0:d.find(h=>{const g=(h.status||"").toString().toUpperCase();return g==="IN_PROGRESS"||g==="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,g,p,f,v,j,y,N;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const b=(r.status||"").toString().toUpperCase();if(!(b==="APPROVED"||b==="REJECTED"||b==="CLOSED"))return!1;const k=((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)||((g=(h=r.summary)==null?void 0:h.sla)==null?void 0:g.status);return k?k!=="breached"&&k.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)||((N=(y=r.summary)==null?void 0:y.sla)==null?void 0:N.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=Ut(s.startDate).startOf("day").toDate(),n=Ut(s.endDate).endOf("day").toDate();else{const i=Ut();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=Ut(d).startOf("day").toDate(),h=Ut(r).startOf("day").toDate(),g=Ut(n).endOf("day").toDate();return u>=h&&u<=g}const l=Ut(o).startOf("day").toDate(),c=Ut(r).startOf("day").toDate(),m=Ut(n).endOf("day").toDate();return l>=c&&l<=m}))}return a}Ut.extend(Nu);Ut.extend(Cu);function E1(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return xe(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function Su(t,s){const a=P1(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var y,N,b,C,k;const m=(c.status||"").toString().toLowerCase().replace("_","-"),d=(c.priority||"").toString().toLowerCase(),u=((y=c.initiator)==null?void 0:y.displayName)||((N=c.initiator)==null?void 0:N.email)||c.initiatorName||"N/A",h=c.department||((b=c.initiator)==null?void 0:b.department)||"N/A",g=((C=c.currentApprover)==null?void 0:C.displayName)||((k=c.currentApprover)==null?void 0:k.email)||c.currentApproverName||"N/A",p=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",f=E1(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,'""')}"`,`"${g.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 M1({page:t,itemsPerPage:s,filters:a,isOrgLevel:r}){var n,i,o,l;if(r){const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.approver&&a.approver!=="all"&&(c.approver=a.approver,c.approverType=a.approverType||"current"),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(n=a.startDate)==null?void 0:n.toISOString()),a!=null&&a.endDate&&(c.endDate=(i=a.endDate)==null?void 0:i.toISOString());const m=await Ot.listWorkflows({page:t,limit:s,...c});let d=[];Array.isArray(m==null?void 0:m.data)?d=m.data:Array.isArray(m)&&(d=m);const u=d.filter(p=>(p.status||"").toString().toUpperCase()!=="DRAFT"),h=(m==null?void 0:m.pagination)||{page:t,limit:s,total:u.length,totalPages:1};return{data:u,allData:[],filteredData:u,pagination:{page:h.page,limit:h.limit||s,total:h.total||u.length,totalPages:h.totalPages||1}}}else{const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(o=a.startDate)==null?void 0:o.toISOString()),a!=null&&a.endDate&&(c.endDate=(l=a.endDate)==null?void 0:l.toISOString());const m=await Ot.listParticipantRequests({page:t,limit:s,...c});let d=[];Array.isArray(m==null?void 0:m.data)?d=m.data:Array.isArray(m)&&(d=m);const u=d.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),h=(m==null?void 0:m.pagination)||{page:t,limit:s,total:u.length,totalPages:1};return{data:u,allData:[],filteredData:u,pagination:h}}}async function I1(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const o=t?await Ot.listWorkflows({page:r,limit:100}):await Ot.listParticipantRequests({page:r,limit:100});let l=[];if(Array.isArray(o==null?void 0:o.data)?l=o.data:Array.isArray(o)&&(l=o),l.length>0){const c=l.filter(m=>(m.status||"").toString().toUpperCase()!=="DRAFT");a.push(...c),r++,o!=null&&o.pagination?n=r<=o.pagination.totalPages:n=l.length===100}else n=!1}return a}function F1({onViewRequest:t}){const{user:s}=$t(),a=x.useMemo(()=>Er(s),[s]),r=vu(),[n,i]=x.useState([]),[o,l]=x.useState(!1),[c,m]=x.useState(!1),[d,u]=x.useState(null),[h,g]=x.useState([]),[p,f]=x.useState(!1),[v,j]=x.useState([]),[y,N]=x.useState(1),[b,C]=x.useState(1),[k,L]=x.useState(0),[R]=x.useState(10),I=jr({allUsers:v,filterValue:r.initiatorFilter,onFilterChange:r.setInitiatorFilter}),w=jr({allUsers:v,filterValue:r.approverFilter,onFilterChange:r.setApproverFilter}),A=x.useCallback(async(_,ee,G,Y)=>{if(a)try{const me=Y==null?void 0:Y.slaCompliance;if(me&&me!=="all"&&me!=="breached"&&me!=="compliant"){const B={};Y!=null&&Y.search&&(B.search=Y.search),Y!=null&&Y.priority&&Y.priority!=="all"&&(B.priority=Y.priority),Y!=null&&Y.department&&Y.department!=="all"&&(B.department=Y.department),Y!=null&&Y.initiator&&Y.initiator!=="all"&&(B.initiator=Y.initiator),Y!=null&&Y.approver&&Y.approver!=="all"&&(B.approver=Y.approver,B.approverType=Y.approverType||"current"),B.slaCompliance=me,_&&(B.dateRange=_),ee&&(B.startDate=ee.toISOString()),G&&(B.endDate=G.toISOString());const ne=await Ot.listWorkflows({page:1,limit:1e3,...B}),V=Array.isArray(ne==null?void 0:ne.data)?ne.data:[],Z=V.length,re=V.filter(Ie=>{const Le=(Ie.status||"").toString().toUpperCase();return Le==="PENDING"||Le==="IN_PROGRESS"}).length,ge=V.filter(Ie=>(Ie.status||"").toString().toUpperCase()==="APPROVED").length,ve=V.filter(Ie=>(Ie.status||"").toString().toUpperCase()==="REJECTED").length,Ue=V.filter(Ie=>(Ie.status||"").toString().toUpperCase()==="CLOSED").length;u({total:Z,pending:re,approved:ge,rejected:ve,draft:0,closed:Ue})}else{const B=await Ve.getRequestStats(_,ee?ee.toISOString():void 0,G?G.toISOString():void 0,Y==null?void 0:Y.priority,Y==null?void 0:Y.department,Y==null?void 0:Y.initiator,Y==null?void 0:Y.approver,Y==null?void 0:Y.approverType,Y==null?void 0:Y.search,Y==null?void 0:Y.slaCompliance);u({total:B.totalRequests||0,pending:B.openRequests||0,approved:B.approvedRequests||0,rejected:B.rejectedRequests||0,draft:B.draftRequests||0,closed:B.closedRequests||0})}}catch(me){console.error("Failed to fetch backend stats:",me)}finally{}},[a]),P=x.useCallback(async()=>{try{f(!0);const _=await Ve.getDepartments();g(_)}catch{}finally{f(!1)}},[]),q=x.useCallback(async()=>{try{const ee=(await Bt.getAllUsers()).map(G=>({userId:G.userId,email:G.email,displayName:G.displayName||G.email}));j(ee)}catch(_){console.error("Failed to fetch users:",_)}},[]),M=x.useRef(r),F=x.useRef(A);x.useEffect(()=>{M.current=r,F.current=A},[r,A]);const S=x.useCallback(async(_=1)=>{try{_===1&&(l(!0),i([]));const ee=M.current.getFilters(),G=await M1({page:_,itemsPerPage:R,filters:ee,isOrgLevel:a});i(G.data),N(G.pagination.page),C(G.pagination.totalPages),L(G.pagination.total)}catch{i([])}finally{l(!1)}},[R,a]),T=x.useCallback(async()=>{try{m(!0);const _=await I1(a);await Su(_,r.getFilters())}catch(_){console.error("Failed to export requests:",_),alert("Failed to export requests. Please try again.")}finally{m(!1)}},[a,r]);x.useEffect(()=>{P(),q()},[P,q]),x.useEffect(()=>{if(a){const _=setTimeout(()=>{const ee={priority:r.priorityFilter!=="all"?r.priorityFilter:void 0,department:r.departmentFilter!=="all"?r.departmentFilter:void 0,initiator:r.initiatorFilter!=="all"?r.initiatorFilter:void 0,approver:r.approverFilter!=="all"?r.approverFilter:void 0,approverType:r.approverFilter!=="all"?r.approverFilterType:void 0,search:r.searchTerm||void 0,slaCompliance:r.slaComplianceFilter!=="all"?r.slaComplianceFilter:void 0};F.current(r.dateRange,r.customStartDate,r.customEndDate,ee)},r.searchTerm?500:0);return()=>clearTimeout(_)}},[a,r.dateRange,r.customStartDate,r.customEndDate,r.priorityFilter,r.departmentFilter,r.initiatorFilter,r.approverFilter,r.approverFilterType,r.searchTerm,r.slaComplianceFilter]),x.useEffect(()=>{const _=setTimeout(()=>{N(1),S(1)},r.searchTerm?500:0);return()=>clearTimeout(_)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.slaComplianceFilter,r.departmentFilter,r.initiatorFilter,r.approverFilter,r.approverFilterType,r.dateRange,r.customStartDate,r.customEndDate]);const D=x.useCallback(_=>{_>=1&&_<=b&&(N(_),S(_))},[b,S]),H=x.useMemo(()=>ni(n),[n]),O=x.useMemo(()=>a&&d?{total:d.total||0,pending:d.pending||0,approved:d.approved||0,rejected:d.rejected||0,draft:d.draft||0,closed:d.closed||0}:T1([],a,d,!1,k,H),[a,d,k,H]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(gu,{isOrgLevel:a,loading:o,exporting:c,onExport:T}),e.jsx(fu,{stats:O,onStatusFilter:_=>{r.setStatusFilter(_)}}),e.jsx(W,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(K,{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(qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),r.hasActiveFilters&&e.jsx(Q,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),r.hasActiveFilters&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:r.clearFilters,className:"gap-2",children:[e.jsx(Et,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(jt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(qt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(pe,{placeholder:"Search requests...",value:r.searchTerm,onChange:_=>r.setSearchTerm(_.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ne,{value:r.statusFilter,onValueChange:r.setStatusFilter,children:[e.jsx(Ce,{className:"h-10","data-testid":"status-filter",children:e.jsx(we,{placeholder:"All Status"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Status"}),e.jsx(z,{value:"pending",children:"Pending"}),e.jsx(z,{value:"approved",children:"Approved"}),e.jsx(z,{value:"rejected",children:"Rejected"}),e.jsx(z,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ne,{value:r.priorityFilter,onValueChange:r.setPriorityFilter,children:[e.jsx(Ce,{className:"h-10","data-testid":"priority-filter",children:e.jsx(we,{placeholder:"All Priority"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Priority"}),e.jsx(z,{value:"express",children:"Express"}),e.jsx(z,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ne,{value:r.departmentFilter,onValueChange:r.setDepartmentFilter,disabled:p||h.length===0,children:[e.jsx(Ce,{className:"h-10","data-testid":"department-filter",children:e.jsx(we,{placeholder:p?"Loading...":"All Departments"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Departments"}),h.map(_=>e.jsx(z,{value:_,children:_},_))]})]}),e.jsxs(Ne,{value:r.slaComplianceFilter,onValueChange:r.setSlaComplianceFilter,children:[e.jsx(Ce,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(we,{placeholder:"All SLA Status"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All SLA Status"}),e.jsx(z,{value:"compliant",children:"Compliant"}),e.jsx(z,{value:"on-track",children:"On Track"}),e.jsx(z,{value:"approaching",children:"Approaching"}),e.jsx(z,{value:"critical",children:"Critical"}),e.jsx(z,{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(J,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:I.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:I.selectedUser.displayName||I.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:I.handleClear,children:e.jsx(dt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(pe,{placeholder:"Search initiator...",value:I.searchQuery,onChange:_=>I.handleSearch(_.target.value),onFocus:()=>{I.searchResults.length>0&&I.setShowResults(!0)},onBlur:()=>setTimeout(()=>I.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),I.showResults&&I.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:I.searchResults.map(_=>e.jsx("button",{type:"button",onClick:()=>I.handleSelect(_),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:_.displayName||_.email}),_.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:_.email})]})},_.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(J,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r.approverFilter!=="all"&&e.jsxs(Ne,{value:r.approverFilterType,onValueChange:_=>r.setApproverFilterType(_),children:[e.jsx(Ce,{className:"h-7 w-32 text-xs",children:e.jsx(we,{})}),e.jsxs(Se,{children:[e.jsx(z,{value:"current",children:"Current Only"}),e.jsx(z,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:w.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:w.selectedUser.displayName||w.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:w.handleClear,children:e.jsx(dt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(pe,{placeholder:"Search approver...",value:w.searchQuery,onChange:_=>w.handleSearch(_.target.value),onFocus:()=>{w.searchResults.length>0&&w.setShowResults(!0)},onBlur:()=>setTimeout(()=>w.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),w.showResults&&w.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:w.searchResults.map(_=>e.jsx("button",{type:"button",onClick:()=>w.handleSelect(_),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:_.displayName||_.email}),_.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:_.email})]})},_.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(Be,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ne,{value:r.dateRange,onValueChange:r.handleDateRangeChange,children:[e.jsx(Ce,{className:"w-[160px] h-10",children:e.jsx(we,{placeholder:"Date Range"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"today",children:"Today"}),e.jsx(z,{value:"week",children:"This Week"}),e.jsx(z,{value:"month",children:"This Month"}),e.jsx(z,{value:"custom",children:"Custom Range"})]})]}),r.dateRange==="custom"&&e.jsxs(Rs,{open:r.showCustomDatePicker,onOpenChange:r.setShowCustomDatePicker,children:[e.jsx(Ds,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(Be,{className:"w-4 h-4"}),r.customStartDate&&r.customEndDate?`${xe(r.customStartDate,"MMM d, yyyy")} - ${xe(r.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Ps,{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(J,{htmlFor:"start-date",children:"Start Date"}),e.jsx(pe,{id:"start-date",type:"date",value:r.customStartDate?xe(r.customStartDate,"yyyy-MM-dd"):"",onChange:_=>{const ee=_.target.value?new Date(_.target.value):void 0;ee?(r.setCustomStartDate(ee),r.customEndDate&&ee>r.customEndDate&&r.setCustomEndDate(ee)):r.setCustomStartDate(void 0)},max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"end-date",children:"End Date"}),e.jsx(pe,{id:"end-date",type:"date",value:r.customEndDate?xe(r.customEndDate,"yyyy-MM-dd"):"",onChange:_=>{const ee=_.target.value?new Date(_.target.value):void 0;ee?(r.setCustomEndDate(ee),r.customStartDate&&ee<r.customStartDate&&r.setCustomStartDate(ee)):r.setCustomEndDate(void 0)},min:r.customStartDate?xe(r.customStartDate,"yyyy-MM-dd"):void 0,max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{size:"sm",onClick:r.handleApplyCustomDate,disabled:!r.customStartDate||!r.customEndDate,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>{r.setShowCustomDatePicker(!1),r.setCustomStartDate(void 0),r.setCustomEndDate(void 0),r.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(yu,{requests:H,loading:o,hasActiveFilters:r.hasActiveFilters,onViewRequest:t}),e.jsx(na,{currentPage:y,totalPages:b,totalRecords:k,itemsPerPage:R,onPageChange:D,loading:o,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}const hc=100;async function pc({page:t,itemsPerPage:s,filters:a}){const r={};a!=null&&a.search&&(r.search=a.search),a!=null&&a.status&&a.status!=="all"&&(r.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(r.priority=a.priority),a!=null&&a.department&&a.department!=="all"&&(r.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(r.initiator=a.initiator),a!=null&&a.approver&&a.approver!=="all"&&(r.approver=a.approver,r.approverType=a.approverType||"current"),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(r.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(r.dateRange=a.dateRange),a!=null&&a.startDate&&(r.startDate=a.startDate instanceof Date?a.startDate.toISOString():a.startDate),a!=null&&a.endDate&&(r.endDate=a.endDate instanceof Date?a.endDate.toISOString():a.endDate);const n=await Ot.listParticipantRequests({page:t,limit:s,...r});let i=[];Array.isArray(n==null?void 0:n.data)?i=n.data:Array.isArray(n)&&(i=n);const o=i.filter(c=>(c.status||"").toString().toUpperCase()!=="DRAFT"),l=(n==null?void 0:n.pagination)||{page:t,limit:s,total:o.length,totalPages:1};return{data:o,allData:[],filteredData:o,pagination:l}}async function L1(t){const s=[];let a=1,r=!0;const n=100,i={};for(t!=null&&t.search&&(i.search=t.search),t!=null&&t.status&&t.status!=="all"&&(i.status=t.status),t!=null&&t.priority&&t.priority!=="all"&&(i.priority=t.priority),t!=null&&t.department&&t.department!=="all"&&(i.department=t.department),t!=null&&t.initiator&&t.initiator!=="all"&&(i.initiator=t.initiator),t!=null&&t.approver&&t.approver!=="all"&&(i.approver=t.approver,i.approverType=t.approverType||"current"),t!=null&&t.slaCompliance&&t.slaCompliance!=="all"&&(i.slaCompliance=t.slaCompliance),t!=null&&t.dateRange&&(i.dateRange=t.dateRange),t!=null&&t.startDate&&(i.startDate=t.startDate instanceof Date?t.startDate.toISOString():t.startDate),t!=null&&t.endDate&&(i.endDate=t.endDate instanceof Date?t.endDate.toISOString():t.endDate);r&&a<=n;){const o=await Ot.listParticipantRequests({page:a,limit:hc,...i}),l=(o==null?void 0:o.data)||[];l.length===0?r=!1:(s.push(...l),a++,l.length<hc&&(r=!1))}return s}function _1({onViewRequest:t}){const s=vu(),[a,r]=x.useState([]),[n,i]=x.useState(!1),[o,l]=x.useState(!1),[c,m]=x.useState([]),[d,u]=x.useState([]),[h,g]=x.useState(!1),[p,f]=x.useState([]),[v,j]=x.useState(1),[y,N]=x.useState(1),[b,C]=x.useState(0),[k]=x.useState(10),L=jr({allUsers:p,filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter}),R=jr({allUsers:p,filterValue:s.approverFilter,onFilterChange:s.setApproverFilter}),I=x.useCallback(async()=>{var O;try{const ee={...s.getFilters()};delete ee.status;const G=await pc({page:1,itemsPerPage:100,filters:ee});m(G.data||[]),((O=G.pagination)==null?void 0:O.total)!==void 0&&C(G.pagination.total)}catch(_){console.error("Failed to fetch requests for stats:",_),m([])}},[s]),w=x.useCallback(async()=>{try{g(!0);const O=await Ve.getDepartments();u(O)}catch{}finally{g(!1)}},[]),A=x.useCallback(async()=>{try{const _=(await Bt.getAllUsers()).map(ee=>({userId:ee.userId,email:ee.email,displayName:ee.displayName||ee.email}));f(_)}catch(O){console.error("Failed to fetch users:",O)}},[]),P=x.useRef(s),q=x.useRef(I);x.useEffect(()=>{P.current=s,q.current=I},[s,I]);const M=x.useCallback(async(O=1)=>{try{O===1&&(i(!0),r([]));const _=P.current.getFilters(),ee=await pc({page:O,itemsPerPage:k,filters:_});r(ee.data),j(ee.pagination.page),N(ee.pagination.totalPages)}catch{r([])}finally{i(!1)}},[k]),F=x.useCallback(async()=>{try{l(!0);const O=await L1(s.getFilters());await Su(O,s.getFilters())}catch(O){console.error("Failed to export requests:",O),alert("Failed to export requests. Please try again.")}finally{l(!1)}},[s]);x.useEffect(()=>{w(),A()},[w,A]),x.useEffect(()=>{const O=setTimeout(()=>{I()},s.searchTerm?500:0);return()=>clearTimeout(O)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]),x.useEffect(()=>{const O=setTimeout(()=>{j(1),M(1)},s.searchTerm?500:0);return()=>clearTimeout(O)},[s.searchTerm,s.statusFilter,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const S=x.useCallback(O=>{O>=1&&O<=y&&(j(O),M(O))},[y,M]),T=x.useMemo(()=>ni(a),[a]),D=x.useMemo(()=>ni(c),[c]),H=x.useMemo(()=>{if(D.length>0){const O=D.filter(Y=>{const me=(Y.status||"").toString().toLowerCase();return me==="pending"||me==="in-progress"}).length,_=D.filter(Y=>(Y.status||"").toString().toLowerCase()==="approved").length,ee=D.filter(Y=>(Y.status||"").toString().toLowerCase()==="rejected").length,G=D.filter(Y=>(Y.status||"").toString().toLowerCase()==="closed").length;return{total:b>0?b:D.length,pending:O,approved:_,rejected:ee,draft:0,closed:G}}else{const O=T.filter(Y=>{const me=(Y.status||"").toString().toLowerCase();return me==="pending"||me==="in-progress"}).length,_=T.filter(Y=>(Y.status||"").toString().toLowerCase()==="approved").length,ee=T.filter(Y=>(Y.status||"").toString().toLowerCase()==="rejected").length,G=T.filter(Y=>(Y.status||"").toString().toLowerCase()==="closed").length;return{total:b>0?b:T.length,pending:O,approved:_,rejected:ee,draft:0,closed:G}}},[b,D,T]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"user-all-requests-page",children:[e.jsx(gu,{isOrgLevel:!1,loading:n,exporting:o,onExport:F}),e.jsx(fu,{stats:H,onStatusFilter:O=>{s.setStatusFilter(O)}}),e.jsx(W,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(K,{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(qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),s.hasActiveFilters&&e.jsx(Q,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),s.hasActiveFilters&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:s.clearFilters,className:"gap-2",children:[e.jsx(Et,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(jt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(qt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(pe,{placeholder:"Search requests...",value:s.searchTerm,onChange:O=>s.setSearchTerm(O.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ne,{value:s.statusFilter,onValueChange:s.setStatusFilter,children:[e.jsx(Ce,{className:"h-10","data-testid":"status-filter",children:e.jsx(we,{placeholder:"All Status"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Status"}),e.jsx(z,{value:"pending",children:"Pending"}),e.jsx(z,{value:"approved",children:"Approved"}),e.jsx(z,{value:"rejected",children:"Rejected"}),e.jsx(z,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ne,{value:s.priorityFilter,onValueChange:s.setPriorityFilter,children:[e.jsx(Ce,{className:"h-10","data-testid":"priority-filter",children:e.jsx(we,{placeholder:"All Priority"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Priority"}),e.jsx(z,{value:"express",children:"Express"}),e.jsx(z,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ne,{value:s.departmentFilter,onValueChange:s.setDepartmentFilter,disabled:h||d.length===0,children:[e.jsx(Ce,{className:"h-10","data-testid":"department-filter",children:e.jsx(we,{placeholder:h?"Loading...":"All Departments"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Departments"}),d.map(O=>e.jsx(z,{value:O,children:O},O))]})]}),e.jsxs(Ne,{value:s.slaComplianceFilter,onValueChange:s.setSlaComplianceFilter,children:[e.jsx(Ce,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(we,{placeholder:"All SLA Status"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All SLA Status"}),e.jsx(z,{value:"compliant",children:"Compliant"}),e.jsx(z,{value:"on-track",children:"On Track"}),e.jsx(z,{value:"approaching",children:"Approaching"}),e.jsx(z,{value:"critical",children:"Critical"}),e.jsx(z,{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(J,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:L.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:L.selectedUser.displayName||L.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:L.handleClear,children:e.jsx(dt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(pe,{placeholder:"Search initiator...",value:L.searchQuery,onChange:O=>L.handleSearch(O.target.value),onFocus:()=>{L.searchResults.length>0&&L.setShowResults(!0)},onBlur:()=>setTimeout(()=>L.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),L.showResults&&L.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:L.searchResults.map(O=>e.jsx("button",{type:"button",onClick:()=>L.handleSelect(O),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:O.displayName||O.email}),O.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:O.email})]})},O.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(J,{className:"text-sm font-medium text-gray-700",children:"Approver"}),s.approverFilter!=="all"&&e.jsxs(Ne,{value:s.approverFilterType,onValueChange:O=>s.setApproverFilterType(O),children:[e.jsx(Ce,{className:"h-7 w-32 text-xs",children:e.jsx(we,{})}),e.jsxs(Se,{children:[e.jsx(z,{value:"current",children:"Current Only"}),e.jsx(z,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:R.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:R.selectedUser.displayName||R.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:R.handleClear,children:e.jsx(dt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(pe,{placeholder:"Search approver...",value:R.searchQuery,onChange:O=>R.handleSearch(O.target.value),onFocus:()=>{R.searchResults.length>0&&R.setShowResults(!0)},onBlur:()=>setTimeout(()=>R.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),R.showResults&&R.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:R.searchResults.map(O=>e.jsx("button",{type:"button",onClick:()=>R.handleSelect(O),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:O.displayName||O.email}),O.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:O.email})]})},O.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(Be,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ne,{value:s.dateRange,onValueChange:s.handleDateRangeChange,children:[e.jsx(Ce,{className:"w-[160px] h-10",children:e.jsx(we,{placeholder:"Date Range"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"today",children:"Today"}),e.jsx(z,{value:"week",children:"This Week"}),e.jsx(z,{value:"month",children:"This Month"}),e.jsx(z,{value:"custom",children:"Custom Range"})]})]}),s.dateRange==="custom"&&e.jsxs(Rs,{open:s.showCustomDatePicker,onOpenChange:s.setShowCustomDatePicker,children:[e.jsx(Ds,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(Be,{className:"w-4 h-4"}),s.customStartDate&&s.customEndDate?`${xe(s.customStartDate,"MMM d, yyyy")} - ${xe(s.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Ps,{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(J,{htmlFor:"start-date",children:"Start Date"}),e.jsx(pe,{id:"start-date",type:"date",value:s.customStartDate?xe(s.customStartDate,"yyyy-MM-dd"):"",onChange:O=>{const _=O.target.value?new Date(O.target.value):void 0;_?(s.setCustomStartDate(_),s.customEndDate&&_>s.customEndDate&&s.setCustomEndDate(_)):s.setCustomStartDate(void 0)},max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"end-date",children:"End Date"}),e.jsx(pe,{id:"end-date",type:"date",value:s.customEndDate?xe(s.customEndDate,"yyyy-MM-dd"):"",onChange:O=>{const _=O.target.value?new Date(O.target.value):void 0;_?(s.setCustomEndDate(_),s.customStartDate&&_<s.customStartDate&&s.setCustomStartDate(_)):s.setCustomEndDate(void 0)},min:s.customStartDate?xe(s.customStartDate,"yyyy-MM-dd"):void 0,max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{size:"sm",onClick:s.handleApplyCustomDate,disabled:!s.customStartDate||!s.customEndDate,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>{s.setShowCustomDatePicker(!1),s.setCustomStartDate(void 0),s.setCustomEndDate(void 0),s.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(yu,{requests:T,loading:n,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(na,{currentPage:v,totalPages:y,totalRecords:b,itemsPerPage:k,onPageChange:S,loading:n,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function O1(){const t=Os();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(K,{className:"p-8 text-center",children:[e.jsx(Pe,{className:"w-12 h-12 text-yellow-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Approver ID Required"}),e.jsx("p",{className:"text-gray-600",children:"Please select an approver to view their performance details."}),e.jsxs(E,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(Ms,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function $1({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(Je,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Approver Performance Report"}),e.jsx("p",{className:"text-sm text-gray-600",children:t})]})]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx(Et,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function U1({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(se,{className:"pb-3",children:e.jsx(ae,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(K,{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(et,{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(cs,{value:a,className:"mt-2 h-2"})]})]}),e.jsxs(W,{children:[e.jsx(se,{className:"pb-3",children:e.jsx(ae,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(K,{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(ye,{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(se,{className:"pb-3",children:e.jsx(ae,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(K,{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(fi,{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(se,{className:"pb-3",children:e.jsx(ae,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(K,{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(Re,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function V1({approverName:t,approverStats:s,calculatedStats:a}){return e.jsxs(W,{"data-testid":"approver-actions-stats",children:[e.jsxs(se,{children:[e.jsx(ae,{children:"Approver's Actions (Filtered)"}),e.jsxs(ue,{children:["Statistics based on ",t,"'s actions with current filters applied"]})]}),e.jsxs(K,{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(Je,{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(ye,{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(Ze,{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(Re,{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(Dr,{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(Te,{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(et,{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(Ap,{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(Pe,{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(qc,{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 B1({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:g,onDateRangeChange:p,onShowCustomDatePickerChange:f,onTempStartDateChange:v,onTempEndDateChange:j,onApplyCustomDate:y,onClearFilters:N}){return e.jsxs(W,{"data-testid":"approver-performance-filters",children:[e.jsx(se,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ae,{children:"Filters"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:N,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(K,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(qt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(pe,{placeholder:"Search requests...",value:t,onChange:b=>d(b.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(Ne,{value:s,onValueChange:u,children:[e.jsx(Ce,{"data-testid":"status-filter",children:e.jsx(we,{placeholder:"Status"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Status"}),e.jsx(z,{value:"pending",children:"Pending"}),e.jsx(z,{value:"approved",children:"Approved"}),e.jsx(z,{value:"rejected",children:"Rejected"}),e.jsx(z,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ne,{value:a,onValueChange:h,children:[e.jsx(Ce,{"data-testid":"priority-filter",children:e.jsx(we,{placeholder:"Priority"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Priority"}),e.jsx(z,{value:"express",children:"Express"}),e.jsx(z,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ne,{value:r,onValueChange:g,children:[e.jsx(Ce,{"data-testid":"sla-compliance-filter",children:e.jsx(we,{placeholder:"SLA Compliance"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All SLA"}),e.jsx(z,{value:"compliant",children:"Compliant"}),e.jsx(z,{value:"on-track",children:"On Track"}),e.jsx(z,{value:"approaching",children:"Approaching"}),e.jsx(z,{value:"critical",children:"Critical"}),e.jsx(z,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ne,{value:n,onValueChange:p,children:[e.jsx(Ce,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(we,{placeholder:"Date Range"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"today",children:"Today"}),e.jsx(z,{value:"week",children:"This Week"}),e.jsx(z,{value:"month",children:"This Month"}),e.jsx(z,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(Rs,{open:l,onOpenChange:f,children:[e.jsx(Ds,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(Be,{className:"w-4 h-4"}),c&&m?`${xe(c,"MMM d")} - ${xe(m,"MMM d")}`:"Select dates"]})}),e.jsx(Ps,{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(J,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(pe,{id:"start-date",type:"date",value:c?xe(c,"yyyy-MM-dd"):"",onChange:b=>{const C=b.target.value?new Date(b.target.value):void 0;C?(v(C),m&&C>m&&j(C)):v(void 0)},max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(pe,{id:"end-date",type:"date",value:m?xe(m,"yyyy-MM-dd"):"",onChange:b=>{const C=b.target.value?new Date(b.target.value):void 0;C?(j(C),c&&C<c&&v(C)):j(void 0)},min:c?xe(c,"yyyy-MM-dd"):void 0,max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(E,{size:"sm",onClick:y,disabled:!c||!m,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-date-button",children:"Apply"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>{f(!1),v(i),j(o),(!i||!o)&&p("month")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const z1=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ls,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:et,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:et,iconColor:"text-gray-600"}}},H1=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:ye,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ze,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Re,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Re,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ye,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Te,iconColor:"text-gray-600"}}},q1=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 W1(t){if(!t)return"N/A";try{return xe(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function K1(t){if(!t)return"N/A";try{return xe(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function G1({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l}){const c=Os();return e.jsxs(W,{"data-testid":"approver-performance-request-list",children:[e.jsxs(se,{children:[e.jsx(ae,{children:"Request Details"}),e.jsxs(ue,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(K,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(Et,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading requests..."})]}):t.length===0?e.jsxs("div",{className:"text-center py-12 text-gray-500","data-testid":"empty-state",children:[e.jsx(Te,{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=z1(m.priority),u=H1(m.status),h=q1(m.slaStatus||""),g=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(K,{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(Q,{className:d.color,"data-testid":"priority-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${d.iconColor}`}),m.priority]}),e.jsxs(Q,{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(Q,{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(ye,{className:"w-3 h-3 mr-1"}),"Approved"]}):m.approvalStatus==="rejected"||m.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-3 h-3 mr-1"}),"Pending"]})}),m.slaStatus&&e.jsx(Q,{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(rt,{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(Re,{className:"w-3 h-3"}),"Submitted: ",W1(m.submissionDate)]}),m.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(ye,{className:"w-3 h-3"}),"Action: ",K1(m.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(et,{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(fi,{className:"w-3 h-3"}),Qe(m.levelElapsedHours)," / ",Qe(m.levelTatHours||0)," TAT"]})]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:f=>{f.stopPropagation(),c(`/request/${m.requestId}`)},"data-testid":"view-request-button",children:e.jsx(gt,{className:"w-4 h-4"})})]})})},m.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(na,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function Y1(){const[t]=Pr(),[s,a]=x.useState(""),[r,n]=x.useState(t.get("status")||"all"),[i,o]=x.useState(t.get("priority")||"all"),[l,c]=x.useState(t.get("slaCompliance")||"all"),[m,d]=x.useState(t.get("dateRange")||"month"),[u,h]=x.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[g,p]=x.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[f,v]=x.useState(!1),[j,y]=x.useState(void 0),[N,b]=x.useState(void 0),C=x.useCallback(()=>{a(""),n("all"),o("all"),c("all"),d("month"),h(void 0),p(void 0),y(void 0),b(void 0),v(!1)},[]),k=x.useCallback(R=>{const I=R;d(I),I!=="custom"?(h(void 0),p(void 0),y(void 0),b(void 0),v(!1)):(y(u),b(g),v(!0))},[u,g]),L=x.useCallback(()=>{if(j&&N){if(j>N){const R=j;h(N),p(R),y(N),b(R)}else h(j),p(N);v(!1)}},[j,N]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:l,dateRange:m,customStartDate:u,customEndDate:g,showCustomDatePicker:f,tempCustomStartDate:j,tempCustomEndDate:N,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:o,setSlaComplianceFilter:c,setDateRange:d,setCustomStartDate:h,setCustomEndDate:p,setShowCustomDatePicker:v,setTempCustomStartDate:y,setTempCustomEndDate:b,clearFilters:C,handleDateRangeChange:k,handleApplyCustomDate:L}}function Z1({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:o,searchTerm:l,itemsPerPage:c}){const[m,d]=x.useState([]),[u,h]=x.useState(null),[g,p]=x.useState([]),[f,v]=x.useState(!0),[j,y]=x.useState(!1),[N,b]=x.useState(1),[C,k]=x.useState(1),[L,R]=x.useState(0),I=x.useRef(!0),w=x.useCallback(async()=>{if(t)try{const F=(await Ve.getApproverPerformance(s,1,100,a,r)).performance.find(S=>S.approverId===t);F&&h(F)}catch(M){console.error("Failed to fetch approver stats:",M)}},[t,s,a,r]),A=x.useCallback(async(M=1)=>{if(!t){v(!1);return}try{v(!0);const F=await Ve.getRequestsByApprover(t,M,c,s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,o!=="all"?o:void 0,l||void 0);d(F.requests),R(F.pagination.totalRecords),k(F.pagination.totalPages),b(M);const S=await Ve.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(S.requests)}catch(F){console.error("Failed to fetch requests:",F)}finally{v(!1),y(!1)}},[t,s,a,r,n,i,o,l,c]);x.useEffect(()=>{I.current&&(I.current=!1,w(),A(1))},[]),x.useEffect(()=>{I.current||(w(),A(1))},[s,a,r,n,i,o,l]);const P=x.useCallback(()=>{y(!0),w(),A(1)},[w,A]),q=x.useCallback(M=>{b(M);const F=(M-1)*c,S=F+c,T=g.slice(F,S);d(T)},[g,c]);return x.useEffect(()=>{const M=(N-1)*c,F=M+c,S=g.slice(M,F);d(S),k(Math.ceil(g.length/c)),N>Math.ceil(g.length/c)&&g.length>0&&b(1)},[g,N,c]),{requests:m,approverStats:u,allFilteredRequests:g,loading:f,refreshing:j,currentPage:N,totalPages:C,totalRecords:L,handleRefresh:P,handlePageChange:q}}function X1(t){const s=t,a=s.filter(g=>(g.approvalStatus||"").toLowerCase()==="approved").length,r=s.filter(g=>(g.approvalStatus||"").toLowerCase()==="rejected").length,n=s.filter(g=>{const p=(g.approvalStatus||"").toLowerCase();return["pending","in_progress","in-progress"].includes(p)}).length,i=s.filter(g=>(g.status||"").toLowerCase()==="closed").length,o=s.filter(g=>{const p=g.isBreached===!0||g.isBreached===1,f=(g.slaStatus||"").toLowerCase()==="breached";return p||f}).length,l=s.filter(g=>{const p=(g.approvalStatus||"").toLowerCase(),f=p==="approved"||p==="rejected",v=["pending","in_progress","in-progress"].includes(p),j=!(g.isBreached===!0||g.isBreached===1)&&(g.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 xc=10;function J1(){const[t]=Pr(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=Y1(),n=Z1({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:xc}),i=x.useMemo(()=>X1(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($1,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(U1,{approverStats:n.approverStats,calculatedStats:i}),e.jsx(V1,{approverName:a,approverStats:n.approverStats,calculatedStats:i}),e.jsx(B1,{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(G1,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:xc,onPageChange:n.handlePageChange})]}):e.jsx(O1,{})}function Q1(){const{user:t}=$t(),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(K,{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(ft,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Mr,{src:(t==null?void 0:t.picture)||""}),e.jsx(yt,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),Hs(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(kt,{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:[Hs(t)&&e.jsxs(Q,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(kt,{className:"w-3 h-3 mr-1"}),"Administrator"]}),Sa(t)&&e.jsxs(Q,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(Je,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(Q,{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(se,{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(rt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(ue,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(K,{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(Vc,{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(rt,{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(rt,{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(rt,{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(Bc,{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(se,{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(No,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(ue,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(K,{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(rt,{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(Tp,{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(No,{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(kt,{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(Q,{variant:Hs(t)||Sa(t)?"default":"secondary",className:Hs(t)?"bg-yellow-400 text-slate-900":Sa(t)?"bg-blue-400 text-slate-900":"",children:Hs(t)?"Administrator":Sa(t)?"Management":"User"}),(Hs(t)||Sa(t))&&e.jsx(ye,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(se,{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(Be,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(ue,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(K,{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(ye,{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(Q,{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 eC="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",tC="https://reflow-uat.royalenfield.com";function sC(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 aC(){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 rC(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:sC(eC)})}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(`${tC}/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 nC(){if(!("Notification"in window))throw new Error("Notifications are not supported in this browser");let t=Notification.permission;if(t==="denied")throw new Error("Notification permission was denied. Please enable notifications in your browser settings and try again.");if(t==="default"&&(t=await Notification.requestPermission(),t!=="granted"))throw new Error("Notification permission was denied. Please enable notifications in your browser settings and try again.");if(t!=="granted")throw new Error("Notification permission is required. Please grant permission and try again.");let s;try{s=await aC()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await rC(s)}catch(a){throw a}}function ss({className:t,...s}){return e.jsx(Rh,{"data-slot":"switch",className:he("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(Dh,{"data-slot":"switch-thumb",className:he("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 ii({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const o=x.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(Ph,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:he("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(Eh,{"data-slot":"slider-track",className:he("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(Mh,{"data-slot":"slider-range",className:he("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:o.length},(l,c)=>e.jsx(Ih,{"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 iC({onConfigUpdate:t}){const[s,a]=x.useState([]),[r,n]=x.useState(!0),[i,o]=x.useState(null),[l,c]=x.useState(null),[m,d]=x.useState({}),[u,h]=x.useState(null);x.useEffect(()=>{g()},[]);const g=async()=>{var w,A;try{n(!0),c(null);const P=await Lr();a(P)}catch(P){c(((A=(w=P.response)==null?void 0:w.data)==null?void 0:A.error)||"Failed to load configurations")}finally{n(!1)}},p=async w=>{var A,P;try{o(w.configKey),c(null);const q=m[w.configKey]??w.configValue;if(w.validationRules){const M=parseFloat(q);if(w.valueType==="NUMBER"){if(w.validationRules.min!==void 0&&M<w.validationRules.min)throw new Error(`Value must be at least ${w.validationRules.min}`);if(w.validationRules.max!==void 0&&M>w.validationRules.max)throw new Error(`Value must be at most ${w.validationRules.max}`)}}await xt(w.configKey,q),a(M=>M.map(F=>F.configKey===w.configKey?{...F,configValue:q}:F)),d(M=>{const F={...M};return delete F[w.configKey],F}),h(`${w.displayName} updated successfully`),setTimeout(()=>h(null),3e3),t&&t()}catch(q){c(q.message||((P=(A=q.response)==null?void 0:A.data)==null?void 0:P.error)||"Failed to save configuration")}finally{o(null)}},f=async w=>{var A,P;if(confirm(`Reset "${w.displayName}" to default value?`))try{o(w.configKey),c(null),await yf(w.configKey),a(q=>q.map(M=>M.configKey===w.configKey?{...M,configValue:M.defaultValue||""}:M)),d(q=>{const M={...q};return delete M[w.configKey],M}),h(`${w.displayName} reset to default`),setTimeout(()=>h(null),3e3)}catch(q){c(((P=(A=q.response)==null?void 0:A.data)==null?void 0:P.error)||"Failed to reset configuration")}finally{o(null)}},v=(w,A)=>{d(P=>({...P,[w]:A}))},j=w=>m[w.configKey]??w.configValue,y=w=>m[w.configKey]!==void 0&&m[w.configKey]!==w.configValue,N=w=>{var q,M,F,S;const A=j(w),P=i===w.configKey;if(!w.isEditable)return e.jsxs("div",{className:"p-3 bg-slate-100 border border-slate-200 rounded-md",children:[e.jsx("p",{className:"text-sm text-slate-700 font-mono",children:w.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Pe,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(w.uiComponent||w.valueType.toLowerCase()){case"toggle":return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${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:O=>v(w.configKey,O?"true":"false"),disabled:P})]});case"slider":const T=parseInt(A)||0,D=((q=w.validationRules)==null?void 0:q.min)||0,H=((M=w.validationRules)==null?void 0:M.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:[T,"%"]}),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,"-",H]})]}),e.jsx(ii,{value:[T],min:D,max:H,step:1,onValueChange:([O])=>{O!==void 0&&v(w.configKey,O.toString())},disabled:P,className:"w-full"})]});case"number":return e.jsx(pe,{type:"number",value:A,onChange:O=>v(w.configKey,O.target.value),disabled:P,min:(F=w.validationRules)==null?void 0:F.min,max:(S=w.validationRules)==null?void 0:S.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(pe,{type:"text",value:A,onChange:O=>v(w.configKey,O.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"})}},b=w=>{switch(w){case"TAT_SETTINGS":return e.jsx(Re,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Te,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(Lt,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(kr,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(Nr,{className:"w-5 h-5"});default:return e.jsx(ra,{className:"w-5 h-5"})}},C=["NOTIFICATION_RULES","DASHBOARD_LAYOUT"],k=["ALLOW_EXTERNAL_SHARING"],L=s.filter(w=>!C.includes(w.configCategory)&&!k.includes(w.configKey)),R=L.reduce((w,A)=>(w[A.configCategory]||(w[A.configCategory]=[]),w[A.configCategory].push(A),w),{});if(Object.keys(R).forEach(w=>{const A=R[w];A&&A.sort((P,q)=>P.sortOrder-q.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(L.length===0)return e.jsx(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(K,{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(ra,{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 I=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(ye,{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(Pe,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:l}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(Ir,{defaultValue:I[0],className:"w-full",children:[e.jsx(Fr,{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:I.map(w=>e.jsx(ht,{value:w,className:"flex-1 min-w-[120px] text-[10px] xs:text-xs sm:text-sm font-medium py-2 sm:py-2.5 px-2 sm:px-3 rounded-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-slate-900 transition-all",children:e.jsx("span",{className:"truncate block",children:w.replace(/_/g," ")})},w))}),I.map(w=>{var A,P,q;return e.jsx(pt,{value:w,className:"space-y-4 mt-6",children:e.jsxs(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(se,{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:b(w)})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-slate-900",children:w.replace(/_/g," ")}),e.jsxs(ue,{className:"text-sm",children:[((A=R[w])==null?void 0:A.length)||0," setting",(((P=R[w])==null?void 0:P.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(K,{className:"space-y-6",children:(q=R[w])==null?void 0:q.map(M=>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(J,{className:"text-sm font-semibold text-slate-900",children:M.displayName}),y(M)&&e.jsx(Q,{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"}),M.requiresRestart&&e.jsx(Q,{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"})]}),M.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:M.description}),M.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:M.defaultValue})]})]})}),N(M),M.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(E,{size:"sm",onClick:()=>p(M),disabled:!y(M)||i===M.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===M.configKey?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(_s,{className:"w-4 h-4"}),"Save Changes"]})}),M.defaultValue&&e.jsxs(E,{size:"sm",variant:"outline",onClick:()=>f(M),disabled:i===M.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(kp,{className:"w-4 h-4"}),"Reset to Default"]})]})]},M.configKey))})]})},w)})]})]})}function oC(){const[t,s]=x.useState([]),[a,r]=x.useState(!0),[n,i]=x.useState(new Date().getFullYear()),[o,l]=x.useState(!1),[c,m]=x.useState(null),[d,u]=x.useState(null),[h,g]=x.useState(null),[p,f]=x.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});x.useEffect(()=>{v()},[n]);const v=async()=>{var w,A;try{r(!0),u(null);const P=await vf(n);s(P)}catch(P){u(((A=(w=P.response)==null?void 0:w.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=w=>{f({holidayDate:w.holidayDate,holidayName:w.holidayName,description:w.description||"",holidayType:w.holidayType,isRecurring:w.isRecurring}),m(w),l(!0)},N=()=>{if(c)return;const w=new Date;return w.setDate(w.getDate()+1),w.toISOString().split("T")[0]},b=async()=>{var w,A;try{if(u(null),!p.holidayDate||!p.holidayName){u("Holiday date and name are required");return}c?(await jf(c.holidayId,p),g("Holiday updated successfully")):(await bf(p),g("Holiday created successfully")),await v(),l(!1),setTimeout(()=>g(null),3e3)}catch(P){u(((A=(w=P.response)==null?void 0:w.data)==null?void 0:A.error)||"Failed to save holiday")}},C=async w=>{var A,P;if(confirm(`Delete "${w.holidayName}"?`))try{u(null),await Nf(w.holidayId),g("Holiday deleted successfully"),await v(),setTimeout(()=>g(null),3e3)}catch(q){u(((P=(A=q.response)==null?void 0:A.data)==null?void 0:P.error)||"Failed to delete holiday")}},k=w=>{switch(w){case"NATIONAL":return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300";case"REGIONAL":return"bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-800 border-blue-300";case"ORGANIZATIONAL":return"bg-gradient-to-r from-purple-50 to-violet-50 text-purple-800 border-purple-300";case"OPTIONAL":return"bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-300"}},L=Array.from({length:5},(w,A)=>new Date().getFullYear()-1+A),R=t.reduce((w,A)=>{const P=new Date(A.holidayDate).toLocaleString("default",{month:"long"});return w[P]||(w[P]=[]),w[P].push(A),w},{}),I=Object.keys(R).sort((w,A)=>{const P=new Date(Date.parse(w+" 1, 2000")).getMonth(),q=new Date(Date.parse(A+" 1, 2000")).getMonth();return P-q});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(ye,{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(Pe,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:d}),e.jsx(E,{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(se,{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(Be,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(ue,{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(Ne,{value:n.toString(),onValueChange:w=>i(parseInt(w)),children:[e.jsx(Ce,{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(we,{})}),e.jsx(Se,{className:"rounded-md",children:L.map(w=>e.jsx(z,{value:w.toString(),children:w},w))})]}),e.jsxs(E,{onClick:j,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(Es,{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(K,{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(Be,{className:"w-10 h-10 text-slate-400"})}),e.jsxs("p",{className:"text-slate-700 font-medium text-lg",children:["No holidays found for ",n]}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:"Add holidays to exclude them from TAT calculations"}),e.jsxs(E,{onClick:j,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Es,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:I.map(w=>{var A,P,q;return e.jsxs(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(se,{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(ae,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[w," ",n]}),e.jsxs(ue,{className:"text-xs sm:text-sm",children:[((A=R[w])==null?void 0:A.length)||0," holiday",(((P=R[w])==null?void 0:P.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(Be,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(K,{className:"space-y-3 pt-4",children:(q=R[w])==null?void 0:q.map(M=>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:M.holidayName}),e.jsx(Q,{variant:"outline",className:`${k(M.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:M.holidayType}),M.isRecurring&&e.jsx(Q,{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:hd(M.holidayDate)}),M.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:M.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>y(M),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Rp,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>C(M),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(yi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},M.holidayId))})]},w)})}),e.jsx(mt,{open:o,onOpenChange:l,children:e.jsxs(nt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(ut,{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(Be,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(it,{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(J,{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(pe,{id:"date",type:"date",value:p.holidayDate,onChange:w=>f({...p,holidayDate:w.target.value}),min:N(),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:c?"Select the holiday date":"Select the holiday date (minimum: tomorrow)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{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(pe,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:p.holidayName,onChange:w=>f({...p,holidayName:w.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(J,{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(pe,{id:"description",placeholder:"Add additional details about this holiday...",value:p.description,onChange:w=>f({...p,description:w.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(Ne,{value:p.holidayType,onValueChange:w=>f({...p,holidayType:w}),children:[e.jsx(Ce,{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(we,{})}),e.jsxs(Se,{className:"rounded-lg",children:[e.jsx(z,{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(z,{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(z,{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(z,{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:w=>f({...p,isRecurring:w.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(J,{htmlFor:"recurring",className:"font-semibold cursor-pointer text-sm text-slate-900 block mb-1",children:"Recurring Holiday"}),e.jsx("p",{className:"text-xs text-slate-600",children:"This holiday will automatically repeat every year on the same date"})]})]})]}),e.jsxs(Rt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(E,{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(E,{onClick:b,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(Be,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function lC(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function cC(){const[t,s]=x.useState(""),[a,r]=x.useState([]),[n,i]=x.useState(!1),[o,l]=x.useState(null),[c,m]=x.useState("USER"),[d,u]=x.useState(!1),[h,g]=x.useState(null),[p,f]=x.useState([]),[v,j]=x.useState(!1),[y,N]=x.useState({admins:0,management:0,users:0}),[b,C]=x.useState("ELEVATED"),[k,L]=x.useState(1),[R,I]=x.useState(1),[w,A]=x.useState(0),P=10,q=x.useRef(null),M=x.useRef(null),F=x.useCallback(lC(async X=>{var B,ne,V;if(!X||X.length<2){r([]);return}i(!0);try{const re=((B=(await Bt.searchUsers(X,20)).data)==null?void 0:B.data)||[];r(re)}catch(Z){console.error("Search failed:",Z),g({type:"error",text:((V=(ne=Z.response)==null?void 0:ne.data)==null?void 0:V.message)||"Failed to search users"})}finally{i(!1)}},300),[]),S=X=>{const B=X.target.value;s(B),F(B)},T=async X=>{l(X),s(X.email),r([]);const B=p.find(ne=>ne.email.toLowerCase()===X.email.toLowerCase()||ne.userId===X.userId);if(B&&B.role)m(B.role);else try{const V=(await Bt.getAllUsers()).find(Z=>Z.email&&Z.email.toLowerCase()===X.email.toLowerCase()||Z.userId&&Z.userId===X.userId);V&&V.role?m(V.role):m("USER")}catch(ne){console.error("Failed to check user role:",ne),m("USER")}},D=async()=>{var X,B;if(!o||!c){g({type:"error",text:"Please select a user and role"});return}u(!0),g(null);try{await Bt.assignRole(o.email,c,o),g({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),m("USER"),await H(),await O()}catch(ne){console.error("Role assignment failed:",ne),g({type:"error",text:((B=(X=ne.response)==null?void 0:X.data)==null?void 0:B.error)||"Failed to assign role"})}finally{u(!1)}},H=async(X=k)=>{var B,ne,V,Z,re,ge;j(!0);try{const ve=await Bt.getUsersByRole(b,X,P),Ue=((ne=(B=ve.data)==null?void 0:B.data)==null?void 0:ne.users)||[],Ie=(Z=(V=ve.data)==null?void 0:V.data)==null?void 0:Z.pagination,Le=(ge=(re=ve.data)==null?void 0:re.data)==null?void 0:ge.summary;f(Ue),Ie&&(L(Ie.currentPage),I(Ie.totalPages),A(Ie.totalUsers)),Le&&N({admins:Le.ADMIN||0,management:Le.MANAGEMENT||0,users:Le.USER||0})}catch(ve){console.error("Failed to fetch users:",ve)}finally{j(!1)}},O=async()=>{var X,B,ne,V,Z,re;try{const ge=await Bt.getRoleStatistics(),ve=((B=(X=ge.data)==null?void 0:X.data)==null?void 0:B.statistics)||((ne=ge.data)==null?void 0:ne.statistics)||[];N({admins:parseInt(((V=ve.find(Ue=>Ue.role==="ADMIN"))==null?void 0:V.count)||"0"),management:parseInt(((Z=ve.find(Ue=>Ue.role==="MANAGEMENT"))==null?void 0:Z.count)||"0"),users:parseInt(((re=ve.find(Ue=>Ue.role==="USER"))==null?void 0:re.count)||"0")})}catch(ge){console.error("Failed to fetch statistics:",ge)}};x.useEffect(()=>{H(1),O()},[b]);const _=X=>{C(X),L(1)},ee=X=>{H(X)},G=X=>{C(X),L(1),requestAnimationFrame(()=>{const B=M.current;B&&B.scrollIntoView({behavior:"smooth",block:"start"})})};x.useEffect(()=>{const X=B=>{q.current&&!q.current.contains(B.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",X),()=>{document.removeEventListener("mousedown",X)}},[a]);const Y=X=>{switch(X){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"}},me=X=>{switch(X){case"ADMIN":return e.jsx(ia,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(Je,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(rt,{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 ${b==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>G("ADMIN"),children:e.jsx(K,{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:b==="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(ia,{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 ${b==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>G("MANAGEMENT"),children:e.jsx(K,{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:b==="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(Je,{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 ${b==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>G("USER"),children:e.jsx(K,{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:b==="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(rt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsxs(W,{className:"shadow-lg border",children:[e.jsx(se,{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(Dp,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold",children:"Assign User Role"}),e.jsx(ue,{className:"text-sm",children:"Search for a user in Okta and assign them a role"})]})]})}),e.jsxs(K,{className:"space-y-5 pt-6",children:[e.jsxs("div",{className:"space-y-2",ref:q,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(qt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(pe,{type:"text",placeholder:"Type name or email address...",value:t,onChange:S,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(X=>e.jsxs("button",{onClick:()=>T(X),className:"w-full text-left p-3 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${X.email}`,children:[e.jsx("p",{className:"font-medium text-gray-900",children:X.displayName||X.email}),e.jsx("p",{className:"text-sm text-gray-600",children:X.email}),X.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:[X.department,X.designation?`${X.designation}`:""]})]},X.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(E,{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(Ne,{value:c,onValueChange:X=>m(X),children:[e.jsx(Ce,{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(we,{placeholder:"Select role"})}),e.jsxs(Se,{className:"rounded-lg",children:[e.jsx(z,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(z,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(z,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(E,{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(kt,{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(ye,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Pe,{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:M,children:e.jsxs(W,{className:"shadow-lg border",children:[e.jsx(se,{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(kt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold",children:"User Management"}),e.jsxs(ue,{className:"text-sm",children:["View and manage user roles (",w," ",b!=="ALL"&&b!=="ELEVATED"?b.toLowerCase():""," users)"]})]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Ne,{value:b,onValueChange:_,children:[e.jsx(Ce,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(we,{placeholder:"Filter by role"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",y.admins+y.management,")"]})]})}),e.jsx(z,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",y.admins,")"]})]})}),e.jsx(z,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",y.management,")"]})]})}),e.jsx(z,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",y.users,")"]})]})}),e.jsx(z,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",y.admins+y.management+y.users,")"]})]})})]})]})})]})}),e.jsx(K,{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(Je,{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:b==="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(X=>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-${X.email}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg ${Y(X.role)} flex items-center justify-center shadow-sm`,children:me(X.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:X.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:X.email}),X.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[X.department,X.designation?`${X.designation}`:""]})]})]}),e.jsx(Q,{className:`${Y(X.role)} shrink-0`,"data-testid":`role-badge-${X.role}`,children:X.role})]})},X.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 ",(k-1)*P+1," to ",Math.min(k*P,w)," of ",w," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>ee(k-1),disabled:k===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)},(X,B)=>{let ne;return R<=5||k<=3?ne=B+1:k>=R-2?ne=R-4+B:ne=k-2+B,e.jsx(E,{variant:k===ne?"default":"outline",size:"sm",onClick:()=>ee(ne),className:`w-9 h-9 p-0 ${k===ne?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${ne}-button`,children:ne},ne)})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>ee(k+1),disabled:k===R,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})})]})}function dC({open:t,onClose:s,success:a,message:r}){return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(nt,{className:"sm:max-w-md",children:[e.jsx(ut,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Lt,{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(ye,{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(Ze,{className:"w-8 h-8 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Subscription Failed"}),e.jsx("p",{className:"text-sm text-gray-600 max-w-sm mb-4 whitespace-pre-line",children:r||"Unable to enable push notifications. Please check your browser settings and try again."}),e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 text-left w-full",children:[e.jsx("p",{className:"text-xs text-amber-800 font-medium mb-2",children:"💡 Troubleshooting Tips:"}),e.jsxs("ul",{className:"text-xs text-amber-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Check if notifications are blocked in browser settings"}),e.jsx("li",{children:"Ensure your browser supports push notifications"}),e.jsx("li",{children:"Try refreshing the page and enabling again"})]})]})]})})}),e.jsx(Rt,{children:e.jsx(E,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}function mC(){const{user:t}=$t(),s=Hs(t),[a,r]=x.useState(!1),[n,i]=x.useState(!1),[o,l]=x.useState(),[c,m]=x.useState(!1),d=async()=>{m(!0),r(!1);try{if(!("Notification"in window)){i(!1),l("Notifications are not supported in this browser. Please use a modern browser like Chrome, Firefox, or Edge."),r(!0),m(!1);return}let u=Notification.permission;if(u==="denied"){i(!1),l(`Notification permission was previously denied. To enable notifications:
1. Click the lock icon (🔒) or info icon () in your browser's address bar
2. Find "Notifications" in the permissions list
3. Change it from "Block" to "Allow"
4. Refresh this page and try again
Alternatively, you can enable notifications in your browser's site settings.`),r(!0),m(!1);return}if(u==="default"&&(u=await Notification.requestPermission(),u==="denied")){i(!1),l(`Notification permission was denied. To enable notifications:
1. Click the lock icon (🔒) or info icon () in your browser's address bar
2. Find "Notifications" in the permissions list
3. Change it from "Block" to "Allow"
4. Refresh this page and try again`),r(!0),m(!1);return}if(u!=="granted"){i(!1),l("Notification permission is required to enable push notifications. Please grant permission and try again."),r(!0),m(!1);return}await nC(),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(K,{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(ra,{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(Ir,{defaultValue:"user",className:"w-full",children:[e.jsxs(Fr,{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(ht,{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(ra,{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(ht,{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(kt,{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(ht,{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(Wc,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(ht,{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(Be,{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(pt,{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(se,{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(Lt,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-gray-900",children:"Notifications"}),e.jsx(ue,{className:"text-sm text-gray-600",children:"Manage notification preferences"})]})]})}),e.jsx(K,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs(E,{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(Lt,{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(se,{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(Dn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(ue,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(K,{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(se,{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(wo,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(ue,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(K,{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(se,{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(kt,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(ue,{className:"text-sm text-gray-600",children:"Application preferences"})]})]})}),e.jsx(K,{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(pt,{value:"roles",className:"mt-0",children:e.jsx(cC,{})}),e.jsx(pt,{value:"system",className:"mt-0",children:e.jsx(iC,{})}),e.jsx(pt,{value:"holidays",className:"mt-0",children:e.jsx(oC,{})})]})]}):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(se,{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(Lt,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-gray-900",children:"Notifications"}),e.jsx(ue,{className:"text-sm text-gray-600",children:"Manage notification preferences"})]})]})}),e.jsx(K,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs(E,{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(Lt,{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(se,{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(Dn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(ue,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(K,{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(se,{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(wo,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(ue,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(K,{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(se,{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(kt,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(ue,{className:"text-sm text-gray-600",children:"Application preferences"})]})]})}),e.jsx(K,{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(K,{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(Pe,{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(dC,{open:a,onClose:()=>r(!1),success:n,message:o})]})}function uC({onNavigate:t}){const[s,a]=x.useState([]),[r,n]=x.useState(!0),[i,o]=x.useState(1),[l,c]=x.useState(1),[m,d]=x.useState(0),[u,h]=x.useState("all"),[g,p]=x.useState(!1),f=20,v=async(I=i,w=u==="unread")=>{var A,P;try{n(I===1);const q=await Ys.list({page:I,limit:f,unreadOnly:w}),M=((A=q.data)==null?void 0:A.notifications)||[],F=((P=q.data)==null?void 0:P.total)||0;a(M),d(F),c(Math.ceil(F/f))}catch(q){console.error("[Notifications] Failed to fetch:",q)}finally{n(!1),p(!1)}};x.useEffect(()=>{v(1,u==="unread")},[u]);const j=async I=>{var w;try{if(I.isRead||(await Ys.markAsRead(I.notificationId),a(A=>A.map(P=>P.notificationId===I.notificationId?{...P,isRead:!0}:P))),I.actionUrl&&t){const A=(w=I.metadata)==null?void 0:w.requestNumber;if(A){let P=`request/${A}`;(I.notificationType==="mention"||I.notificationType==="comment"||I.notificationType==="worknote")&&(P+="?tab=worknotes"),t(P)}}}catch(A){console.error("[Notifications] Error handling notification click:",A)}},y=async()=>{try{p(!0),await Ys.markAllAsRead(),await v(i,u==="unread")}catch(I){console.error("[Notifications] Error marking all as read:",I),p(!1)}},N=async I=>{try{await Ys.delete(I),a(w=>w.filter(A=>A.notificationId!==I)),d(w=>w-1)}catch(w){console.error("[Notifications] Error deleting notification:",w)}},b=()=>{p(!0),v(i,u==="unread")},C=I=>{I<1||I>l||(o(I),v(I,u==="unread"))},k=I=>{const w="w-6 h-6";switch(I){case"mention":case"comment":return e.jsx(js,{className:`${w} text-blue-600`});case"worknote":return e.jsx(Te,{className:`${w} text-purple-600`});case"assignment":return e.jsx(Ar,{className:`${w} text-indigo-600`});case"approval":return e.jsx(ye,{className:`${w} text-green-600`});case"rejection":return e.jsx(Ze,{className:`${w} text-red-600`});case"tat_alert":return e.jsx(Re,{className:`${w} text-orange-600`});case"tat_breach":return e.jsx(Pe,{className:`${w} text-red-600`});case"tat_breach_initiator":return e.jsx(as,{className:`${w} text-amber-600`});default:return e.jsx(Lt,{className:`${w} text-gray-600`})}},L=I=>{switch(I==null?void 0:I.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(I=>!I.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(Lt,{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(E,{variant:"outline",size:"sm",onClick:b,disabled:g,className:"gap-2",children:[e.jsx(Et,{className:`w-4 h-4 ${g?"animate-spin":""}`}),"Refresh"]}),R>0&&e.jsxs(E,{variant:"outline",size:"sm",onClick:y,disabled:g,className:"gap-2",children:[e.jsx(Pp,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{variant:u==="all"?"default":"outline",size:"sm",onClick:()=>{h("all"),o(1)},children:"All Notifications"}),e.jsxs(E,{variant:u==="unread"?"default":"outline",size:"sm",onClick:()=>{h("unread"),o(1)},children:["Unread",R>0&&e.jsx(Q,{className:"ml-2 bg-red-500 text-white",children:R})]})]}),e.jsxs(W,{children:[e.jsxs(se,{children:[e.jsx(ae,{children:"Recent Activity"}),e.jsx(ue,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(K,{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(Lt,{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(I=>{var w;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${I.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>j(I),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:k(I.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 ${I.isRead?"font-semibold":"font-bold"} text-gray-900`,children:I.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[I.priority&&I.priority!=="LOW"&&e.jsx(Q,{variant:"outline",className:`text-xs ${L(I.priority)}`,children:I.priority}),!I.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:I.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[Mc(new Date(I.createdAt),{addSuffix:!0}),((w=I.metadata)==null?void 0:w.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",I.metadata.requestNumber]})]}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:A=>{A.stopPropagation(),N(I.notificationId)},children:e.jsx(yi,{className:"w-3.5 h-3.5"})})]})]})]})},I.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(E,{variant:"outline",size:"sm",onClick:()=>C(i-1),disabled:i===1,children:[e.jsx(Hc,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,l)},(I,w)=>{let A;return l<=5||i<=3?A=w+1:i>=l-2?A=l-4+w:A=i-2+w,e.jsx(E,{variant:i===A?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>C(A),children:A},A)})}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>C(i+1),disabled:i===l,children:["Next",e.jsx(gi,{className:"w-4 h-4"})]})]})]})]})}function hC({onBack:t}){return e.jsx("div",{className:"flex items-center justify-between","data-testid":"detailed-reports-header",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(E,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(Ms,{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(Te,{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 uo({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 g=s&&a?`${xe(s,"MMM d, yyyy")} - ${xe(a,"MMM d, yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${h}-container`,children:[e.jsx(Be,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ne,{value:t,onValueChange:o,"data-testid":`${h}-select`,children:[e.jsx(Ce,{className:"w-[160px]",children:e.jsx(we,{placeholder:"Date Range"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"today",children:"Today"}),e.jsx(z,{value:"week",children:"This Week"}),e.jsx(z,{value:"month",children:"This Month"}),e.jsx(z,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(Rs,{open:r,onOpenChange:l,children:[e.jsx(Ds,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${h}-custom-trigger`,children:[e.jsx(Be,{className:"w-4 h-4"}),g]})}),e.jsx(Ps,{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(J,{htmlFor:`${h}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(pe,{id:`${h}-start-date`,type:"date",value:n?xe(n,"yyyy-MM-dd"):"",onChange:p=>{const f=p.target.value?new Date(p.target.value):void 0;c(f)},max:xe(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":`${h}-start-input`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:`${h}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(pe,{id:`${h}-end-date`,type:"date",value:i?xe(i,"yyyy-MM-dd"):"",onChange:p=>{const f=p.target.value?new Date(p.target.value):void 0;m(f)},min:n?xe(n,"yyyy-MM-dd"):void 0,max:xe(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(E,{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(E,{size:"sm",variant:"outline",onClick:u,"data-testid":`${h}-cancel-button`,children:"Cancel"})]})]})})]})]})}function pC(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 Au(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 Tu(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 xC(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function gC({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:g,onStartDateChange:p,onEndDateChange:f,onApplyCustomDate:v,onCancelCustomDate:j,onPageChange:y,onExport:N,onViewRequest:b}){return e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(se,{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(Ht,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(ue,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",onClick:N,disabled: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(uo,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:m,tempCustomEndDate:d,onDateRangeChange:h,onShowCustomDatePickerChange:g,onStartDateChange:p,onEndDateChange:f,onApply:v,onCancel:j,testIdPrefix:"lifecycle"})})]}),e.jsxs(K,{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(Pe,{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(C=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${C.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:()=>b(C.requestId||C.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:k=>{k.stopPropagation(),b(C.requestId||C.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${C.id}`,children:C.id}),e.jsx(Q,{className:Au(C.priority),"data-testid":`lifecycle-priority-${C.id}`,children:C.priority}),e.jsx(Q,{className:Tu(C.status),"data-testid":`lifecycle-status-${C.id}`,children:C.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:C.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:C.initiator})," on ",C.initDate]}),C.currentStage&&!C.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",C.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:C.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",C.currentLevel,"/",C.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:C.overallTAT}),C.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[C.breachCount," breach",C.breachCount>1?"es":""]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>b(C.requestId||C.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${C.id}`,children:e.jsx(gi,{className:"w-4 h-4"})})]})]})})},C.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(E,{variant:"outline",size:"sm",onClick:()=>y(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>y(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function ho({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:he("w-full caption-bottom text-sm",t),...s})})}function po({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:he("[&_tr]:border-b",t),...s})}function xo({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:he("[&_tr:last-child]:border-0",t),...s})}function aa({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:he("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function ct({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:he("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:he("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function fC({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:g,onDateRangeChange:p,onShowCustomDatePickerChange:f,onStartDateChange:v,onEndDateChange:j,onApplyCustomDate:y,onCancelCustomDate:N,onCategoryChange:b,onSeverityChange:C,onClearFilters:k,onPageChange:L,onExport:R,onViewRequest:I}){const w=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(se,{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(Ep,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(ue,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",onClick:R,disabled:g,"data-testid":"export-activity-button",children:[e.jsx(ts,{className:"w-4 h-4"}),g?"Exporting...":"Download CSV"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(uo,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:m,tempCustomEndDate:d,onDateRangeChange:p,onShowCustomDatePickerChange:f,onStartDateChange:v,onEndDateChange:j,onApply:y,onCancel:N,testIdPrefix:"activity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Category:"}),e.jsxs(Ne,{value:u,onValueChange:b,"data-testid":"activity-category-filter",children:[e.jsx(Ce,{className:"w-40",children:e.jsx(we,{placeholder:"All Categories"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Categories"}),e.jsx(z,{value:"WORKFLOW",children:"Workflow"}),e.jsx(z,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(z,{value:"DOCUMENT",children:"Document"}),e.jsx(z,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(z,{value:"SYSTEM",children:"System"}),e.jsx(z,{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(Ne,{value:h,onValueChange:C,"data-testid":"activity-severity-filter",children:[e.jsx(Ce,{className:"w-40",children:e.jsx(we,{placeholder:"All Severities"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"all",children:"All Severities"}),e.jsx(z,{value:"INFO",children:"Info"}),e.jsx(z,{value:"WARNING",children:"Warning"}),e.jsx(z,{value:"ERROR",children:"Error"}),e.jsx(z,{value:"CRITICAL",children:"Critical"})]})]})]}),w&&e.jsx(E,{variant:"ghost",size:"sm",onClick:k,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(K,{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(Pe,{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(ho,{children:[e.jsx(po,{children:e.jsxs(aa,{className:"bg-gray-50",children:[e.jsx(ct,{className:"font-semibold",children:"Timestamp"}),e.jsx(ct,{className:"font-semibold",children:"User"}),e.jsx(ct,{className:"font-semibold",children:"Action"}),e.jsx(ct,{className:"font-semibold",children:"Details"}),e.jsx(ct,{className:"font-semibold",children:"IP Address"}),e.jsx(ct,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(xo,{children:t.map((A,P)=>e.jsxs(aa,{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(Q,{className:pC(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 q=A.requestId;q&&I(q)},className:"hover:underline","data-testid":`activity-request-link-${P}`,children:e.jsx(Q,{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(E,{variant:"outline",size:"sm",onClick:()=>L(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>L(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function yC({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:g,exporting:p,onThresholdChange:f,onThresholdBlur:v,onDateRangeChange:j,onShowCustomDatePickerChange:y,onStartDateChange:N,onEndDateChange:b,onApplyCustomDate:C,onCancelCustomDate:k,onSearchChange:L,onPageChange:R,onExport:I,onViewRequest:w}){return e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(se,{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(fi,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(ue,{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(pe,{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(Q,{variant:"outline",className:"font-semibold","data-testid":"aging-total-badge",children:[n.totalRecords," workflows"]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",onClick:I,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(uo,{dateRange:l,customStartDate:c,customEndDate:m,showCustomDatePicker:d,tempCustomStartDate:u,tempCustomEndDate:h,onDateRangeChange:j,onShowCustomDatePickerChange:y,onStartDateChange:N,onEndDateChange:b,onApply:C,onCancel:k,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(qt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(pe,{placeholder:"Search by Request ID, Title, or Initiator...",value:g,onChange:A=>L(A.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(K,{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(Pe,{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(ho,{children:[e.jsx(po,{children:e.jsxs(aa,{className:"bg-gray-50",children:[e.jsx(ct,{className:"font-semibold",children:"Request ID"}),e.jsx(ct,{className:"font-semibold",children:"Title"}),e.jsx(ct,{className:"font-semibold",children:"Initiator"}),e.jsx(ct,{className:"font-semibold",children:"Start Date"}),e.jsx(ct,{className:"font-semibold",children:"Days Open"}),e.jsx(ct,{className:"font-semibold",children:"Current Stage"}),e.jsx(ct,{className:"font-semibold",children:"Assigned To"}),e.jsx(ct,{className:"font-semibold",children:"Priority"}),e.jsx(ct,{className:"font-semibold",children:"Status"})]})}),e.jsx(xo,{children:t.map(A=>e.jsxs(aa,{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:()=>w(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(Q,{className:`${xC(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(Q,{className:Au(A.priority),"data-testid":`aging-priority-${A.id}`,children:A.priority})}),e.jsx(at,{children:e.jsx(Q,{className:Tu(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(E,{variant:"outline",size:"sm",onClick:()=>R(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>R(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function An(t="month"){const[s,a]=x.useState(t),[r,n]=x.useState(void 0),[i,o]=x.useState(void 0),[l,c]=x.useState(!1),[m,d]=x.useState(void 0),[u,h]=x.useState(void 0),g=x.useCallback(b=>{const C=b;a(C),C!=="custom"?(n(void 0),o(void 0),d(void 0),h(void 0),c(!1)):(d(r),h(i),c(!0))},[r,i]),p=x.useCallback(()=>{if(m&&u){if(m>u){const b=m;n(u),o(b),d(u),h(b)}else n(m),o(u);c(!1)}},[m,u]),f=x.useCallback(()=>{c(!1),d(r),h(i),(!r||!i)&&(n(void 0),o(void 0),a("month"))},[r,i]),v=x.useCallback(b=>{b?(d(b),u&&b>u&&h(b)):d(void 0)},[u]),j=x.useCallback(b=>{b?(h(b),m&&b<m&&d(b)):h(void 0)},[m]),y=x.useCallback(()=>r&&i?`${xe(r,"MMM d, yyyy")} - ${xe(i,"MMM d, yyyy")}`:"Select dates",[r,i]),N=x.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:g,handleApplyCustomDate:p,handleCancelCustomDate:f,handleStartDateChange:v,handleEndDateChange:j,getDisplayDateRange:y,reset:N}}function vC(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return Qe(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${Qe(r)}`:`${a}d`}function ku(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 Ks(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 Ru(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 bC=10;function jC({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=x.useState([]),[i,o]=x.useState(!0),[l,c]=x.useState(!1),[m,d]=x.useState(null),[u,h]=x.useState({page:1,totalPages:1,totalRecords:0}),g=x.useRef(!0),p=x.useCallback(async(f=1)=>{const v=f===1&&g.current;try{v?o(!0):c(!0),d(null);const j=await Ve.getLifecycleReport(f,bC,t,s,a),y=j.lifecycleData.map(N=>{const b=vC(N.overallTATHours);return{id:N.requestNumber,requestId:N.requestId,title:N.title,priority:N.priority||"medium",status:N.status,initiator:N.initiatorName||"Unknown",initDate:ku(N.submissionDate),currentStage:N.currentStageName||`Level ${N.currentLevel}`,overallTAT:b,currentLevel:N.currentLevel,totalLevels:N.totalLevels,breachCount:N.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&&(g.current=!1)},[t,s,a]);return x.useEffect(()=>{t==="custom"&&(!s||!a)||p(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:l,error:m,pagination:u,fetchData:p}}const NC=20;function wC({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,o]=x.useState([]),[l,c]=x.useState(!0),[m,d]=x.useState(!1),[u,h]=x.useState(null),[g,p]=x.useState({page:1,totalPages:1,totalRecords:0}),f=x.useRef(!0),v=x.useCallback(async(j=1)=>{const y=j===1&&f.current;try{y?c(!0):d(!0),h(null);const N=await Ve.getActivityLogReport(j,NC,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),b=N.activities.map(C=>{const k=Ru(C.type||"",C.details),L=(C.type||"").toLowerCase()==="login"||C.requestId==="00000000-0000-0000-0000-000000000001"||C.requestId==="SYSTEM_LOGIN",R=L?C.details||"User login":C.requestTitle||C.requestNumber||C.details||"N/A";return{timestamp:C.timestamp?ku(C.timestamp):"N/A",user:C.userName||"Unknown",action:k,details:R,ip:C.ipAddress||"N/A",userAgent:C.userAgent||null,requestId:L?"System Login":C.requestNumber||C.requestId||"-",userId:C.userId}});o(b),p({page:N.pagination.currentPage,totalPages:N.pagination.totalPages,totalRecords:N.pagination.totalRecords})}catch(N){console.error("Failed to fetch activity data:",N),h((N==null?void 0:N.message)||"Failed to load activity data")}finally{y?c(!1):d(!1)}y&&(f.current=!1)},[r,n,t,s,a]);return x.useEffect(()=>{t==="custom"&&(!s||!a)||v(1)},[r,n,t,s,a]),{activityLog:i,loading:l,loadingPage:m,error:u,pagination:g,fetchData:v}}const CC=20;function SC({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,o]=x.useState([]),[l,c]=x.useState(!0),[m,d]=x.useState(!1),[u,h]=x.useState(null),[g,p]=x.useState({page:1,totalPages:1,totalRecords:0}),f=x.useRef(!0),v=x.useCallback(async(y=1)=>{const N=y===1&&f.current;try{N?c(!0):d(!0),h(null);const b=parseInt(t,10);if(isNaN(b)||b<1){h("Please enter a valid threshold (minimum 1 day)");return}const C=await Ve.getWorkflowAgingReport(b,y,CC,s,a,r),k=C.agingData.map(L=>({id:L.requestNumber||L.requestId,requestId:L.requestId,title:L.title,initiator:L.initiatorName||"Unknown",startDate:L.submissionDate?new Date(L.submissionDate).toLocaleDateString():"N/A",daysOpen:L.daysOpen,currentStage:L.currentStageName||`Level ${L.currentLevel}`,assignedTo:L.currentApproverName||"N/A",priority:L.priority||"medium",status:L.status||"pending"}));o(k),p({page:C.pagination.currentPage,totalPages:C.pagination.totalPages,totalRecords:C.pagination.totalRecords})}catch(b){console.error("Failed to fetch aging data:",b),h((b==null?void 0:b.message)||"Failed to load aging data")}finally{N?c(!1):d(!1)}N&&(f.current=!1)},[t,s,a,r]),j=x.useMemo(()=>i.filter(y=>{var b,C,k;if(!n)return!0;const N=n.toLowerCase();return((b=y.id)==null?void 0:b.toLowerCase().includes(N))||((C=y.title)==null?void 0:C.toLowerCase().includes(N))||((k=y.initiator)==null?void 0:k.toLowerCase().includes(N))}),[i,n]);return x.useEffect(()=>{s==="custom"&&(!a||!r)||v(1)},[t,s,a,r]),{agingWorkflows:j,loading:l,loadingPage:m,error:u,pagination:g,fetchData:v}}function AC(t="7"){const[s,a]=x.useState(t),[r,n]=x.useState(null),i=x.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=x.useCallback(()=>{(s===""||isNaN(parseInt(s,10))||parseInt(s,10)<1)&&(a("1"),n(null))},[s]);return{threshold:s,thresholdError:r,setThreshold:a,handleThresholdChange:i,handleThresholdBlur:o}}async function TC(t,s,a){const r=await Ve.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 Xs(i.requestId||i.requestNumber),l=i.submissionDate?Ks(i.submissionDate):"N/A",c=i.closureDate?Ks(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),g=(o==null?void 0:o.approvals)||[];if(g.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 g.forEach(p=>{const f=p.levelStartTime?Ks(p.levelStartTime):"N/A",v=p.levelEndTime||p.completedAt?Ks(p.levelEndTime||p.completedAt):"N/A",j=p.tatHours||0,y=p.tatDays||(j>0?(j/8).toFixed(2):"0");let N="N/A",b="N/A",C="N/A",k="N/A";if(p.levelStartTime){const R=new Date(p.levelStartTime);if(b=(((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(b);C=Math.max(0,j-A).toFixed(2),k=(A/j*100).toFixed(2),p.status==="APPROVED"||p.status==="REJECTED"?N=A<=j?"Compliant":"Breached":p.status==="IN_PROGRESS"||p.status==="PENDING"?N=A<=j?"On Track":"At Risk":N="N/A"}}const L=[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(),N,b,C,k];n.push(L.join(","))})}catch(o){console.error(`Failed to fetch details for request ${i.requestNumber}:`,o);const l=i.submissionDate?Ks(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(","))}go(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function kC(t,s,a,r,n){const i=await Ve.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=Ru(l.type||"",l.details),d=[l.timestamp?Ks(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(","))}),go(o,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function RC(t,s,a,r){const n=await Ve.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?Ks(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(","))}),go(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function go(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 DC(){const[t,s]=x.useState(!1),[a,r]=x.useState(!1),[n,i]=x.useState(!1),o=x.useCallback(async(m,d,u)=>{try{s(!0),await TC(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=x.useCallback(async(m,d,u,h,g)=>{try{r(!0),await kC(m,d,u,h,g)}catch(p){console.error("Failed to export activity data:",p),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),c=x.useCallback(async(m,d,u,h)=>{try{i(!0),await RC(m,d,u,h)}catch(g){console.error("Failed to export aging data:",g),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 PC({onBack:t}){const s=Os(),[a,r]=x.useState(""),[n,i]=x.useState("all"),[o,l]=x.useState("all"),c=An("month"),m=An("month"),d=An("month"),u=AC("7"),h=jC({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),g=wC({dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,filterCategory:n,filterSeverity:o}),p=SC({threshold:u.threshold,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,searchQuery:a}),f=DC(),v=x.useCallback(()=>{t?t():s("/dashboard")},[t,s]),j=x.useCallback(k=>{s(`/request/${k}`)},[s]),y=x.useCallback(()=>{f.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[f,c]),N=x.useCallback(()=>{f.handleExportActivity(m.dateRange,m.customStartDate,m.customEndDate,n,o)},[f,m,n,o]),b=x.useCallback(()=>{const k=parseInt(u.threshold,10);!isNaN(k)&&k>=1&&f.handleExportAging(k,d.dateRange,d.customStartDate,d.customEndDate)},[f,u.threshold,d]),C=x.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(hC,{onBack:v}),e.jsx(gC,{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(fC,{activityLog:g.activityLog,loading:g.loading,loadingPage:g.loadingPage,error:g.error,pagination:g.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:C,onPageChange:g.fetchData,onExport:N,onViewRequest:j}),e.jsx(yC,{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:b,onViewRequest:j})]})})}function EC({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(J,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(Ne,{value:t,onValueChange:a,children:[e.jsx(Ce,{id:"default-period",children:e.jsx(we,{})}),e.jsx(Se,{children:n.map(i=>e.jsx(z,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(pe,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function MC({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})]})]})}const IC=["CSV","Excel","PDF","JSON"];function FC({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(J,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:IC.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Ni,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(J,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function LC({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(pe,{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 _C(){const[t,s]=x.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{ke.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(W,{children:[e.jsxs(se,{children:[e.jsx(ae,{children:"Analytics & Reporting Configuration"}),e.jsx(ue,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(EC,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(jt,{}),e.jsx(MC,{autoRefresh:t.autoRefresh,realTimeUpdates:t.realTimeUpdates,dataExport:t.dataExport,onAutoRefreshChange:n=>r({autoRefresh:n}),onRealTimeUpdatesChange:n=>r({realTimeUpdates:n}),onDataExportChange:n=>r({dataExport:n})}),e.jsx(jt,{}),e.jsx(FC,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(LC,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(E,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(_s,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const OC=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"}},$C=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function UC({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(ho,{children:[e.jsx(po,{children:e.jsxs(aa,{children:[e.jsx(ct,{children:"User"}),e.jsx(ct,{children:"Role"}),e.jsx(ct,{children:"Department"}),e.jsx(ct,{children:"Status"}),e.jsx(ct,{className:"text-right",children:"Actions"})]})}),e.jsx(xo,{children:t.length===0?e.jsx(aa,{children:e.jsx(at,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(aa,{className:"hover:bg-muted/50",children:[e.jsx(at,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ft,{className:"size-10",children:e.jsx(yt,{className:"bg-re-green text-white",children:$C(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(Q,{className:OC(n.role),children:n.role})}),e.jsx(at,{children:n.department}),e.jsx(at,{children:e.jsxs(Q,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Rn,{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(E,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx(Rr,{className:"w-4 h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(Mp,{className:"w-4 h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(yi,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function VC({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 BC(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function zC(){const[t,s]=x.useState(""),[a,r]=x.useState([]),[n,i]=x.useState(!1),[o,l]=x.useState(null),[c,m]=x.useState("USER"),[d,u]=x.useState(!1),[h,g]=x.useState(!1),[p,f]=x.useState(null),[v,j]=x.useState([]),[y,N]=x.useState(!1),[b,C]=x.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[k,L]=x.useState("ELEVATED"),[R,I]=x.useState(1),[w,A]=x.useState(1),[P,q]=x.useState(0),M=10,F=x.useRef(null),S=x.useCallback(BC(async V=>{var Z,re,ge;if(!V||V.length<2){r([]);return}i(!0);try{const Ue=((Z=(await Bt.searchUsers(V,20)).data)==null?void 0:Z.data)||[];r(Ue)}catch(ve){console.error("Search failed:",ve),f({type:"error",text:((ge=(re=ve.response)==null?void 0:re.data)==null?void 0:ge.message)||"Failed to search users"})}finally{i(!1)}},300),[]),T=V=>{const Z=V.target.value;s(Z),S(Z)},D=async V=>{var Z,re;try{const ge=v.find(Le=>Le.email.toLowerCase()===V.toLowerCase());if(ge)return ge.role;const Ie=(((re=(Z=(await Bt.getUsersByRole("ALL",1,1e3)).data)==null?void 0:Z.data)==null?void 0:re.users)||[]).find(Le=>{var tt;return((tt=Le.email)==null?void 0:tt.toLowerCase())===V.toLowerCase()});return Ie&&Ie.role?Ie.role:null}catch(ge){return console.error("Failed to fetch user role:",ge),null}},H=async V=>{l(V),s(V.email),r([]),g(!0);try{const Z=await D(V.email);m(Z||"USER")}catch(Z){console.error("Failed to fetch user role:",Z),m("USER")}finally{g(!1)}},O=async()=>{var V,Z;if(!o||!c){f({type:"error",text:"Please select a user and role"});return}u(!0),f(null);try{await Bt.assignRole(o.email,c),f({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),m("USER"),await _(),await ee(),ke.success("Role assigned successfully")}catch(re){console.error("Role assignment failed:",re);const ge=((Z=(V=re.response)==null?void 0:V.data)==null?void 0:Z.error)||"Failed to assign role";f({type:"error",text:ge}),ke.error(ge)}finally{u(!1)}},_=async(V=R)=>{var Z,re,ge,ve,Ue,Ie;N(!0);try{const Le=await Bt.getUsersByRole(k,V,M),tt=((re=(Z=Le.data)==null?void 0:Z.data)==null?void 0:re.users)||[],He=(ve=(ge=Le.data)==null?void 0:ge.data)==null?void 0:ve.pagination,Dt=(Ie=(Ue=Le.data)==null?void 0:Ue.data)==null?void 0:Ie.summary;j(tt.map(_e=>({userId:_e.userId,email:_e.email,displayName:_e.displayName||_e.email,role:_e.role||"USER",department:_e.department,designation:_e.designation,isActive:_e.isActive!==!1}))),He&&(I(He.currentPage),A(He.totalPages),q(He.totalUsers)),Dt&&C(_e=>({..._e,admins:Dt.ADMIN||0,management:Dt.MANAGEMENT||0,users:Dt.USER||0,total:(Dt.ADMIN||0)+(Dt.MANAGEMENT||0)+(Dt.USER||0)}))}catch(Le){console.error("Failed to fetch users:",Le),ke.error("Failed to load users")}finally{N(!1)}},ee=async()=>{var V,Z,re,ge,ve,Ue;try{const Ie=await Bt.getRoleStatistics(),Le=((Z=(V=Ie.data)==null?void 0:V.data)==null?void 0:Z.statistics)||((re=Ie.data)==null?void 0:re.statistics)||[],tt={admins:parseInt(((ge=Le.find(He=>He.role==="ADMIN"))==null?void 0:ge.count)||"0"),management:parseInt(((ve=Le.find(He=>He.role==="MANAGEMENT"))==null?void 0:ve.count)||"0"),users:parseInt(((Ue=Le.find(He=>He.role==="USER"))==null?void 0:Ue.count)||"0")};C(He=>({...He,...tt,total:tt.admins+tt.management+tt.users,active:He.active||tt.admins+tt.management+tt.users,inactive:He.inactive||0}))}catch(Ie){console.error("Failed to fetch statistics:",Ie)}};x.useEffect(()=>{_(1),ee()},[k]);const G=V=>{L(V),I(1)},Y=V=>{_(V)},me=async(V,Z)=>{var re,ge;try{await Bt.updateUserRole(V,Z),ke.success("User role updated successfully"),await _(),await ee()}catch(ve){console.error("Failed to update user role:",ve),ke.error(((ge=(re=ve.response)==null?void 0:re.data)==null?void 0:ge.error)||"Failed to update user role")}},X=async V=>{v.find(re=>re.userId===V)&&ke.info("User status toggle functionality coming soon")},B=async V=>{const Z=v.find(re=>re.userId===V);if(Z){if(Z.role==="ADMIN"){ke.error("Cannot delete admin user");return}ke.info("User deletion functionality coming soon")}};x.useEffect(()=>{const V=Z=>{F.current&&!F.current.contains(Z.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",V),()=>{document.removeEventListener("mousedown",V)}},[a]);const ne={total:b.total,active:b.active,inactive:b.inactive,admins:b.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(VC,{stats:ne}),e.jsxs(W,{children:[e.jsx(se,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ae,{children:"Assign User Role"}),e.jsx(ue,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(E,{onClick:O,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(Es,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(K,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",ref:F,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(qt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(pe,{type:"text",placeholder:"Type name or email address...",value:t,onChange:T,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(V=>e.jsxs("button",{onClick:()=>H(V),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:V.displayName||V.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:V.email}),V.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[V.department,V.designation?`${V.designation}`:""]})]},V.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(E,{variant:"ghost",size:"sm",onClick:()=>{l(null),s(""),m("USER"),g(!1)},children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Select Role"}),e.jsxs(Ne,{value:c,onValueChange:V=>m(V),disabled:h,children:[e.jsx(Ce,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(we,{placeholder:h?"Loading current role...":"Select role"})}),e.jsxs(Se,{className:"rounded-lg",children:[e.jsx(z,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(z,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(z,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ia,{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(ye,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Pe,{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(se,{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(ae,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(ue,{children:["View and manage user accounts and roles (",P," ",k!=="ALL"&&k!=="ELEVATED"?k.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Ne,{value:k,onValueChange:G,children:[e.jsx(Ce,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(we,{placeholder:"Filter by role"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",b.admins+b.management,")"]})]})}),e.jsx(z,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",b.admins,")"]})]})}),e.jsx(z,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",b.management,")"]})]})}),e.jsx(z,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",b.users,")"]})]})}),e.jsx(z,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",b.admins+b.management+b.users,")"]})]})})]})]})})]})}),e.jsx(K,{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(Je,{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:k==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(UC,{users:v.map(V=>({id:V.userId,name:V.displayName,email:V.email,role:V.role,department:V.department||"N/A",status:V.isActive?"active":"inactive"})),onEdit:V=>{const Z=v.find(re=>re.userId===V);if(Z){const re=Z.role==="USER"?"MANAGEMENT":Z.role==="MANAGEMENT"?"ADMIN":"USER";me(V,re)}},onToggleStatus:X,onDelete:B}),w>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t mt-4",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(R-1)*M+1," to ",Math.min(R*M,P)," of ",P," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>Y(R-1),disabled:R===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,w)},(V,Z)=>{let re;return w<=5||R<=3?re=Z+1:R>=w-2?re=w-4+Z:re=R-2+Z,e.jsx(E,{variant:R===re?"default":"outline",size:"sm",onClick:()=>Y(re),className:`w-9 h-9 p-0 ${R===re?"bg-re-green hover:bg-re-green/90":""}`,children:re},re)})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>Y(R+1),disabled:R===w,children:"Next"})]})]})]})})]})]})}function HC({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(se,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wr,{className:"w-5 h-5 text-re-green"}),e.jsx(ae,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(ue,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(K,{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(J,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(pe,{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(Re,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(pe,{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(Re,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function qC({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(se,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lt,{className:"w-5 h-5 text-re-green"}),e.jsx(ae,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(ue,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(K,{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(J,{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(ii,{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(Lt,{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(J,{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(ii,{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 WC({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(se,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"w-5 h-5 text-re-green"}),e.jsx(ae,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(ue,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(K,{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(J,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(pe,{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(Re,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(pe,{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(Re,{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(J,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(Ne,{value:a.toString(),onValueChange:u=>o(parseInt(u)),children:[e.jsx(Ce,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(we,{placeholder:"Select start day"})}),e.jsx(Se,{children:Ra.map(u=>e.jsx(z,{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(J,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(Ne,{value:r.toString(),onValueChange:u=>l(parseInt(u)),children:[e.jsx(Ce,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(we,{placeholder:"Select end day"})}),e.jsx(Se,{children:Ra.map(u=>e.jsx(z,{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 KC(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({expressHours:24,standardHours:72,reminderThreshold1:50,reminderThreshold2:75,workStartHour:9,workEndHour:18,workStartDay:1,workEndDay:5});x.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const m=await Lr("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),ke.error("Failed to load TAT configurations")}finally{s(!1)}},l=async()=>{var m,d;try{r(!0),await Promise.all([xt("DEFAULT_TAT_EXPRESS_HOURS",n.expressHours.toString()),xt("DEFAULT_TAT_STANDARD_HOURS",n.standardHours.toString()),xt("TAT_REMINDER_THRESHOLD_1",n.reminderThreshold1.toString()),xt("TAT_REMINDER_THRESHOLD_2",n.reminderThreshold2.toString()),xt("WORK_START_HOUR",n.workStartHour.toString()),xt("WORK_END_HOUR",n.workEndHour.toString()),xt("WORK_START_DAY",n.workStartDay.toString()),xt("WORK_END_DAY",n.workEndDay.toString())]),ke.success("TAT configuration saved successfully"),await o()}catch(u){console.error("Failed to save TAT configuration:",u),ke.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(K,{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(se,{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(Re,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(ue,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(HC,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:m=>c({expressHours:m}),onStandardChange:m=>c({standardHours:m})}),e.jsx(jt,{}),e.jsx(WC,{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(jt,{}),e.jsx(qC,{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(E,{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(_s,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function GC({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 YC({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(J,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(Ne,{value:t,onValueChange:a,children:[e.jsx(Ce,{id:"notification-frequency",children:e.jsx(we,{placeholder:"Select frequency"})}),e.jsxs(Se,{children:[e.jsx(z,{value:"Immediate",children:"Immediate"}),e.jsx(z,{value:"Hourly",children:"Hourly"}),e.jsx(z,{value:"Daily",children:"Daily"}),e.jsx(z,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(pe,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function ZC({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{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 XC(){const[t,s]=x.useState({emailNotifications:!0,inAppNotifications:!0,autoReminders:!0,notificationFrequency:"Immediate",reminderFrequency:12,emailTemplate:"Dear [Name], You have a pending approval request [Request ID] that requires your attention. TAT remaining: [TAT]. Please review at your earliest convenience."}),a=()=>{ke.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(W,{children:[e.jsxs(se,{children:[e.jsx(ae,{children:"Notification Configuration"}),e.jsx(ue,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(GC,{emailNotifications:t.emailNotifications,inAppNotifications:t.inAppNotifications,autoReminders:t.autoReminders,onEmailNotificationsChange:n=>r({emailNotifications:n}),onInAppNotificationsChange:n=>r({inAppNotifications:n}),onAutoRemindersChange:n=>r({autoReminders:n})}),e.jsx(jt,{}),e.jsx(YC,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(ZC,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(E,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(_s,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function JC({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(se,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xa,{className:"w-5 h-5 text-re-green"}),e.jsx(ae,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(ue,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(K,{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(J,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(pe,{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(xa,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(pe,{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(Dr,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const QC=[{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 e2({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(se,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ip,{className:"w-5 h-5 text-re-green"}),e.jsx(ae,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(ue,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(K,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:QC.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(J,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(pe,{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 t2(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({maxFileSizeMB:10,retentionDays:365,allowedFileTypes:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"});x.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const m=await Lr("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),ke.error("Failed to load document configurations")}finally{s(!1)}},l=async()=>{var m,d;try{r(!0),await Promise.all([xt("MAX_FILE_SIZE_MB",n.maxFileSizeMB.toString()),xt("DOCUMENT_RETENTION_DAYS",n.retentionDays.toString()),xt("ALLOWED_FILE_TYPES",n.allowedFileTypes)]),ke.success("Document policy saved successfully"),await o()}catch(u){console.error("Failed to save document configuration:",u),ke.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(K,{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(se,{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(Te,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(ue,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(JC,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:m=>c({maxFileSizeMB:m}),onRetentionDaysChange:m=>c({retentionDays:m})}),e.jsx(jt,{}),e.jsx(e2,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:m=>c({allowedFileTypes:m})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(E,{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(_s,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function s2(){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 a2=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],r2=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 n2({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(Q,{className:r2(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:a2.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Ni,{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 i2(){const[t,s]=x.useState({Initiator:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0},Approver:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0},Spectator:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0}}),a=()=>{ke.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(se,{children:[e.jsx(ae,{children:"Dashboard Layout Configuration"}),e.jsx(ue,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(K,{className:"space-y-4",children:[e.jsx(s2,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(n2,{role:i,kpis:t[i]||{},onKPIToggle:(o,l)=>r(i,o,l)},i))}),e.jsxs(E,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(_s,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}const o2=[{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 l2({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(se,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kc,{className:"w-5 h-5 text-re-green"}),e.jsx(ae,{className:"text-base font-semibold",children:"AI Provider & API Keys"})]}),e.jsx(ue,{className:"text-sm",children:"Select your AI provider and configure API keys"})]}),e.jsxs(K,{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(J,{htmlFor:"ai-provider",className:"text-sm font-medium",children:"AI Provider"}),e.jsxs(Ne,{value:s,onValueChange:g=>l(g),children:[e.jsx(Ce,{id:"ai-provider",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(we,{placeholder:"Select AI provider"})}),e.jsx(Se,{children:o2.map(g=>e.jsx(z,{value:g.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:g.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"-"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.description})]})},g.value))})]})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs(J,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Fp,{className:"w-4 h-4"}),"API Keys"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"claude-key",className:"text-xs text-muted-foreground",children:"Claude API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"claude-key",type:i.claude?"text":"password",value:a,onChange:g=>c(g.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(E,{type:"button",variant:"outline",size:"icon",onClick:()=>u("claude"),className:"border-gray-200",children:i.claude?e.jsx(ir,{className:"w-4 h-4"}):e.jsx(bt,{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(J,{htmlFor:"openai-key",className:"text-xs text-muted-foreground",children:"OpenAI API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"openai-key",type:i.openai?"text":"password",value:r,onChange:g=>m(g.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(E,{type:"button",variant:"outline",size:"icon",onClick:()=>u("openai"),className:"border-gray-200",children:i.openai?e.jsx(ir,{className:"w-4 h-4"}):e.jsx(bt,{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(J,{htmlFor:"gemini-key",className:"text-xs text-muted-foreground",children:"Gemini API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"gemini-key",type:i.gemini?"text":"password",value:n,onChange:g=>d(g.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(E,{type:"button",variant:"outline",size:"icon",onClick:()=>u("gemini"),className:"border-gray-200",children:i.gemini?e.jsx(ir,{className:"w-4 h-4"}):e.jsx(bt,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Get your API key from ai.google.dev"})]})]})]})]})]})}function c2({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(se,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kr,{className:"w-5 h-5 text-re-green"}),e.jsx(ae,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(ue,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(K,{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 d2({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(se,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wc,{className:"w-5 h-5 text-re-green"}),e.jsx(ae,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(ue,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(K,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Characters"}),e.jsx(pe,{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 m2(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({claude:!1,openai:!1,gemini:!1}),[o,l]=x.useState({aiEnabled:!0,aiProvider:"claude",claudeApiKey:"",openaiApiKey:"",geminiApiKey:"",aiRemarkGeneration:!0,maxRemarkChars:500});x.useEffect(()=>{c()},[]);const c=async()=>{try{s(!0);const g=await Lr("AI_CONFIGURATION"),p={};g.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(g){console.error("Failed to load AI configurations:",g),ke.error("Failed to load AI configurations")}finally{s(!1)}},m=async()=>{var g,p;try{r(!0),await Promise.all([xt("AI_ENABLED",o.aiEnabled.toString()),xt("AI_PROVIDER",o.aiProvider),xt("CLAUDE_API_KEY",o.claudeApiKey),xt("OPENAI_API_KEY",o.openaiApiKey),xt("GEMINI_API_KEY",o.geminiApiKey),xt("AI_REMARK_GENERATION_ENABLED",o.aiRemarkGeneration.toString()),xt("AI_REMARK_MAX_CHARACTERS",o.maxRemarkChars.toString())]),ke.success("AI configuration saved successfully"),await c()}catch(f){console.error("Failed to save AI configuration:",f),ke.error(((p=(g=f.response)==null?void 0:g.data)==null?void 0:p.error)||"Failed to save AI configuration")}finally{r(!1)}},d=g=>{l(p=>({...p,...g}))},u=g=>{i(p=>({...p,[g]:!p[g]}))},h=g=>!g||g.length===0?"":g.length<=8?"••••••••":g.substring(0,4)+"••••••••"+g.substring(g.length-4);return t?e.jsx(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(K,{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(se,{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(kr,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(ue,{className:"text-sm text-gray-600",children:"Configure AI provider, API keys, and enable/disable AI-powered features"})]})]})}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(l2,{aiEnabled:o.aiEnabled,aiProvider:o.aiProvider,claudeApiKey:o.claudeApiKey,openaiApiKey:o.openaiApiKey,geminiApiKey:o.geminiApiKey,showApiKeys:n,onAiEnabledChange:g=>d({aiEnabled:g}),onProviderChange:g=>d({aiProvider:g}),onClaudeApiKeyChange:g=>d({claudeApiKey:g}),onOpenaiApiKeyChange:g=>d({openaiApiKey:g}),onGeminiApiKeyChange:g=>d({geminiApiKey:g}),onToggleApiKeyVisibility:u,maskApiKey:h}),e.jsx(jt,{}),e.jsx(c2,{aiRemarkGeneration:o.aiRemarkGeneration,onRemarkGenerationChange:g=>d({aiRemarkGeneration:g})}),e.jsx(jt,{}),e.jsx(d2,{maxRemarkChars:o.maxRemarkChars,onMaxRemarkCharsChange:g=>d({maxRemarkChars:g})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(E,{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(_s,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const gc=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function u2({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(J,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(Ne,{value:t,onValueChange:a,children:[e.jsx(Ce,{id:"spectator-permission",children:e.jsx(we,{placeholder:"Select permission"})}),e.jsx(Se,{children:gc.map(n=>e.jsx(z,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(Ne,{value:s,onValueChange:r,children:[e.jsx(Ce,{id:"link-sharing-permission",children:e.jsx(we,{placeholder:"Select permission"})}),e.jsx(Se,{children:gc.map(n=>e.jsx(z,{value:n,children:n},n))})]})]})]})}function h2({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 p2(){const[t,s]=x.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{ke.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(W,{children:[e.jsxs(se,{children:[e.jsx(ae,{children:"Workflow Sharing Policy"}),e.jsx(ue,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(u2,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(jt,{}),e.jsx(h2,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(E,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(_s,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function x2(){const{user:t}=$t(),[s,a]=x.useState(""),[r,n]=x.useState("sharing"),i=[{name:"Request Volume & Status",count:4,kpis:[{id:"total-requests",title:"Total Requests Created",description:"Count of all workflow requests created in a selected period.",value:5,change:12,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"open-requests",title:"Open Requests",description:"Number of workflows currently in progress with age.",value:3,change:-5,changeType:"down",period:"Today",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"approved-requests",title:"Approved Requests",description:"Requests fully approved and closed.",value:1,change:8,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"rejected-requests",title:"Rejected Requests",description:"Requests rejected at any approval stage.",value:1,period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"}]},{name:"TAT Efficiency",count:3,kpis:[{id:"avg-tat-compliance",title:"Average TAT Compliance %",description:"% of workflows completed within defined TAT vs breached ones at every level.",value:100,unit:"%",change:3,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200"},{id:"avg-approval-cycle",title:"Avg Approval Cycle Time (Days)",description:"Average total time from creation to closure.",value:5.2,unit:" days",change:-15,changeType:"down",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200",thresholdBreached:!0},{id:"delayed-workflows",title:"Delayed Workflows",description:"Requests currently breaching their TAT.",value:0,change:-2,changeType:"down",period:"Today",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200"}]},{name:"Approver Load",count:2,kpis:[{id:"pending-actions",title:"Pending Actions (My Queue)",description:"Requests currently awaiting user's approval with age.",value:3,period:"Today",visibleTo:["Management","Admin"],category:"Approver Load",bgColor:"bg-orange-50",borderColor:"border-orange-200"},{id:"approvals-completed",title:"Approvals Completed (Today/Week)",description:"Count of actions taken within a time frame.",value:0,change:22,changeType:"up",period:"Week",visibleTo:["Management","Admin"],category:"Approver Load",bgColor:"bg-orange-50",borderColor:"border-orange-200"}]},{name:"Engagement & Quality",count:2,kpis:[{id:"comments-worknotes",title:"Comments / Work Notes Added",description:"Measures collaboration activity.",value:8,change:18,changeType:"up",period:"Week",visibleTo:["Management","Admin"],category:"Engagement & Quality",bgColor:"bg-purple-50",borderColor:"border-purple-200"},{id:"attachments-uploaded",title:"Attachments Uploaded",description:"Number of documents added to workflows.",value:16,change:10,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Engagement & Quality",bgColor:"bg-purple-50",borderColor:"border-purple-200"}]},{name:"AI & Closure Insights",count:2,kpis:[{id:"avg-conclusion-length",title:"Avg Conclusion Remark Length",description:"Indicates depth of closure remarks (optional).",value:85,unit:" chars",change:5,changeType:"up",period:"Month",visibleTo:["Management","Admin"],category:"AI & Closure Insights",bgColor:"bg-pink-50",borderColor:"border-pink-200"},{id:"ai-summary-adoption",title:"AI Summary Adoption %",description:"How many closures used AI-generated text vs manual edits.",value:0,unit:"%",change:25,changeType:"up",period:"Month",visibleTo:["Management","Admin"],category:"AI & Closure Insights",bgColor:"bg-pink-50",borderColor:"border-pink-200"}]}],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(kt,{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(Q,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]}),e.jsx(jt,{}),e.jsxs(Ir,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(Fr,{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(ht,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(qc,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(ht,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Ls,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(ht,{value:"users",className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(ht,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(ht,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(Lt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(ht,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Te,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(ht,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(Lp,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(ht,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(Kc,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(ht,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(Nr,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(pt,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(W,{children:[e.jsx(se,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ae,{children:"KPI Configuration"}),e.jsx(ue,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(Q,{className:"bg-blue-50 text-blue-700",children:[l," / ",l," KPIs Active"]})]})}),e.jsxs(K,{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(qt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(pe,{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(Ht,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:m.name}),e.jsxs(Q,{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(Q,{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(_p,{className:"w-3 h-3"}):e.jsx(Op,{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(Q,{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(Pe,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},d.id))})]},m.name))]})]})}),e.jsx(pt,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(_C,{})}),e.jsx(pt,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(zC,{})}),e.jsx(pt,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(KC,{})}),e.jsx(pt,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(XC,{})}),e.jsx(pt,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(t2,{})}),e.jsx(pt,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(i2,{})}),e.jsx(pt,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(m2,{})}),e.jsx(pt,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(p2,{})})]})]})}function g2({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[o,l]=x.useState(""),[c,m]=x.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()},g=a==="approve"?{title:"Approve Request",description:"Please provide your approval comments and remarks",icon:ye,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:Ze,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=g.icon;return e.jsx(mt,{open:t,onOpenChange:u,children:e.jsxs(nt,{className:"max-w-2xl bg-white",children:[e.jsxs(ut,{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 ${g.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(it,{className:"text-xl",children:g.title}),e.jsx(Xt,{className:"mt-1",children:g.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(Q,{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(Q,{className:g.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(J,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(us,{id:"comment",placeholder:g.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(ye,{className:"w-4 h-4 text-green-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium text-green-800",children:"Approval Confirmation"}),e.jsx("p",{className:"text-green-700 mt-1",children:"This request will be forwarded to the next approver or completed if this is the final step."})]})]})})]}),e.jsxs(Rt,{className:"gap-2",children:[e.jsx(E,{variant:"outline",onClick:u,disabled:c,children:"Cancel"}),e.jsx(E,{onClick:d,disabled:!o.trim()||c||o.length>500,className:g.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 f2=(t,s,a,r,n,i,o,l)=>{let c=document.documentElement,m=["light","dark"];function d(g){(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[g]?i[g]:g)):c.setAttribute(p,g)}),u(g)}function u(g){l&&m.includes(g)&&(c.style.colorScheme=g)}function h(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)d(r);else try{let g=localStorage.getItem(s)||a,p=o&&g==="system"?h():g;d(p)}catch{}},y2=x.createContext(void 0),v2={setTheme:t=>{},themes:[]},b2=()=>{var t;return(t=x.useContext(y2))!=null?t:v2};x.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 x.createElement("script",{...m,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${f2.toString()})(${d})`}})});const j2=({...t})=>{const{theme:s="system"}=b2();return e.jsx($p,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function N2({onViewRequest:t}){const{user:s}=$t();return Er(s)?e.jsx(F1,{onViewRequest:t}):e.jsx(_1,{onViewRequest:t})}function w2({onLogout:t}){const s=Os(),[a,r]=x.useState(null),[n,i]=x.useState([]),[o,l]=x.useState(""),[c,m]=x.useState("");x.useEffect(()=>{const y=localStorage.getItem("dynamicRequests");if(y)try{const N=JSON.parse(y);i(N)}catch(N){console.error("Error parsing dynamic requests:",N)}},[]),x.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,N,b)=>{l(y),m(N||"Unknown Request");const C=(b==null?void 0:b.toLowerCase())==="draft"||b==="DRAFT";s(C?`/edit-request/${y}`:`/request/${y}`)},h=()=>{s(-1)},g=()=>{s("/new-request")},p=y=>{var C,k,L,R,I,w,A,P,q,M,F;if(y.templateType){y.templateType==="claim-management"&&s("/claim-management");return}const N=`RE-REQ-2024-${String(Object.keys(pd).length+n.length+1).padStart(3,"0")}`,b={id:N,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:((C=y.approvers)==null?void 0:C.length)||1,currentApprover:((L=(k=y.approvers)==null?void 0:k[0])==null?void 0:L.name)||((w=(I=(R=y.approvers)==null?void 0:R[0])==null?void 0:I.email)==null?void 0:w.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(S=>S).map((S,T)=>{var O;const D=(S==null?void 0:S.name)||((O=S==null?void 0:S.email)==null?void 0:O.split("@")[0])||`Approver ${T+1}`,H=(S==null?void 0:S.email)||"";return{step:T+1,approver:`${D}${H?` (${H})`:""}`,role:(S==null?void 0:S.role)||`Level ${(S==null?void 0:S.level)||T+1} Approver`,status:T===0?"pending":"waiting",tatHours:S!=null&&S.tat?typeof S.tat=="string"?parseInt(S.tat):S.tat:48,elapsedHours:0,assignedAt:T===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(y.spectators||[]).filter(S=>S&&(S.name||S.email)).map(S=>{var D;const T=(S==null?void 0:S.name)||((D=S==null?void 0:S.email)==null?void 0:D.split("@")[0])||"Observer";return{name:T,role:(S==null?void 0:S.role)||(S==null?void 0:S.department)||"Observer",avatar:T.split(" ").map(H=>H[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 ${((q=(P=y.approvers)==null?void 0:P[0])==null?void 0:q.name)||((F=(M=y.approvers)==null?void 0:M[0])==null?void 0:F.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,b]),s("/my-requests"),ke.success("Request Submitted Successfully!",{description:`Your request "${y.title}" (${N}) has been created and sent for approval.`,duration:5e3})},f=(y,N)=>new Promise(b=>{setTimeout(()=>{y==="approve"?ke.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):ke.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),r(null),b(!0)},1e3)}),v=()=>{r(null)},j=y=>{var C;const b={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",(C=y.activityType)==null?void 0:C.toLowerCase().replace(/\s+/g,"-")]};i(k=>[...k,b]),ke.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(Bp,{children:[e.jsx(ot,{path:"/login/callback",element:e.jsx(sd,{})}),e.jsx(ot,{path:"/",element:e.jsx(St,{currentPage:"dashboard",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(Lo,{onNavigate:d,onNewRequest:g})})}),e.jsx(ot,{path:"/dashboard",element:e.jsx(St,{currentPage:"dashboard",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(Lo,{onNavigate:d,onNewRequest:g})})}),e.jsx(ot,{path:"/open-requests",element:e.jsx(St,{currentPage:"open-requests",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(Jg,{onViewRequest:u})})}),e.jsx(ot,{path:"/closed-requests",element:e.jsx(St,{currentPage:"closed-requests",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(hf,{onViewRequest:u})})}),e.jsx(ot,{path:"/shared-summaries",element:e.jsx(St,{currentPage:"shared-summaries",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(m0,{})})}),e.jsx(ot,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(St,{currentPage:"shared-summaries",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(u0,{})})}),e.jsx(ot,{path:"/my-requests",element:e.jsx(St,{currentPage:"my-requests",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(N1,{onViewRequest:u,dynamicRequests:n})})}),e.jsx(ot,{path:"/requests",element:e.jsx(St,{currentPage:"requests",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(N2,{onViewRequest:u})})}),e.jsx(ot,{path:"/approver-performance",element:e.jsx(St,{currentPage:"approver-performance",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(J1,{})})}),e.jsx(ot,{path:"/request/:requestId",element:e.jsx(St,{currentPage:"request-detail",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(d0,{requestId:"",onBack:h,dynamicRequests:n})})}),e.jsx(ot,{path:"/work-notes/:requestId",element:e.jsx(h0,{})}),e.jsx(ot,{path:"/new-request",element:e.jsx(lc,{onBack:h,onSubmit:p})}),e.jsx(ot,{path:"/edit-request/:requestId",element:e.jsx(lc,{onBack:h,onSubmit:p,requestId:void 0,isEditMode:!0})}),e.jsx(ot,{path:"/claim-management",element:e.jsx(u1,{onBack:h,onSubmit:j})}),e.jsx(ot,{path:"/profile",element:e.jsx(St,{currentPage:"profile",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(Q1,{})})}),e.jsx(ot,{path:"/settings",element:e.jsx(St,{currentPage:"settings",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(mC,{})})}),e.jsx(ot,{path:"/notifications",element:e.jsx(St,{currentPage:"notifications",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(uC,{onNavigate:d})})}),e.jsx(ot,{path:"/detailed-reports",element:e.jsx(St,{currentPage:"detailed-reports",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(PC,{})})}),e.jsx(ot,{path:"/admin",element:e.jsx(St,{currentPage:"admin",onNavigate:d,onNewRequest:g,onLogout:t,children:e.jsx(x2,{})})})]}),e.jsx(j2,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),a&&e.jsx(g2,{isOpen:!!a,onClose:v,action:a,requestId:o,requestTitle:c,onSubmit:f})]})}function C2(t){const{onLogout:s}=t||{};return e.jsx(Vp,{children:e.jsx(w2,{onLogout:s})})}function S2(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=$t(),[i,o]=x.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 x.useEffect(()=>{},[t,s,a,r]),l?e.jsx(sd,{}):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(C2,{onLogout:c}),i&&e.jsx(Ix,{isOpen:i,onClose:()=>o(!1)})]}):e.jsx(Ex,{})}Mn.createRoot(document.getElementById("root")).render(e.jsx(Vh.StrictMode,{children:e.jsx(Qp,{children:e.jsx(S2,{})})}));export{le as a};
//# sourceMappingURL=index-BY7hqx1l.js.map